Search code examples
tridiontridion-2011

Overriding Content of SDL Tridion Component using Event Handlers


How can a field value of a Component be overridden using Event Handler? When I have the code snippet below, there is no error while saving the Component. But content changes done by the Event hanlder is not reflected back in the Component. I expect the single value field "size" to have "blabla..." as the value.

// Call to Subscribe the events
EventSystem.Subscribe<Component, SaveEventArgs>(ComponentSaveInitiatedHandler,
                                                EventPhases.Initiated); 

private void ComponentSaveInitiatedHandler(Component component, 
                                          SaveEventArgs args, EventPhases phases)
{
    if (component.Schema.Title == "XYZ")
    {
        ItemFields Fields = new ItemFields(component.Content, component.Schema);
        SingleLineTextField textField = (SingleLineTextField)Fields["size"];
        textField.Value = "blabla...";
    }
}

Solution

  • You need to update the Content property with the XML string, as follows:

    ItemFields Fields = new ItemFields(component.Content, component.Schema);
    SingleLineTextField textField = (SingleLineTextField)Fields["size"];
    textField.Value = "blabla...";
    component.Content = Fields.ToXml();