Thursday, 10 March 2016

Forms in DD4T MVC and SDL Tridion

How to create forms in DD4T MVC and SDL Tridion using Schema and components

Here we have used only two different schema to create forms.

·         Form field Schema: - Is used to create the controls such as text box, radio button etc.

o   Here i have field type ,field name and label text
o   You can create field Type as category,Keywords to list down all the possible controls





·         Form Builder Schema: - Is used to give the title, Description and here we also linked all our components which was created using Schema Form Field.

o   In This component we will linked all are component created using Form Field  Schema which contains all the different types of fields type Components “First Name, Last Name”.
o   Insert this component as component presentation in your page .





In your DD4T application you can using following sample code lines to render the controls 

@if (FormBuilder.Fields.ContainsKey("title"))
  {
     @FormBuilder.Fields["title"].Value
   }
 @if (FormBuilder.Fields.ContainsKey("description"))
 {
   @FormBuilder.Fields["description"].Value

  }

First Read EmbeddedValues ["sections"] and then LinkedComponentValues

@foreach (var fieldComp in FormBuilder.Fields["fields"].LinkedComponentValues)

{

var fieldType = fieldComp.Fields.ContainsKey("type") ? fieldComp.Fields["type"].Keywords[0].Key : string.Empty;

//In our case it’s a text field

var fieldName = fieldComp.Fields.ContainsKey("name") ? fieldComp.Fields["name"].Value : string.Empty;



var fieldValue = (fieldComp.Fields.ContainsKey("label") && fieldComp.Fields["label"].EmbeddedValues[0].ContainsKey("text")) ? fieldComp.Fields["label"].EmbeddedValues[0][" text"].Values[0] : string.Empty;




<label for=\"{0}\">{1}</label> .FormatArgs(fieldname,fieldname)

//We are using Switch cases to check the field Type and generate control accordingly

switch (fieldType)
{
case "text":
<input type="text" name="@fieldName" />
Break;
case "button":
<button type="button">@fieldValue</button>
}
 }



Happy Coding and keep Sharing !!!!

No comments:

Post a Comment