Umbraco:create childnodes in content using C#
Asked Answered
E

2

11

I am working with umbraco 6.1.6. I want to know how to add a node into the content tree programmatically?

This is the structure I want:

content

  • Home
    • start
    • calender
    • frontpage sliders
    • fotos
    • news

Here childnodes have the same document types. How can I create these childnodes programatically using C#?

Ensiform answered 23/10, 2013 at 6:47 Comment(0)
M
13

Try this,

using umbraco.cms.businesslogic.web;

DocumentType dt = DocumentType.GetByAlias("alias");

// The umbraco user that should create the document, 
// 0 is the umbraco system user, and always exists
umbraco.BusinessLogic.User u = new umbraco.BusinessLogic.User(0);

//Replace 1055 with id of parent node
Document doc = Document.MakeNew("new child node name", dt, u, 1055);

//after creating the document, prepare it for publishing 
doc.Publish(u);

//Tell umbraco to publish the document
umbraco.library.UpdateDocumentCache(doc.Id);

OR

using Umbraco.Core;
using Umbraco.Core.Models;
using Umbraco.Core.Services;

// Get the Umbraco Content Service
var contentService = Services.ContentService;
var product = contentService.CreateContent(
    "my new presentation", // the name of the product
    1055, // the parent id should be the id of the group node 
    "Presentation", // the alias of the product Document Type
    0);

// We need to update properties (product id, original name and the price)
product.SetValue("title", "My new presentation");

// finally we need to save and publish it (which also saves the product!)
// - that's done via the Content Service
contentService.SaveAndPublish(product);

Hope this helps

Milliary answered 25/10, 2013 at 4:16 Comment(2)
Just for information: how can I get the ID of a content I've just creaerd? There are no overload for SaveAndPublish method which return any IdCommunicate
@Communicate ContentService.CreateContent returns an IContent instance and it has a property called Id which points to your newly created content's Id.Lately
G
2

You need to use Umbraco's API for that. This is all covered in the Umbraco documentation here: http://our.umbraco.org/documentation/Reference/

In a nutshell, you can use the CreateContent() method of the API's ApplicationContext.Current.Services.ContentService.

Ganny answered 24/10, 2013 at 10:30 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.