Creating and Modifying Sitecore Items programmatically

This post is dedicated to the newborn Sitecore developers. Generally, the newborn  Sitecore developers stuck in a situation when they need to create a new Sitecore item or modify the existing or new item programmatically.

This post will take them to their destination where they will find a piece of code which will help them in achieving their goal of creating/modifying Sitecore items programmatically.

Creating item programmatically

This below code will explain you the process of creating an item dynamically

//Disable the Security
using (new SecurityDisabler())
{
   //First get the desired DB where you want to create the item
   Database master = Sitecore.Configuration.Factory.GetDatabase("master");
   if (master != null)
   {
     //Here you need the Parent Item (new item will be child of this item)
     Item parentItem = master.GetItem(new ID("{4F67FC21-199E-414C-BE96-E861281F1413}"));
     //Get the template for the new item
     TemplateItem template = master.GetTemplate(new ID("{E5934ED6-8D4F-4FEB-AA1A-AA06C783195F}"));
     if (template != null)
     {
       //Now, use Parent item to add a new item underneath and pass the item name and template as parameter
       Item newItem = parentItem?.Add("NewItem", template);
     }
   }
}

 Modifying the Item content programmatically

the below code will help you understand the item alteration dynamically

//again disable the security
using (new SecurityDisabler())
{
    //get the item to modify the content
   //Get the DB to get the Item
   Database master = Sitecore.Configuration.Factory.GetDatabase("master");
   
   //get the Item from the DB to modify the content
   var item = master.getItem(new ID("{4F67FC21-199E-414C-BE96-E861281F1413}"));
   
   //Enter into the item editing state
   item.Editing.BeginEdit();
    
   //Now you can edit the item field values as belwo
    item["title"] = "some value"
   
   //once you are done with the editing, come out of editing satate then
   item.Editing.EndEdit();
}

So that’s the very basic of Sitecore API where you could create/modify the items dynamically from your C# code.

Happy Coding!!!

Complex Field Types – Part 2 (Link Types)

The second post in the series of Complex Field Types. Here, I will explain to you the “Link Types”.

There are six types of link types available in Sitecore. Find about them here…

LinkTypes

  1. Droplink: This field type is similar to the Droplist (Droplist is available as a List type see here). For the end user, it works as Droplist list only, but in backend, it refers to an item instead of rendering string like Droplist does. It references to items based on the source provided to the field in the template. The selection type is the Single item at a time. Droplink does not support the field render. The source of Droplink can be XPath query, GUID and Item Path.

    Droplink2

  2. Droptree: Droptree shows items as a tree-view instead of showing them as the dropdown. The user is allowed to select a single item at a time. It shows complete Sitecore tree if the source is not provided at the time of field declaration. The source can be XPath Query or GUID and Item Path. Droptree does not support field render.Droptree1

    Droptree-no-source
    If No Source is Provided when the field was created
  3. General Link: General link allows editors to insert a link to Sitecore Item or to an external URL or a custom anchor tag or Email address or even can insert a JavaScript function. This type is quite common across Sitecore developers and it’s being used frequently. General Link types support the field render.

    General-Link
    This is an example of inserting the javascript into the link field.
  4. General Link with Search: Similar to General Link type, this type comes with an extra feature “Search for a link”. This feature allows editors to search for an item which is referenced in the field. This field type supports field render.General-Link-search1

    General-Link-search2
    That’s the window you see when you click on Search for a link

Version Identity: and Version Link: field types are used by Sitecore for internal purposes.

For List Types, you can refer to my previous post.

References :

 

 

Complex Field Types – Part 1 ( List Types)

The first post in the series of Complex Field Types. In this post, I will explain to you the “List Types”.

The List types fields are used when a user needs to select one or more values from a list of available options. For example- A Multilist field allows the editors to choose multiple values from a list of available values, A Droplits allows the editors to choose a value from a list of available values.

ListTypes-1

