symfony2的FOSRestController无法验证ajax post请求

时间:2016-04-30 22:08:58

标签: rest validation symfony

我正在开发一个Symfony 2.6.1应用程序,我有一个使用FormTypes呈现的表单和一个使用注释作为验证的实体。表单被提交给FOSRestController的AJAX POST调用。问题是isValid()函数返回FALSE并且我没有收到任何错误消息......

我的FOSRestController看起来如下:

class RestGalleryController extends FOSRestController{

    /**
     * @Route(requirements={"_format"="json"})
     */
    public function postGalleriesAction(\Symfony\Component\HttpFoundation\Request $request){

        return $this->processForm(new \Law\AdminBundle\Entity\Gallery());   
    }
    private function processForm(\Law\AdminBundle\Entity\Gallery $gallery){

        $response = array('result' => 'Default');

        $gallery->setName('TEST'); //Just added this to be sure it was a problem with the validator
        $form = $this->createForm(
            new \Law\AdminBundle\Form\Type\GalleryType(), 
            $gallery
        );
        $form->handleRequest($this->getRequest());

        if ($form->isValid()) {

            $response['result'] = 'Is Valid!';
        }else{
            var_dump( $form->getErrorsAsString() );
            die;           
        }
        return $response;
    }

我的图库实体课程如下:

<?php

namespace Law\AdminBundle\Entity;

use Doctrine\Common\Collections\ArrayCollection;
use Symfony\Component\Validator\Constraints as Assert;
use Doctrine\ORM\Mapping as ORM;

/**
 * Gallery
 *
 * @ORM\Table(name="gallery")
 * @ORM\Entity
 */
class Gallery{

    /**
     * @var string
     * @Assert\NotBlank()
     * @ORM\Column(name="name", type="text", nullable=false)
     */
    private $name;

    public function __construct(){
        $this->images = new ArrayCollection();
    }
    /**
     * Set name
     *
     * @param string $name
     * @return Gallery
     */
    public function setName($name){
        $this->name = $name;

        return $this;
    }
    /**
     * Get name
     *
     * @return string 
     */
    public function getName(){
        return $this->name;
    }
}

GalleryType,封装形式:

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;

class GalleryType extends AbstractType
{
    /**
     * {@inheritdoc}
     */
    public function buildForm(FormBuilderInterface $builder, array $options){
        $builder->add('name');
    }
    /**
     * {@inheritdoc}
     */
    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setDefaults(array(
            'data_class'        => 'Law\AdminBundle\Entity\Gallery',
            'csrf_protection'   => false,
        ));
    }
    /**
     * {@inheritdoc}
     */
    public function getName()
    {
        return 'Gallery';
    }
}

最后,在我的app / config / config.yml中,验证设置如下:

validation:      { enable_annotations: true }

要获得验证错误,我还尝试使用以下功能,但未成功:

private function getErrorMessages(\Symfony\Component\Form\Form $form) {
    $errors = array();

    foreach ($form->getErrors() as $key => $error) {
        if ($form->isRoot()) {
            $errors['#'][] = $error->getMessage();
        } else {
            $errors[] = $error->getMessage();
        }
    }

    foreach ($form->all() as $child) {
        if (!$child->isValid()) {
            $errors[$child->getName()] = $this->getErrorMessages($child);
        }
    }

    return $errors;
} 

修改

如果我手动使用验证器,它可以工作:

    $formGallery = new Gallery();
    $formGallery->setName($this->getRequest()->get('name', NULL));
    $validator = $this->get('validator');
    $errors = $validator->validate($formGallery);

所以我的GalleryType并没有使用验证器。

1 个答案:

答案 0 :(得分:1)

这是因为我猜你使用handleRequest空提交的数据。在这种情况下你可以这样称呼:

// remove form->handleRequest call
// $form->handleRequest($this->getRequest());
$form->submit($request->request->all());

因为handleRequest将自动提交表单,除非存在一个字段。处理空array表格的请求时,表单未提交,这就是为什么isValid返回false没有错误。

注意:检查您是否发送空POST数组或类似:

`Gallery` => []

如果要发送空的Gallery数组,一切都应该按预期工作。

您可以粘贴通过AJAX请求发送的数据吗?