Creating a dynamic image in Rich Text fields

Have you ever inserted an image, then changed its alt or title tags in the Media Library and noticed that the change does not propagate into the rich text field? It’s because Sitecore only inserts static values into the field HTML when you insert an image. If you’ve ever wanted or needed those images to act dynamically – so that changing alt or title text affects the field HTML -then this article might help you.

The Secret? Tokens!

We can modify the rich text editor dialogs so that when a user inserts Sitecore media, the ALT and TITLE text being sent is actually just a token – i.e. {{alt}}. There is no specific syntax required, just use something that you like. That means that we’re actually inserting “{{alt}}” and “{{title}}” into the field HTML, not the actual (static) values. The goal then is to create a pipeline processor that will read the field and look for those tokens, and replace them with the current values of the Alt and Title fields of the media item.

Customizing the InsertImage dialog

The first thing we will want to do is modify the InsertImage dialog. The InsertImage dialog is a Sitecore dialog, and the source can be found with any Sitecore installation. You would need two files:

  1. The InsertImage.xml file for the dialog, which can be found in the webroot of your site under sitecore\shell\Controls\Rich Text Editor/InsertImage.
  2. The InsertImageForm.cs file (code behind file) which can be extracted from the Sitecore.Client.dll. You can use .NET Reflector, DotPeek, or JustDecompile (I personally use the last one). Look for a Sitecore.Shell.Controls.RichTextEditor.InsertImage entry.

You will want to take these two files and preferably put them in your solution. Place these in a new folder, e.g. Controls/RichTextEditor/InsertSitecoreMediaExtended and make the following changes:

  • Keep the .xml file name the same. In the .xml file, there is a line which points to the code behind file – update that with the location of the file in the solution and the assembly name.
  • Update the name of the .cs file to match the parent folder (InsertSitecoreMediaExtended.cs). In that file, remove everything except the OnOK and SetDimensions methods. You will need to modify the OnOK method so that alt and title are set using tokens:
image.Add("Alt", StringUtil.EscapeQuote("{{alt}}"));
image.Add("Title", StringUtil.EscapeQuote("{{title}}"));

Optional: You can edit the Telerik.Web.UI.Editor.DialogControls.SetImageProperties dialog by adding a title field and checkboxes next to the alt and title fields to make it easier for content editors to specify this option.

Let’s make a new pipeline!

You will want to extend the RenderField pipeline in Sitecore.Kernel, specifically the GetFieldValue processor. So when Sitecore gets the value of the RTE field, we’re going to modify the HTML by swapping tokens for media item values. Create a new folder in your pipelines folder or project named GetFieldValueExtended, and a new class file under it with the same name.

Now you’ll need to tell Sitecore to run your custom processor. There are a few options – patch:before, patch:after or overwrite completely. I personally used the patch:after option. If you choose to overwrite, make sure your processor implements all of the same code as the original. Create a new patch file in the App_Config/Include folder similar to the below. (In my case, the solution has a Processor project.)

<configuration xmlns:patch="http://www.sitecore.net/xmlconfig/">
    <sitecore>
        <pipelines>
            <renderField>
                <processor
                    type="MyProject.Processor.RenderField.GetFieldValueExtended, MyProject.Processor"
                    patch:after="processor[@type='Sitecore.Pipelines.RenderField.GetFieldValue, Sitecore.Kernel']" />
            </renderField>
        </pipelines>
    </sitecore>
</configuration>

In your custom processor class file, set up the Process event with some Asserts and other logic needed before doing the swap. Create the tokens as constants for flexibility. Here is the full code used, which is currently running in a production environment with no issues. I highly recommend HtmlAgilityPack for spelunking in the HTML. (NOTE: The code assumes your production environment Sitecore database is web, which may not be true in your case.)

    public class GetFieldValueExtended
    {
        private const string AltToken = "{{alt}}";
        private const string TitleToken = "{{title}}";

        public void Process(RenderFieldArgs args)
        {
            Assert.ArgumentNotNull(args, "args");
            Assert.ArgumentNotNull(args.Item, "args.Item");
            Assert.ArgumentNotNull(args.Item.Database, "args.Item.Database");
            Assert.ArgumentNotNull(args.GetField(), "args.GetField()");

            if (args.Item.Database.Name.Equals("web"))
            {
                if (args.GetField().Value.Contains(AltToken) || args.GetField().Value.Contains(TitleToken))
                {
                    args.Result.FirstPart =  ReplaceTokens(args.GetField().Value);
                }
            }
        }

        private string ReplaceTokens(string fieldValue)
        {
            if (fieldValue.Contains("img") == false) return fieldValue;

            var document = new HtmlAgilityPack.HtmlDocument();
            document.LoadHtml(fieldValue);

            foreach (var img in document.DocumentNode.Descendants("img"))
            {
                var imgSrc = img.Attributes["src"];
                if (imgSrc == null) continue;

                // Remove query string from src (if it exists)
                var mediaUrl = CleanImageSource(imgSrc.Value);

                // Get media item ID based on media url
                DynamicLink dynamicLink;
                if (!DynamicLink.TryParse(mediaUrl, out dynamicLink)) continue;
                MediaItem mediaItem = Sitecore.Context.Database.GetItem(dynamicLink.ItemId,
                    dynamicLink.Language ?? Sitecore.Context.Language);

                // Replace the tokens
                if (img.Attributes["alt"] != null && img.Attributes["alt"].Value.Trim() == AltToken)
                {
                    img.Attributes["alt"].Value = mediaItem.Alt;
                }

                if (img.Attributes["title"] != null && img.Attributes["title"].Value.Trim() == TitleToken)
                {
                    img.Attributes["title"].Value = mediaItem.Title;
                }
            }

            return document.DocumentNode.OuterHtml;
        }

        private string CleanImageSource(string imgSrcValue)
        {
            // First match the SHA1
            var shaMatcher = new Regex("\b[0-9a-f]{5,40}\b");
            var match = shaMatcher.Match(imgSrcValue);

            if (match.Success)
            {
                // Setup media url
                return string.Format("/~/media/{0}.ashx", match.Value);
            }

            return imgSrcValue;
        }
    }

 

Completion

Overall, this was a great feature that the client needed as they tried to make their website ADA compliant, by including the appropriate alt and title text values. I hope this helps you in your Sitecore development adventures.

How to Remove Up/Down Arrow Icons from a TreeList field in Sitecore

I was recently requested to update one of our client’s TreeList fields so that the Selected list was alphabetically sorted. Part of this change was to hide those blue up/down arrow buttons to the right of the selected list on the field. While it’s not as easy as I was hoping it would be, I found a solution for this. It involves rendering the field in a completely different way – through code.

2015-12-01 09_02_06-Sitecore

First, add a new class file for your field type. I put mine under a Fields folder in my project, but it can be anywhere technically. Make no changes to the class at this point.

Next, create a new field type in Sitecore. To do that, in the Core database, navigate to sitecore/system/Field types/List Types. Right click the List Type folder and create your list type – I believe it should be created from the System/Templates/Template field type. Once created, fill in the Assembly (Visual Studio Project name) and Class (Visual Studio path to your field type class) fields. Save and publish the list type.

 

2015-11-30 18_13_26-Sitecore

 

Next,we will implement the rendering change for our new field. I used Reflector to get the source from Treeist.cs. It’s actually in the OnLoad event, which I found interesting. Anyway, I have supplied a code sample – note it’s rather long; Sitecore is basically gathering all the info, and assembling the HTML dynamically:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.UI;
using Sitecore;
using Sitecore.Configuration;
using Sitecore.Data;
using Sitecore.Data.Fields;
using Sitecore.Data.Items;
using Sitecore.Diagnostics;
using Sitecore.Globalization;
using Sitecore.Resources;
using Sitecore.SecurityModel;
using Sitecore.Shell.Applications.ContentEditor;
using Sitecore.Web.UI.HtmlControls;
using Sitecore.Web.UI.Sheer;
using Sitecore.Web.UI.WebControls;

namespace Your.Namespace.Here
{
    public class AlphaTreeList : TreeList
    {
        private Listbox _listBox;

        protected override void OnLoad(EventArgs e)
        {
            RenderTreeListWithoutUpDownArrows(e);
        }

        private string FormTemplateFilterForDisplay()
        {
            // Taken from TreeList.cs using reflector

            if ((string.IsNullOrEmpty(this.IncludeTemplatesForDisplay) && string.IsNullOrEmpty(this.ExcludeTemplatesForDisplay)) && (string.IsNullOrEmpty(this.IncludeItemsForDisplay) && string.IsNullOrEmpty(this.ExcludeItemsForDisplay)))
            {
                return string.Empty;
            }
            string str = string.Empty;
            string str2 = ("," + this.IncludeTemplatesForDisplay + ",").ToLowerInvariant();
            string str3 = ("," + this.ExcludeTemplatesForDisplay + ",").ToLowerInvariant();
            string str4 = "," + this.IncludeItemsForDisplay + ",";
            string str5 = "," + this.ExcludeItemsForDisplay + ",";
            if (!string.IsNullOrEmpty(this.IncludeTemplatesForDisplay))
            {
                if (!string.IsNullOrEmpty(str))
                {
                    str = str + " and ";
                }
                str = str + string.Format("(contains('{0}', ',' + @@templateid + ',') or contains('{0}', ',' + @@templatekey + ','))", str2);
            }
            if (!string.IsNullOrEmpty(this.ExcludeTemplatesForDisplay))
            {
                if (!string.IsNullOrEmpty(str))
                {
                    str = str + " and ";
                }
                str = str + string.Format("not (contains('{0}', ',' + @@templateid + ',') or contains('{0}', ',' + @@templatekey + ','))", str3);
            }
            if (!string.IsNullOrEmpty(this.IncludeItemsForDisplay))
            {
                if (!string.IsNullOrEmpty(str))
                {
                    str = str + " and ";
                }
                str = str + string.Format("(contains('{0}', ',' + @@id + ',') or contains('{0}', ',' + @@key + ','))", str4);
            }
            if (string.IsNullOrEmpty(this.ExcludeItemsForDisplay))
            {
                return str;
            }
            if (!string.IsNullOrEmpty(str))
            {
                str = str + " and ";
            }
            return (str + string.Format("not (contains('{0}', ',' + @@id + ',') or contains('{0}', ',' + @@key + ','))", str5));
        }

