Require a field in symfony2 server side

61 Views Asked by At

I have a form in Symfony2 which I am building with buildForm I add constraints like so,

$builder
->add('firstName', 'text', [
        'required' => true,
        'constraints' => [
            new NotBlank(),
        ],
    ]
)

Everything works fine until I delete the input from my html and submit it without the firstName. I don't get any errors and it submits normally. Is there a way to absolutely require the firstName, even if is not present in the submit data

2

There are 2 best solutions below

2
Benoît On BEST ANSWER

You must use an assert with your entity as explained in the symfony documentation here

like this:

class User
{
    /**
     * @orm:Column(type="string", nullable=false)
     * @assert:NotBlank
     */
    private $firstname;
}
0
Mike Doe On

You did not submit any data, the form is not submitted hence no validation is triggered.

Instead of:

$this->handleRequest($request);

Try to always submit the form even if the data is missing:

$form->submit($request->request->all());

I cannot guarantee this code is valid in your context since you did not provide your controller code.