Try our conversational search powered by Generative AI!

Set the default option to enum constant string

Vote:
 

I have a string property which allows user to select multiple enum options. I want to set the default option to 'Option1' for the string property.
Property allows multiple selections of the Enum but I want the default option to be set for 'Option1'

[Display(
Name = "options",
GroupName = SystemTabNames.Content,
Order = 30
)]
[SelectMany(SelectionFactoryType = typeof(EnumSelectionFactory))]
public virtual string Option { get; set; }

public override void SetDefaultValues(ContentType contentType)
{
base.SetDefaultValues(contentType);
Option = Forms.Option.Option1.ToString();
}


public enum Option
{
Option1 = 0,
Option2 = 1
}

public class EnumSelectionFactory : ISelectionFactory
{
public IEnumerable GetSelections(
ExtendedMetadata metadata)
{
var values = Enum.GetValues(typeof(TEnum));
foreach (var value in values)
{
yield return new SelectItem
{
Text = GetValueName((Enum)value),
Value = value
};
}
}

private string GetValueName(Enum value)
{
return EnumHelper.StringValueOf(value, true);
}
}

#160727
Edited, Oct 04, 2016 18:22
Vote:
 

It's a bit odd to have default options checked for a SelectMany control. If something needs to be checked maybe you can combine your SelectionFactory decoration with [Required]?

#160728
Oct 04, 2016 21:57
Vote:
 

In terms of funcitonality in the code behind, I could get the option set to the 'Option1' and is working fine, but in the CMS I don't see that option checked. Is there anyway in CMS we can make the option checked?

#160749
Oct 05, 2016 11:14
Vote:
 

It's working when I set the default value in the settings of property in Admin mode. I was expecting the code written to set the default value should automatically be picked up without any explicit setting.

#160756
Oct 05, 2016 12:28
Vote:
 

Does it work if you just go Option = "Option1";"?

#160757
Oct 05, 2016 12:31
* 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.