So, let’s go ahead and explore them one by one

  1. Checklist: Checklist type allows editors to select more than one values from a list of available checklist values. Checklist stores values in as a pipe-separated list of IDs. The checklist doesn’t allow editors to order their selections. Checklist type field cannot be rendered so a developer has to read the selected values and display them on the page.Checklist
  2. Droplist: A Droplist stores the name of the items. It allows the editors to select one value from the dropdown list. Droplist is similar to Droplink, the only difference is – Droplist stores item name while the Droplink stores the ID of the item.Droplist
  3. Grouped Droplist: Grouped Droplist field type allows editors to select a single grandchild of the Item specified in the source of the field. This type cannot be rendered. It stores the value as a string (the name of the selected Item is the value).GroupedDroplist
  4. Grouped Droplink: Grouped Droplink field type allows editors to select a single grandchild of the item specified in the source of the field. It’s similar as Grouped Droplist, the only difference is – this field stores the Item ID while Grouped Droplist stores the name of the Item. This field type cannot be rendered.GroupedDroplink
  5. Multilist: Multilist field type allows editors to select the one or multiple values from the available values coming from the specified source of the field. It stores the IDs of the selected items. You can order the selected values. Multilist type cannot be rendered, so to display the selected values, a developer has to read the values using code.Multilist-1Multilist-2
  6. Multilist with Search: Similar to Multilist type, this field type allows editors to search the values. The selected values displayed with their path with parent item (Countries – India). Also, you get some other option there like Next, previous, Refresh etc. Other features remain the same as Multilist. This field cannot be rendered.Multilist-Search
  7. Name Value List: Name Value List type allows editors to store the value in the key-value pair. It inserts a new row when you enter the value in the first row. Also, it does not support any special character in the key field while in value you can use them. The values are stored separated by “&”. This field cannot be rendered.NameValueList
  8. Name Lookup Value List: This field type is an extended version of Name Value List type having many of the similar features. The only difference here is – Name Lookup Value List uses a Dropdown list to choose the value against a key. The editor is still required to type the key name, the dropdown is only for Value field. This field cannot be rendered.NameLookupValue
  9. Treelist: Treelist accommodate the selected items from the source provided in Field’s source property. If no source is provided, it will list the whole Sitecore tree and user editors will be able to select any item from there. Treelist stores the values in pipe-separated IDs. This field type cannot be rendered.Treelist
  10. TreelistEx: TreelistEx is very much similar to Treelist, except that for this field type, the selection option will be opened as a pop-up window. This field type cannot be rendered. TreelistEx is far better than Treelist when performance is the concern.TreelistEx

Above explained field types are List Types and in my next post to this series, I’ll come up with the Link Types. So stay tuned here for more on Field types.

References :

  1. https://sdn.sitecore.net/upload/sitecore6/65/data_definition_reference_sc64-65-usletter.pdf
  2. https://gopigujjula.com/2017/01/Saturday-Sitecore-Learning-Template-Part-3/
  3. https://trnktms.com/2016/10/15/sitecore-name-value-list-field-with-special-characters/

Understanding the Rendering Parameters

Being a Sitecore developer, you must have heard a term called “Rendering Parameters”. In today’s post we’ll together explore the Rendering Parameters with WWH (What, When & how) scenarios.

What is Rendering Parameter?

When to use Rendering Parameters?

How to use Rendering Parameters?

So I’ll keep this post as simple as possible and will explain you the concept of Rendering Parameters.

What is Rendering Parameter?

Rendering Parameter is a way to pass the additional item(s) to the rendering or component apart from rendering data source.

When to use Rendering Parameters?

Let’s assume, you are in a situation where content editors need to use some additional items on a component apart from its actual data source. For example – I am going to use Rendering parameter to pass an additional CSS class to the component, which will allow my content editors to choose the style of their component.

How to use Rendering Parameters?

Let’s jump to the exercise to understand the complete scenario and see how we can make use of Rendering Parameter.

This complete exercise is divided into 3 easy tasks. Which I’ll be explaining you one by one.

Task-1 Creating a Parameter Template

Create a new template and make sure this template inherits from a base template of standard Rendering Parameters – “/System/Layout/Rendering Parameters/Standard Rendering Parameters”

RP-1

And create the fields as per your requirement. In my scenario – I just need a single text field. See the below image.

RP-2

Task -2  Reference you parameter template

Reference you parameter template on your required rendering under the Editor Options section of your rendering, as shown below

