1

I'm using EPiServer CMS 7.5. I have a block that has a LinkItemCollection property.

public virtual LinkItemCollection LinkList { get; set; }

The user can drag-and-drop any document from the Assets pane into the Link Item Collection. How do I prevent the user from adding a document that already exists in the Link Item Collection?

Jen
  • 153
  • 2
  • 13

1 Answers1

1

Ok I have found a way to check duplicates in a Link Item Collection while in forms edit mode.

I have created a helper class that checks duplicates in a collection:

public static class EnumerableExtensions
    {
        public static bool HasDuplicates<T>(this IEnumerable<T> subjects)
        {
            return HasDuplicates(subjects, EqualityComparer<T>.Default);
        }

        public static bool HasDuplicates<T>(this IEnumerable<T> subjects, IEqualityComparer<T> comparer)
        {
            if (subjects == null)
                throw new ArgumentNullException("subjects");

            if (comparer == null)
                throw new ArgumentNullException("comparer");

            var set = new HashSet<T>(comparer);

            foreach (var s in subjects)
                if (!set.Add(s))
                    return true;

            return false;
        }

Then I created a custom Validator for my Link Item Collection:

public class LinkItemCollectionValidator : IValidate<LinkItemCollection>
    {
        public IEnumerable<ValidationError> Validate(LinkItemCollection instance)
        {
            var errors = new List<ValidationError>();                                                
            List<string> list = new List<string>();

            foreach (var i in instance)
            {
                list.Add(i.Text);
            }

            if (list.HasDuplicates())
            {
                errors.Add(new ValidationError()
                {
                    ErrorMessage = "Duplicate content is not allowed",
                    PropertyName = "LinkList",
                    Severity = ValidationErrorSeverity.Error,
                    ValidationType = ValidationErrorType.StorageValidation
                });
            }

            return errors;
        }
Jen
  • 153
  • 2
  • 13