Hi,
Iām currently struggling with how to retrieve the correct values when using a JSON field with a plugin attached to it. Iām using the onBeforeItemUpsert hook with the code example from the docs but it only describes a āsimpleā case with a fixed name and a small tree to get the value to be handled.
This is my code but itās linked to a specific setup within my project (a model with a modular content field called āsectionsā)ā¦ Is there a better way?
onBeforeItemUpsert(createOrUpdateItemPayload, ctx): any {
const entitySelectorFieldAttributes = Object.values(ctx.fields).find(
(field) => field?.attributes.appearance.field_extension === "entitySelector",
)?.attributes;
if (typeof entitySelectorFieldAttributes === "undefined") {
return; // no plugin was used
}
for (const locale of ctx.site.attributes.locales) {
const sectionsFieldPath = `data.attributes.sections.${locale}`;
const sectionsJson = get(createOrUpdateItemPayload, sectionsFieldPath) as any;
if (typeof sectionsJson === "undefined") {
continue; // no sections were provided
}
const parameters = entitySelectorFieldAttributes.appearance.parameters;
for (const section of Array.from(sectionsJson)) {
const apiKeyJson = get(section, `attributes.${entitySelectorFieldAttributes.api_key}`);
if (typeof apiKeyJson === "undefined") {
continue; // no value is present for "categories", "products", ...
}
const apiKeyArray = JSON.parse(apiKeyJson);
if (typeof parameters["minimumEntityCount"] !== "undefined") {
const minimumEntityCount = parseInt(parameters["minimumEntityCount"] as string);
if (apiKeyArray.length < minimumEntityCount) {
ctx.alert(`Minimum entity count is ${minimumEntityCount}`);
return false;
}
}
if (typeof parameters["maximumEntityCount"] !== "undefined") {
const maximumEntityCount = parseInt(parameters["maximumEntityCount"] as string);
if (apiKeyArray.length > maximumEntityCount) {
ctx.alert(`Maximum entity count is ${maximumEntityCount}`);
return false;
}
}
}
}
}