How can I get the sitecore field from a property of an object rendered with glassmapper?

We use the Glass Mapper with Sitecore, with our models we can get the values ​​of the sitecore fields. But I want to easily get the sitecore fields (sitecore field type) using the model without hardcoding any strings (when using GetProperty()

, you need the property name string) into the method.

So, I wrote this thing to achieve this, however I am not happy with the need to pass 2 types when using it as it looks terrible when you have a long model ID.

   public static string SitecoreFieldName<T, TU>(Expression<Func<TU>> expr)
    {
         var body = ((MemberExpression)expr.Body);
         var attribute = (typeof(T).GetProperty(body.Member.Name).GetCustomAttributes(typeof(SitecoreFieldAttribute), false)[0]) as SitecoreFieldAttribute;
         return attribute.FieldName;
    }

      

The best way - to get it: Model.SomeProperty.SitecoreField()

. However, I cannot figure out how to do this. As it can be an extension to any type.

Thank!

+3


source to share


2 answers


public static string SitecoreFieldName<TModel>(Expression<Func<TModel, object>> field)
{
    var body = field.Body as MemberExpression;

    if (body == null)
    {
        return null;
    }

    var attribute = typeof(TModel).GetProperty(body.Member.Name)
        .GetCustomAttributes(typeof(SitecoreFieldAttribute), true)
        .FirstOrDefault() as SitecoreFieldAttribute;

    return attribute != null
        ? attribute.FieldName
        : null;
}

      



Note that I put inherit=true

on the method call GetCustomAttributes

.
Otherwise, inherited attributes are ignored.

+4


source


I don't understand why my question went away - they voted. So you think this is the perfect code already?

With the help of another senior developer, I improved it today so it doesn't need two types and is clearer in the syntax of use:

public static Field GetSitecoreField<T>(T model, Expression<Func<T, object>> expression) where T : ModelBase
    {
        var body = ((MemberExpression)expression.Body);
        var attributes = typeof(T).GetProperty(body.Member.Name).GetCustomAttributes(typeof(SitecoreFieldAttribute), false);
        if (attributes.Any())
        {
            var attribute = attributes[0] as SitecoreFieldAttribute;
            if (attribute != null)
            {
                return model.Item.Fields[attribute.FieldName];
            }
        }
        return null;
    }

      



and I can just call it by doing the following:

GetSitecoreField(Container.Model<SomeModel>(), x => x.anyField)

      

Hope this helps anyone using Glass Mapper with Sitecore and wants to get the current sitecore field from the model property.

0


source







All Articles