Create content item and set custom field values

Topics: Writing modules
May 14, 2012 at 12:45 PM

I'm trying to create a new content item and set the values of custom fields on it. I can create the content item like this (where content is an instance of the Orchard ContentManager):

var document = content.New("Document");

 

The custom fields are in a content part that is attached to the Document content type.

I now need to set the values of some HTML fields (not the field type included with the 1.4 release, but a custom one we've made). I've tried getting the part and calling Storage.Set() on the field:

var fieldsPart = document.Parts.First(p => p.PartDefinition.Name == "DocumentFieldsPart");

var introduction = fieldsPart.Fields.First(f => f.PartFieldDefinition.Name == "Introduction").Storage.Set("OriginalMarkupIntroduction", "Some stuff here");

 

But that doesn't work. I've also tried casting the field into the correct type and setting it that way:

var fieldsPart = document.Parts.First(p => p.PartDefinition.Name == "DocumentFieldsPart");

var introduction = fieldsPart.Fields.First(f => f.PartFieldDefinition.Name == "Introduction");

((HtmlField.Fields.HtmlField)introduction).FrontendMarkup = "Some stuff here";

 

That doesn't work either! I'm doing this after all of it to save the item:

content.Create(document, VersionOptions.Published);

 

The content item is indeed created, but the Introduction and Body fields are empty. :(

Any help is appreciated.

May 14, 2012 at 4:06 PM
Edited Jun 14, 2012 at 2:49 PM

I've now realised if I pass VersionOptions.LatestVersion into the overloaded version of the content.Create method it works fine.

Would be grateful if someone could confirm this is the correct way to achieve what I'm doing.

Thanks.

Mar 21, 2013 at 5:10 AM
I had the same issue. It didn't matter what VersionOption I chose. In the end, I figured out that I had to call the Create method first, then set the field value.