I am trying to write an event so that when a component is saved, some of its fields are copied in the localized versions of the component.
My algorithm is as follows: I first find the root component (i.e. in the publication where it's created), then scan down the BP and obtain a list of localized components. Then I loop over those components, copying the fields from the saved component (on which the event is fired) to mirror the fields.
The problem I am having is that I only want to run through the list once, so if the component is localized three times in child publications I would expect three local copies to be updated, but there are actually many more iterations happening. I understand the problem; everytime I call .save() the event system is triggered once again (breaking the foreach loop).
The basics of the event are as follows (note the code is very simplified, excluding the ItemFields copying etc):
public ContentCreationEvents()
{
EventSystem.Subscribe<Component, SaveEventArgs>(SyncProductOfferLocalizedComponents, EventPhases.TransactionCommitted);
}
public void SyncProductOfferLocalizedComponents(Component comp, SaveEventArgs args, EventPhases phases)
{
if(comp.Schema.Title == "Product Offer")
{
// Get the saved component (comps) fields to be mirrored.
// .. Retrieve all localized components into a list here ..
foreach(Component localComponent in localizedComponents)
{
// Mirror the fields via ItemFields (overwrite existing fields)
bool checkedOut = localComponent.TryCheckOut();
if(checkedOut)
{
localComponent.Content() = updateFields.toXml();
localComponent.Save();
localComponent.CheckIn();
}
}
}
}
My questions are: What stops this from being an infinite loop? It seems to me like everytime we call save, the event system should continuously be triggered, yet it is not. The loop is executing by about a multiple of 3/4 compared to what I would expect.
My second question is: how can I loop through the components, updating their fields without re-triggering the event system which causes us to needlessly loop over components that have already been saved. Perhaps I am missing a fatal flaw in my design; please feel free to recommend a new strategy or possibly a different event phase to trigger on.