Required Fields on Symfony Forms

For the past three days I have been tearing my hair out. The problem was trying to show the required fields on a Symfony form. Kris Wallsmith has a nice method for achieving this here: http://kriswallsmith.net/post/144021872/symfony-denote-required-form-fields

Unfortunately every single field in the form was showing as required. Having created the database schema, and set the validators, I knew for certain that every field on the form was not “required” and should not show as such. Ah, but how to fix it?

After much head scratching and pulling out of hair, the answer finally struck me. Here it is in case you stumble upon the same problem.

If you’ve read the Practical Symfony book, or worked your way through the Jobeet tutorial, you will have read the phrase “It is almost always better to add the new validator to the existing ones by using the special sfValidatorAnd validator”. This is true, unless the existing validator is setting the field as required and the new validator is not. This is what was happening in my case. I was using:

  $this->validatorSchema['email'] = new sfValidatorAnd(array(
    $this->validatorSchema['email'],
    new sfValidatorEmail(),
  ));

when, to get the desired effect I needed:

  $this->validatorSchema['email'] =
    new sfValidatorEmail();

Replacing the validators insteading of adding new ones to the old ones solved the problem.

{lang: 'en-GB'}

WordPress Themes