Set Field Values Dynamically

Topics: Customizing Orchard, General, Writing modules
Dec 12, 2012 at 3:48 PM
Edited Dec 12, 2012 at 3:52 PM

I'm trying to build an integration layer that dynamically sets field values on a content part. This runs in a ScheduledTaskHandler behind the scenes. I know how to set the field values using dynamic when I know the field name at runtime:

((dynamic)contentItem).ContentPart.FieldName = value;

My question is how would I set the field value if all I know at run time is the field name and the value I want to set of the ContentPart? I tried using reflection to no avail so I wonder if this is even possible?

Dec 12, 2012 at 4:30 PM
Edited Dec 12, 2012 at 4:31 PM

Try something like this:

packagePart.Fields.Single(f => f.Name == "MyFieldName").Storage.Set("Value", "A value");

Or, if you know the field type, this:

((TextField) packagePart.Fields.Single(f => f.Name == "MyFieldName")).Value = "A value";

Caveat of course is that you do need to know how the value is to be stored. Usually this is stored keyed by "Value".

Dec 12, 2012 at 6:59 PM
Edited Dec 12, 2012 at 7:00 PM

Thanks for the reply. The issue I have with your example is the Fields collection is always empty? Even if I query for the content item using IContentManager the fields collection doesn't contain any data. Also, what if I am creating a new content item and not updating an existing one? Won't the fields collection be empty?

Dec 12, 2012 at 8:58 PM

If you have a content item of a content type that has a content part with fields, and you query the Fields collection of that content part of the content item, you should get a list of all the attached content fields to that part. I just tested this, and it works. Make sure that in your case, you actually have one ore more content fields attached to the content part that you are interrogating. It works.

If you create a new content item of a content type with a content part with one or more content fields, the Fields collection of that content part of the content item should not be empty; it should contain a list of attached content fields.

Dec 12, 2012 at 9:29 PM
Edited Dec 12, 2012 at 9:33 PM

Thanks sfmskywalker. I finally got this working. Apparently the Fields collection was on another Content Part of my Content Item. I always thought the Fields collection was on the Part with the same name as the Content Item, but for whatever reason that was not the case here. The way I finally resolved this was using the following code for anyone interested:

var customField = myPart.ContentItem.Parts.SelectMany(t => t.Fields).FirstOrDefault(field => field.Name == "MyFieldName");
((dynamic) customField).Value = someValue;

However I couldn't get the .Storage.Set("Value", "A Value") method to work at all. This particular field was a BooleanField but I'm not sure if that has anything to do with it. Regardless, the method above will give me what I need for now.