RP-3

Once you reference your parameter template to your rendering, you can then check the same by going to the content item where you are using this rendering and go to the Presentation > Details > Final Layout and select your rendering and click edit – you should see your Rendering Parameter field there. See the image below

RP-4

You can notice here that your complete template field(s) and section are available here and Content Editors can make use of this to pass some additional data to the component or rendering.

Task -3 Read the parameter value in code

In my scenario, I am using MVC and used a controller rendering to make it work. So I’ll show the code to access the parameter value in MVC controller action.

 public ActionResult Index()
        {

            var item = Sitecore.Context.Item;
            var addtionalCssParameter = RenderingContext.Current.Rendering.Parameters["Background Class"];

            var model = new StandardPage
            {
                Title = item.Fields["Title"].Value,
                Description = item.Fields["Description"].Value,
                AdditionalCss = addtionalCssParameter
            };
            return View(model);
        }

Well, if you are using ASP.NET instead of MVC then I assume you must be using the Sublayout as renderings and that should not be a show stopper for you. You can still use the rendering parameters in the same way we use for MVC controller renderings. The Only task which is going to be a bit different is –  reading the parameter value in code.

So nothing to worry, here is the code to read the rendering parameter value from .ascx.cs file.

public string AdditionalCss
        {
            get
            {
                var sublayout = ((Sublayout) this.Parent);
                NameValueCollection renderingParameter = Sitecore.Web.WebUtil.ParseUrlParameters(sublayout.Parameters);
                return renderingParameter["background Class"];
            }
        }

And that’s all about the Rendering Parameters.
I hope this post will help you in your further Sitecore journey. Happy Coding 🙂

WFFM WebFroms Customizing the SuccessRedirect Pipeline

Like any other pipelines in Sitecore, WFFM pipelines are also customizable. I am showing you here how to customize the WFFM WebForms SuccessRedirect pipeline.

The SuccessRedirect pipeline is used to process the Success page URL which you provide on the form under the success action. This pipeline is responsible to process the URL provided by the user and can process internal, external and media URLs.

You can find SuccessRedirect class under the Sitecore.Form.Core.Pipelines.FormSubmit namespace

in the below example, I am going to add a QueryString to the success page URL. I’ll read a cookie and use its value for QueryString.

See the example here

namespace SitecoreTricks.Helper.Pipelines
{
   public class SuccessRedirect:ClientPipelineArgs
   {
     public void Process(SubmitSuccessArgs args)
     {
       Assert.IsNotNull((object)args, "args");
       if (args.Form != null)
       {
         if (!args.Form.SuccessRedirect)
              return;
         args.AbortPipeline();
         LinkField successPage = args.Form.SuccessPage;
         UrlString urlString = (UrlString)null;
         if (successPage.LinkType == "external")
             urlString = new UrlString(successPage.Url);
         else if (successPage.TargetItem != null)
         {
            switch (successPage.LinkType)
            {
               case "internal":
                    UrlOptions defaultUrlOptions = LinkManager.GetDefaultUrlOptions();
                    defaultUrlOptions.SiteResolving = Settings.Rendering.SiteResolving;
                    urlString = new UrlString(LinkManager.GetItemUrl(successPage.TargetItem, defaultUrlOptions));
                    break;
              case "media":
                   urlString = new UrlString(MediaManager.GetMediaUrl(new MediaItem(successPage.TargetItem)));
                   break;
            }
        }
        else
           DependenciesManager.Logger.Warn(string.Format("Web Forms for Marketers : Success page for the form does not exist. Form ID: '{0}'.", (object)args.Form.ID), new object());

        if (urlString == null)
            return;
        string attribute = successPage.GetAttribute("querystring");
        if (!string.IsNullOrEmpty(attribute))
             urlString.Parameters.Add(WebUtil.ParseUrlParameters(attribute));
        HttpCookie cookie = HttpContext.Current.Request.Cookies["testCookie"];
        if (cookie != null)
        {
           var finalUrl = urlString + "?" + cookie.Value;
           cookie.Expires = DateTime.Now.AddDays(-1);
           WebUtil.Redirect(finalUrl, false);
        }
        else
        {
           WebUtil.Redirect(urlString.ToString(), false);
        }
        WebUtil.Redirect(urlString.ToString(), false);
     }
     else
     {
       Uri result;
       if (!Uri.TryCreate(args.Result, UriKind.RelativeOrAbsolute, out result))
           return;
       try
       {
          string pathAndQuery = result.PathAndQuery;
       }
       catch (Exception ex)
       {
         return;
       }
       args.AbortPipeline();
       WebUtil.Redirect(args.Result, false);
     }
   }
 }
}

