Skip to content

Instantly share code, notes, and snippets.

@KKings
Created June 8, 2015 19:27
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save KKings/53bac04918cda42f483e to your computer and use it in GitHub Desktop.
Save KKings/53bac04918cda42f483e to your computer and use it in GitHub Desktop.
Sitecore 8 WebEditCommand for creating items in configurable locations
namespace NavArts.Sitecore.WebEdit
{
using System;
using System.Collections.Specialized;
using global::Sitecore;
using global::Sitecore.Configuration;
using global::Sitecore.Data;
using global::Sitecore.Data.Fields;
using global::Sitecore.Data.Items;
using global::Sitecore.Diagnostics;
using global::Sitecore.Globalization;
using global::Sitecore.SecurityModel;
using global::Sitecore.Shell.Applications.WebEdit.Commands;
using global::Sitecore.Shell.Framework.Commands;
using global::Sitecore.Web.UI.Sheer;
/// <summary>
/// A configurable WebEditCommand to create Sitecore Items in a specified location.
///
/// Available Parameters:
///
/// * locationId (required) - Location to create the new item
/// * templateId (required) - Template Id of the item to create
/// * fieldId (optional) - If specified, will attempt to add the crated item id to a multilist field. Multilist field is assumed
/// to be on the 'Context Item' of the rendering (if datasource is set, the datasource item).
/// </summary>
[Serializable]
public class AddToLocation : WebEditCommand
{
/// <summary>
/// Main execution point of the WebEditCommand
/// </summary>
public override void Execute(CommandContext context)
{
Assert.ArgumentNotNull((object)context, "context");
NameValueCollection parameters = new NameValueCollection();
parameters["parent"] = context.Parameters["id"];
parameters["master"] = context.Parameters["master"];
// Get Language
var itemUri = ItemUri.ParseQueryString();
var language = context.Parameters["language"];
if (String.IsNullOrEmpty(language) && itemUri != null)
{
language = itemUri.Language.ToString();
}
parameters["language"] = language;
// Store the custom parameters
parameters["templateId"] = context.Parameters["templateId"] ?? String.Empty;
parameters["locationId"] = context.Parameters["locationId"] ?? String.Empty;
parameters["fieldId"] = context.Parameters["fieldId"] ?? String.Empty;
Context.ClientPage.Start((object)this, "Run", parameters);
}
/// <summary>
/// Handles the Postback of the Sheer Dialogs
/// </summary>
protected static void Run(ClientPipelineArgs args)
{
Assert.ArgumentNotNull((object)args, "args");
var language = Language.Parse(args.Parameters["language"]);
var parent = Context.ContentDatabase.Items[args.Parameters["parent"], language];
Assert.IsNotNull((object)parent, typeof(Item));
// Retrival of custom parameters
var templateId = AddToLocation.GetSitecoreId(args.Parameters, "templateId");
var locationId = AddToLocation.GetSitecoreId(args.Parameters, "locationId", parent.ID.ToString());
var fieldId = AddToLocation.GetSitecoreId(args.Parameters, "fieldId");
Assert.IsNotNull((object)templateId, typeof(ID));
Assert.IsNotNull((object)locationId, typeof(ID));
var locationItem = Context.ContentDatabase.GetItem(locationId);
Assert.IsNotNull((object)locationItem, typeof(Item));
var branch = Context.ContentDatabase.Branches[templateId.ToString(), language];
Assert.IsNotNull((object)branch, typeof(BranchItem));
if (args.IsPostBack)
{
if (!args.HasResult)
{
return;
}
var item = Context.Workflow.AddItem(args.Result, branch, locationItem);
// Add to a MultilistField
if (!fieldId.IsNull)
{
AddToLocation.AddToMultiField(parent, fieldId, item.ID);
}
SheerResponse.Eval(
"scForm.browser.getParentWindow(scForm.browser.getFrameElement(window).ownerDocument).location.reload(true)");
}
else if (!locationItem.Access.CanCreate())
{
Context.ClientPage.ClientResponse.Alert("You do not have permission to create an item here.");
}
else
{
SheerResponse.Input(String.Format("Enter a name for the new {0}:", branch.DisplayName),
branch.DisplayName,
Settings.ItemNameValidation,
Translate.Text("'$Input' is not a valid name."), Settings.MaxItemNameLength);
args.WaitForPostBack();
}
}
/// <summary>
/// Gets a Sitecore Id from a NameValueCollection
/// </summary>
/// <param name="collection">Collection of Parameters</param>
/// <param name="parameter">Parameter Key</param>
/// <param name="defaultValue">Default value if no parameter under that key found. Default
/// value is also returned if the value cannot be parsed into a </param>
/// <returns>Sitecore Id</returns>
private static ID GetSitecoreId(NameValueCollection collection, string parameter, string defaultValue = null)
{
if (collection == null || !collection.HasKeys() || String.IsNullOrEmpty(parameter))
{
return null;
}
var value = collection[parameter] ?? String.Empty;
if (String.IsNullOrEmpty(value))
{
value = defaultValue;
}
ID output;
ID.TryParse(value, out output);
return output;
}
/// <summary>
/// Adds a Sitecore Id to a Multilist Field
/// <para>All parameters are required.</para>
/// </summary>
/// <param name="item">Context Item</param>
/// <param name="fieldId">Multilist Field</param>
/// <param name="value">Value to add to the multilist field</param>
private static void AddToMultiField(Item item, ID fieldId, ID value)
{
if (item == null || fieldId.IsNull || value.IsNull)
{
return;
}
MultilistField multiListField = item.Fields[fieldId];
if (multiListField == null)
{
return;
}
using (new SecurityDisabler())
{
using (new EditContext(item))
{
multiListField.Add(value.ToString());
}
}
}
}
}
<?xml version="1.0"?>
<configuration xmlns:patch="http://www.sitecore.net/xmlconfig/">
<sitecore>
<commands>
<!-- Registration of the AddToLocation command -->
<command name="webedit:addtolocation" type="NavArts.Sitecore.WebEdit.AddToLocation,NavArts.Sitecore"/>
</commands>
</sitecore>
</configuration>
@pmandava
Copy link

pmandava commented Sep 1, 2015

Excellent.Really Helpful.

@tillito77
Copy link

In my solution, WebEditCommand is marked as "obsolete". What is the alternative? How can I get rid of the warning?

@KKings
Copy link
Author

KKings commented Sep 21, 2016

Which version of Sitecore are you using?

@bhavik-symsoft
Copy link

Awesome! Note: same issue as @tillito77. Using Sitecore 8.1 (rev. 160519).

@KKings
Copy link
Author

KKings commented Jan 26, 2017

This is marked as obsolete but unfortunately, I do not see an alternative. I would ignore the warning for now until Sitecore provides an update.

Also, make sure you are referencing the Sitecore.ExperienceEditor.dll

@KKings
Copy link
Author

KKings commented Jan 30, 2017

Confirmed with Sitecore that the [Obsolete] attribute was a mistake, and is removed on Sitecore 8.2 - update 2

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment