0

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

2
  • Where did you save the validation.yml file? Commented Jan 20, 2016 at 12:18
  • in src/ApiBundle/Resource/config/ I think the file is loaded, as if I use the validator service straightly, it works. Commented Jan 20, 2016 at 13:34

1 Answer 1

1

Please replace with

$form->handleRequest();

to

$form->handleRequest($request);

I hope it will work.

Sign up to request clarification or add additional context in comments.

3 Comments

That would throw an exception, as handleRequest instanciates a NativeRequestHandler, which requires the $request param to be null
@Wminded what you mean "which requires the $request param to be null"?
the method has this check: if (null !== $request) { throw new UnexpectedTypeException($request, 'null'); }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.