Programmatically add a new field in a template in sitecore

1.5k Views Asked by At

In Sitecore is it possible to programmatically add a new field in a template?

I have a template "DictionaryName", in this template I want to add a field "Newname" with its type "Single-Line Text".

3

There are 3 best solutions below

0
On BEST ANSWER

I wrote and tested this code for you - it worked out perfect on my machine and created new single line field within template specified. Here is the method:

    private void AddFieldToTemplate(string fieldName, string tempatePath)
    {
        const string templateOftemplateFieldId = "{455A3E98-A627-4B40-8035-E683A0331AC7}";

        // this will do on your "master" database, consider Sitecore.Context.Database if you need "web"
        var templateItem = Sitecore.Configuration.Factory.GetDatabase("master").GetItem(tempatePath);
        if (templateItem != null)
        {
            var templateSection = templateItem.Children.FirstOrDefault(i => i.Template.Name == "Template section");
            if (templateSection != null)
            {
                var newField = templateSection.Add(fieldName, new TemplateID(new ID(templateOftemplateFieldId)));
                using (new EditContext(newField))
                {
                    newField["Type"] = "Text"; // text stands for single-line lext field type
                }
            }
            {
                // there are no template sections here, you may need to create one. template has only inherited fields if any
            }
        }
    }

And below is the usage - first string parameter is the name of your new field, the second is string value for template path within the database you are using:

AddFieldToTemplate("New Single Line Field", "/sitecore/templates/Sample/Sample Item");

Replace "Sample Item" template with your template path and set desired field name to add. Also do not forget usings for namespaces:

using Sitecore;
using Sitecore.Data;
using Sitecore.Data.Items;

Hope this helps!

0
On

Wrote this Example for you.

Want to find out more https://doc.sitecore.com/legacy-docs/SC71/data-definition-api-cookbook-sc70-a4.pdf

public JsonResult CreateTemplate()
    {
        try
        {
            using(new SecurityDisabler())
            {
                ///Get Database
                Database master = Sitecore.Configuration.Factory.GetDatabase("master");

                /// Every node in content tree ia an Item. Ex- Templates,Field, Item, etc.
                /// Template: /sitecore/templates/System/Templates/Template -{AB86861A-6030-46C5-B394-E8F99E8B87DB}
                var templateId = master.GetTemplate(new ID("{AB86861A-6030-46C5-B394-E8F99E8B87DB}"));

               /// parentItem is the item/ Template folder where you want to create your template.
               /// ParentItem: /sitecore/templates/[new folder {Guid}]
                Item parentItem = master.GetItem(new ID("{3C7516ED-7E3E-4442-8124-26691599596E}"));


                Item newItem = parentItem.Add("HelloTemplate", templateId);

                // adding Field in Templates.
                TemplateItem exampleTemplate = master.Templates[new ID(newItem.ID.ToString())];

                TemplateSectionItem data = exampleTemplate?.GetSection("data");

                if( data == null || data.InnerItem.Parent.ID != exampleTemplate.ID)
                {
                    data = exampleTemplate.AddSection("Data", false);
                }
                TemplateFieldItem title = data?.GetField("title");
                if(title == null)
                {
                    TemplateFieldItem field = data.AddField("Title");
                }
            }
                return Json(new { Result = "item created" }, JsonRequestBehavior.AllowGet);
            
        }
        catch (Exception ex)
        {
            return Json(new { Result = "item not created " + ex.Message+"\n"+ex.StackTrace } , JsonRequestBehavior.AllowGet);
        }
    }
0
On

You can access programmatically a template from the item and then add a an item to this template. The template is a usual item childrens.