-
Notifications
You must be signed in to change notification settings - Fork 27
Using the ContentService
you can use the content service to create new content, save/publish or sort, move, delete, publish, unpublish or do any of the other things the backoffice allows you to do.
after injecting the ContentService
into your controller, you can do the following to create new content:
var viewModel = await contentService.Create<Page>(parentId, "en-gb",nodeName,published:true);
await contentService.SaveContent(viewModel);
you can use Create<T>
to first make a new instance of your ViewModel. you could actually create a new instance of your ViewModel directly without using Create<T>
but then you'd have to set a bunch of properties yourself rather than letting the create method do it for you. note that if you don't supply the template
argument to the Create<T>
method and you haven't set the Allowed Templates for your ViewModel in the settings section of the backoffice, it will throw an error. if you had set the Allowed Templates, it would be able to pick the first allowed template from the list and set the template to that. so make sure you either provide the template argument or set the Allowed Templates in the settings section.
SaveContent<T>
is used to create, save and publish your ViewModels. if your ViewModel's Published
property is set to true, it will publish.
if you want to edit existing content, you will first need to get the revision from the database using the Puck repository. so inject an instance of I_Puck_Repository
into your controller and get the revision by doing this:
var homepageRevision = repo.CurrentRevision(homepageGUID, "en-gb");
you now have an instance of PuckRevision
but ContentService
saves ViewModels not revisions so next you need to get an instance of your ViewModel:
var homepageViewModel = homepageRevision.ToBaseModel() as Homepage;
now you have an instance of your ViewModel, you can edit it:
homepageViewModel.Title = "Welcome to the Homepage";
and then you can save it:
contentService.SaveContent(homepageViewModel);
by default, saving will create a new revision but you can opt to overwrite the current revision if you like, by setting the makeRevision
argument to false.