Is there any way to add a field to a "Content Type" programmatically?

Topics: Customizing Orchard, Writing modules
Sep 30, 2012 at 3:21 AM

ContentDefinitionManager.AlterTypeDefinition is not able to create programmatically???

Coordinator
Sep 30, 2012 at 6:15 AM

Of course it is. What makes you think it isn't? There are many exmaples of that in migrations of existing modules.

Sep 30, 2012 at 11:10 AM

Hi Bertrand,

I couldn't able to find the method in  ContentDefinitionManager.AlterTypeDefinition class. What I am trying to do is create fields. I appriciate if you can forward me sample link.

Regards,

Hayri

Sep 30, 2012 at 11:20 AM

By the way I am trying to create a field to a ContentType not ContentPart.

Regards,

Hayri

Coordinator
Sep 30, 2012 at 7:48 PM

You can't add a field to a content type, you always add it to a content part. It's just that if that part has the same name as the type, nice magical things happen.

ContentDefinitionManager.AlterPartDefinition("Product",
              builder => builder.WithField("ProductImage", fieldBuilder => fieldBuilder.OfType("MediaPickerField").WithDisplayName("Product Image")));

Jul 9, 2014 at 7:04 PM
Edited Jul 9, 2014 at 7:21 PM
"...nice magical things happen." Who wouldn't want to be a magician. Thanks for the tip, Bertrand.

Also, after Bertrand's step above, we still must add the Part to the Content Type. I.e.
ContentDefinitionManager.AlterTypeDefinition("Product", 
    builder => builder.WithPart("Product"));