Using glass mapper to map droplink field in Sitecore

2.2k Views Asked by At

Has anyone ever used GlassMapper to map complex field types in Sitecore? Glass seems to work well with string fields but Droplinks, Droplists or other types in Sitecore dont map in the model. There is no field type of DropLink. There is a LookupField but it doesn't work with droplinks or droplists.

1

There are 1 best solutions below

3
James Darrall On

In your use case it is actually quite straightforward to achieve this in GlassMapper.

A droplist will only store the name of the item that has been selected - so it would be best mapped to a string.

A Droplink stores an ID of the item being linked. You can use a type that you have already created to represent the linked item, and Glass is smart enough to find the item in Sitecore by ID and then cast it to whatever type you had in place. If no item is selected in the droplink, it will return null.

As an example to illustrate:

[SitecoreType(TemplateId = "{149FA0C9-1111-1111-1111-FD9194EAC887}", AutoMap = true)]
public class MyLinkingItem
{
    public Guid Id { get; set; }

    //Should be the Name of your Droplink field
    public MyLinkedItem LinkedItem { get; set; }
}

[SitecoreType(TemplateId = "{149FA0C9-2222-2222-2222-FD9194EAC887}", AutoMap = true)]
public class MyLinkedItem
{
    public Guid Id { get; set; }
}

You can use similar tactics for other complex field types. For example, any kind of Multilist field e.g. Treelist can be represented by an IEnumerable<MyLinkedItem>.