Setting Sitecore Image field values (updated for 6.x+)

A couple of years ago, I wrote a post on how to assign a Sitecore image media item to an image field using the Sitecore 5.3 API.  As it stands, I haven’t really had need to do this since, but I got asked about it the other day by someone at the office.  So, I thought I’d post a little update to the original article.

John Wilson posted a comment on the article, which got most of the way there.  John correctly pointed out that the MediaPath property had been deprecated and suggested dropping that from the snippet.  However, I have noticed that the content editor still uses the property when it displays the field in the Content Editor interface.  I think that behaviour is a little odd, and almost certainly an oversight; but fortunately it can be worked around using the SetAttribute method present on all xml-based field classes.

So, the original (v5.3) suggestion was to use the following code:

public void AssignMediaItem(ImageField field, Item mediaItem)
{
    field.MediaID = mediaItem.ID;
    MediaUrlOptions options = new MediaUrlOptions();
    field.Src = MediaManager.GetMediaUrl(mediaItem, options);
    field.MediaPath = mediaItem.Paths.MediaPath;
    field.SetAttribute("showineditor", "1");
}

With current versions of Sitecore, I would suggest doing the following instead:

public void AssignMediaItem(ImageField field, Item mediaItem)
{
    field.MediaID = mediaItem.ID;
    field.SetAttribute("mediapath", mediaItem.Paths.MediaPath);
    field.SetAttribute("showineditor", "1");
}

This code can obviously be made into an extension method; although I’ll leave the target class up to you.