Once you are done with the code customizations then you need to make a config change. You need to find the Sitecore.Forms.Config file and navigate to <successAction> tag under the pipelines. Paste your custom processor there.

See the below example

<processor type=”SitecoreTricks.Helper.Pipelines.SuccessRedirect, SitecoreTricks.Helper”/>

and that’s it. you are done with your WFFM pipeline customization.

Creating a Custom Field Validator

While working on some of my previous Sitecore projects, I had to create some custom field validators. Most of the time, the Sitecore beginners are stuck with such tasks, So I thought of writing it down here to help them in creating their first ever custom field validator. So we are going to use a validator that we create to validate the End Date.

  • Creating the custom validator and inherit it from StandardValidator
using System;
using System.Runtime.Serialization;
using Sitecore.Data.Fields;
using Sitecore.Data.Items;
using Sitecore.Data.Validators; 

namespace SitecoreTricks.Utils.Helpers
{

[Serializable]
class EndDateValidator: StandardValidator
{

public EndDateValidator()
{}

public EndDateValidator(SerializationInfo info, StreamingContext context) : base(info, context) { }

protected override ValidatorResult Evaluate()
{
Item item = base.GetItem();
DateField start = item.Fields["Start Date"];
DateField end = item.Fields["End Date"];
if (start.DateTime <= end.DateTime) return ValidatorResult.Valid; this.Text = $"The End Date ({end.DateTime}) should be equal to or greater than the Start Date ({start.DateTime})"; return ValidatorResult.CriticalError; } protected override ValidatorResult GetMaxValidatorResult() { return GetFailedResult(ValidatorResult.CriticalError); } public override string Name => "End Date Validator";
}
}

Note – We used the Serializable attribute and created a constructor as well to make sure that our custom validator works fine with validator button. If we don’t use Serializable attribute and constructor, the Validator button would throw an exception.

  • Creating the custom Validation Rule in Sitecore

To get the custom date validator on work, we need to have a validation rule item defined in Sitecore (/sitecore/system/Settings/Validation Rules/Field Rules).

Validator1

Note – Remember to use your namespace and class under the “Type” field.  Also, provide the Title and Description.

  • Now apply the validation rule on your field.

Go to your template and navigate to the field. Scroll down the content window and expand the “Validation Rule” section and that’s the place where you are going to use your custom field validator.

Here you will see four fields where you can use the validator. These four fields are as below

  1. Quick Action Bar – This will show you the validation error on bar left of the content tree.
  2. Validation Button – This will run the validation by clicking of the Validation button in review tab.
  3. Validation Bar – This will show you the validation result in bar right to the content editor.
  4. Workflow – this runs the Validation of workflow actions.

Below are the above four fields where I have selected my custom End Date Validator

Validator-2

  • Now see the magic of your custom validator.

Create an item of the type of your template (in my case it is Event details) and the play with the End Date value and you will see the validation result on all the places where you have selected your validator in above image.

Validation Result for choosing the End Date Validator on Quick Action Bar will display as below

Validator-result1

Validation Result for choosing the End Date Validator on Validation Button will display as below

Validator-result3

Validation Result for choosing the End Date Validator on Validation Bar will display as below

Validator-result2

So that’s how you are going to use your custom validator. But there are few more things to keep in mind which are as below.

From our custom class, we are returning the “Critical Error” as result of validation failure, but there is some more result which can be returned here depending on the requirement.

  1. Suggestion
  2. Valid
  3. Warning
  4. CriticalError
  5. Error
  6. FatelError
  7. Unknown

ResultType

That’s it. Now help your content editors by implementing the existing as well as by creating the custom validators.