Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to retrieve alt text for Image field when using Sitecore Item Web API?

When using the Sitecore Item Web API to return an item that has an Image field the Sitecore Item Web API returns a JSON response which contains a Value which is the image tag but doesn't have any alt text. Is there a way to have the Sitecore Item Web API return the details of the referenced Media Library Item?

Example Image Field Type Response from the Sitecore Item Web API:

                "{7EEA5007-E518-4E68-837B-51BEAB56230A}": {
                "Name": "Image",
                "Type": "Image",
                "Value": "\u003cimage mediaid=\"{E1F8CD6F-8276-4967-983C-C37E1481CDC0}\" mediapath=\"/Images/Fragrances/Collections/M039_img4\" src=\"~/media/E1F8CD6F82764967983CC37E1481CDC0.ashx\" /\u003e"
            }

It appears I could parse the value for the GUID and then use Sitecore Item Web API to query the Image Item in the Media Library and retrieve the GUID but this would be messy when a parent has multiple children as I would have to request the alt tag for each separately.

like image 336
benadamski Avatar asked Oct 22 '22 09:10

benadamski


1 Answers

Sitecore Item Web API introduces some new pipelines declared in Sitecore.ItemWebAPI.config

The key pipeline you are looking for is itemWebApiRead. This references the type Sitecore.ItemWebApi.Pipelines.Read.GetResult, Sitecore.ItemWebApi which executes the method GetFieldInfo. This method actually sets the values returned for each field in the response.

As the method is virtual we can simply write our own class which inherits from Sitecore.ItemWebApi.Pipelines.Read.GetResult and implement our own GetFieldInfo method

Implementation

using Sitecore.Data.Fields;

namespace WebApi
{
    public class GetResult: Sitecore.ItemWebApi.Pipelines.Read.GetResult
    {
        protected override Sitecore.ItemWebApi.Dynamic GetFieldInfo(Field field)
        {
            var fieldInfo = base.GetFieldInfo(field);
            
            if (field.TypeKey == "image")
            {
                var imageField = (ImageField) field;
                fieldInfo.Add("Alt", imageField.Alt);
            }

            return fieldInfo;
        }
    }
}

As you can see, all we need to do is check the field.TypeKey to see if it is an image. If so, we cast to and ImageField and then add in the value of the Alt property to our fieldInfo object.

Result

"{4A0E7425-5927-42D6-9438-A17E875DE50A}": {
    "Name": "Image",
    "Type": "Image",
    "Value": "<image mediaid=\"{00065A73-4859-4CF3-9F51-4D01D39CAD75}\" mediapath=\"/Images/128\" src=\"~/media/00065A7348594CF39F514D01D39CAD75.ashx\" />",
    "Alt": "sitecore logo"
}

If you need to add further customisations for other field types you can always add a switch statement based off the TypeKey.

like image 74
Kieranties Avatar answered Jan 02 '23 20:01

Kieranties