Don't miss out Virtual Happy Hour this Friday (April 26).

Try our conversational search powered by Generative AI!

How to make a default value in a block types property?

Vote:
 

When you create a new block type in code, how do you make it default to a value for a property?

E.g. below we have a property of "type".   How would we make it default to a default value, e..g. "heavy" if that is used 99% of the time?

        [Display(
            Order = 2, 
            GroupName = SystemTabNames.Content,
            Description = "type of item, e.g. heavy"
            )]
        [Required]
        public virtual string type { get; set; }
#224652
Jun 24, 2020 7:24
Vote:
 

Hi, override the SetDefaultValues(ContentType contentType), call the base implementation and set your property value in the method like: type = "heavy"; The value is set when the block is created in edit mode (but not if you create it programmatically (well unless you call the methos)).

Also you can also implement the property getter in a way that it will return a default value if the value is null, like this:

get
{
   string setValue = this.GetPropertyValue(b => b.type);

   if(string.IsNullOrWhitespace(setValue))
   {
      // return a default value if nothing is set
      return "heavy";
   }

   return setValue;
}

(oh btw, as a side note, your property type should not be with lower case but Type with capital T)

#224656
Jun 24, 2020 8:03
Vote:
 

I tried this, but it doesnt work unfortunately (tried cleaning and rebuilding the project). No idea why. Also tried using a different property name (MyType) in case it was reserved in some way.  When I create a new block of this type, the "Type" field is still blank, and I have to manually type in the fields value.

        public virtual string Type
        {
            get {
                string val = this.GetPropertyValue(b => b.Type);
                if (string.IsNullOrWhiteSpace(val)){
                    return "heavy";
                    } 
                return val;
            }
            set { type = value; }
        }
#224749
Edited, Jun 25, 2020 8:45
Vote:
 

Just to clarify - that property overriding doesn't show the value in edit mode - you get that default value in your view for example if there is no value set by editor.

#224750
Jun 25, 2020 8:59
Vote:
 

How about setting default value?

public override void SetDefaultValues(ContentType contentType)
{
	base.SetDefaultValues(contentType);
	type = "heavy";
}

It sets the value when you create the block, so you don't have to.

#224755
Jun 25, 2020 9:46
- Jun 25, 2020 9:59
See my first post, I said that already.
* 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.