Set Field thru code

Topics: Troubleshooting, Writing modules
Developer
Oct 8, 2011 at 4:50 PM

Hi Chaps,

I am dynamically creating parts on the fly with fields attached to them, what I would like is to set those fields thru code... now to do this with a normal Part you do.. something like this...

contentItem.As<T>().Fields.First(o => o.Name == fieldName).Storage.Set(null, valueToSet);

So my question is.. how do I do this with the Infoset stuff? using ContentPartFieldDefinition objects?

Coordinator
Oct 8, 2011 at 10:35 PM

Did you try "casting" the content item to dynamic? It should be so much easier.

Developer
Oct 9, 2011 at 1:34 AM

No I didnt... this is how far I got until I asked for help...

contentItem.TypeDefinition.Parts.Where(o => o.PartDefinition.Name == "ArticlePart").FirstOrDefault().PartDefinition.Fields.First(o => o.Name == fieldName).Storage.Set(null, valueToSet);

The Part is created dynamicaly. (p.s. the above doesnt compile)

Ideas?

Coordinator
Oct 9, 2011 at 1:35 AM

Which shouldn't matter if you use the dynamic access model. That's why I was suggesting it ;)

Developer
Oct 9, 2011 at 1:38 AM

Okay so what your saying is that in the above approach this should work?

contentItem.As<dynamic>().Fields.First(o => o.Name == fieldName).Storage.Set(null, valueToSet);

Coordinator
Oct 9, 2011 at 1:43 AM

No. Rather something like dynmaic item = contentItem and then look at what you can do with Clay to retrieve part and field value.

Coordinator
Oct 9, 2011 at 1:58 AM

dynamic contentItem = contentManager.Get(42);
contentItem.PARTNAME.FIELDNAME.FIELDPROPERTY = "foo";

or, if it's a field attached to a content type directly, not a part:

contentItem.CONTENTTYPE.FIELDNAME.FIELDPROPERTY = "foo";

 

Coordinator
Oct 9, 2011 at 5:36 AM

right, but what if the field name is in a variable?

Developer
Oct 9, 2011 at 12:47 PM

Sebastians example should word for me... though I now have to take out the spaces in the Fieldnames.. hmmm