Search code examples
orchardcms

Orchard - how to access taxonomy field of a custom content type programmatically


I have a custom content type called Store, which has a Brands taxonomy field. A Store can have multiple Brands associated with it.

I have been tasked with building an import/export routine that allows the user to upload a CSV file containing new Stores and their associated Brands.

I can create the Stores other fields OK, but can't work out how to set the taxonomy field?

Can anyone tell me how I access the Taxonomy field for my custom content type?

Thanks in advance.


Solution

  • OK so (as Bertrand suggested), using the Import/Export feature might be a better way to go, but as a relative noob on Orchard I don't have the time to spend looking at it and couldn't find a good tutorial.

    Below is an alternative approach, using the TaxonomyService to programatically assign Terms to a ContentItem.

    First of all, inject the ContentManager and TaxonomyService into the constructor...

    private ITaxonomyService _taxonomyService;
    private IContentManager _contentManager;
    
    public MyAdminController(IContentManager contentManager, ITaxonomyService taxonomyService)
    {
         _contentManager = contentManager;
         _taxonomyService = taxonomyService;
    }
    

    Create your ContentItem & set the title

    var item = _contentManager.New("MyContentType");
    item.As<TitlePart>().Title = "My New Item";
    
    _contentManager.Create(item);
    

    Now we have a ContentItem to work with. Time to get your taxonomy & find your term(s)...

    var taxonomy = _taxonomyService.GetTaxonomyByName("Taxonomy Name");
    var termPart = _taxonomyService.GetTermByName(taxonomy.Id, "Term Name");
    

    Add the terms to a List of type TermPart...

    List<TermPart> terms = new List<TermPart>();
    terms.Add(termPart);
    

    Finally, call UpdateTerms, passing in the ContentItem, terms to assign and the name of the field on the ContentItem you want to update...

    _taxonomyService.UpdateTerms(item, terms.AsEnumerable<TermPart>(), "My Field");
    

    Hope this helps someone. Probably me next time round! : )