Command template:
This is one of the Sitecore templates that can be used when there is a need to create a fixed pattern content but with dynamic names.
For example, in the below image if you have a news item available "ABP" and you want to create new news every hour or day then you will be required to segregate that news according to day or month or year whatever suits you. (as in this news "Delhi News" is segregated by year)
For this, the content author needs to create first a folder specific to the day, month, or year then s/he will create the news item under it.
So, what if we simply select the "ABP" and right-click -> insert item and then that folder itself gets created as per your code logic, and then your news "Delhi News" also automatically gets created under that folder.
This is done by using the command template, let us see how to do it:
Step-1:
Create Two templates "News" and "News Item" with required fields for "ABP" and "Delhi News" items respectively.
Step-2:
Create command template using "/sitecore/templates/Branches/System/Branch/Command Template"
Step-3:
For the logic of creating a folder under the news items and then new news item under that folder, we will have to create a custom command by inheriting from Sitecore.Shell.Framework.Commands.Command from and then we have to refer that class in our config to know which command to execute while creating the item.
Let's name our command as "newsbycategory:newsitem" and include it in the \App_Config\Sitecore\CMS.Core\Sitecore.Commands.config (in case of Sitecore 9.x) and \App_Config\Commands.config (in case of 8.x) as following:
Step-4:
Now we will write the code for our logic in the class "BasicCompany.Feature.POC.Commands.NewsItemCommand" as shown in the type attribute of the screenshot in Step-3
Create a class in your project with name "NewsItemCommand" and inherit it with "Sitecore.Shell.Framework.Commands.Command" class. The complete code is below:
public class NewsItemCommand : Command
{
public override void Execute(CommandContext context)
{
if (context.Items != null && context.Items.Length > 0)
{
Item contextItem = context.Items[0];
NameValueCollection parameters = new NameValueCollection();
parameters["id"] = contextItem.ID.ToString();
parameters["name"] = contextItem.Name;
parameters["database"] = contextItem.Database.Name;
parameters["language"] = contextItem.Language.ToString();
Sitecore.Context.ClientPage.Start(this, "Run", parameters); //Run method executes on
}
}
protected void Run(Sitecore.Web.UI.Sheer.ClientPipelineArgs args)
{
if (args.IsPostBack)
{
if (!(string.IsNullOrEmpty(args.Result)) && (args.Result != "undefined") && (args.Result != "null"))
{
}
}
else
{
Sitecore.Text.UrlString url = new Sitecore.Text.UrlString("/sitecore modules/shell/Demo/CreateNews.aspx");
url.Append("id", args.Parameters["id"]);
url.Append("database", args.Parameters["database"]);
Sitecore.Context.ClientPage.ClientResponse.ShowModalDialog(url.ToString(), true);
args.WaitForPostBack(true);
}
}
}
Now, this piece of code will run when you will create new news items under "ABP" (or any items of type template "news"). We will see in the next how this code will get hit.
Step-5:
We need to assign the command name "newsbycategory:newsitem", as shown in Step-3, to our newly created command template. Then we will assign that command template in the insert options for the "News" template as shown below.
Step-6:
If you would have noticed in the code for the Run method in Step-4, this method will open a popup from path "/sitecore modules/shell/Demo/CreateNews.aspx" to let the author enter the name of the new news item. Which will be like as shown below
Step-7:
To create the popup lets create an aspx page in the Visual Studio and then we will copy that aspx page from Visual Studio to our Sitecore website folder's location present at "/website/sitecore modules/shell/Demo/".
When you will create the aspx page you will require the following code.
Markup of the popup to paste in the CreateNews.aspx
Enter News Item Name:
<br />
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<br />
<asp:Button ID="Button1" runat="server" Text="Ok" OnClick="btnOK_Click" />
<asp:Button ID="Button2" runat="server" Text="Cancel" OnClick="btnCancel_Click" />
Code for OK button, double click on OK button in design mode then VS will create the method for you:
protected void btnOk_Click(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty(TextBox1.Text))
{
Sitecore.Data.Database currentDatabase = Sitecore.Configuration.Factory.GetDatabase("master");
Item parentItem = currentDatabase.GetItem(Sitecore.Web.WebUtil.GetQueryString("id"));
if (parentItem != null)
{
//check if News item contains a folder with current year
Item[] children = parentItem.Axes.GetDescendants();
Item currentYearItem = children.Where(x => x.TemplateName == "Folder" && x.Name == DateTime.Now.Year.ToString()).SingleOrDefault();
if (currentYearItem == null)
{
Sitecore.Data.Items.TemplateItem folderTemplate = currentDatabase.GetTemplate(Sitecore.TemplateIDs.Folder);
if (folderTemplate != null)
{
Item i = parentItem.Add(DateTime.Now.Year.ToString(), folderTemplate);
currentYearItem = i;
}
}
//create a news item and add it to the current folder
TemplateItem newsItemTemplate = currentDatabase.GetTemplate(new Sitecore.Data.ID("{79E88D8D-BD16-48B0-92EE-D1D518DC83A3}"));
Item newsItem = currentYearItem.Add(TextBox1.Text, newsItemTemplate);
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "Close", "window.top.dialogClose();", true);
}
}
else
{
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "Warning", "alert('Please enter news item');", true);
}
}
Code for the CANCEL button:
protected void btnCancel_Click(object sender, EventArgs e)
{
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "Close", "window.top.dialogClose();", true);
}
What is happening on the clicking of the OK button?
On clicking ok button btnOK_Click method run in this,
- It is checking if any folder is created under the "News" type item if not then it will create a folder with year name using the default folder template.
- Create the new item under this folder on the basis of the template "News Item" as shown in the highlighted with yellow. (The guid passed in the code is of "News Item")
Step-8:
Now everything is in place lets create an item based on the "News" template, for example, "BBC" and then we will try to create new news item, for example, "Delhi Monsoon" under that. You will see that current year's folder will be automatically created and under that our new item will be placed.
https://sitecorepeanuts.blogspot.com/2020/08/command-templates-in-sitecore.html
ReplyDelete