Updating Images

Updating Images

Updating Images

The Sitecore.Configuration.Factory class encapsulates the general information available in the web.config file and contains methods that provide access to this information and the means to override it

This snippet uses a fields collection to reference the field

  • Returns null if the field does not exist or the field value is null
  • Does not generate inline editing controls for the Page Editor
  • Useful for field types other than simple field types

  1. Create an object for the database where the item is located - replace SitecoreDB with the name of the Sitecore database where you want to perform the update, typically “master”
  2. Create an object for the target item in the database- replace itempath with the relative path to the item in the Content Tree, such as “home/about/item1” or start the path with a backslash (/) to indicate an absolute path, such as “/sitecore/content/home/about/item1”– a null value will be set in either case if the item does not exist - Sitecore does compare case when evaluating item paths
  3. Create an object for the target image of the item - replace imagepath with the absolute path to the item in the Content Tree, such as “/sitecore/media library/images/project”
  4. Open the edit state for the item
  5. Close the edit state for the item


C# Web Control Code

Sitecore.Data.Database db = Sitecore.Configuration.Factory.GetDatabase("SitecoreDB");

Sitecore.Data.Items.Item item = db.GetItem("itempath");

Sitecore.Data.Items.Item imageitem = db.GetItem("imagepath");

Sitecore.Data.Items.MediaItem media = new Sitecore.Data.Items.MediaItem(imageitem);

Sitecore.Data.Fields.ImageField image = item.Fields["fieldname"];

if (image.MediaID != imageitem.ID )

{

       item. ItemEditing.BeginEdit();

      image.Clear();

      image.Src = Sitecore.Resources.Media.MediaManager.GetMediaUrl(media);

image.MediaID = media.ID;

      if (!String.IsNullOrEmpty(imageitem.Alt))

      {

              image.Alt = imageitem.Alt;

      }

       Else

       {

             image.Alt = imageitem.DisplayName;

      }

       item. ItemEditing.EndEdit();

}