Created
August 31, 2012 09:41
-
-
Save janhebnes/3550905 to your computer and use it in GitHub Desktop.
Sitecore CMS - Event for handling changing the DataSources from path information to GUIDs to be inserted in the item:saving event prior to the save event
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/// <summary> | |
/// The layout data sources are saved with a text path and not a guid. | |
/// </summary> | |
public class EnsureDataSourceIsGUID | |
{ | |
public void OnItemSaving(object sender, EventArgs args) | |
{ | |
Sitecore.Diagnostics.Log.Info("Running EnsureDataSourceIsGUID", this); | |
Item item = Event.ExtractParameter(args, 0) as Item; | |
if (item.Database.Name == "master") | |
{ | |
LayoutField layoutField = new LayoutField(item.Fields[Sitecore.FieldIDs.LayoutField]); | |
if (!layoutField.InnerField.HasValue) | |
{ | |
return; | |
} | |
if (string.IsNullOrEmpty(layoutField.Value)) | |
{ | |
return; | |
} | |
LayoutDefinition layout = LayoutDefinition.Parse(layoutField.Value); | |
for (int i = 0; i < layout.Devices.Count; i++) | |
{ | |
DeviceDefinition device = layout.Devices[i] as DeviceDefinition; | |
for (int j = 0; j < device.Renderings.Count; j++) | |
{ | |
RenderingDefinition rendering = device.Renderings[j] as RenderingDefinition; | |
if (!string.IsNullOrEmpty(rendering.Datasource) && rendering.Datasource.StartsWith("/")) | |
{ | |
Item datasourceItem = item.Database.GetItem(rendering.Datasource); | |
if (datasourceItem == null) | |
{ | |
Sitecore.Diagnostics.Log.Warn(string.Format("Could not find datasource item at path {0} while saving item {1}", rendering.Datasource, item.ID), this); | |
continue; | |
} | |
rendering.Datasource = datasourceItem.ID.ToString(); | |
} | |
} | |
} | |
layoutField.Value = layout.ToXml(); | |
} | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment