In Sitecore, there is a General Link field type which allows user to create links of internal, media, external, anchor, mail, ext. The hyper link created is based on text. Now I have a requirement to insert an image and attach a hyper link to an internal page. General Link field doesn’t provide such function even the Media Link sounds very close but not. Here are two solutions came up my mind: 1, extend SitecoreHelper to create a LinkImageField to render field inside another one; 2, add Image Link menu to the General Link field type in Sitecore.
In this post, I am going to show the implementation of the first solution which is simpler and more straightforward.
For example, the template has two fields: Logo (type: Image), Logo Link (type: General Link). We want to render the Logo field nested in Logo Link field with hyper link to internal, external, media, anchor, mail, ext.
To make it simple, let’s make an extension of SitecoreHelper to create a new LinkImageField. The important tip here is using BeginField() and EndField() function to achieve one field nested in another field.
public static HtmlString LinkImageField(this Sitecore.Mvc.Helpers.SitecoreHelper helper, String imgFieldName, String imgLinkFieldName, Item item, String imgClass, bool disableEditing = false) { var str = helper.BeginField(imgLinkFieldName, item, new { haschildren = true }) + helper.Field(imgFieldName, item, new { @class = imgClass, DisableEditing = disableEditing }).ToString() + helper.EndField(); return new HtmlString(str); }
Here is a simple and clean way to use it in MVC rendering view.
@Html.Sitecore().LinkImageField(LogoFieldName, LogoLinkFieldName, item, imgClass)