public static void CreateDateField(Guid productTypeId, string fieldName, string fieldLabel)
{
CatalogManager catalogManager = CatalogManager.GetManager();
ProductType productType = catalogManager.GetProductType(productTypeId);
if (productType == null)
{
return; //The product type does not exist.
}
Type productClrType = TypeResolutionService.ResolveType(productType.ClrType);
string fieldClrType = typeof(DateTime?).FullName;
UserFriendlyDataType userFriendlyDataType = UserFriendlyDataType.Date;
var wcfField = new WcfField()
{
Name = fieldName,
ContentType = productClrType.FullName,
FieldTypeKey = userFriendlyDataType.ToString(),
IsCustom = true,
//Database mapping
DatabaseMapping = new WcfDatabaseMapping()
{
ClrType = fieldClrType,
ColumnName = fieldName.ToLower(),
Nullable = true,
DbType = "DATE",
},
//Field definition
Definition = new WcfFieldDefinition()
{
Title = fieldLabel,
FieldName = fieldName,
FieldType = typeof(DateField).FullName,
}
};
CustomFieldsContext.Validate(wcfField, productClrType);
var typeContext = new CustomFieldsContext(productClrType.FullName);
typeContext.SaveFieldDefinition(wcfField, productClrType.Name, null);
typeContext.SaveChanges();
using (MetadataManager metadataManager = MetadataManager.GetManager())
{
MetaType metaType = metadataManager.GetMetaType(productClrType);
MetaField metaField = metadataManager.CreateMetafield(fieldName);
CustomFieldsContext.SetFieldDatabaseMappings(metaField, metaType, userFriendlyDataType, wcfField, metadataManager);
metaField.Title = fieldLabel;
metaField.MetaAttributes.Add(new MetaFieldAttribute { Name = "UserFriendlyDataType", Value = userFriendlyDataType.ToString() });
metaField.MetaAttributes.Add(new MetaFieldAttribute { Name = "IsCommonProperty", Value = "true" });
metaType.Fields.Add(metaField);
metadataManager.SaveChanges();
}
//SystemManager.RestartApplication(false);
}