If I simply attempt to add a Group using the Kontent Management API (v2) to an existing Kontent type I get the following error (see code below which generates this error):
Validation errors: 511 Every element should have a correct content group reference when using groups
What is the process for adding a group via the Management API in this case using C#? I would assume that I need to add a group Reference
to all the existing elements first, but how do I do that when I cannon add the group through the API? Can I create a valid Reference
simply using a new ContentGroupModel()
object before adding it to the actual type in Kontent?
Here is my existing code, which throws the above error:
var updatedType = await service.ModifyContentTypeAsync(
Reference.ById(existingContentType.Id),
new ContentTypeAddIntoPatchModel
{
Path = "/content_groups",
Value = new ContentGroupModel
{
Name = "New Group",
CodeName = "new_group"
}
}
);
I was able to work it out. It turns out you can use the Codename
of the new group, even before adding it in Kontent, as a reference. Then give that reference to the content_group property/path for existing elements in the model.
Here is the code I have now that adds the new Group and adds it to all existing elements dynamically:
using Kentico.Kontent.Management.Models.Shared;
using Kentico.Kontent.Management.Models.Types;
using Kentico.Kontent.Management.Models.Types.Patch;
//
// ...
//
// First, Get type from the client. Then ...
var elementCodenames = myType.Elements.Select(el => el.Codename);
// Create reference to the codename of the group to be created
var groupRef = Reference.ByCodename("new_group");
// Create the modify models
var modifyModels = new ContentTypeOperationBaseModel[] {
new ContentTypeAddIntoPatchModel
{
Path = "/content_groups", // Add to content_groups path
Value = new ContentGroupModel
{
Name = "New Group",
CodeName = "new_group" // Same codename as above
}
}
}
.Concat(
// Dynamically add new group, by ref, to existing elements
elementCodenames.Select(codename => new ContentTypeReplacePatchModel
{
Path = $"/elements/codename:{codename}/content_group",
Value = groupRef // Group reference created above from the codename
})
);
// Make call to add new group AND link group to elements in the one call
var response = await client.ModifyContentTypeAsync(myTypeIdentifier, modifyModels.ToArray());
Leaving out other details, like retrieving the existing type, but for reference here are the API Docs: https://docs.kontent.ai/reference/management-api-v2