Search code examples
orchardcmstaxonomy

Orchard CMS: How to add a Taxonomy field to a Content Type on a migration?


I need to define a new Content Type having a Taxonomy field on my module's migrations. I guess I need to do something like this:

ContentDefinitionManager.AlterTypeDefinition("ContentTypeName",
            cfg => cfg
                .WithPart("TermsPart", builder => builder
                    .WithSetting(...

But I could not make it work.


Solution

  • I finally made it thanks to Giscard's answer. The important thing to know about Orchard is that a field can't be attached to a content type. When you attach it to a content type in the admin UI, Orchard does some magic behind the scenes to hide this fact, it creates a content part inside that content type, with the same name as the content type, and then attaches the field(s) to that new content part.

    So here is the solution:

            //Create new table for the new part
            SchemaBuilder.CreateTable(typeof(SampleRecord).Name, table => table
                .ContentPartRecord()
                .Column("SampleColumn", DbType.String)
            );
    
            //Attach field to the new part
            ContentDefinitionManager.AlterPartDefinition(
                typeof(SamplePart).Name, 
                cfg => cfg
                    .Attachable()
                    .WithField("Topic", fcfg => fcfg
                        .OfType("TaxonomyField")
                        .WithDisplayName("Topic")
                        .WithSetting("Taxonomy", "Topics")
                        .WithSetting("LeavesOnly", "true")
                        .WithSetting("SingleChoice", "true")
                        .WithSetting("Required", "true"))
                );
    
            //Attach part to the new Content Type
            ContentDefinitionManager.AlterTypeDefinition("Sample",
                     cfg => cfg
                         .WithPart(typeof(SamplePart).Name
                    ));
    

    I created a table with a column named "SampleColumn" and I attached a field "Topic" for the Taxonomy named "Topics". Hope it helps someone else.