【问题标题】:When to call validator in Symfony forms?何时在 Symfony 表单中调用验证器?
【发布时间】:2017-01-15 22:08:23
【问题描述】:

我不知道在这种情况下何时调用验证?我在Form/Model/User.php 类中对属性做了一些限制,不知道在哪里调用,怎么调用。以及如何在同一页面显示错误。 正确执行此操作的最佳做​​法是什么?

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,
   ));
}

【问题讨论】:

    标签: symfony symfony-forms symfony-validator


    【解决方案1】:

    您是否创建了一个 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) }}
    

    【讨论】:

    • 我发现了问题所在,tnx for nice adice
    【解决方案2】:

    好的,这就是问题所在:'validation_groups' => ['registration'],我只为一个字段设置了这个组,现在我删除它并且工作正常,不需要 callig 验证器在 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
        ));
    }
    

    【讨论】:

    • $form->isValid() 只要您设置了验证,就会自动为您验证表单,不需要其他任何内容。
    猜你喜欢
    • 2013-07-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-23
    • 1970-01-01
    • 1970-01-01
    • 2016-03-08
    • 1970-01-01
    相关资源
    最近更新 更多