        private void RenderTreeListWithoutUpDownArrows(EventArgs args)
        {
            // Taken from TreeList.cs OnLoad() using reflector

            Assert.ArgumentNotNull(args, "args");

            if (!Sitecore.Context.ClientPage.IsEvent)
            {
                this.SetProperties();
                GridPanel panel = new GridPanel();
                this.Controls.Add(panel);
                panel.Columns = 4;
                this.GetControlAttributes();
                foreach (string str in base.Attributes.Keys)
                {
                    panel.Attributes.Add(str, base.Attributes[str]);
                }
                panel.Attributes["id"] = this.ID;
                panel.Style["margin"] = "0px 0px 4px 0px";
                base.SetViewStateString("ID", this.ID);
                Literal literal = new Literal("All")
                {
                    Class = "scContentControlMultilistCaption"
                };
                panel.Controls.Add(literal);
                panel.SetExtensibleProperty(literal, "Width", "50%");
                panel.SetExtensibleProperty(literal, "Row.Height", "20px");
                LiteralControl control = new LiteralControl(Images.GetSpacer(0x18, 1));
                panel.Controls.Add(control);
                panel.SetExtensibleProperty(control, "Width", "24px");
                literal = new Literal("Selected")
                {
                    Class = "scContentControlMultilistCaption"
                };
                panel.Controls.Add(literal);
                panel.SetExtensibleProperty(literal, "Width", "50%");
                control = new LiteralControl(Images.GetSpacer(0x18, 1));
                panel.Controls.Add(control);
                panel.SetExtensibleProperty(control, "Width", "24px");
                Scrollbox scrollbox = new Scrollbox();
                scrollbox.ID = Sitecore.Web.UI.HtmlControls.Control.GetUniqueID("S");
                panel.Controls.Add(scrollbox);
                if (!UIUtil.IsIE())
                {
                    scrollbox.Padding = "0px";
                }
                scrollbox.Style["border"] = UIUtil.IsIE() ? ((string)"3px window-inset") : ((string)"2px inset silver");
                object obj2 = base.ServerProperties["SetMasters.FixBorder"];
                if (((UIUtil.IsFirefox() && (obj2 != null)) && (obj2.ToString() == "true")) || UIUtil.IsWebkit())
                {
                    scrollbox.Style["height"] = "100%";
                    scrollbox.Style["-moz-box-sizing"] = "border-box";
                }
                panel.SetExtensibleProperty(scrollbox, "rowspan", "2");
                panel.SetExtensibleProperty(scrollbox, "VAlign", "top");
                TreeviewEx ex = new TreeviewEx();
                ex.ID = this.ID + "_all";
                scrollbox.Controls.Add(ex);
                ex.DblClick = this.ID + ".Add";
                ex.AllowDragging = false;
                ImageBuilder builder = new ImageBuilder
                {
                    Src = "Applications/16x16/nav_right_blue.png",
                    ID = this.ID + "_right",
                    Width = 0x10,
                    Height = 0x10,
                    Margin = UIUtil.IsIE() ? ((string)"2px") : ((string)"2px 0px 2px 2px"),
                    OnClick = Sitecore.Context.ClientPage.GetClientEvent(this.ID + ".Add")
                };
                ImageBuilder builder2 = new ImageBuilder
                {
                    Src = "Applications/16x16/nav_left_blue.png",
                    ID = this.ID + "_left",
                    Width = 0x10,
                    Height = 0x10,
                    Margin = UIUtil.IsIE() ? ((string)"2px") : ((string)"2px 0px 2px 2px"),
                    OnClick = Sitecore.Context.ClientPage.GetClientEvent(this.ID + ".Remove")
                };
                LiteralControl control2 = new LiteralControl(builder + "<br/>" + builder2);
                panel.Controls.Add(control2);
                panel.SetExtensibleProperty(control2, "Width", "30");
                panel.SetExtensibleProperty(control2, "Align", "center");
                panel.SetExtensibleProperty(control2, "VAlign", "top");
                panel.SetExtensibleProperty(control2, "rowspan", "2");
                Listbox listbox = new Listbox();
                panel.Controls.Add(listbox);
                panel.SetExtensibleProperty(listbox, "VAlign", "top");
                panel.SetExtensibleProperty(listbox, "Height", "100%");
                this._listBox = listbox;
                listbox.ID = this.ID + "_selected";
                listbox.DblClick = this.ID + ".Remove";
                listbox.Style["width"] = "100%";
                listbox.Size = "10";
                listbox.Attributes["onchange"] = "javascript:document.getElementById('" + this.ID +
                                                 "_help').innerHTML=this.selectedIndex>=0?this.options[this.selectedIndex].innerHTML:''";
                listbox.Attributes["class"] = "scContentControlMultilistBox";
                this._listBox.TrackModified = false;
                ex.Enabled = !this.ReadOnly;
                listbox.Disabled = this.ReadOnly;
                panel.SetExtensibleProperty(control2, "Width", "30");
                panel.SetExtensibleProperty(control2, "Align", "center");
                panel.SetExtensibleProperty(control2, "VAlign", "top");
                panel.SetExtensibleProperty(control2, "rowspan", "2");
                panel.Controls.Add(new LiteralControl("
")); DataContext context = new DataContext(); panel.Controls.Add(context); context.ID = Sitecore.Web.UI.HtmlControls.Control.GetUniqueID("D"); context.Filter = this.FormTemplateFilterForDisplay(); ex.DataContext = context.ID; ex.DisplayFieldName = this.DisplayFieldName; context.DataViewName = "Master"; if (!string.IsNullOrEmpty(this.DatabaseName)) { context.Parameters = "databasename=" + this.DatabaseName; } context.Root = this.DataSource; context.Language = Language.Parse(this.ItemLanguage); panel.Fixed = true; ex.ShowRoot = true; panel.SetExtensibleProperty(scrollbox, "Height", "100%"); this.RestoreState(); } } private void RestoreState() { // Taken from TreeList.cs using reflector string[] strArray = this.Value.Split((char[])new char[] { '|' }); if (strArray.Length > 0) { Database contentDatabase = Sitecore.Context.ContentDatabase; if (!string.IsNullOrEmpty(this.DatabaseName)) { contentDatabase = Factory.GetDatabase(this.DatabaseName); } for (int i = 0; i < strArray.Length; i = (int)(i + 1)) { string path = strArray[i]; if (!string.IsNullOrEmpty(path)) { ListItem item = new ListItem(); item.ID = Sitecore.Web.UI.HtmlControls.Control.GetUniqueID("I"); this._listBox.Controls.Add(item); item.Value = item.ID + "|" + path; Item item2 = contentDatabase.GetItem(path); if (item2 != null) { item.Header = this.GetHeaderValue(item2); } else { item.Header = path + ' ' + Translate.Text("[Item not found]"); } } } SheerResponse.Refresh(this._listBox); } } private void SetProperties() { // Taken from TreeList.cs using reflector string id = StringUtil.GetString((string[])new string[] { this.Source }); if (Sitecore.Data.ID.IsID(id)) { this.DataSource = this.Source; } else if ((this.Source != null) && !id.Trim().StartsWith("/", StringComparison.OrdinalIgnoreCase)) { this.ExcludeTemplatesForSelection = StringUtil.ExtractParameter("ExcludeTemplatesForSelection", this.Source).Trim(); this.IncludeTemplatesForSelection = StringUtil.ExtractParameter("IncludeTemplatesForSelection", this.Source).Trim(); this.IncludeTemplatesForDisplay = StringUtil.ExtractParameter("IncludeTemplatesForDisplay", this.Source).Trim(); this.ExcludeTemplatesForDisplay = StringUtil.ExtractParameter("ExcludeTemplatesForDisplay", this.Source).Trim(); this.ExcludeItemsForDisplay = StringUtil.ExtractParameter("ExcludeItemsForDisplay", this.Source).Trim(); this.IncludeItemsForDisplay = StringUtil.ExtractParameter("IncludeItemsForDisplay", this.Source).Trim(); string str2 = StringUtil.ExtractParameter("AllowMultipleSelection", this.Source).Trim().ToLowerInvariant(); this.AllowMultipleSelection = (bool)(string.Compare(str2, "yes", StringComparison.InvariantCultureIgnoreCase) == 0); this.DataSource = StringUtil.ExtractParameter("DataSource", this.Source).Trim().ToLowerInvariant(); this.DatabaseName = StringUtil.ExtractParameter("databasename", this.Source).Trim().ToLowerInvariant(); } else { this.DataSource = this.Source; } } } }

The above code is a bit different from the source I pulled with reflector. I had to change a number of unrecognizable method calls, like get_Item get_ID. For example,

panel.Attributes.set_Item("id", this.get_ID());

would become

panel.Attributes["id"] = this.ID;

Also, I did not call base.OnLoad() after the rendering code above. If you do, you may get errors in Sitecore. Looking at the logs you might get errors saying, “Multiple controls with the same ID ‘Field[SomeNumber]_all’ were found.”. Make sure not to render the field twice. 😉

Finally, notice that the RenderTrreeListWithoutUpDownArrows() submethod is missing the code that adds the up and down arrows – this was my objective:

ImageBuilder builder3 = new ImageBuilder
            {
                Src = "Applications/16x16/nav_up_blue.png",
                ID = this.ID + "_up",
                Width = 0x10,
                Height = 0x10,
                Margin = "2px",
                OnClick = Sitecore.Context.ClientPage.GetClientEvent(this.ID + ".Up")
            };
            ImageBuilder builder4 = new ImageBuilder
            {
                Src = "Applications/16x16/nav_down_blue.png",
                ID = this.ID + "_down",
                Width = 0x10,
                Height = 0x10,
                Margin = "2px",
                OnClick = Sitecore.Context.ClientPage.GetClientEvent(this.ID + ".Down")
            };
            control2 = new LiteralControl(builder3 + "<br/>" + builder4);
            panel.Controls.Add(control2);

You could also do this for left and right arrows, or another element of the field.

Finally, change the field type on your item’s template to your new custom field type, and publish.

The result is a custom TreeList field that simply does not have up/down arrows.

2015-12-01 09_05_42-Sitecore

I hope this helps you. I will write another blog about how I handled sorting my custom TreeList field’s selected section alphabetically, so look for that  to pop up soon. If you have any questions, feel free to comment.

 

Sitecore publish skips items

I recently came into a situation where I would publish an item and the log at the end of the publish wizard would inform me that the item was skipped for one of my environments (pub), but the web database was updated fine.

So every time I made a change to this item it would not show on pub. I tried transferring the item from master -> pub, which worked, but when a user later published the item, it was removed from pub and was no longer available.

The ‘simple’ fix for this problem is to use the Republish Everything setting, instead of ‘Smart Publish’, but that fix did not work in my situation.

By doing some digging into the item’s field sections, I found one called Publishing. In it was a field called Publishing targets. I noticed that Staging (‘web’) was selected but Production (‘pub’) was not. So I checked the box for Production, saved and published the item, and… it worked!

I’m not sure how this setting got changed. One interesting note is that if no target is checked, then Sitecore will publish to ALL targets. Check this field section out if you ever run into this problem. You can also set this on the Publish tab -> Change by clicking on the Targets tab and checking the box of a target.