From 95b06d19e383fc68f468ba4b697759273b8ec439 Mon Sep 17 00:00:00 2001 From: selankon Date: Fri, 11 Oct 2024 12:12:14 +0200 Subject: [PATCH] Create a submit form controller --- .../Process/MultiElectionQuestions.tsx | 37 +++++++++++++++++-- 1 file changed, 34 insertions(+), 3 deletions(-) diff --git a/src/components/Process/MultiElectionQuestions.tsx b/src/components/Process/MultiElectionQuestions.tsx index d398438..a3abe53 100644 --- a/src/components/Process/MultiElectionQuestions.tsx +++ b/src/components/Process/MultiElectionQuestions.tsx @@ -9,9 +9,15 @@ import { DefaultElectionFormId, VoteButtonLogic, } from '@vocdoni/chakra-components' -import { Flex } from '@chakra-ui/react' +import { Flex, FormControl, FormErrorMessage, useMultiStyleConfig } from '@chakra-ui/react' +import { Controller, FieldValues, ValidateResult } from 'react-hook-form' -export type MultiElectionQuestionsFormProps = { ConnectButton?: ComponentType } & ElectionQuestionsFormProps +export type SubmitFormValidation = (values: Record) => ValidateResult | Promise + +export type MultiElectionQuestionsFormProps = { + ConnectButton?: ComponentType + validate?: SubmitFormValidation +} & ElectionQuestionsFormProps export const MultiElectionVoteButton = (props: ButtonProps) => { const { isAbleToVote, voting, voted } = useMultiElections() @@ -29,12 +35,16 @@ export const MultiElectionQuestionsForm = ({ formId, onInvalid, ConnectButton, + validate, ...props }: MultiElectionQuestionsFormProps) => { + const styles = useMultiStyleConfig('ElectionQuestions') const { voteAll, fmethods, renderWith } = useMultiElections() + const { handleSubmit, control } = fmethods + return ( -
+ {renderWith.length > 0 && ( {renderWith.map(({ id }) => ( @@ -44,6 +54,27 @@ export const MultiElectionQuestionsForm = ({ ))} )} + {/*This controller is a trick to perform a form additional validation. + Adding the validation on the handleSubmit method caused UX errors when trying to rerun the validation again + because the error was already on error state. + On this way, the validation works as expected.*/} + ) => { + if (validate) return validate(formFields) + return true + }, + }} + render={({ fieldState: { error: fieldError } }) => { + return ( + + {fieldError?.message as string} + + ) + }} + /> ) }