During on the my Event Systems, I came across the requirement of creating (and populating) new Embedded Schema fields.
To do so, I still used the ItemFields collection, which has a constructor accepting a Schema parameter. This is the one to use, but the counter-intuitive part was to obtain the Embedded Schema. I ended up getting it from the field definition of the 'outer' Schema field.
Finally notice that when the Component needs to be saved, the ItemFields collection needs first be saved into the Component's content.
ItemFields fields = new ItemFields(component.Content, component.Schema);
The whole code above runs inside the method ComponentPostSavedEvent(Component component, SaveEventArgs args, EventPhases phase)
To do so, I still used the ItemFields collection, which has a constructor accepting a Schema parameter. This is the one to use, but the counter-intuitive part was to obtain the Embedded Schema. I ended up getting it from the field definition of the 'outer' Schema field.
Finally notice that when the Component needs to be saved, the ItemFields collection needs first be saved into the Component's content.
ItemFields fields = new ItemFields(component.Content, component.Schema);
EmbeddedSchemaField linksField = fields["Links"] as
EmbeddedSchemaField;
EmbeddedSchemaFieldDefinition linksFieldDefinition =
linksField.Definition as EmbeddedSchemaFieldDefinition;
ItemFields newItemField = new ItemFields(linksFieldDefinition.EmbeddedSchema);
((ComponentLinkField)newItemField["Component"]).Value = anotherComponent;
((NumberField)newItemField["Version"]).Value = 13;
linksField.Values.Add(newItemField);
component.Content = fields.ToXml();
component.Save(true);
The whole code above runs inside the method ComponentPostSavedEvent(Component component, SaveEventArgs args, EventPhases phase)
Comments
Thanks,
Milos
Hao - you owe me a drink now :)