Home » Render Field
Category Archives: Render Field
Add a Custom Attribute to the General Link Field in Sitecore
In my current project, I needed to find a way to give content authors the ability to add a custom attribute — let’s call this custom attribute Tag for simplicity– to the “Insert Link” and “Insert External Link” dialogs of the General Link field (NOTE: the following solution does not use the “out of the box” SPEAK dialogs that ship with Sitecore 7.2 and up. This solution uses the older Sheer UI dialogs. Perhaps I will share a solution in the future on how to do the following using the newer SPEAK dialogs).
You might be asking why? Well, let’s imagine that there is some magical JavaScript code that puts a click event on links, and grabs the value of the tag attribute for reporting purposes — perhaps the JavaScript calls a service that captures this information.
In this post, I am going to share how I went about doing this minus the code I needed to add to get this to work in the Glass.Mapper ORM (I’m going to show you this code in my next blog post).
I first built the following custom LinkField class (this class is not used in this solution but will be used in my next blog post where I should how to integrate the functionality below in Glass.Mapper. I’m just setting the stage 😉 ):
using Sitecore.Data.Fields; namespace Sitecore.Sandbox.Data.Fields { public class TagLinkField : LinkField { public TagLinkField(Field innerField) : base(innerField) { } public TagLinkField(Field innerField, string runtimeValue) : base(innerField, runtimeValue) { } public string Tag { get { return GetAttribute("tag"); } set { this.SetAttribute("tag", value); } } } }
The class above subclasses Sitecore.Data.Fields.Link (this lives in Sitecore.Kernel.dll) — this class represents a link in Sitecore — and added a new Tag property (this class will magically parse or save this value into the field’s underlying XML).
Next, I created the following Sheer UI form for a custom “Insert Link” dialog:
using System; using System.Xml; using System.Collections.Specialized; using Sitecore; using Sitecore.Data; using Sitecore.Data.Items; using Sitecore.Diagnostics; using Sitecore.Shell.Applications.Dialogs; using Sitecore.Shell.Applications.Dialogs.InternalLink; using Sitecore.Web.UI.HtmlControls; using Sitecore.Web.UI.Sheer; using Sitecore.Xml; namespace Sitecore.Sandbox.Shell.Applications.Dialogs.InternalLink { public class TagInternalLinkForm : InternalLinkForm { private const string TagAttributeName = "tag"; protected Edit Tag; private NameValueCollection customLinkAttributes; protected NameValueCollection CustomLinkAttributes { get { if(customLinkAttributes == null) { customLinkAttributes = new NameValueCollection(); ParseLinkAttributes(GetLink()); } return customLinkAttributes; } } protected override void OnLoad(EventArgs e) { Assert.ArgumentNotNull(e, "e"); base.OnLoad(e); if (Context.ClientPage.IsEvent) { return; } LoadControls(); } protected override void ParseLink(string link) { base.ParseLink(link); ParseLinkAttributes(link); } protected virtual void ParseLinkAttributes(string link) { Assert.ArgumentNotNull(link, "link"); XmlDocument xmlDocument = XmlUtil.LoadXml(link); if (xmlDocument == null) { return; } XmlNode node = xmlDocument.SelectSingleNode("/link"); if (node == null) { return; } CustomLinkAttributes[TagAttributeName] = XmlUtil.GetAttribute(TagAttributeName, node); } protected virtual void LoadControls() { string tagValue = CustomLinkAttributes[TagAttributeName]; if (!string.IsNullOrWhiteSpace(tagValue)) { Tag.Value = tagValue; } } protected override void OnOK(object sender, EventArgs args) { Assert.ArgumentNotNull(sender, "sender"); Assert.ArgumentNotNull(args, "args"); Item selectionItem = Treeview.GetSelectionItem(); if (selectionItem == null) { Context.ClientPage.ClientResponse.Alert("Select an item."); } else { string attributeFromValue = LinkForm.GetLinkTargetAttributeFromValue(this.Target.Value, this.CustomTarget.Value); string queryString = this.Querystring.Value; if (queryString.StartsWith("?", StringComparison.InvariantCulture)) queryString = queryString.Substring(1); Packet packet = new Packet("link", new string[0]); LinkForm.SetAttribute(packet, "text", (Control)Text); LinkForm.SetAttribute(packet, "linktype", "internal"); LinkForm.SetAttribute(packet, "anchor", (Control)Anchor); LinkForm.SetAttribute(packet, "title", (Control)Title); LinkForm.SetAttribute(packet, "class", (Control)Class); LinkForm.SetAttribute(packet, "querystring", queryString); LinkForm.SetAttribute(packet, "target", attributeFromValue); LinkForm.SetAttribute(packet, "id", selectionItem.ID.ToString()); TrimEditControl(Tag); LinkForm.SetAttribute(packet, TagAttributeName, (Control)Tag); Assert.IsTrue(!string.IsNullOrEmpty(selectionItem.ID.ToString()) && ID.IsID(selectionItem.ID.ToString()), "ID doesn't exist."); SheerResponse.SetDialogValue(packet.OuterXml); SheerResponse.CloseWindow(); } } protected virtual void TrimEditControl(Edit control) { if(control == null || string.IsNullOrEmpty(control.Value)) { return; } control.Value = control.Value.Trim(); } } }
The OnLoad method invokes its base class’ OnLoad method — the base class’ OnLoad method loads values from the field’s XML into the Edit controls on the form — and also parses the value from the tag XML attribute and places it into the Tag Edit control.
The ParseLink method above is where values from the field’s XML are extracted — these are extracted from the XML attributes of the field. The ParseLink method delegates to the ParseLinkAttributes method which extracts the value from the tag attribute.
The OnOK method is where values from the Edit controls are extract and passed to a class instance that generates XML for the field. I could not call the base class’ OnOK method since it would prevent me from saving the custom tag attribute and value, so I “borrowed/stole” code from it, and then added my modifications.
I then added new Tag Literal and Edit controls to the “Internal Link” dialog, and also updated the CodeBeside xml element to point to my new class (I copy and pasted this from /sitecore/shell/Applications/Dialogs/InsertLink.InsertLink.xml and put my new file into /sitecore/shell/Override/InternalLink/InsertLink.xml in my website root — always put custom Sheer UI dialogs XML files in /sitecore/shell/Override/ so that you don’t run into issues when upgrading Sitecore):
<?xml version="1.0" encoding="utf-8" ?> <control xmlns:def="Definition" xmlns="http://schemas.sitecore.net/Visual-Studio-Intellisense"> <InternalLink> <FormDialog Icon="Network/32x32/link.png" Header="Internal Link" Text="Select the item that you want to create a link to and specify the appropriate properties." OKButton="OK"> <Stylesheet Key="Style"> .ff input { width: 160px; } </Stylesheet> <CodeBeside Type="Sitecore.Sandbox.Shell.Applications.Dialogs.InternalLink.TagInternalLinkForm, Sitecore.Sandbox" /> <DataContext ID="InternalLinkDataContext"/> <GridPanel Columns="2" Width="100%" Height="100%" CellPadding="4" Style="table-layout:fixed"> <Scrollbox Width="100%" Height="100%" Class="scScrollbox scFixSize" Background="window" Padding="0" Border="1px solid #CFCFCF" GridPanel.VAlign="top" GridPanel.Width="100%" GridPanel.Height="100%"> <TreeviewEx ID="Treeview" DataContext="InternalLinkDataContext" MultiSelect="False" Width="100%"/> </Scrollbox> <Scrollbox Width="256" Height="100%" Background="transparent" Border="none" GridPanel.VAlign="top" GridPanel.Width="256"> <GridPanel CellPadding="2" Columns="2"> <Literal Text="Link Description:" GridPanel.NoWrap="true"/> <Edit ID="Text"/> <Literal Text="Anchor:" GridPanel.NoWrap="true"/> <Edit ID="Anchor"/> <Label for="Target" GridPanel.NoWrap="true"><Literal Text="Target Window:"/></Label> <Combobox ID="Target" Width="100%" Change="OnListboxChanged"> <ListItem Value="Self" Header="Active browser"/> <ListItem Value="New" Header="New browser"/> <ListItem Value="Custom" Header="Custom"/> </Combobox> <Panel ID="CustomLabel" Background="transparent" Border="none" GridPanel.NoWrap="true" GridPanel.Align="right"><Label For="CustomTarget"><Literal Text="Custom:" /></Label></Panel> <Edit ID="CustomTarget" /> <Literal Text="Style Class:" GridPanel.NoWrap="true"/> <Edit ID="Class"/> <Literal Text="Alternate Text:" GridPanel.NoWrap="true"/> <Edit ID="Title"/> <Literal Text="Query String:" GridPanel.NoWrap="true"/> <Edit ID="Querystring"/> <Literal Text="Tag:" GridPanel.NoWrap="true"/> <Edit ID="Tag"/> </GridPanel> </Scrollbox> </GridPanel> </FormDialog> </InternalLink> </control>
Likewise, I repeated the steps for the “External Link” dialog’s code-beside class (I’m not going to go into details here since they are the same as the “Insert Link” dialog class above):
using System; using Sitecore; using Sitecore.Diagnostics; using Sitecore.Shell.Applications.Dialogs; using Sitecore.Shell.Applications.Dialogs.ExternalLink; using Sitecore.Web.UI.HtmlControls; using Sitecore.Web.UI.Sheer; using Sitecore.Xml; using System.Collections.Specialized; using System.Xml; namespace Sitecore.Sandbox.Shell.Applications.Dialogs.ExternalLink { public class TagExternalLinkForm : ExternalLinkForm { private const string TagAttributeName = "tag"; protected Edit Tag; private NameValueCollection customLinkAttributes; protected NameValueCollection CustomLinkAttributes { get { if (customLinkAttributes == null) { customLinkAttributes = new NameValueCollection(); ParseLinkAttributes(GetLink()); } return customLinkAttributes; } } protected override void ParseLink(string link) { base.ParseLink(link); ParseLinkAttributes(link); } protected virtual void ParseLinkAttributes(string link) { Assert.ArgumentNotNull(link, "link"); XmlDocument xmlDocument = XmlUtil.LoadXml(link); if (xmlDocument == null) { return; } XmlNode node = xmlDocument.SelectSingleNode("/link"); if (node == null) { return; } CustomLinkAttributes[TagAttributeName] = XmlUtil.GetAttribute(TagAttributeName, node); } protected override void OnLoad(EventArgs e) { Assert.ArgumentNotNull(e, "e"); base.OnLoad(e); if (Context.ClientPage.IsEvent) { return; } LoadControls(); } protected virtual void LoadControls() { string tagValue = CustomLinkAttributes[TagAttributeName]; if (!string.IsNullOrWhiteSpace(tagValue)) { Tag.Value = tagValue; } } protected override void OnOK(object sender, EventArgs args) { Assert.ArgumentNotNull(sender, "sender"); Assert.ArgumentNotNull(args, "args"); string path = GetPath(); string attributeFromValue = LinkForm.GetLinkTargetAttributeFromValue(Target.Value, CustomTarget.Value); Packet packet = new Packet("link", new string[0]); LinkForm.SetAttribute(packet, "text", (Control)Text); LinkForm.SetAttribute(packet, "linktype", "external"); LinkForm.SetAttribute(packet, "url", path); LinkForm.SetAttribute(packet, "anchor", string.Empty); LinkForm.SetAttribute(packet, "title", (Control)Title); LinkForm.SetAttribute(packet, "class", (Control)Class); LinkForm.SetAttribute(packet, "target", attributeFromValue); TrimEditControl(Tag); LinkForm.SetAttribute(packet, TagAttributeName, (Control)Tag); SheerResponse.SetDialogValue(packet.OuterXml); SheerResponse.CloseWindow(); } private string GetPath() { string url = this.Url.Value; if (url.Length > 0 && url.IndexOf("://", StringComparison.InvariantCulture) < 0 && !url.StartsWith("/", StringComparison.InvariantCulture)) { url = string.Concat("http://", url); } return url; } protected virtual void TrimEditControl(Edit control) { if (control == null || string.IsNullOrEmpty(control.Value)) { return; } control.Value = control.Value.Trim(); } } }
I also added a Label and Edit control for the Tag as I did for the “Insert Link” dialog above (the “out of the box” External Link dialog xml file lives in /sitecore/shell/Applications/Dialogs/ExternalLink/ExternalLink.xml of the Sitecore website root. When creating custom one be sure to put it in /sitecore/shell/override of your website root):
<?xml version="1.0" encoding="utf-8" ?> <control xmlns:def="Definition" xmlns="http://schemas.sitecore.net/Visual-Studio-Intellisense"> <ExternalLink> <FormDialog Header="Insert External Link" Text="Enter the URL for the external website that you want to insert a link to and specify any additional properties for the link." OKButton="Insert"> <CodeBeside Type="Sitecore.Sandbox.Shell.Applications.Dialogs.ExternalLink.TagExternalLinkForm, Sitecore.Sandbox"/> <GridPanel Class="scFormTable" CellPadding="2" Columns="2" Width="100%"> <Label For="Text" GridPanel.NoWrap="true"> <Literal Text="Link description:"/> </Label> <Edit ID="Text" Width="100%" GridPanel.Width="100%"/> <Label For="Url" GridPanel.NoWrap="true"> <Literal Text="URL:"/> </Label> <Border> <GridPanel Columns="2" Width="100%"> <Edit ID="Url" Width="100%" GridPanel.Width="100%" /> <Button id="Test" Header="Test" Style="margin-left: 10px;" Click="OnTest"/> </GridPanel> </Border> <Label for="Target" GridPanel.NoWrap="true"> <Literal Text="Target window:"/> </Label> <Combobox ID="Target" GridPanel.Width="100%" Width="100%" Change="OnListboxChanged"> <ListItem Value="Self" Header="Active browser"/> <ListItem Value="New" Header="New browser"/> <ListItem Value="Custom" Header="Custom"/> </Combobox> <Panel ID="CustomLabel" Disabled="true" Background="transparent" Border="none" GridPanel.NoWrap="true"> <Label For="CustomTarget"> <Literal Text="Custom:" /> </Label> </Panel> <Edit ID="CustomTarget" Width="100%" Disabled="true"/> <Label For="Class" GridPanel.NoWrap="true"> <Literal Text="Style class:" /> </Label> <Edit ID="Class" Width="100%" /> <Label for="Title" GridPanel.NoWrap="true"> <Literal Text="Alternate text:"/> </Label> <Edit ID="Title" Width="100%" /> <Label for="Tag" GridPanel.NoWrap="true"> <Literal Text="Tag:"/> </Label> <Edit ID="Tag" Width="100%" /> </GridPanel> </FormDialog> </ExternalLink> </control>
Since the “out of the box” “External Link” dialog isn’t tall enough for the new Tag Label and Edit controls — I had no quick way of changing this since the height of the dialog is hard-coded in Sitecore.Shell.Applications.ContentEditor.Link in Sitecore.Client — I decided to create a new Content Editor field for the General Link field — this is further down in this post — which grabs the Url of the dialog and dimensions from a custom pipeline I built (the dimensions live in the patch configuration file that is found later on in this post). This custom pipeline uses the following PipelineArgs class:
using Sitecore.Collections; using Sitecore.Pipelines; namespace Sitecore.Sandbox.Pipelines.DialogInfo { public class DialogInfoArgs : PipelineArgs { public string Message { get; set; } public string Url { get; set; } public SafeDictionary<string, string> Parameters { get; set; } public DialogInfoArgs() { Parameters = new SafeDictionary<string, string>(); } public bool HasInformation() { return !string.IsNullOrWhiteSpace(Url); } } }
Each dialog defined in a pipeline processor of this custom pipeline will specify the dialog’s Url; it’s message — this is how the code ascertains which dialog to load; and any properties of the dialog (e.g. height).
I then built the following class that serves as a processor for this custom pipeline:
using System; using System.Xml; using Sitecore.Collections; using Sitecore.Diagnostics; namespace Sitecore.Sandbox.Pipelines.DialogInfo { public class SetDialogInfo { protected virtual string ParameterNameAttributeName { get; private set; } protected virtual string ParameterValueAttributeName { get; private set; } protected virtual string Message { get; private set; } protected virtual string Url { get; private set; } protected virtual SafeDictionary<string, string> Parameters { get; private set; } public SetDialogInfo() { Parameters = new SafeDictionary<string, string>(); } public void Process(DialogInfoArgs args) { Assert.ArgumentNotNull(args, "args"); if(!CanProcess(args)) { return; } SetDialogInformation(args); } protected virtual bool CanProcess(DialogInfoArgs args) { return !string.IsNullOrWhiteSpace(Message) && !string.IsNullOrWhiteSpace(Url) && args != null && !string.IsNullOrWhiteSpace(args.Message) && string.Equals(args.Message, Message, StringComparison.CurrentCultureIgnoreCase); } protected virtual void SetDialogInformation(DialogInfoArgs args) { args.Url = Url; args.Parameters = Parameters; } protected virtual void AddParameter(XmlNode node) { Assert.ArgumentNotNullOrEmpty(ParameterNameAttributeName, "ParameterNameAttributeName"); Assert.ArgumentNotNullOrEmpty(ParameterValueAttributeName, "ParameterValueAttributeName"); if (node == null || !IsAttributeSet(node.Attributes[ParameterNameAttributeName]) || !IsAttributeSet(node.Attributes[ParameterValueAttributeName])) { return; } Parameters[node.Attributes[ParameterNameAttributeName].Value] = node.Attributes[ParameterValueAttributeName].Value; } protected bool IsAttributeSet(XmlAttribute attribute) { return attribute != null && !string.IsNullOrEmpty(attribute.Value); } } }
The Sitecore Configuration Factory injects the dialog’s url, message and parameters into the class instance.
The CanProcess method determines if there is match with the message that is sent via the DialogInfoArgs instance passed to the processor’s Process method. If there is a match, the Url and dialog parameters are set on the DialogInfoArgs instance.
If there isn’t a match, the processor just exits and does nothing.
I then built the following class to serve as a custom Sitecore.Shell.Applications.ContentEditor.Link:
using System; using System.Collections.Specialized; using Sitecore.Collections; using Sitecore.Diagnostics; using Sitecore.Pipelines; using Sitecore.Shell.Applications.ContentEditor; using Sitecore.Web.UI.Sheer; using Sitecore.Sandbox.Pipelines.DialogInfo; namespace Sitecore.Sandbox.Shell.Applications.ContentEditor { public class TagLink : Link { public override void HandleMessage(Message message) { Assert.ArgumentNotNull(message, "message"); if (message["id"] != ID) { return; } DialogInfoArgs info = GetDialogInformation(message.Name); if (info.HasInformation()) { Insert(info.Url, ToNameValueCollection(info.Parameters)); return; } base.HandleMessage(message); } protected virtual DialogInfoArgs GetDialogInformation(string message) { Assert.ArgumentNotNullOrEmpty(message, "message"); DialogInfoArgs args = new DialogInfoArgs { Message = message }; CorePipeline.Run("dialogInfo", args); return args; } protected virtual NameValueCollection ToNameValueCollection(SafeDictionary<string, string> dictionary) { if(dictionary == null) { return new NameValueCollection(); } NameValueCollection collection = new NameValueCollection(); foreach(string key in dictionary.Keys) { collection.Add(key, dictionary[key]); } return collection; } } }
The HandleMessage method above passes the message name to the custom <dialogInfo> pipeline and gets back a DialogInfoArgs instance with the dialog’s Url and parameters if there is a match. If there is no match, then the HandleMessage method delegates to its base class’ HandleMessage method (there are dialog Urls and Parameters baked in it).
Now we need to let Sitecore know about the above Content Editor class. We do so like this:
Now that the Content Editor bits are in place, we need some code to render the tag on the front-end of the website. I do this in the following class which serves as a custom <renderField> pipeline processor:
using System.Xml; using Sitecore.Pipelines.RenderField; using Sitecore.Xml; namespace Sitecore.Sandbox.Pipelines.RenderField { public class SetTagAttributeOnLink { private string TagXmlAttributeName { get; set; } private string TagAttributeName { get; set; } private string BeginningHtml { get; set; } public void Process(RenderFieldArgs args) { if (!CanProcess(args)) { return; } args.Result.FirstPart = AddTagAttributeValue(args.Result.FirstPart, TagAttributeName, GetXmlAttributeValue(args.FieldValue, TagXmlAttributeName)); } protected virtual bool CanProcess(RenderFieldArgs args) { return !string.IsNullOrWhiteSpace(TagAttributeName) && !string.IsNullOrWhiteSpace(BeginningHtml) && !string.IsNullOrWhiteSpace(TagXmlAttributeName) && args != null && args.Result != null && HasXmlAttributeValue(args.FieldValue, TagAttributeName) && !string.IsNullOrWhiteSpace(args.Result.FirstPart) && args.Result.FirstPart.ToLower().StartsWith(BeginningHtml.ToLower()); } protected virtual bool HasXmlAttributeValue(string linkXml, string attributeName) { return !string.IsNullOrWhiteSpace(GetXmlAttributeValue(linkXml, attributeName)); } protected virtual string GetXmlAttributeValue(string linkXml, string attributeName) { XmlDocument xmlDocument = XmlUtil.LoadXml(linkXml); if(xmlDocument == null) { return string.Empty; } XmlNode node = xmlDocument.SelectSingleNode("/link"); if (node == null) { return string.Empty; } return XmlUtil.GetAttribute(TagAttributeName, node); } protected virtual string AddTagAttributeValue(string html, string attributeName, string attributeValue) { if(string.IsNullOrWhiteSpace(html) || string.IsNullOrWhiteSpace(attributeName) || string.IsNullOrWhiteSpace(attributeValue)) { return html; } int index = html.LastIndexOf(">"); if (index < 0) { return html; } string firstPart = html.Substring(0, index); string attribute = string.Format(" {0}=\"{1}\"", attributeName, attributeValue); string lastPart = html.Substring(index); return string.Concat(firstPart, attribute, lastPart); } } }
The Process method above delegates to the CanProcess method which determines if the generated HTML by the previous <renderField> pipeline processors should be manipulated — the code should only run it the generated HTML is a link and only when there is a tag attribute set on the field.
If the HTML should be manipulated, we basically add the tag attribute with its value it to the generated link HTML — this is done in the AddTagAttributeValue method.
I then wired everything together via the following patch configuration file:
<configuration xmlns:patch="http://www.sitecore.net/xmlconfig/"> <sitecore> <controlSources> <source mode="on" namespace="Sitecore.Sandbox.Shell.Applications.ContentEditor" assembly="Sitecore.Sandbox" prefix="sandbox-content"/> </controlSources> <fieldTypes> <fieldType name="General Link"> <patch:attribute name="type">Sitecore.Sandbox.Data.Fields.TagLinkField, Sitecore.Sandbox</patch:attribute> </fieldType> <fieldType name="General Link with Search"> <patch:attribute name="type">Sitecore.Sandbox.Data.Fields.TagLinkField, Sitecore.Sandbox</patch:attribute> </fieldType> <fieldType name="link"> <patch:attribute name="type">Sitecore.Sandbox.Data.Fields.TagLinkField, Sitecore.Sandbox</patch:attribute> </fieldType> </fieldTypes> <pipelines> <dialogInfo> <processor type="Sitecore.Sandbox.Pipelines.DialogInfo.SetDialogInfo, Sitecore.Sandbox"> <ParameterNameAttributeName>name</ParameterNameAttributeName> <ParameterValueAttributeName>value</ParameterValueAttributeName> <Message>contentlink:externallink</Message> <Url>/sitecore/shell/Applications/Dialogs/External link.aspx</Url> <parameters hint="raw:AddParameter"> <parameter name="height" value="300" /> </parameters> </processor> </dialogInfo> <renderField> <processor patch:after="processor[@type='Sitecore.Pipelines.RenderField.GetInternalLinkFieldValue, Sitecore.Kernel']" type="Sitecore.Sandbox.Pipelines.RenderField.SetTagAttributeOnLink, Sitecore.Sandbox"> <TagXmlAttributeName>tag</TagXmlAttributeName> <TagAttributeName>tag</TagAttributeName> <BeginningHtml><a </BeginningHtml> </processor> </renderField> </pipelines> </sitecore> </configuration>
Let’s try this out!
For testing I added two General Link fields to the Sample Item template (/sitecore/templates/Sample/Sample Item in the master database):
I also had to add two Link field controls to the sample rendering.xslt that ships with Sitecore:
Let’s test the “Insert Link” dialog:
After clicking the “OK” button and saving the Item, I looked at the “Raw values” on the field and saw that the tag was added to the field’s xml:
Let’s see if this works on the “Insert External Link” dialog:
After clicking the “OK” button and saving the Item, I looked at the “Raw values” on the field and saw that the tag was added to the field’s xml:
After publishing everything, I navigated to my home page and looked at its rendered HTML. As you can see, the tag attributes were added to the links:
If you have any comments or thoughts on this, please drop a comment.
Until next time, keep on Sitecoring!
Add Additional Item Fields to RSS Feeds Generated by Sitecore
Earlier today a colleague had asked me how to add additional Item fields into RSS feeds generated by Sitecore.
I could have sworn there was an easy way to do this, but when looking at the RSS Feed Design dialog in Sitecore, it appears you are limited to three fields on your Items “out of the box”:
After a lot of digging in Sitecore.Kernel.dll, I discovered that one can inject a subclass of Sitecore.Syndication.PublicFeed to override/augment RSS feed functionality:
As a proof-of-concept, I whipped up the following subclass of Sitecore.Syndication.PublicFeed:
using System.ServiceModel.Syndication; // Note: you must reference System.ServiceModel.dll to use this! using Sitecore.Diagnostics; using Sitecore.Configuration; using Sitecore.Data.Items; using Sitecore.Pipelines; using Sitecore.Pipelines.RenderField; using Sitecore.Syndication; namespace Sitecore.Sandbox.Syndication { public class ImageInContentPublicFeed : PublicFeed { private static string ImageFieldName { get; set; } private static string RenderFieldPipelineName { get; set; } static ImageInContentPublicFeed() { ImageFieldName = Settings.GetSetting("RSS.Fields.ImageFieldName"); RenderFieldPipelineName = Settings.GetSetting("Pipelines.RenderField"); } protected override SyndicationItem RenderItem(Item item) { SyndicationItem syndicationItem = base.RenderItem(item); AddImageHtmlToContent(syndicationItem, GetImageFieldHtml(item)); return syndicationItem; } protected virtual string GetImageFieldHtml(Item item) { if (string.IsNullOrWhiteSpace(ImageFieldName)) { return string.Empty; } return GetImageFieldHtml(item, ImageFieldName); } private static string GetImageFieldHtml(Item item, string imageFieldName) { Assert.ArgumentNotNull(item, "item"); Assert.ArgumentNotNullOrEmpty(imageFieldName, "imageFieldName"); Assert.ArgumentNotNullOrEmpty(RenderFieldPipelineName, "RenderFieldPipelineName"); if (item == null || item.Fields[imageFieldName] == null) { return string.Empty; } RenderFieldArgs args = new RenderFieldArgs { Item = item, FieldName = imageFieldName }; CorePipeline.Run(RenderFieldPipelineName, args); if (args.Result.IsEmpty) { return string.Empty; } return args.Result.ToString(); } protected virtual void AddImageHtmlToContent(SyndicationItem syndicationItem, string imageHtml) { if (string.IsNullOrWhiteSpace(imageHtml) || !(syndicationItem.Content is TextSyndicationContent)) { return; } TextSyndicationContent content = syndicationItem.Content as TextSyndicationContent; syndicationItem.Content = new TextSyndicationContent(string.Concat(imageHtml, content.Text), TextSyndicationContentKind.Html); } } }
The class above ultimately overrides the RenderItem(Item item) method defined on Sitecore.Syndication.PublicFeed — it is declared virtual. The RenderItem(Item item) method above delegates to the RenderItem(Item item) method of Sitecore.Syndication.PublicFeed; grabs the System.ServiceModel.Syndication.SyndicationContent instance set in the Content property of the returned SyndicationItem object — this happens to be an instance of System.ServiceModel.Syndication.TextSyndicationContent; delegates to the <renderField> pipeline to generate HTML for the image set in the Image Field on the item; creates a new System.ServiceModel.Syndication.TextSyndicationContent instance with the HTML of the image combined with the HTML from the original TextSyndicationContent instance; sets the Content property with this new System.ServiceModel.Syndication.TextSyndicationContent instance; and returns the SyndicationItem instance to the caller.
Since I hate hard-coding things, I put the Image Field’s name and <renderField> pipeline’s name in a patch configuration file:
<configuration xmlns:patch="http://www.sitecore.net/xmlconfig/"> <sitecore> <settings> <setting name="RSS.Fields.ImageFieldName" value="Image" /> <setting name="Pipelines.RenderField" value="renderField" /> </settings> </sitecore> </configuration>
I then mapped the above subclass of Sitecore.Syndication.PublicFeed to the RSS Feed Item I created:
For testing, I added two Items — one with an image and another without an image:
After publishing everything, I loaded the RSS feed in my browser and saw the following:
If you know of other ways to add additional Item fields into Sitecore RSS feeds, please share in a comment.
Omit HTML Breaks From Rendered Multi-Line Text Fields in Sitecore
Earlier today while preparing a training session on how to add JavaScript from a Multi-Line Text field to a rendered Sitecore page, I encountered something I had seen in the past but forgot about: Sitecore FieldControls and the FieldRenderer Web Control will convert newlines into HTML breaks.
For example, suppose you have the following JavaScript in a Multi-Line Text field:
You could use a Text FieldControl to render it:
<%@ Control Language="c#" AutoEventWireup="true" TargetSchema="http://schemas.microsoft.com/intellisense/ie5" %> <sc:Text ID="scJavaScript" Field="JavaScript" runat="server" />
Unfortunately, your JavaScript will not work since it will contain HTML breaks:
Why does this happen? In the RenderField() method in Sitecore.Web.UI.WebControls.FieldRenderer — this lives in Sitecore.Kernel.dll, and is called by all FieldControls — passes a “linebreaks” parameter to the <renderField> pipeline:
The Process() method in Sitecore.Pipelines.RenderField.GetMemoFieldValue — this serves as one of the “out of the box” processors of the <renderField> pipeline — converts all carriage returns, line feeds, and newlines into HTML breaks:
What can we do to prevent this from happening? Well, you could spin up a new class with a Process() method to serve as a new <renderField> pipeline processor, and use that instead of Sitecore.Pipelines.RenderField.GetMemoFieldValue:
using System; using Sitecore.Diagnostics; using Sitecore.Pipelines.RenderField; namespace Sitecore.Sandbox.Pipelines.RenderField { public class GetRawMemoFieldValueWhenApplicable { public void Process(RenderFieldArgs args) { Assert.ArgumentNotNull(args, "args"); if(!AreEqualIgnoreCase(args.FieldTypeKey, "memo") && !AreEqualIgnoreCase(args.FieldTypeKey, "multi-line text")) { return; } bool omitHtmlBreaks; if (bool.TryParse(args.Parameters["omitHtmlBreaks"], out omitHtmlBreaks)) { return; } Assert.IsNotNull(DefaultGetMemoFieldValueProcessor, "DefaultGetMemoFieldValueProcessor must be set in your configuration!"); DefaultGetMemoFieldValueProcessor.Process(args); } private static bool AreEqualIgnoreCase(string stringOne, string stringTwo) { return string.Equals(stringOne, stringTwo, StringComparison.CurrentCultureIgnoreCase); } private GetMemoFieldValue DefaultGetMemoFieldValueProcessor { get; set; } } }
The Process() method in the class above looks for an “omitHtmlBreaks” parameter, and just exits out of the Process() method when it is set to true — it leaves the field value “as is”.
If the “omitHtmlBreaks”parameter is not found in the RenderFieldArgs instance, or it is set to false, the Process() method delegates to the Process() method of its DefaultGetMemoFieldValueProcessor property — this would be an instance of the “out of the box” Sitecore.Pipelines.RenderField.GetMemoFieldValue, and this is passed to the new <renderField> pipeline processor via the following configuration file:
<?xml version="1.0" encoding="utf-8" ?> <configuration xmlns:patch="http://www.sitecore.net/xmlconfig/"> <sitecore> <pipelines> <renderField> <processor patch:instead="processor[@type='Sitecore.Pipelines.RenderField.GetMemoFieldValue, Sitecore.Kernel']" type="Sitecore.Sandbox.Pipelines.RenderField.GetRawMemoFieldValueWhenApplicable, Sitecore.Sandbox"> <DefaultGetMemoFieldValueProcessor type="Sitecore.Pipelines.RenderField.GetMemoFieldValue, Sitecore.Kernel" /> </processor> </renderField> </pipelines> </sitecore> </configuration>
Let’s test this.
I added the “omitHtmlBreaks” parameter to the control I had shown above:
<%@ Control Language="c#" AutoEventWireup="true" TargetSchema="http://schemas.microsoft.com/intellisense/ie5" %> <sc:Text ID="scJavaScript" Field="JavaScript" Parameters="omitHtmlBreaks=true" runat="server" />
When I loaded my page, I was given a warm welcome:
When I viewed my page’s source, I no longer see HTML breaks:
If you have any thoughts on this, or know of another way to do this, please share in a comment.
Embedded Tweets in Sitecore: A Proof of Concept
In a previous post, I showcased a “proof of concept” for shortcodes in Sitecore — this is a shorthand notation for embedding things like YouTube videos in your webpages without having to type up a bunch of HTML — and felt I should follow up with another “proof of concept” around incorporating Embedded Tweets in Sitecore.
You might be asking “what’s an Embedded Tweet?” An Embedded Tweet is basically the process of pasting a Tweet URL from Twitter into an editable content area of your website/blog/whatever (think Rich Text field in Sitecore), and let the code that builds the HTML for your site figure out how to display it.
For example, I had used an Embedded Tweet in a recent post:
This is what is seen on the rendered page:
While doing some research via Google on how to do this in Sitecore, I found this page from Twitter that discusses how you could go about accomplishing this, and discovered how to get JSON containing information about a Tweet — including its HTML — using one of Twitter’s API URLs:
The JSON above drove me to build the following POCO class to represent data returned by that URL:
using System.Runtime.Serialization; namespace Sitecore.Sandbox.Pipelines.RenderField.Tweets { public class Tweet { [DataMember(Name = "cache_age")] public int CacheAgeMilliseconds { get; set; } [DataMember(Name = "url")] public string Url { get; set; } [DataMember(Name = "html")] public string Html { get; set; } } }
I decided to omit some of the JSON properties returned by the Twitter URL from my class above — width and height are examples — since I felt I did not need to use them for this “proof of concept”.
I then leveraged the class above in the following class that will serve as a <renderField> pipeline processor to embed Tweets:
using System; using System.IO; using System.Net; using System.Text.RegularExpressions; using System.Web; using Sitecore.Caching; using Sitecore.Diagnostics; using Sitecore.Pipelines.RenderField; using Newtonsoft.Json; using Newtonsoft.Json.Linq; namespace Sitecore.Sandbox.Pipelines.RenderField.Tweets { public class ExpandTweets { private string TwitterWidgetScriptTag {get ; set; } private string TwitterApiUrlFormat { get; set; } private string _TweetPattern; private string TweetPattern { get { return _TweetPattern; } set { _TweetPattern = value; if (!string.IsNullOrWhiteSpace(_TweetPattern)) { _TweetPattern = HttpUtility.HtmlDecode(_TweetPattern); } } } private HtmlCache _HtmlCache; private HtmlCache HtmlCache { get { if (_HtmlCache == null) { _HtmlCache = CacheManager.GetHtmlCache(Context.Site); } return _HtmlCache; } } public void Process(RenderFieldArgs args) { Assert.ArgumentNotNull(args, "args"); AssertRequired(); if(!ShouldFieldBeProcessed(args)) { return; } args.Result.FirstPart = ExpandTweetUrls(args.Result.FirstPart); } private static bool ShouldFieldBeProcessed(RenderFieldArgs args) { Assert.ArgumentNotNull(args, "args"); Assert.ArgumentNotNull(args.FieldTypeKey, "args.FieldTypeKey"); string fieldTypeKey = args.FieldTypeKey.ToLower(); return fieldTypeKey == "text" || fieldTypeKey == "rich text" || fieldTypeKey == "single-line text" || fieldTypeKey == "multi-line text"; } private void AssertRequired() { Assert.IsNotNullOrEmpty(TwitterWidgetScriptTag, "TwitterWidgetScriptTag must be set! Check your configuration!"); Assert.IsNotNullOrEmpty(TwitterApiUrlFormat, "TwitterApiUrlFormat must be set! Check your configuration!"); Assert.IsNotNullOrEmpty(TweetPattern, "TweetPattern must be set! Check your configuration!"); } protected virtual string ExpandTweetUrls(string html) { string htmlExpanded = html; MatchCollection matches = Regex.Matches(htmlExpanded, TweetPattern, RegexOptions.Compiled | RegexOptions.IgnoreCase); foreach (Match match in matches) { string tweetHtml = GetTweetHtml(match.Groups["id"].Value); if (!string.IsNullOrWhiteSpace(tweetHtml)) { htmlExpanded = htmlExpanded.Replace(match.Value, tweetHtml); } } if (matches.Count > 0) { htmlExpanded = string.Concat(htmlExpanded, TwitterWidgetScriptTag); } return htmlExpanded; } protected virtual string GetTweetHtml(string id) { string html = GetTweetHtmlFromCache(id); if (!string.IsNullOrWhiteSpace(html)) { return html; } Tweet tweet = GetTweetFromApi(id); AddTweetHtmlToCache(id, tweet); return tweet.Html; } private string GetTweetHtmlFromCache(string id) { return HtmlCache.GetHtml(id); } private void AddTweetHtmlToCache(string id, Tweet tweet) { if (string.IsNullOrWhiteSpace(tweet.Html)) { return; } if (tweet.CacheAgeMilliseconds > 0) { HtmlCache.SetHtml(id, tweet.Html, DateTime.Now.AddMilliseconds(tweet.CacheAgeMilliseconds)); return; } HtmlCache.SetHtml(id, tweet.Html); } protected virtual Tweet GetTweetFromApi(string id) { HttpWebRequest request = (HttpWebRequest)WebRequest.Create(string.Format(TwitterApiUrlFormat, id)); try { HttpWebResponse response = (HttpWebResponse)request.GetResponse(); using (StreamReader reader = new StreamReader(response.GetResponseStream())) { var result = reader.ReadToEnd(); JObject jObject = JObject.Parse(result); return JsonConvert.DeserializeObject<Tweet>(jObject.ToString()); } } catch (Exception ex) { Log.Error(this.ToString(), ex, this); } return new Tweet { Html = string.Empty }; } } }
Methods in the class above find all Tweet URLs in the Rich Text, Single-Line Text, or Multi-Line Text field being processed — the code determines if it’s a Tweet URL based on a pattern that is supplied by a configuration setting (you will see this below in this post); extract Tweets’ Twitter identifiers (these are located at the end of the Tweet URLs); and attempt to find the Tweets’ HTML in Sitecore’s HTML cache.
If the HTML is found in cache for a Tweet, we return it. Otherwise, we make a request to Twitter’s API to get it, put it in cache one we have it (it is set to expire after a specified number of milliseconds from the time it was retrieved: Twitter returns the number of milliseconds in one full year by default), and then we return it.
If the returned HTML is not empty, we replace it in the field’s value for display.
If the HTML returned is empty — this could happen when an exception is encountered during the Twitter API call (of course we log the exception in the Sitecore log when this happens 😉 ) — we don’t touch the Tweet URL in the field’s value.
Once all Tweet URLs have been processed, we append a script tag referencing Twitter’s widget.js file — this is supplied through a configuration setting, and it does the heavy lifting on making the Tweet HTML look Twitterific 😉 — to the field’s rendered HTML.
I then tied everything together using the following patch configuration file:
<?xml version="1.0" encoding="utf-8"?> <configuration xmlns:patch="http://www.sitecore.net/xmlconfig/"> <sitecore> <pipelines> <renderField> <processor type="Sitecore.Sandbox.Pipelines.RenderField.Tweets.ExpandTweets, Sitecore.Sandbox" patch:after="processor[@type='Sitecore.Pipelines.RenderField.GetTextFieldValue, Sitecore.Kernel']"> <TwitterWidgetScriptTag><script async src="//platform.twitter.com/widgets.js" charset="utf-8"></script></TwitterWidgetScriptTag> <TwitterApiUrlFormat>https://api.twitter.com/1/statuses/oembed.json?id={0}&omit_script=true</TwitterApiUrlFormat> <TweetPattern>https://twitter.com/.+/status/(?<id>\d*)</TweetPattern> </processor> </renderField> </pipelines> </sitecore> </configuration>
Let’s see this in action!
I created a test Item, and added some legitimate and bogus Tweet URLs into one of its Rich Text fields (please pardon the grammatical issues in the following screenshots :-/):
This isn’t the most aesthetically pleasing HTML, but it will serve its purpose for testing:
After saving and publishing, I navigated to my test Item’s page, and saw this:
If you have any suggestions on making this better, or have other ideas for embedding Tweets in Sitecore, please share in a comment.
Shortcodes in Sitecore: A Proof of Concept
Today I stumbled upon a post in one of the SDN forums asking whether anyone had ever implemented shortcodes in Sitecore.
I have not seen an implementation of this for Sitecore — if you know of one, please drop a comment — but am quite familiar with these in WordPress — I use them to format code in my blog posts using the [code language=”csharp”]//code goes in here[/code] shortcode — and felt I should take on the challenge of implementing a “proof of concept” for this in Sitecore.
I first created a POCO that will hold shortcode data: the shortcode itself and the content (or markup) that the shortcode represents after being expanded:
namespace Sitecore.Sandbox.Pipelines.ExpandShortcodes { public class Shortcode { public string Unexpanded { get; set; } public string Expanded { get; set; } } }
I thought it would be best to put the logic that expands shortcodes into a new pipeline, and defined a pipeline arguments class for it:
using Sitecore.Pipelines; namespace Sitecore.Sandbox.Pipelines.ExpandShortcodes { public class ExpandShortcodesArgs : PipelineArgs { public string Content { get; set; } } }
There really isn’t much to this arguments class — we will only be passing around a string of content that will contain shortcodes to be expanded.
Before moving forward on building pipeline processors for the new pipeline, I saw that I could leverage the template method pattern to help me process collections of Shortcode instances in an abstract base class:
using System.Collections.Generic; using System.Linq; using System.Text.RegularExpressions; using Sitecore.Diagnostics; namespace Sitecore.Sandbox.Pipelines.ExpandShortcodes { public abstract class ExpandShortcodesProcessor { public virtual void Process(ExpandShortcodesArgs args) { if (string.IsNullOrWhiteSpace(args.Content)) { return; } IEnumerable<Shortcode> shortcodes = GetShortcodes(args.Content); if (shortcodes == null || !shortcodes.Any()) { return; } args.Content = ExpandShortcodes(shortcodes, args.Content); } protected abstract IEnumerable<Shortcode> GetShortcodes(string content); protected virtual string ExpandShortcodes(IEnumerable<Shortcode> shortcodes, string content) { Assert.ArgumentNotNull(shortcodes, "shortcodes"); Assert.ArgumentNotNull(content, "content"); string contentExpanded = content; foreach (Shortcode shortcode in shortcodes) { contentExpanded = contentExpanded.Replace(shortcode.Unexpanded, shortcode.Expanded); } return contentExpanded; } } }
The above class iterates over all Shortcode instances, and replaces shortcodes with their expanded content.
Each subclass processor of ExpandShortcodesProcessor are to “fill in the blanks” of the algorithm defined in the base class by implementing the GetShortcodes method only — this is where the heavy lifting of grabbing the shortcodes from the passed string of content, and the expansion of these shortcodes are done. Both are then set in new Shortcode instances.
Once the base class was built, I developed an example ExpandShortcodesProcessor subclass to expand [BigBlueText]content goes in here[/BigBlueText] shortcodes (in case you’re wondering, I completely fabricated this shortcode — it does not exist in the real world):
using System.Collections.Generic; using System.Text.RegularExpressions; namespace Sitecore.Sandbox.Pipelines.ExpandShortcodes { public class ExpandBigBlueTextShortcodes : ExpandShortcodesProcessor { protected override IEnumerable<Shortcode> GetShortcodes(string content) { if(string.IsNullOrWhiteSpace(content)) { return new List<Shortcode>(); } IList<Shortcode> shortcodes = new List<Shortcode>(); MatchCollection matches = Regex.Matches(content, @"\[BigBlueText\](.*?)\[/BigBlueText\]", RegexOptions.IgnoreCase); foreach (Match match in matches) { string innerText = match.Groups[1].Value.Trim(); if (!string.IsNullOrWhiteSpace(innerText)) { shortcodes.Add ( new Shortcode { Unexpanded = match.Value, Expanded = string.Format(@"<span style=""font-size:56px;color:blue;"">{0}</span>", innerText) } ); } } return shortcodes; } } }
I followed the above example processor with another — a new one to expand [YouTube id=”video id goes in here”] shortcodes (this one is made up as well, although YouTube shortcodes do exist out in the wild):
using System.Collections.Generic; using System.Text.RegularExpressions; namespace Sitecore.Sandbox.Pipelines.ExpandShortcodes { public class ExpandYouTubeShortcodes : ExpandShortcodesProcessor { protected override IEnumerable<Shortcode> GetShortcodes(string content) { if(string.IsNullOrWhiteSpace(content)) { return new List<Shortcode>(); } IList<Shortcode> shortcodes = new List<Shortcode>(); MatchCollection matches = Regex.Matches(content, @"\[youtube\s+id=""(.*?)""\]", RegexOptions.IgnoreCase); foreach (Match match in matches) { string id = match.Groups[1].Value.Trim(); if (!string.IsNullOrWhiteSpace(id)) { shortcodes.Add ( new Shortcode { Unexpanded = match.Value, Expanded = string.Format(@"", id) } ); } } return shortcodes; } } }
Next I built a renderField pipeline processor to invoke our new pipeline when the field is a text field of some sort — yes, all fields in Sitecore are fundamentally strings behind the scenes but I’m referring to Single-Line Text, Multi-Line Text, Rich Text, and the deprecated text fields — to expand our shortcodes:
using Sitecore.Diagnostics; using Sitecore.Pipelines; using Sitecore.Pipelines.RenderField; using Sitecore.Sandbox.Pipelines.ExpandShortcodes; namespace Sitecore.Sandbox.Pipelines.RenderField { public class ExpandShortcodes { public void Process(RenderFieldArgs args) { if (!ShouldFieldBeProcessed(args)) { return; } args.Result.FirstPart = GetExpandedShortcodes(args.Result.FirstPart); } private static bool ShouldFieldBeProcessed(RenderFieldArgs args) { Assert.ArgumentNotNull(args, "args"); Assert.ArgumentNotNull(args.FieldTypeKey, "args.FieldTypeKey"); string fieldTypeKey = args.FieldTypeKey.ToLower(); return fieldTypeKey == "text" || fieldTypeKey == "rich text" || fieldTypeKey == "single-line text" || fieldTypeKey == "multi-line text"; } private static string GetExpandedShortcodes(string content) { Assert.ArgumentNotNull(content, "content"); ExpandShortcodesArgs args = new ExpandShortcodesArgs { Content = content }; CorePipeline.Run("expandShortcodes", args); return args.Content; } } }
I cemented all the pieces together using a Sitecore configuration file — this should go in your /App_Config/Include/ folder:
<?xml version="1.0" encoding="utf-8"?> <configuration xmlns:patch="http://www.sitecore.net/xmlconfig/"> <sitecore> <pipelines> <expandShortcodes> <processor type="Sitecore.Sandbox.Pipelines.ExpandShortcodes.ExpandYouTubeShortcodes, Sitecore.Sandbox" /> <processor type="Sitecore.Sandbox.Pipelines.ExpandShortcodes.ExpandBigBlueTextShortcodes, Sitecore.Sandbox" /> </expandShortcodes> <renderField> <processor type="Sitecore.Sandbox.Pipelines.RenderField.ExpandShortcodes, Sitecore.Sandbox" patch:after="processor[@type='Sitecore.Pipelines.RenderField.GetTextFieldValue, Sitecore.Kernel']" /> </renderField> </pipelines> </sitecore> </configuration>
Let’s see the above code in action.
I created a test item, and added BigBlueText and YouTube shortcodes into two different text fields:
I saved, published, and then navigated to the test item:
As you can see, our shortcodes were expanded.
If you have any thoughts on this, or ideas around a better shortcode framework for Sitecore, please share in a comment.
Custom Sitecore Rich Text Editor Button: Inserting Dynamic Content
Last Thursday, I stumbled upon an article discussing how to create and add a custom button to the Rich Text Editor in Sitecore. This article referenced an article written by Mark Stiles — his article set the foundation for me to do this very thing last Spring for a client.
Unlike the two articles above, I had to create two different buttons to insert dynamic content — special html containing references to other items in the Sitecore content tree via Item IDs — which I would ‘fix’ via a RenderField pipeline when a user would visit the page containing this special html. I had modeled my code around the ‘Insert Link’ button by delegating to a helper class to ‘expand’ my dynamic content as the LinkManager class does for Sitecore links.
The unfortunate thing is I cannot show you that code – it’s proprietary code owned by a previous employer.
Instead, I decided to build something similar to illustrate how I did this. I will insert special html that will ultimately transform into jQuery UI dialogs.
First, I needed to create items that represent dialog boxes. I created a new template with two fields — one field containing the dialog box’s heading and the other field containing copy that will go inside of the dialog box:
I then created three dialog box items with content that we will use later on when testing:
With the help of xml defined in /sitecore/shell/Controls/Rich Text Editor/InsertLink/InsertLink.xml and /sitecore/shell/Controls/Rich Text Editor/InsertImage/InsertImage.xml, I created my new xml control definition in a file named /sitecore/shell/Controls/Rich Text Editor/InsertDialog/InsertDialog.xml:
<?xml version="1.0" encoding="utf-8" ?> <control xmlns:def="Definition" xmlns="http://schemas.sitecore.net/Visual-Studio-Intellisense"> <RichText.InsertDialog> <!-- Don't forget to set your icon 🙂 --> <FormDialog Icon="Business/32x32/message.png" Header="Insert a Dialog" Text="Select the dialog content item you want to insert." OKButton="Insert Dialog"> <!-- js reference to my InsertDialog.js script. --> <!-- For some strange reason, if the period within the script tag is not present, the dialog form won't work --> <script Type="text/javascript" src="/sitecore/shell/Controls/Rich Text Editor/InsertDialog/InsertDialog.js">.</script> <!-- Reference to my InsertDialogForm class --> <CodeBeside Type="Sitecore.Sandbox.RichTextEditor.InsertDialog.InsertDialogForm,Sitecore.Sandbox" /> <!-- Root contains the ID of /sitecore/content/Dialog Content Items --> <DataContext ID="DialogFolderDataContext" Root="{99B14D44-5A0F-43B6-988E-94197D73B348}" /> <GridPanel Width="100%" Height="100%" Style="table-layout:fixed"> <GridPanel Width="100%" Height="100%" Style="table-layout:fixed" Columns="3" GridPanel.Height="100%"> <Scrollbox Class="scScrollbox scFixSize" Width="100%" Height="100%" Background="white" Border="1px inset" Padding="0" GridPanel.Height="100%" GridPanel.Width="50%" GridPanel.Valign="top"> <TreeviewEx ID="DialogContentItems" DataContext="DialogFolderDataContext" Root="true" /> </Scrollbox> </GridPanel> </GridPanel> </FormDialog> </RichText.InsertDialog> </control>
My dialog form will house one lonely TreeviewEx containing all dialog items in the /sitecore/content/Dialog Content Items folder I created above.
I then created the ‘CodeBeside’ DialogForm class to accompany the xml above:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Sitecore.Data; using Sitecore.Data.Items; using Sitecore.Diagnostics; using Sitecore.Shell.Framework; using Sitecore.Web; using Sitecore.Web.UI.HtmlControls; using Sitecore.Web.UI.Pages; using Sitecore.Web.UI.Sheer; using Sitecore.Web.UI.WebControls; namespace Sitecore.Sandbox.RichTextEditor.InsertDialog { public class InsertDialogForm : DialogForm { protected DataContext DialogFolderDataContext; protected TreeviewEx DialogContentItems; protected string Mode { get { string mode = StringUtil.GetString(base.ServerProperties["Mode"]); if (!string.IsNullOrEmpty(mode)) { return mode; } return "shell"; } set { Assert.ArgumentNotNull(value, "value"); base.ServerProperties["Mode"] = value; } } protected override void OnLoad(EventArgs e) { Assert.ArgumentNotNull(e, "e"); base.OnLoad(e); if (!Context.ClientPage.IsEvent) { Inialize(); } } private void Inialize() { SetMode(); SetDialogFolderDataContextFromQueryString(); } private void SetMode() { Mode = WebUtil.GetQueryString("mo"); } private void SetDialogFolderDataContextFromQueryString() { DialogFolderDataContext.GetFromQueryString(); } protected override void OnOK(object sender, EventArgs args) { Assert.ArgumentNotNull(sender, "sender"); Assert.ArgumentNotNull(args, "args"); string selectedItemID = GetSelectedItemIDAsString(); if (string.IsNullOrEmpty(selectedItemID)) { return; } string selectedItemPath = GetSelectedItemPath(); string javascriptArguments = string.Format("{0}, {1}", EscapeJavascriptString(selectedItemID), EscapeJavascriptString(selectedItemPath)); if (IsWebEditMode()) { SheerResponse.SetDialogValue(javascriptArguments); base.OnOK(sender, args); } else { string closeJavascript = string.Format("scClose({0})", javascriptArguments); SheerResponse.Eval(closeJavascript); } } private string GetSelectedItemIDAsString() { ID selectedID = GetSelectedItemID(); if (selectedID != ID.Null) { return selectedID.ToString(); } return string.Empty; } private ID GetSelectedItemID() { Item selectedItem = GetSelectedItem(); if (selectedItem != null) { return selectedItem.ID; } return ID.Null; } private string GetSelectedItemPath() { Item selectedItem = GetSelectedItem(); if (selectedItem != null) { return selectedItem.Paths.FullPath; } return string.Empty; } private Item GetSelectedItem() { return DialogContentItems.GetSelectionItem(); } private static string EscapeJavascriptString(string stringToEscape) { return StringUtil.EscapeJavascriptString(stringToEscape); } protected override void OnCancel(object sender, EventArgs args) { Assert.ArgumentNotNull(sender, "sender"); Assert.ArgumentNotNull(args, "args"); if (IsWebEditMode()) { base.OnCancel(sender, args); } else { SheerResponse.Eval("scCancel()"); } } private bool IsWebEditMode() { return string.Equals(Mode, "webedit", StringComparison.InvariantCultureIgnoreCase); } } }
This DialogForm basically sends a selected Item’s ID and path back to the client via the scClose() function defined below in a new file named /sitecore/shell/Controls/Rich Text Editor/InsertDialog/InsertDialog.js:
function GetDialogArguments() { return getRadWindow().ClientParameters; } function getRadWindow() { if (window.radWindow) { return window.radWindow; } if (window.frameElement && window.frameElement.radWindow) { return window.frameElement.radWindow; } return null; } var isRadWindow = true; var radWindow = getRadWindow(); if (radWindow) { if (window.dialogArguments) { radWindow.Window = window; } } function scClose(dialogContentItemId, dialogContentItemPath) { // we're passing back an object holding data needed for inserting our special html into the RTE var dialogInfo = { dialogContentItemId: dialogContentItemId, dialogContentItemPath: dialogContentItemPath }; getRadWindow().close(dialogInfo); } function scCancel() { getRadWindow().close(); } if (window.focus && Prototype.Browser.Gecko) { window.focus(); }
I then had to add a new javascript command in /sitecore/shell/Controls/Rich Text Editor/RichText Commands.js to open my dialog form and map this to a callback function — which I named scInsertDialog to follow the naming convention of other callbacks within this script file — to handle the dialogInfo javascript object above that is passed to it:
RadEditorCommandList["InsertDialog"] = function(commandName, editor, args) { scEditor = editor; editor.showExternalDialog( "/sitecore/shell/default.aspx?xmlcontrol=RichText.InsertDialog&la=" + scLanguage, null, //argument 500, 400, scInsertDialog, //callback null, // callback args "Insert Dialog", true, //modal Telerik.Web.UI.WindowBehaviors.Close, // behaviors false, //showStatusBar false //showTitleBar ); }; function scInsertDialog(sender, dialogInfo) { if (!dialogInfo) { return; } // build our special html to insert into the RTE var placeholderHtml = "<hr class=\"dialog-placeholder\" style=\"width: 100px; display: inline-block; height: 20px;border: blue 4px solid;\"" + "data-dialogContentItemId=\"" + dialogInfo.dialogContentItemId +"\" " + "title=\"Dialog Content Path: " + dialogInfo.dialogContentItemPath + "\" />"; scEditor.pasteHtml(placeholderHtml, "DocumentManager"); }
My callback function builds the special html that will be inserted into the Rich Text Editor. I decided to use a <hr /> tag to keep my html code self-closing — it’s much easier to use a self-closing html tag when doing this, since you don’t have to check whether you’re inserting more special html into preexisting special html. I also did this for the sake of brevity.
I am using the title attribute in my special html in order to assist content authors in knowing which dialog items they’ve inserted into rich text fields. When a dialog blue box is hovered over, a tooltip containing the dialog item’s content path will display.
I’m not completely satisfied with building my special html in this javascript file. It probably should be moved into C# somewhere to prevent the ease of changing it — someone could easily just change it without code compilation, and break how it’s rendered to users. We need this html to be a certain way when ‘fixing’ it in our RenderField pipeline defined later in this article.
I then went into the core database and created a new Rich Text Editor profile under /sitecore/system/Settings/Html Editor Profiles:
Next, I created a new Html Editor Button (template: /sitecore/templates/System/Html Editor Profiles/Html Editor Button) using the __Html Editor Button master — wow, I never thought I would use the word master again when talking about Sitecore stuff 🙂 — and set its click and icon fields:
Now, we need to ‘fix’ our special html by converting it into presentable html to the user. I do this using the following RenderField pipeline:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Sitecore; using Sitecore.Data.Items; using Sitecore.Diagnostics; using Sitecore.Links; using Sitecore.Pipelines.RenderField; using Sitecore.Xml.Xsl; using HtmlAgilityPack; namespace Sitecore.Sandbox.Pipelines.RenderField { public class ExpandDialogContent { public void Process(RenderFieldArgs renderFieldArgs) { if (ShouldFieldBeProcessed(renderFieldArgs)) { ExpandDialogContentTags(renderFieldArgs); } } private bool ShouldFieldBeProcessed(RenderFieldArgs renderFieldArgs) { return renderFieldArgs.FieldTypeKey.ToLower() == "rich text"; } private void ExpandDialogContentTags(RenderFieldArgs renderFieldArgs) { HtmlNode documentNode = GetHtmlDocumentNode(renderFieldArgs.Result.FirstPart); HtmlNodeCollection dialogs = documentNode.SelectNodes("//hr[@class='dialog-placeholder']"); foreach (HtmlNode dialogPlaceholder in dialogs) { HtmlNode dialog = CreateDialogHtmlNode(dialogPlaceholder); if (dialog != null) { dialogPlaceholder.ParentNode.ReplaceChild(dialog, dialogPlaceholder); } else { dialogPlaceholder.ParentNode.RemoveChild(dialogPlaceholder); } } renderFieldArgs.Result.FirstPart = documentNode.InnerHtml; } private HtmlNode GetHtmlDocumentNode(string html) { HtmlDocument htmlDocument = CreateNewHtmlDocument(html); return htmlDocument.DocumentNode; } private HtmlDocument CreateNewHtmlDocument(string html) { HtmlDocument htmlDocument = new HtmlDocument(); htmlDocument.LoadHtml(html); return htmlDocument; } private HtmlNode CreateDialogHtmlNode(HtmlNode dialogPlaceholder) { string dialogContentItemId = dialogPlaceholder.Attributes["data-dialogContentItemId"].Value; Item dialogContentItem = TryGetItem(dialogContentItemId); if(dialogContentItem != null) { string heading = dialogContentItem["Dialog Heading"]; string content = dialogContentItem["Dialog Content"]; return CreateDialogHtmlNode(dialogPlaceholder.OwnerDocument, heading, content); } return null; } private Item TryGetItem(string id) { try { return Context.Database.Items[id]; } catch (Exception ex) { Log.Error(this.ToString(), ex, this); } return null; } private static HtmlNode CreateDialogHtmlNode(HtmlDocument htmlDocument, string heading, string content) { if (string.IsNullOrEmpty(content)) { return null; } HtmlNode dialog = htmlDocument.CreateElement("div"); dialog.Attributes.Add("class", "dialog"); dialog.Attributes.Add("title", heading); dialog.InnerHtml = content; return dialog; } } }
The above uses Html Agility Pack for finding all instances of my special <hr /> tags and creates new html that my jQuery UI dialog code expects. If you’re not using Html Agility Pack, I strongly recommend checking it out — it has saved my hide on numerous occasions.
I then inject this RenderField pipeline betwixt others via a new patch include file named /App_Config/Include/ExpandDialogContent.config:
<?xml version="1.0" encoding="utf-8"?> <configuration xmlns:patch="http://www.sitecore.net/xmlconfig/"> <sitecore> <pipelines> <renderField> <processor type="Sitecore.Sandbox.Pipelines.RenderField.ExpandDialogContent, Sitecore.Sandbox" patch:after="processor[@type='Sitecore.Pipelines.RenderField.GetInternalLinkFieldValue, Sitecore.Kernel']" /> </renderField> </pipelines> </sitecore> </configuration>
Now, it’s time to see if all of my hard work above has paid off.
I set the rich text field on my Sample Item template to use my new Rich Text Editor profile:
Using the template above, I created a new test item, and opened its rich text field’s editor:
I then clicked my new ‘Insert Dialog’ button and saw Dialog items I could choose to insert:
Since I’m extremely excited, I decided to insert them all:
I then forgot which dialog was which — the three uniform blue boxes are throwing me off a bit — so I hovered over the first blue box and saw that it was the first dialog item:
I then snuck a look at the html inserted — it was formatted the way I expected:
I then saved my item, published and navigated to my test page. My RenderField pipeline fixed the special html as I expected:
I would like to point out that I had to add link and script tags to reference jQuery UI’s css and js files — including the jQuery library — and initialized my dialogs using the jQuery UI Dialog constructor. I have omitted this code.
This does seem like a lot of code to get something so simple to work.
However, it is worth the effort. Not only will you impress your boss and make your clients happy, you’ll also be dubbed the ‘cool kid’ at parties. You really will, I swear. 🙂
Until next time, have a Sitecoretastic day!