Friday 10 October 2014

Differences in Sitecore Image Data Type From 6.x to 7.x

Sitecore's raw data difference

When selecting an image, Sitecore generates some xml which is saved and used when getting the image from the field on your template. There is a difference from 6.x and 7.x. In 7.x the attributes src and mediapath have been removed.

6.x
<image mediaid="{5B2DA590-21FF-409D-9E03-4759D5CB65BE}" mediapath="/Images/TestImage" src="~/media/Images/TestImage.ashx" height="" width="" hspace="" vspace="" />

7.x
<image mediaid="{5B2DA590-21FF-409D-9E03-4759D5CB65BE}" height="" width="" hspace="" vspace="" />

The problem with retrieving data

A normal thing to do with images is to get the url of the image. For instance we need it for the open graph meta-tag og:image. As documented in the Presentation Component
XSL Reference for Sitecore 6.2 or later you can use the 'src' to get the source of the image. Like the following, but the problem is that this stopped working in Sitecore 7.x since the src attribute was removed.

<meta name="og:image" content="{sc:fld('FieldName', $sc_currentitem, 'src')}" />

The problem after updating from 6.x to 7.x

When selecting a new image, you rarely would press 'clear' and then select a new image. When selecting the new image sitecore will change the mediaid and the height/width. The mediapath/src will remain. If your code hasn't been updated it will seem like you can't change the image or the old image is still being loaded.

So how do we fix this?

We have the mediaid from the field and thats all. We can output an image with sc:image but that doesn't work if we only need the images url. We also have sc:GetMediaUrl that takes an Item or XPathNodeIterator as an argument and we have the sc:Item which takes an item ID as argument. Putting that together 

7.x
<xsl:variable name="imageId" select="sc:fld('FieldName', $sc_currentitem, 'mediaid')"/>
<xsl:variable name="imageItem" select="sc:item($imageId, $sc_currentitem)"/>
<xsl:variable name="imageUrl" select="sc:GetMediaUrl($imageItem)"/>

or all in one statement <xsl:variable name="imageUrl" select="sc:GetMediaUrl(sc:item(sc:fld('FieldName', $sc_currentitem, 'mediaid'), $sc_currentitem))"/>

<meta name="og:image" content="{$imageUrl}" />

Not as easy as it used to be, but again using Razor would be alot easier.