How to change the value of a custom table field or forms field directly in the form using API

   —   
While developing custom web parts, you may have a requirement to insert or edit a record in the custom table or forms table while at the same time using a predefined alternative form to create a form. This article demonstrates initialization of an alternative form and how to work with its data.
For custom tables you just need to insert following code into the markup:

<cms:CustomTableForm ID="custTableForm" runat="server" AlternativeFormFullName=" customtable.SampleTable.myAlternativeForm " />

In the code behind you need to initialize the form:

protected void Page_Load(object sender, EventArgs e) { if (!Page.IsPostBack) { //Item ID int key=0; string customTable = "customtable.SampleTable"; //Code name of custom table key = QueryHelper.GetInteger("myQueryParameter",0); //Get query parameter from URL //Definition of custom table in this case DataClassInfo dataClassInfo = DataClassInfoProvider.GetDataClass(customTable); custTableForm.CustomTableId = dataClassInfo.ClassID; custTableForm.AlternativeFormFullName = "customtable.SampleTable.test"; custTableForm.SiteName = CMSContext.CurrentSite.SiteName; custTableForm.ItemID = key; custTableForm.ShowPrivateFields = true; if (key == 0) { custTableForm.FormMode = FormModeEnum.Insert; } else { custTableForm.FormMode = FormModeEnum.Update; // Custom code for modification of field custTableForm.BasicForm.OnAfterDataLoad += new EventHandler(custTableForm_OnAfterDataLoad); } } } void custTableForm_OnAfterDataLoad(object sender, EventArgs e) { if (custTableForm.BasicForm.FieldControls != null) { // Get form control information EditingFormControl ctrl = custTableForm.BasicForm.FieldEditingControls["to"] as EditingFormControl; if (ctrl != null) { // Replace value of NameOfField field with value of Column2 ctrl.Value = ValidationHelper.GetString(custTableForm.BasicForm.GetFieldValue("from"), ""); } } }


In case you request the page using a query parameter containing an ID of record which you would like to edit, the form will be in 'update mode' so you can modify data.

Optionally, you may need to automatically change the value of the file (for example if the field is empty). In this case you can call OnAfterDataLoadEventHandler which will ensure that data from a different column will be copied to the empty one.

Analogically, for forms you can insert the following control into your markup:

<cms:BizForm ID="formElem" runat="server" IsLiveSite="false" />

Configuration of the code behind is similar to the custom table form control.
 
-it-


See also: Creating an alternative form

Applies to: Kentico CMS 6.0
Share this article on   LinkedIn