Search code examples
c#sitecoreglass-mappersitecore7.1

Disable version check for specific property in Sitecore glass mapper


I'm using SItecore 7.1 with Glass.Mapper.Sc 3.1.7.26. I have the following model, where the Service Id field is shared:

[SitecoreType]
public class ServiceMapping
{
    [SitecoreField(FieldName = "Service Id")]
    public virtual string ServiceId { get; set; }
}

And I have the following model which references the Service Mapping over a Droptree field (also shared):

[SitecoreType]
public class OnlineService
{
    [SitecoreInfo(SitecoreInfoType.DisplayName)]
    public virtual string DisplayName { get; set; }

    [SitecoreField(FieldName = "Service")]
    public virtual ServiceMapping ServiceMapping { get; set; }
}

When I load an Instance of OnlineService it must be language dependent, due to the DisplayName. Let's assume that I have the OnlineService available in german and english, and my ServiceMapping only in english, then I get null for the ServiceMapping object when requesting the page in german.

Is it possible to give the ServiceMapping.ServiceId property a setting that it should not check for an existing language version? I know that there is the VersionCountDisabler(), but I can't use this because I need the OnlineService class to check the language version.


Solution

  • Hum, this is a tricky one, the code below isn't tested (I am writing this as I think of the solution) but should point you in the write direction.

    public class MyCrazyType : SitecoreFieldTypeMapper
    {
        public override object GetFieldValue(string fieldValue, Mapper.Sc.Configuration.SitecoreFieldConfiguration config, SitecoreDataMappingContext context)
        {
            using (new VersionCountDisabler())
            {
                return base.GetFieldValue(fieldValue, config, context);
            }
        }
    
        public override bool CanHandle(Mapper.Configuration.AbstractPropertyConfiguration configuration, Context context)
        {
            //this will mean this handle only works for this type
            return configuration.PropertyInfo.PropertyType == typeof (ServiceMapping);
        }
    
    }
    

    Using this Glass will map the an empty item to the target type.

    You will need to register the handler with Glass, see this tutorial: http://glass.lu/docs/tutorial/sitecore/tutorial19/tutorial19.html