简体   繁体   English

Symfony2-在REST API项目中使用表单验证

[英]Symfony2 - using form validation in REST API project

In a Symfony REST API project and we are implementing a validation for the params passed to the end points. 在一个Symfony REST API项目中,我们正在对传递到端点的参数进行验证。 I'm trying to using forms for this purpose but they don't seem to work as expected. 我正在尝试为此目的使用表单,但是它们似乎无法按预期工作。

Given this end point as example: 以这个端点为例:

GET /users/

which accepts a companyId as param 接受companyId作为参数

we want that this param is required and integer. 我们希望此参数是必需的并且是整数。

The controller 控制器

public function getUsersAction(Request $request)
{
    $user = new User();

    $form  = $this->createForm(new UserType(), $user, array(
        'method' => 'GET'
    ));

    $form->handleRequest();

    if ( ! $form->isValid()) {
        // Send a 400
        die('form is not valid');
    } else {
        die('form is valid');
    }
}

The form type 表格类型

class UserType extends FormType
{
    /**
     * @param FormBuilderInterface $builder
     * @param array                $options
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        parent::buildForm($builder, $options);
        $builder->add('companyId', 'integer');
    }

    /**
     * @param OptionsResolver $resolver
     */
    public function configureOptions(OptionsResolver $resolver)
    {
        parent::configureOptions($resolver);

        $resolver->setDefaults(array(
            'data_class' => 'ApiBundle\Entity\User',
            'csrf_protection' => false

        ));
    }

    /**
     * @return string
     */
    public function getName()
    {
        return ''; // if this is not empty, the form is not submitted at all
    }
}

The validation.yml validation.yml

ApiBundle\Entity\User:
    properties:
        companyId:
            - Type:
                type: integer
            - NotBlank: ~
            - NotNull: ~

The config.yml config.yml

framework:
    validation:      { enabled: true, enable_annotations: false }

The Problem 问题

$form->isValid() in the controller is always true 控制器中的$ form-> isValid()始终为true

Please replace with 请替换为

$form->handleRequest();

to

$form->handleRequest($request);

I hope it will work. 我希望它能起作用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM