Symfony3 - getErrors在Ajax表单中始终为空

时间:2017-07-12 11:27:42

标签: php jquery ajax forms symfony

我目前正在ajax中进行表单验证。 (我使用Symfony3)

我希望能够在ajax中编辑用户的信息。我的ajax查询工作正常,直到我的控制器无法传递函数$form->isValid()

我看了几篇文章和教程,但我的印象是版本3的操作不同(或者我只是犯了错误^^')

这是我在ajax中编辑用户的功能:

public function editMemberAction(Request $request, User $entity)
    {
        if ($request->isXmlHttpRequest()) {
            $form = $this->createForm('ProjectBundle\Form\User\UserType', $entity,array('validation_groups' => array('Default'), 'organisation' => array()));
            $form->handleRequest($request);
            if ($form->isValid()) {
                $em = $this->getDoctrine()->getManager();
                $passwordOriginal = $entity->getPassword();
                $plainPassword = $form->get('plainPassword')->getData();
                if (!empty($plainPassword)) {
                    $encoder = $this->get('security.password_encoder');
                    $encoded = $encoder->encodePassword($entity, $plainPassword);

                    $entity->setPassword($encoded);
                } else {
                    $entity->setPassword($passwordOriginal);
                }

                $entity->setUpdatedAt(new \DateTime('now', new \DateTimeZone('Europe/Paris')));
                $entity->setUpdatedBy($this->getUser());

                $em->persist($entity);
                $em->flush();
                return new Response(json_encode(array('success' => true)));
            } else {
                dump($form->getErrors());die();
                return new Response(json_encode(array(
                    'res'    => false,
                    'errors' => $this->getErrorsAsArray($form))));
            }

        }
        return new Response();
    }

即使我正确地填写了我的表单,我也会一直进入其他,当我想查看错误时,我总是得到一个空的错误数组。

当前的转储显示了一个巨大的数组:

My dump array

但是当我在表格底部的“错误”部分看到时,错误变量是空的:

errors array

我的用户类型表单:

class UserType extends AbstractType
{
    /**
     * {@inheritdoc}
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add('lastname',null,array('required' => true))
            ->add('firstname')
            ->add('gender',null,array('required'=>true))
            ->add('organisationMember',null,array(
                'required' => true,
                'choices' => $options['organisation'],
                'group_by' => 'type_organisation',
                'placeholder' => 'Choisissez votre organisation'
            ))
            ->add('job')
            ->add('mobile')
            ->add('phone')
            ->add('alert_failure')
            ->add('alert_full')
            ->add('alert_other')
            ->add('plainPassword', TextType::class, array('required' => false))
            ->add('email')
            ->add('profile', null, array(
                'required' => true,
                'placeholder' => 'Choose an organisation !',
            ));
    }

我的用户实体(只是一部分)带有Assert:

<?php

namespace ProjectBundle\Entity\User;

use Doctrine\ORM\Mapping as ORM;
use FOS\UserBundle\Model\User as BaseUser;
use Gedmo\Mapping\Annotation as Gedmo;
use Gedmo\SoftDeleteable\Traits\SoftDeleteableEntity;
use Gedmo\Timestampable\Traits\TimestampableEntity;
use ProjectBundle\Entity\Gender\Gender;
use ProjectBundle\Entity\Organisation\Organisation;
use ProjectBundle\Entity\Traits\BlameableEntity;
use ProjectBundle\Entity\User\Profile;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Component\Validator\Context\ExecutionContextInterface;
use Doctrine\Common\Collections\ArrayCollection;
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntityValidator;


/**
 * @ORM\Entity(repositoryClass="ProjectBundle\Repository\User\UserRepository")
 * @Gedmo\SoftDeleteable(fieldName="deletedAt")
 * @ORM\Entity
 * @UniqueEntity("email")
 * @ORM\Table(name="user")
 */
class User extends BaseUser
{
    use TimestampableEntity;
    use SoftDeleteableEntity;
    use BlameableEntity;
    /**
     * @var int
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;


    /**
     * @Assert\NotBlank(groups={"ajout"})
     */
    protected $username;

    /**
     * @Assert\NotBlank(groups={"registration"})
     * @Assert\Length(groups={"registration"},
     *      min = 2,
     *      max = 254,
     *      minMessage = "Votre mot de passe doit comporter au minimum {{ limit }} caractères.",
     *      maxMessage = "Votre mot de passe doit comporter au maximum {{ limit }} caractères."
     * )
     *
     * @var string
     */
    protected $plainPassword;


    /**
     * @Assert\NotBlank()
     *
     * @Assert\Email(
     *     message = "L'adresse mail '{{ value }}' n'est pas valide.",
     *     checkMX = true
     * )
     *
     * @var string
     */
    protected $email;

    /**
     * @var string
     * @Assert\NotBlank()
     *
     * @ORM\Column(name="lastname", type="string", length=100, nullable = true)
     */
    private $lastname;

    /**
     * @var string
     * @Assert\NotBlank()
     *
     * @ORM\Column(name="firstname", type="string", length=100, nullable = true)
     */
    private $firstname;

    /**
     * @var string
     * @Assert\NotBlank()
     * @ORM\Column(name="job", type="string", length=100)
     */
    private $job;

    /**
     * @var string
     * @Assert\NotBlank()
     * @ORM\Column(name="phone", type="string", length=15)
     */
    private $phone;

    /**
     * @var string
     *
     * @ORM\Column(name="mobile", type="string", length=15)
     */
    private $mobile;

即使我只检查移动字段,例如:

dump($form['email']->getErrors()->__toString());

它是空的..

所以我尝试使用如下函数:

private function getErrors($form)
    {
        $errors = array();

        if ($form instanceof \Symfony\Component\Form\Form) {

            // соберем ошибки элемента
            foreach ($form->getErrors() as $error) {

                $errors[] = $error->getMessage();
            }

            // пробежимся под дочерним элементам
            foreach ($form->all() as $key => $child) {
                /** @var $child \Symfony\Component\Form\Form */
                if ($err = $this->getErrors($child)) {
                    $errors[$key] = $err;
                }
            }
        }

        return $errors;
    }

但是错误数组总是再次为空..

有什么想法吗?谢谢 !

0 个答案:

没有答案