How to create blocks in "for this page" or "for this block"?

Vote:
 

Hi,

i'm trying to create content in a ContentArea of a page. I want to store this block in "for this page", as if the user would create it there manually.
But i get an exception "...is not allowed to be created under ArticlePage ..." at _contentRepository.Save. So how to do it correctly? This is my code:

private ContentReference CreateArticleContent(MappedArticleEntry articleEntry, ArticlePage articlePage)
{
	if (string.IsNullOrWhiteSpace(articleEntry.Content))
	{
		this.LogError($"Parsed article-content is null or empty. {nameof(MappedArticleEntry.NewsId)} <{articleEntry.NewsId}>");
		return null;
	}

	CultureInfo culture = articleEntry.Language.TryParseCultureInfo(out CultureInfo ci) ? ci : ArticlePageImportActionCreate.DefaultCulture;
	try
	{
		IContent block = (IContent)_contentRepository.GetDefault<ContentTemplateBlock.ContentTemplateBlock>(articlePage.GetContentLink(), culture);
		block.Name = $"{_ARTICLE_CONTENT_BLOCK_NAME_PREFIX}{articlePage.GetContentLink()?.ID.ToString() ?? articleEntry.NewsId}";
                block.HtmlContent = new XhtmlString(articleEntry.Content);
		ContentReference newArticleContentReference = _contentRepository.Save(block, SaveAction.Publish, AccessLevel.NoAccess);
		this.LogInformation($"Created article-content-block for <{articleEntry.NewsId}> in culture <{culture}> with Length <{articleEntry.Content.Length}>. Generated block-id <{newArticleContentReference.ID}>");
		return newArticleContentReference;
	}
	catch (Exception e)
	{
		this.LogError(e, $"Error creating article-content-block for <{articleEntry.NewsId}> in culture <{culture}> with Length <{articleEntry.Content.Length}>.");
		return null;
	}
}
#252927
Edited, Apr 09, 2021 12:45
Vote:
 

Hi,

In your example, it looks like you're creating the block as a child of the articlePage where you should be creating it in that page's asset folder. The asset folder doesn't exist by default but you can get or create it as a single action like this:

var contentAssetHelper = ServiceLocator.Current.GetInstance<ContentAssetHelper>();
var assetFolderLink = contentAssetHelper.GetOrCreateAssetFolder(articlePage.ContentLink).ContentLink;

You can then use assetFolderLink as the parent of your new block in your GetDefault() call.

#252929
Apr 09, 2021 13:23
Tim Schmelter - Apr 09, 2021 13:44
Thanks for your quick response. It looks promising, but i get a different exception now: Access was denied to content 25031_98182. The required access level was "Edit, Publish". I thought that NoAccess would mean that it works always.
Edit: Thanks again. The reason was a service that listened to published content, so i think i can fix that.
Paul Gruffydd - Apr 09, 2021 16:43
Great. Glad to hear it worked.
* You are NOT allowed to include any hyperlinks in the post because your account hasn't associated to your company. User profile should be updated.