Last active
September 18, 2023 19:45
-
-
Save paulsterling/96801e3ca70b6ddb174c6435191e5f36 to your computer and use it in GitHub Desktop.
Umbraco v12 Bulk Find and Replace using ContentService
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using Umbraco.Cms.Web.BackOffice.Controllers; | |
using Umbraco.Cms.Core.Services; | |
using Microsoft.AspNetCore.Mvc; | |
namespace FindAndReplace.Core.Controllers | |
{ | |
public class FindAndReplaceApiController : UmbracoAuthorizedApiController | |
{ | |
private readonly IContentTypeService _contentTypeService; | |
private readonly IContentService _contentService; | |
public FindAndReplaceApiController(IContentTypeService contentTypeService, | |
IContentService contentService) | |
{ | |
_contentTypeService = contentTypeService; | |
_contentService = contentService; | |
} | |
/// <summary> | |
/// Url: /umbraco/backoffice/api/FindAndReplaceApi/PostBulkUpdate | |
/// </summary> | |
public ActionResult PostBulkUpdate() | |
{ | |
// ContentType by alias | |
var contentType = _contentTypeService.Get("article"); | |
var contentOfType = _contentService.GetPagedOfType(contentType.Id, 0, int.MaxValue, out long totalArchive, null); | |
foreach (var content in contentOfType) | |
{ | |
// the node name can be used as the title | |
if(content.Name.Contains("youtube", StringComparison.InvariantCultureIgnoreCase)) | |
{ | |
content.Name = content.Name.Replace("youtube", "MyTube", StringComparison.InvariantCultureIgnoreCase); | |
} | |
// alternately, we could iterate all properties from the document | |
if(content.HasProperty("title")) | |
{ | |
foreach(var value in content.Properties["title"].Values) | |
{ | |
// if this is a JSON object (eg, BlockList) we may want to add some safety to check the Json is still valid | |
if(value.EditedValue.ToString().Contains("youtube", StringComparison.InvariantCultureIgnoreCase)) | |
{ | |
var newValue = value.EditedValue.ToString().Replace("youtube", "MyTube", StringComparison.InvariantCultureIgnoreCase); | |
content.Properties["title"].SetValue(newValue); | |
} | |
} | |
} | |
if(content.IsDirty()) | |
{ | |
_contentService.SaveAndPublish(content); | |
} | |
} | |
return new OkResult(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment