I have a grid with a completely custom edit Dialog using an edit template. The fields inside this dialog are then 'read' on actionBegin as follows:
const actionBegin = (args: DialogEditDataArgs) => {
console.log(args);
if (args.requestType === "save" && args.form) {
//convert to integers
args.data.categoryId = parseInt(args.data.categoryId);
args.data.topicId = parseInt(args.data.topicId);
// get original answer list if it exists
let initialAnswers;
if (args.data.answers) {
initialAnswers = args.data.answers;
}
//find and create answers list:
const answerDivs = args.form.querySelectorAll(".answer-div");
// Construct the answer array
const finalAnswers = Array.from(answerDivs).map((div) => {
// Get the answer index from the div class
const index = Number(div.className.split("answer-index-")[1].split(" ")[0]);
// Get the id from the data-id attribute
const id = Number(div.getAttribute("data-id"));
// Get the answer content from the label
const content = div.querySelector("label").textContent;
// Check if this answer is the correct one
const isCorrect = div.querySelector(".correct-answer") !== null;
// Return the answer object
// Prepare the answer object
let answerObject = {
index,
content,
isCorrect,
};
// Conditionally add the 'id' property only if id is not 0
// needed because if there is an id, the backend API will try to update answer instead of create (which doesn’t require id)
if (id !== 0) {
answerObject.id = id;
}
// Return the answer object
return answerObject;
});
// also return deletedAnswers list to handle in the backend API for deletion of answers.
let deletedAnswers;
if (initialAnswers) {
deletedAnswers = initialAnswers.filter((initAnswer) => !finalAnswers.find((finalAnswer) => finalAnswer.id === initAnswer.id));
}
// Add the answers to args.data
args.data.answers = finalAnswers;
args.data.deletedAnswers = deletedAnswers;
args.data.textbookId = 1;
//perform validation with zod
const answerSchema = z.object({
index: z.number(),
content: z.string(),
isCorrect: z.boolean(),
id: z.number().optional(),
});
const formSchema = z.object({
id: z.number(),
content: z.string().nonempty("Question content is required"),
topicId: z.number(),
categoryId: z.number(),
textbookId: z.number().optional(),
answers: z.array(answerSchema).max(8, "A maximum of 8 answers may be added"),
deletedAnswers: z.array(answerSchema).optional(),
});
const result = formSchema.safeParse(args.data);
if (result.success) {
// If validation passes, the save operation continues
// No need to do anything here as it will continue by default
} else {
// If validation fails, prevent the save operation from happening
setValidationErrors(result.error);
args.cancel = true;
}
}
};