November Happy Hour will be moved to Thursday December 5th.

Limit the selection option of ISelectionFactory checkboxes

Vote:
 


I have ISelectionFactory which provides collection of ProductNode and it gives me checkboxes of nodes in admin mode. User can select multiploe options over there. But I want to allow only 2.

#202095
Mar 14, 2019 3:12
Vote:
 

I would suggest creating a ValidationAttribute for SelectionFactories which will allow you to specifiy the maximum number of elements you want to permit to be selected.

Example Validation Attribute:

    [AttributeUsage(AttributeTargets.Property)]
    public class MaxSelectFactoryItemsAttribute : ValidationAttribute
    {
        private int _max;

        public MaxSelectFactoryItemsAttribute(int max)
        {
            _max = max;
        }

        public override bool IsValid(object value)
        {
            string error = $"restricted to {_max} items!";
            ICollection collection;
            if (value is string)
            {
                collection = ((string)value).Split(',') as ICollection;
            }
            else
            {
                collection = value as ICollection;
            }
            if (collection?.Count > _max)
            {
                ErrorMessage = error;

                return false;
            }

            return true;
        }

        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            var result = base.IsValid(value, validationContext);

            if (!string.IsNullOrWhiteSpace(result?.ErrorMessage))
            {
                result.ErrorMessage = $"{validationContext.DisplayName} {ErrorMessage}";
            }

            return result;
        }
    }

Example of using the attribute when declaring an element with a SelectionFactory:

        [Display(GroupName = SystemTabNames.Content)]
        [SelectManyExtended(SelectionFactoryType = typeof(ArticleTagSelectionFactory))]
        [MaxSelectFactoryItems(3)]
        public virtual string ArticleTags { get; set; }

Just amend the ValidationAttribute accordingly to handle a collection of product nodes.

#202097
Mar 14, 2019 8:51
Vote:
 

Thanks, it works .

#202135
Mar 15, 2019 3:37
This topic was created over six months ago and has been resolved. If you have a similar question, please create a new topic and refer to this one.
* You are NOT allowed to include any hyperlinks in the post because your account hasn't associated to your company. User profile should be updated.