Glass Mapper makes your life as as Sitecore developer a lot easier. It's an ORM which will give you strongly-typed C# models for your Sitecore items. By default you need to write these Glass Mapper models yourself which can be a lot of work and and error prone. It's possible to generate these Glass Mapper models with Leprechaun. Since version 1.0.1 a script file for Glass Mapper has been added.
In the GlassMapper.csx file you have full control over what is generated. So this makes it also possible to extend your Glass Mapper models. By making the generated classes partial you can make your own partial class and add extra properties.
Sometimes you don't want to add properties to the generated class, but override them. By default all Sitecore fields of a template are generated. Since version 1.1.1 it's possible to exclude a field from generation by a PR I made. By adding "Do not auto generate" as a template field it's possible per field to manage if it needs to be generated.
This field is stored in the Rainbow serialized file so it can be read in the script file. Replace the RenderInterfaceFields in GlassMapper.csx script with the following:
// This is the ID from the template field.
public static readonly System.Guid DoNotAutoGenerateId = new System.Guid("{CA075FD6-5BDD-44E6-881F-74AE42568C44}");
public string RenderInterfaceFields(TemplateCodeGenerationMetadata template)
{
var localCode = new System.Text.StringBuilder();
foreach (var field in template.OwnFields)
{
var autoGenerate = !field.AllFields.ContainsKey(DoNotAutoGenerateId) || field.AllFields[DoNotAutoGenerateId] != "1";
if (autoGenerate)
{
localCode.AppendLine($@"
/// <summary>{field.HelpText}</summary>
[SitecoreField(FieldName = {template.Namespace}.Constants.{template.CodeName}.Fields.{field.CodeName}_FieldName)]
{GetFieldType(field)} {field.CodeName} {{ get; }}");
}
}
return localCode.ToString();
}
Now the field can be excluded from generation. You can write your own implementation for this property in a custom partial class. For example for a Multilist with Search which is only allowed to select specific items:
public partial class ContactService
{
[SitecoreField(FieldId = Constants.ContactService.Fields.ContactChannelsIdString)]
public virtual IEnumerable<ContactChannel> ContactChannels { get; set; }
}
This makes Leprechaun much more flexible. You could add even more template fields to do all kinds of crazy things in your GlassMapper.csx script.