How to add a new field to a document type using API

   —   
This knowledge base article will show you how to add a new field into a document type definition using Kentico CMS API.
In this particular case, we will create a new field of type Upload file. Creating a new field usually involves a few steps, starting with creating a new FormFieldInfo object and setting all properties according to your needs.  As soon as the new field is created in the database using the TableManager.AddTableColumn method, you will need to update the ClassXmlSchema and ClassFormDefinition properties of the DataClassInfo object and generate new default queries. Moreover, if there is any other document type that inherits from the updated one, you need to call the FormHelper.UpdateInheritedClass method to ensure the new field is being inherited.

The following code snippet demonstrates how a new field can be created:  

  using CMS.SettingsProvider;
  using CMS.FormEngine;

  string classname = "classname";
  DataClassInfo dci = DataClassInfoProvider.GetDataClass(classname);
  if (dci != null)
  {
      FormInfo fi = new FormInfo(dci.ClassFormDefinition);
      if (fi != null)
      {
          // Field definition
          FormFieldInfo ffi = new FormFieldInfo();
          ffi.Name = "FieldName";
          ffi.DataType = FormFieldDataTypeEnum.File;
          ffi.AllowEmpty = true;
          ffi.System = false;
          ffi.FieldType = CMS.FormEngine.FormFieldControlTypeEnum.UploadControl;
          ffi.Visible = true;
          ffi.Caption = "Field Caption";
          ffi.Description = "Field Description";
          ffi.RegularExpression = "";
          ffi.Enabled = true;
          ffi.Settings["allowed_extensions"] = "bmp;gif;jpg;jpeg;png;";
          ffi.Settings["extensions"] = "custom";

          fi.AddFormField(ffi);

          // Create a new column directly in the database
          CMS.DataEngine.TableManager.AddTableColumn(dci.ClassTableName, ffi.Name, "uniqueidentifier", true, null);

          dci.ClassXmlSchema = CMS.DataEngine.TableManager.GetXmlSchema(dci.ClassTableName);
          dci.ClassFormDefinition = fi.GetXmlDefinition();

          // Update DataClassInfo object
          DataClassInfoProvider.SetDataClass(dci);

          // Update inherited classes with new field
          FormHelper.UpdateInheritedClasses(dci);

          // Generate default queries
          CMS.DataEngine.SqlGenerator.GenerateDefaultQueries(dci, true, true);
      }
  }



If you would like to get more information about the Kentico CMS Form Engine and how to use its related controls (BasicForm, DataForm, CMSForm), I would like point you to this great webinar: Kentico CMS Form Engine.
-ml-


See also: Kentico CMS API reference

Applies to: Kentico CMS 6.0
Share this article on   LinkedIn