Showing posts with label DD4T. Show all posts
Showing posts with label DD4T. Show all posts

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 !!!!

Friday, 4 March 2016

Drop down on page (DD4T MVC)should be in sync with Custom database. Create Keywords update Component and publish page

Requirement :- All filter drop down on DD4T MVC page should be in sync real-time with custom database






All the above drop-down are populating based on category and keywords.So we need to read client database create  keyword update the component presentation of filter component and publish the page.


Here, I have created the C# console application which keep on running and making sure that the SQL database and tridion taxonomies are in sync.


I have escaped the code of SQL connectivity and loops to iterate the data :)  
  1. Create core service ISessionAwareCoreService Client
public static class CoreServiceConnectionScheme
    {
        public const String netTcp = "net.tcp";
        public const String wsHttp = "http";
        public const String undefined = "undefined";
    }

    public static class CoreServiceFactory
    {
        public static ICoreServiceFrameworkContext GetCoreServiceContext(Uri endpointUri, NetworkCredential windowsNetworkCredentials)
        {
            switch (endpointUri.Scheme.ToLower())
            {
                case CoreServiceConnectionScheme.wsHttp:
                    return GetWsHttpContext(endpointUri, windowsNetworkCredentials);
                case CoreServiceConnectionScheme.netTcp:
                    return GetNetTcpContext(endpointUri, windowsNetworkCredentials);
                default:
                    throw new ArgumentException("The uri connection scheme specified [{0}] is invalid; a valid scheme (ie. http for WsHttp, or net.tcp for NetTcp must be specified).");
            }
        }
public static ICoreServiceFrameworkContext GetWsHttpContext(Uri endpointUri, NetworkCredential windowsNetworkCredentials)
        {
return new CoreServiceFrameworkWsHttpContext(endpointUri, windowsNetworkCredentials);
        }
public static ICoreServiceFrameworkContext GetNetTcpContext(Uri endpointUri, NetworkCredential windowsNetworkCredentials)
        {
return new CoreServiceFrameworkNetTcpContext(endpointUri, windowsNetworkCredentials);
        }
    }


   2. Go to Main method 


static void Main(string[] args)
{
Logger.WriteLog(Logger.LogLevel.INFO, "Calling Keyword creation process");           
CreateKeywords.Process();
Logger.WriteLog(Logger.LogLevel.INFO, "Calling Keyword creation process End"); 
}

    3. Create a class

public class CreateKeywords

{   
public static ICoreServiceFrameworkContext coreService = null;
public static void Process()
{
XmlDocument doc = new XmlDocument();
coreService = CoreServiceFactory.GetCoreServiceContext(new Uri(ConfigurationManager.AppSettings["CoreServiceURL"].ToString()), new NetworkCredential(ConfigurationManager.AppSettings["UserName"].ToString(), ConfigurationManager.AppSettings["Password"].ToString(), ConfigurationManager.AppSettings["Domain"].ToString()));

#region Creating Keywords and updating component
Logger.WriteLog(Logger.LogLevel.INFO, "Checking keyword already exist in tridion or not");  
TridionObjectInfo obj = Helper.GetTridionObject(coreService, ItemType.Keyword, "tcm:1-440-512", "Test");
var tcmID = obj.ObjectCount == 0 ? TridionKeyword.GenerateKeyword(coreService, "3 Test", "Test", "tcm:1-440-512") : "";
Logger.WriteLog(Logger.LogLevel.INFO, "Returned Tcmuri of keyword " + tcmID);

ComponentData component = (ComponentData)coreService.Client.Read(ConfigurationManager.AppSettings["CompId"].ToString(), new ReadOptions());

4. Create new element in component.Content XML 

doc.LoadXml(component.Content);
XmlElement createchild = doc.CreateElement("Filter1");
createchild.InnerText = 3 Test;
doc.DocumentElement.AppendChild(createchild);
component.Content=doc.InnerXml;

component.Id = ConfigurationManager.AppSettings["CompId"].ToString();
Logger.WriteLog(Logger.LogLevel.INFO, "Updating Component " + component.Id);
component = (ComponentData)coreService.Client.Update(component, new ReadOptions());


 Logger.WriteLog(Logger.LogLevel.INFO, "Updating Component done " + component.Id + "Sending page for publishing " + ConfigurationManager.AppSettings["PageId"].ToString());

}

5.To Generate Keywords


public static string GenerateKeyword(ICoreServiceFrameworkContext coreService, string value, string key, string CategoryID)
        {
            try
            {
                KeywordData keyword = (KeywordData)coreService.Client.GetDefaultData(ItemType.Keyword, CategoryID);
                keyword.Id = "tcm:0-0-0";
                keyword.Title = value;
                keyword.Key = key;

                keyword = (KeywordData)coreService.Client.Create(keyword, new ReadOptions());
                Logger.WriteLog(Logger.LogLevel.INFO, "KeyWord TcmID :" + keyword.Id.ToString() + " Under category ID" + CategoryID);
                return keyword.Id.ToString();
            }
            catch(Exception ex)
            {               
                Logger.WriteLog(Logger.LogLevel.ERROR, "GenerateKeyword :" + ex.Message);             
                return "";
            }
           
6. To Publish Use

coreService.Client.Publish(new[] { PageId}, pubData, new[] { target.ToString() }, PublishPriority.High, null);


7. On your DD4T Mvc App you can bind dropdown with keywords

<select id="Filter1">                    
@if (Model.Fields.ContainsKey("Filter1"))
{
foreach (var value in Model.Fields["Filter1"].Keywords)
{
<option value="@value.Key">@value.Title</option>                       
}
}
</select>



Happy Coding and keep Sharing !!!!