How can I add a violation to a collection?

后端 未结 3 1095
天命终不由人
天命终不由人 2020-12-10 06:06

My form looks like this:

public function buildForm(FormBuilderInterface $builder, array $options)
{
    $factory = $builder->getFormFactory();

    $build         


        
3条回答
  •  渐次进展
    2020-12-10 06:23

    I have a case very similar. I have a CollectionType with a Custom Form (with DataTransformers inside, etc...), i need check one by one the elements and mark what of them is wrong and print it on the view.

    I make that solution at the ConstraintValidator (my custom validator):

    The validator must target to CLASS_CONSTRAINT to work or the propertyPath doesnt work.

    public function validate($value, Constraint $constraint) {
        /** @var Form $form */
        $form = $this->context->getRoot();
        $studentsForm = $form->get("students"); //CollectionType's name in the root Type
        $rootPath = $studentsForm->getPropertyPath()->getElement(0);
    
        /** @var Form $studentForm */
        foreach($studentsForm as $studentForm){
            //Iterate over the items in the collection type
            $studentPath = $studentForm->getPropertyPath()->getElement(0);
    
            //Get the data typed on the item (in my case, it use an DataTransformer and i can get an User object from the child TextType)
            /** @var User $user */
            $user = $studentForm->getData();
    
            //Validate your data
            $email = $user->getEmail();
            $user = $userRepository->findByEmailAndCentro($email, $centro);
    
            if(!$user){
                //If your data is wrong build the violation from the propertyPath getted from the item Type
                $this->context->buildViolation($constraint->message)
                    ->atPath($rootPath)
                    ->atPath(sprintf("[%s]", $studentPath))
                    ->atPath("email") //That last is the name property on the item Type
                    ->addViolation();
            }
        }
    }
    

    Just i validate agains the form elements in the collection and build the violation using the propertyPath from the item in the collection that is wrong.

提交回复
热议问题