Rolintocour
Rolintocour

Reputation: 3168

Symfony2: Dynamically validate a form

I have a form, based on various objects, that is built dynamically, with fields read in DB. This works fine.

Now I need to validate the form, with rules that are explained in the DB. Example of vaidation:

if($myobject->getValue() !=== $value_from_db) then addViolation('bzzzz')

Any explanation I found on the internet is related to static validation. Is there no way to apply a validator to a form or an object, so that the $form->isValid() method considers it ?

Note: I use Propel and not Doctrine.

Upvotes: 1

Views: 188

Answers (1)

Cerad
Cerad

Reputation: 48865

You can set constraints on individual form types.

use Cerad\Bundle\PersonBundle\ValidatorConstraint\AYSO\VolunteerIdConstraint  as IdConstraint;

class VolunteerIdFormType extends AbstractType
{
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
    $resolver->setDefaults(array(
        'label' => 'AYSO Volunteer ID (8-digits)',
        'attr'  => array('placeholder' => 'AYSO ID', 'size' => 10),
        'constraints' => new IdConstraint(),
    ));
}

Of course you will need to make your own custom constraints to get the database interaction. http://symfony.com/doc/current/cookbook/validation/custom_constraint.html#constraint-validators-with-dependencies

Upvotes: 1

Related Questions