SaaS CMS has officially launched! Learn more now.

Default image on image properties if not set



Is there any way to specify a default image if not set by an editor?

[Display(Order = 200)]
public virtual Url MainImage { get; set; }

I want to be able to set a default placeholder image, if a property is not set to an instance of an image.

Apr 08, 2014 12:25

Would you perhaps be better handling that in your template rather than your model? Only I imagine you'll need a static image within the project rather than a dynamic media item for a default image.

You could also then set the default image on a template by template basis.

Apr 08, 2014 12:44

Another option is to override the SetDefaultValues() method perhaps, or in the back office via CMS > Admin > Content type > your item - however I'm not sure how you'd set a default value for that particular type.

Apr 08, 2014 12:50

There is an example on how you can accomplish fallback in your model property by implementing custom getter/setter for your property in the SiteLogotypeBlock.Url property in the Alloy template package.

Apr 08, 2014 13:12

I had the solution open, so I thought I'd try save you a few minutes :)

public virtual Url Url
        var url = this.GetPropertyValue(b => b.Url);
        return url == null || url.IsEmpty()
                   ? new Url("/Static/gfx/logotype.png")
                   : url;
        this.SetPropertyValue(b => b.Url, value);

Is there a reason you'd use this rather than the SetDefaultValues? I'm still trying to resolve everything I learnt on the fundamentals course with what I've actually seen in practice.

Apr 08, 2014 13:29

The difference between setting a default value and doing fallback when fetching the value is that the first will save a value in the database. This means that it's not as simple to change this over time since you have the value defined in lots of different places. Also, for a use case as in the Alloy template, it feels a bit akward to save a reference to a fallback image. That of course does not mean that it's always the right choice.

Apr 08, 2014 13:32

Ah, I understand, so with the getter/setter method you can change you placeholder image site wide at a later date and also not grow the database. Better method then in this case :)

Apr 08, 2014 13:35

Exactly, so in most cases this is probably preferred before a default value if you think that there is a big chance that the editor will not change the image.

Apr 08, 2014 13:38
* 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.