Search code examples
c#sitecoresitecore7.2

How to edit the Sitecore Image Field from codebehind


I have a sitecore Item 'CurrentItem' with a field "image". I am editing it from code behind as follows:

//Get the Image from /sitecore/media library/Images/Test
Item imageItem = Sitecore.Context.Database.GetItem("{AEBB3071-3462-405C-9CD3-A2B515B343D1}")
//Edit   
CurrentItem.Editing.BeginEdit();
CurrentItem["image"] = imageItem.ToString();
CurrentItem.Editing.EndEdit();

PS: imageItem is a picture under /sitecore/media library/Images/Test

I also tried with CurrentItem["image"] = imageItem.Paths.Path; But still no luck.


Solution

  • You need to take the field as ImageField and set the MediaID property to the ID of the MediaItem:

    //Get the Image from /sitecore/media library/Images/Test
    Sitecore.Data.Items.MediaItem imageItem = Sitecore.Context.Database.GetItem("{AEBB3071-3462-405C-9CD3-A2B515B343D1}")
    //Edit   
    CurrentItem.Editing.BeginEdit();
    var imageField = CurrentItem.Fields["image"] as ImageField;
    imageField.MediaID = imageItem.ID;
    imageField.MediaPath = imageItem.MediaPath;
    CurrentItem.Editing.EndEdit();
    

    Also you can take a look at this blog post for more explanations for the post 6.X Versions.