Quantcast
Channel: Pipeline – SitecoreJunkie.com
Viewing all articles
Browse latest Browse all 51

Set Default Alternate Text on Images Uploaded to the Sitecore Media Library

$
0
0

For the past couple of years, I have been trying to come up with an idea for adding a custom <getMediaCreatorOptions> pipeline processor — this is no lie or exaggeration — but had not thought of any good reason to do so until today: I figured out that I could add a processor to set default alternate text on an image being uploaded into the Sitecore Media Library.

The following class contains code to serve as a <getMediaCreatorOptions> pipeline processor to set default alternate text on an image Item during upload:

using Sitecore.Diagnostics;
using Sitecore.Pipelines.GetMediaCreatorOptions;

namespace Sitecore.Sandbox.Pipelines.GetMediaCreatorOptions
{
    public class SetDefaultAlternateTextIfNeed
    {
        public void Process(GetMediaCreatorOptionsArgs args)
        {
            Assert.ArgumentNotNull(args, "args");
            if (!string.IsNullOrWhiteSpace(args.Options.AlternateText))
            {
                return;
            }

            args.Options.AlternateText = GetAlternateText(args);
        }

        protected virtual string GetAlternateText(GetMediaCreatorOptionsArgs args)
        {
            Assert.ArgumentNotNull(args, "args");
            if (string.IsNullOrWhiteSpace(args.Options.Destination) || args.Options.Destination.IndexOf("/") < 0)
            {
                return string.Empty;
            }

            int startofNameIndex = args.Options.Destination.LastIndexOf("/") + 1;
            return args.Options.Destination.Substring(startofNameIndex);
        }
    }
}

The code above will set the AlternateText property of the Options property of the GetMediaCreatorOptionsArgs instance when its not set: I set it to be the name of the Media Library Item by default — I extract this from the path destination of the Item.

I then registered the above class as a <getMediaCreatorOptions> pipeline processor in the following Sitecore configuration file:

<?xml version="1.0" encoding="utf-8" ?>
<configuration xmlns:patch="http://www.sitecore.net/xmlconfig/">
  <sitecore>
    <pipelines>
      <getMediaCreatorOptions>
        <processor type="Sitecore.Sandbox.Pipelines.GetMediaCreatorOptions.SetDefaultAlternateTextIfNeed, Sitecore.Sandbox"/>
      </getMediaCreatorOptions>
    </pipelines>
  </sitecore>
</configuration>

Let’s try this out.

I went to my Media Library, and selected an image to upload:

selected-image-upload

During the upload, I did not specify its alternate text.

As you can see, it was given an alternate text value by default:

default-alt-text-set

If you have any thoughts on this, please drop a comment.

But whatever you do, just don’t let this happen to you:

anxiety-cat



Viewing all articles
Browse latest Browse all 51

Trending Articles