Search code examples
sitecoresitecore7.2

Sitecore How to specify Data field type when adding a field by Template.AddField(string, string);


If I have a Sitecore Item item and I add a Data field "My Field" to it using:

 item.Template.AddField("My Field", "Data");

How Can I specify the field type for it. e.g Single-Line Text


Solution

  • The AddField(...) method returns the added template field (it doesn't have a type yet).

    You can then set the type on the template field like this:

    var templateField = item.Template.AddField("Field name", "Section name");
    
    using (new EditContext(templateField.InnerItem)) {
        templateField.Type = "Single-Line Text";
    }
    

    The type value should correspond to the name of the field type - e.g. Single-Line Text, Rich Text, Grouped Droplist etc.

    Depending on your security you might also need to add the whole thing in a SecurityDisabler.

    using (new SecurityDisabler()) {
        var templateField = item.Template.AddField("Field name", "Section name");
    
        using (new EditContext(templateField.InnerItem)) {
            templateField.Type = "Single-Line Text";
        }
    }