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 :

 

 

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 🙂

Field Level Restrictions in Sitecore

Requirement: As an admin user, I want read only access on a field for a specific role.

Solution: First of all having read or write access on a particular field is not possible in Sitecore. So now the question is, what can be done in this situation? And the answers is, by restricting the field itself for required user or role. To achieve this, you have to break the inheritance of this field for the required role.

  1. Go to Role Manager and Create a new Role

Role

  1. Select the newly created role and add the required role in members list.

role-members

  1. Go to Security Editor and select the newly created role and then navigate to field (to be restricted)

Security-Editor

That’s it, we are done with restricting a field access for a particular role. Now, the field will not be visible for the selected role users on template item.

Hide a field on WFFM (No CSS & JS)

WFFM provides an inbuilt way to hide one or more fields form rendered for an end user. Of course, I am not gonna use any CSS or JS to achieve this, instead, I’ll show you to do this by using an inbuilt feature of WFFM.

  1. Go to Form Designer and select the field you want to hide and scroll the left bar and click on Edit button shown under the Rules section.

WFFM1

2. Clicking on Edit button will open a popup with some predefined conditions and actions. Search for the “Database” and select the “where the current database name compares to value”. Click on “compare to select the compare rule and from there select “Is Equal To” and then click on “Value” and enter your web database connection string name like “web”.

WFFM-Edit-Rule-1

3. Now select the “hide element” actions tab and click ok.

WFFM-Edit-Rule-2

that’s it. Save the changes and publish the form. Now, the selected filed will not be available in the browser.