Reputation: 785
I have been hunting around for a solution to this, but cannot find anything for version 7.
I just have to update a date property on an Umbraco 7 node. (not the publish date) Then I need to tell umbraco to republish the page/update caching.
In the code below the individual node is "item", if it finds the item has a checkbox property set to true then it should increment the date by 1 year.
if(item.annual.ToString()=="True")
{
item.deadlineDate = item.deadlineDate.AddYears(1);
}
Any and all suggestions gratefully welcome,
Regards, Damien Holley
Upvotes: 3
Views: 3468
Reputation: 4450
Assuming your item
variable is dynamic, you first need to to pass its id to the management API service:
var contentService = ApplicationContext.Current.Services.ContentService;
var content = contentService.GetById(item.Id);
content.SetValue("deadlineDate", item.deadlineDate.AddYears(1));
contentService.SaveAndPublish(content);
This will persist the value and make it available elsewhere in the application. It will also update using the admin user's account, so if you want the audit trail to show something else, you need to use pass the user id to the SaveAndPublish
method.
Finally, you need to be careful with using the Management API within views. Not only is it possible lose data due to frontend user actions but it can also lead to performance issues as the ContentService
will always hit the database, unlike the query APIs (IPublishedContent
or DynamicPublishedContent
).
EDIT: I've just noticed the comments in Jannik's answer which more or less provide the same answer.
Upvotes: 8
Reputation: 3425
ContentService is your friend :-) https://our.umbraco.org/documentation/Reference/Management/Services/ContentService
With it, you can both save and publish content.
Upvotes: 6