Sitecore Page Editor provides a Set associated content button in the floating toolbar around each component:
This allows you to set the Data source for the component.
The selection can be restricted by Template or Location (in the Sitecore tree) by setting the page editor options on the component:
If you have some components that require a data source and others that do not, it can be confusing for editors because the Set associated content button is always visible. The only way to see if it is intended to be used in a particular instance is by clicking it and seeing whether the developer has set the restrictions – if not then it allows you to pick any item from the whole site tree and you realise you probably aren’t meant to use it.
I thought it would be nice to only show the button if the Template restriction has been set, so the editor doesn’t try to use it when it isn’t intended.
To do this, I created a custom class to replace the built-in SetDatasource command:
using Sitecore.Data.Items; using Sitecore.Shell.Applications.WebEdit.Commands; using Sitecore.Shell.Framework.Commands; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Training.Utilities.BaseCore.Commands { public class SetDatasourceIfTemplateSet : SetDatasource { public override CommandState QueryState(CommandContext context) { Sitecore.Data.ID renderingId; if (Sitecore.Data.ID.TryParse(context.Parameters["renderingId"], out renderingId)) { Item renderingItem = Sitecore.Context.Database.GetItem(renderingId); if (string.IsNullOrEmpty(renderingItem["Datasource Template"])) { return CommandState.Hidden; } } return base.QueryState(context); } } }
Then in the /App_Config/Commands.config file, replace the webedit:setdatasource command type with our custom version:
<command name="webedit:setdatasource" type="Training.Utilities.BaseCore.Commands.SetDatasourceIfTemplateSet,Training.Utilities"/>
Then the button will only show up if a Datasource Template has been assigned.