Skip to content

Instantly share code, notes, and snippets.

@mskutta
Last active September 2, 2015 13:34
Show Gist options
  • Save mskutta/311b71b0a3f123bdd02f to your computer and use it in GitHub Desktop.
Save mskutta/311b71b0a3f123bdd02f to your computer and use it in GitHub Desktop.
Glass Mapper Validate Required Field
public class ValidateItemTask : IObjectConstructionTask
{
private bool IsValid(ObjectConstructionArgs args)
{
var context = (SitecoreTypeCreationContext) args.AbstractTypeCreationContext;
var service = (SitecoreService)args.Service;
var requiredFields = GetRequiredFields(args);
foreach (var requiredField in requiredFields)
{
var field = Utilities.GetField(context.Item, requiredField.FieldId, requiredField.FieldName);
// If the field does not exist it is not valid.
if (field == null)
return false;
// If the field value is empty it is not valid.
var value = field.GetValue(true, true);
if (string.IsNullOrEmpty(value))
return false;
// Perform type specific checks.
switch (field.Type)
{
case "Checkbox":
case "Date":
case "Datetime":
case "Integer":
case "Number":
case "Multi-Line Text":
case "Password":
case "Rich Text":
case "Single-Line Text":
break;
case "General Link":
case "General Link with Search":
{
var linkField = ((LinkField) field);
if (linkField.IsInternal)
{
var item = linkField.TargetItem;
if (item == null || item.Versions.Count == 0)
return false;
}
else if (linkField.IsMediaLink)
{
var item = linkField.TargetItem;
if (item == null)
return false;
}
break;
}
case "Grouped Droplink":
case "Droplink":
case "Droptree":
{
ID itemId;
if (!ID.TryParse(value, out itemId))
return false;
var item = service.Database.GetItem(itemId);
if (item == null || item.Versions.Count == 0)
return false;
break;
}
case "Multilist":
case "Multilist with Search":
case "Checklist":
case "Searchable Tree List":
case "Treelist":
case "TreelistEx":
case "ItemAggregate":
{
var itemIds = ID.ParseArray(value);
var exists = itemIds.Select(itemId => service.Database.GetItem(itemId))
.Any(item => item != null && item.Versions.Count != 0);
if (!exists)
return false;
break;
}
case "File":
{
FileField fileField = field;
if (fileField.MediaItem == null)
return false;
break;
}
case "Image":
{
ImageField imageField = field;
if (imageField.MediaItem == null)
return false;
break;
}
default:
throw new NotImplementedException(string.Format("Support for the field type '{0}' has not been implemented.", field.Type));
}
}
return true;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment