Creating date fields

To learn more about the different steps to create a custom field, read the Creating custom fields article.

Here is a list of the things that are specific for the short text field:

  • Field CLR type: typeof(DateTime?).FullName
  • User friendly data type: UserFriendlyDataType.Date
  • DB type: “DATE”
  • Field type: typeof(DateField).FullName

Here is a code example:

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);
}

Next steps

+1-888-365-2779
sales@sitefinity.com

Related topics:

Feedback

How useful is this article?

Tell us more

Submit
Your message was successfully sent.

We appreciate your feedback.

Your message could not be sent.

OK