3

I am writing an event which is executed on page save and I need to validate one of the Page metadata fields. If it is blank then I have to set that value from the Structure Group Metadata field,

public void Validate(RepositoryLocalObject page)
    {
        try
        {
            var metadata = new ItemFields(page.Metadata, page.MetadataSchema);

            var categorisation = ((EmbeddedSchemaField)metadata["categorisation"]).Value;
            if (categorisation == null)
            {
                var item = page.OrganizationalItem;
                if (item.Metadata != null && item.MetadataSchema != null)
                {
                    var parentMetaData = new ItemFields(item.Metadata, item.MetadataSchema);
                    if (parentMetaData != null)
                    {
                        EmbeddedSchemaField pageFields = (EmbeddedSchemaField)metadata["categorisation"];

                        var parenetCategorisation = ((EmbeddedSchemaField)parentMetaData["categorisation"]).Value;

                        pageFields.Value = parenetCategorisation;

                        if (parenetCategorisation != null)
                        {
                            page.Metadata["categorisation"].InnerText = pageFields.ToString(); 
                        }
                    }
                }
            }

        }
        catch(Exception ex)
        {
            throw new Exception("Not all section fields have been set " + ex.Message + " " + ex.StackTrace);
        }
    }

I am getting the error on the below line,

 page.Metadata["categorisation"].InnerText = pageFields.ToString(); 

Could anyone suggest that how to set this value to page metadata fields?

  • That's a nice requirement to help authors--basically if they don't set something at a specific context, use a default fallback option (SG in this case). Other options would be to default to the SG's values (similar to this approach for metadata or to handle "blank" fields with templating. If authors want to see the "default" (SG) values even before saving, I'd recommend doing this earlier. If it's after-the-fact, then templates may be just as flexible. – Alvin Reyes Oct 15 '13 at 18:51
9

Something along these lines (untested code)

Itemfields meta = new ItemFields(page.Metadata, page.MetadataSchema);
SingleLineTextField categorisationField = (SingleLineTextField)meta["categorisation"];
categorisationField.Value = "Some value";
page.Metadata = meta.ToXml();
9

Page.Metadata is an XmlElement, you cannot access it 'page.Metadata["categorisation"]'. You will have to set the entire metadata of the Page.

page.Metadata = metadata.ToXml(); 

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.