symfony2的FOSRestController无法验证ajax post请求

MiG*_*iGU 9 validation rest 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;
    }
Run Code Online (Sandbox Code Playgroud)

我的图库实体课程如下:

<?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;
    }
}
Run Code Online (Sandbox Code Playgroud)

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';
    }
}
Run Code Online (Sandbox Code Playgroud)

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

validation:      { enable_annotations: true }
Run Code Online (Sandbox Code Playgroud)

为了获得验证错误,我还尝试使用以下函数,但未成功:

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;
} 
Run Code Online (Sandbox Code Playgroud)

编辑:

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

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

所以它就像我的GalleryType没有使用验证器.

Kam*_*nek 1

我猜这是因为您正在使用handleRequest空提交的数据。在这种情况下,您可以这样调用:

// remove form->handleRequest call
// $form->handleRequest($this->getRequest());
$form->submit($request->request->all());
Run Code Online (Sandbox Code Playgroud)

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

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

`Gallery` => []
Run Code Online (Sandbox Code Playgroud)

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

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