Search code examples
kentico

kentico add new form field via API


Hello Kentico experts,

I need to create some new form fields dynamically via Kentico API. I found a solution but it is for Kentico 6 and it is not available for my version (i'm using Kentico 8).

https://devnet.kentico.com/articles/how-to-add-a-new-field-to-a-document-type-using-api

Please help !

Thanks, Duong


Solution

  • This should work:

    string classname = "classname";
    DataClassInfo dci = DataClassInfoProvider.GetDataClassInfo(classname);
    if (dci != null)
    {
        FormInfo fi = new FormInfo(dci.ClassFormDefinition);
        if (fi != null)
        {
            // Field definition
            FormFieldInfo ffi = new FormFieldInfo();
            ffi.Name = "FieldName";
            ffi.AllowEmpty = true;
            ffi.System = false;
            ffi.FieldType = CMS.FormEngine.FormFieldControlTypeEnum.UploadControl;
            ffi.Visible = true;
            ffi.Caption = "Field Caption";
            ffi.Enabled = true;
            // Set whatever properties are relevant to you
    
            fi.AddFormItem(ffi);
    
            TableManager tm = new TableManager(null);
            tm.AddTableColumn(dci.ClassTableName, ffi.Name, "uniqueidentifier", true, null);
    
            dci.ClassXmlSchema = tm.GetXmlSchema(dci.ClassTableName);
            dci.ClassFormDefinition = fi.GetXmlDefinition();
    
            // Update DataClassInfo object
            DataClassInfoProvider.SetDataClassInfo(dci);
    
            // Update inherited classes with new field
            FormHelper.UpdateInheritedClasses(dci);
    
        }
    }   
    

    You can always check the API changes between versions on Kentico DevNet.