什么时候调用 Symfony 表单中的验证器?

When to call validator in Symfony forms?

我不知道在这种情况下什么时候调用验证?我在 Form/Model/User.php class 中对属性做了一些约束,不知道在哪里调用它和 how.And 如何在同一页面上显示错误。 正确执行此操作的最佳做​​法是什么?

public function userRegistrationAction(Request $request) {
$formUser = new FormUser();
$form = $this->createForm(UserType::class, $formUser);
$form->handleRequest($request);

if($form->isSubmitted() && $form->isValid()) {
  $userEntity = new EntityUser();

  $name = $form['name']->getData();
  $surname = $form['surname']->getData();
  $email = $form['email']->getData();
  $password = $this->get('security.password_encoder')
    ->encodePassword($userEntity, $form['password']->getData());
  $now = new\DateTime('now');

  $userEntity->setName($name);
  $userEntity->setSurname($surname);
  $userEntity->setEmail($email);
  $userEntity->setPassword($password);
  $userEntity->setCreated($now);

  $entityManager = $this->getDoctrine()->getManager();
  $entityManager->persist($userEntity);
  $entityManager->flush();

  $request->getSession()
    ->getFlashBag()
    ->add('success', '- Success! ');

   return $this->render('AppBundle:Welcome:homepage.html.twig', array(
     'name' => $name,
     'lastName' => $surname,
   ));
}

好的,这是问题所在:'validation_groups' => ['registration'],我只为一个字段设置了这个组,现在我删除了这个并且工作得很好,在 isValid 之后不需要调用验证器。

public function configureOptions(OptionsResolver $resolver)
{
    $resolver->setDefaults(array(
        'validation_groups' => ['registration'], //delete this 
        'method' => 'post',
        'data_class' => User::class,
        'csrf_protection' => true,
        'cascade_validation' => true
    ));
}

您是否创建了一个 formUser 实体来填写表单然后填写用户实体?这会导致大量裁员。

您的控制器应如下所示:

<?php

public function userRegistrationAction(Request $request)
{
    $userEntity = new EntityUser();

    /*
      You can directly provide your user entity to your form
      There is no need to create a specific entity fir the form
    */ 
    $form = $this->createForm(UserType::class, $userEntity);

    $form->handleRequest($request);

    /*
      method isValid checks the form has been submitted so there 
      is no need to call isSubmitted by yourself
    */
    if ($form->isValid()) {
        /*
          The password encryption part could be improved by 
          doing it outside of the controller
        */
        $password = $this->get('security.password_encoder')
            ->encodePassword($userEntity, $userEntity->getPassword())
        ;
        $userEntity->setPassword($password);

        $entityManager = $this->getDoctrine()->getManager();

        /*
          By providing your user at your form at the begining all it
          remains to do is persisting it and flush the manager
          to insert it into your database.
        */
        $entityManager->persist($userEntity);
        $entityManager->flush();

        $this->addFlash('success', '- Success! ');

        return $this->render('AppBundle:Welcome:homepage.html.twig', array(
             'name' => $name,
             'lastName' => $surname,
        ));
    }

    return $this->render('AppBundle:User:userRegistration.html.twig', array(
        'form' => $form->createView()
    ));
}

现在你的表格应该是这样的

<?php

class UserType extends AbstractType
{
    /**
     * @param FormBuilderInterface $builder
     * @param array $options
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('name')
            ->add('surname')
            ->add('email')
            ->add('password', PasswordType::class)
            ->add('submit', SubmitType::class)
        ;
    }

    /**
     * @param OptionsResolver $resolver
     */
    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'AppBundle\Entity\EntityUser',
        ));
    }

    /**
     * @return string
     */
    public function getName()
    {
        return 'user_type';
    }
}

您的实体 EntityUser

<?php

/**
 * @ORM\HasLifecycleCallbacks()
 */
class EntityUser extends Entity
{
     /**
      * @ORM\PrePersist
      */
     public function setCreatedAtValue()
     {
        /*
          By using the PrePersist annotation you will automatically set
          the createdAt property
        */
        $this->createdAt = new \DateTime();
     }
}

最后是你的树枝模板

{# form_row is a shortcut to render at once
        form_errors(form.field)
        form_label(form.field)
        form_widget(form.field)
    so if you have errors on some of your fields there will be displayed #}

{{ form_start(form) }}
    {{ form_row(form.name) }}
    {{ form_row(form.surname }}
    {{ form_row(form.email) }}
    {{ form_row(form.password) }}
    {{ form_row(form.submit) }}
{{ form_end(form) }}