Listening to Users: a new Image Field Mapping suffix

We’ve made a  small change to ModelMapping based on Developer feedback.

ModelMapping’s advanced features allow you to decorate your Model’s Property names with specific suffixes in order to grab values from Sitecore’s more complex Field types (Fields based on XmlField).

When originally built, the suffixes available were strictly limited to the extended properties of these Xml Field Types. For Image Fields, this meant exposing:

  • “Alt”
  • “Height”
  • “Width”

Pretty straightforward. If you needed to construct an <img/> tag by hand (rather than allow FieldRenderer to do it) you could couple the above suffixes and a property Attribute to get all the facts to create an <img/> tag:

[RenderAsUrl(false)]
public string ImageFieldName {get;set;}
public string ImageFieldNameAlt {get;set;}
public string ImageFieldNameHeight {get;set}
public string ImageFieldNameWidth {get;set;}

However, there are drawbacks:

  • You have to use Custom Experience Buttons to edit the Image Field.
  • Under circumstances where you need to allow FieldRenderer to create an <img/> tag but you also need the URL of the image, you are stuck.

I also found that the [RenderAsUrl(false)] Attribute was counter-intuitive for many developers. Once Developers understood the concept of field Suffixes, they unanimously tried to use “Src” to grab the Image URL from Sitecore, even though Sitecore’s ImageField object contains no equivalent property.

Just Fix It

After a few bouts of explaining that Suffixes were only meant to retrieve known properties from Sitecore Field Types, I decided that it was probably better to bend the architectural rules a bit. Thus, the ImageSrcMapper Field Mapper has been added to Constellation..ModelMapping.

Use

When building your Model class, create a public string property after the name of your Image field, and suffix it with Src. This will produce the Media URL for the Image referenced in the field (if present), similarly to the effect achieved by decorating the Model field with [RenderAsUrl()]

This change to ModelMapper is presently available on NuGet for Sitecore 9.1.1 installations and up!

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.