Wminded
Wminded

Reputation: 15

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. 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

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

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

The config.yml

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

The Problem

$form->isValid() in the controller is always true

Upvotes: 0

Views: 795

Answers (1)

Ashok Chitroda
Ashok Chitroda

Reputation: 361

Please replace with

$form->handleRequest();

to

$form->handleRequest($request);

I hope it will work.

Upvotes: 1

Related Questions