Search code examples
orchardcmsorchardcms-1.9

How to programatically create a content item of an existing type in Orchard


I have a Registration content type that I created through the Admin GUI. It only has an id and a common part and some text fields. Can I just do something like:

var registration = services.ContentManager.New("Registration"); 
registration.Name = "My Name";
registration.Comment = "Some random comment";
services.ContentManager.Create(registration, VersionOptions.Published);

Or will I have to go through the ordeal of completely defining my content type in code and manually taking care of persistence? All of the tutorials that I can find online as well as the official documentation only ever deal with creating content types and items from scratch. There seem to be no examples of simply creating a new item of an existing type.


Solution

  • You can do it like this just fine. If you want to set more settings though, you should cast it do dynamic so you can just rather simply put any value there:

    dynamic registration = services.ContentManager.New("Registration");
    
    // It is dynamic, so you can now set any property on it:
    // <contentItem>.<theContentPart>.<thePropertyName> = someValue
    // <contentItem>.<theContentPart>.<theField>.Value = someValue
    
    // Set properties of a part
    registration.ThePartThatHasTheNameProperty.Name = "My Name";
    registration.ThePartThatHasTheCommentProperty.Comment = "Some random comment";
    
    // Set properties of a field
    registration.ThePartThatHasTheField.TheField.Value = "Some value";
    
    services.ContentManager.Create(registration, VersionOptions.Published);
    

    Or, strongly typed:

    var registration = services.ContentManager.New("Registration");
    
    registration.As<SomePart>().SomeProperty = "Some value";
    registration.As<SomeOtherPart>().SomeOtherProperty = "Some other value";