Hi Eric,
I've recently worked with these from code, and what worked for me was following this blog post.
To control what gets displayed in the UI list view, I use the following attribute on the property:[ListItemHeaderProperty(nameof(MyBlock.Title))]
public virtual IList<MyBlock>? MyBlocks { get; set; }
When building the list, I use contentRepository to create new blocks. Refactoring your example, it would look like this:
var page = contentRepository.Get<MyPage>(pageReference);
// Create your blocksvar block1 = contentRepository.GetDefault<MyBlock>(pageReference);block1.Title = "First Block";block1.Content = new XhtmlString("<p>This is the first block's content.</p>");
var block2 = contentRepository.GetDefault<MyBlock>(pageReference);block2.Title = "Second Block";block2.Content = new XhtmlString("<p>This is the second block's content.</p>");
page.Blocks = new List<MyBlock> { block1, block2 };
contentRepository.Save(page, SaveAction.Publish, AccessLevel.NoAccess);
From what I understood from the blog post, this is the recommended way to build the list. However, there's a minor caveat: when the page is being created for the first time, it won’t have a valid content reference yet. So, calling newPage.ContentLink will return a null reference, and passing that to contentRepository.GetDefault<MyBlock>(newPage.ContentLink) will throw an exception.
In that case, you’ll need to first save the page with simple properties only. Once it has a valid ContentLink, you can then add the list of blocks and publish it again.
When creating inline blocks in a IList<BlockType> there seems to be a need for adding a "Name" for each block added. This seems to be handled automaticly when creating as an editor, from documentation:
Override auto-generated name for inline-creating blocks, https://docs.developers.optimizely.com/content-management-system/docs/inline-edit-settings#override-auto-generated-name-for-inline-creating-blocks.
What is the best practice and or how can this be solved from code when using something likte ContentRepository.GetDefault<>(...)
For instance something like this did not do the trick :/
public virtual IList<MyBlock> Blocks { get; set; } = new List<MyBlock>();
var page = contentRepository.Get<MyPage>(pageReference);
// Create your block inline
var block1 = new MyBlock
{
Title = "First Block",
Content = new XhtmlString("<p>This is the first block's content.</p>")
};
var block2 = new MyBlock
{
Title = "Second Block",
Content = new XhtmlString("<p>This is the second block's content.</p>")
};
page.Blocks = new List<MyBlock> { block1, block2 };
contentRepository.Save(page, SaveAction.Publish, AccessLevel.NoAccess);