2

Im sure this must be a RTM question, but I must be looking in the wrong places. In symfony 1.4 I used post validator callbacks quite a lot. For example checking that start and end dates were in the correct order. I am developing an app in Silex but cant figure out how to add similar functionality as a validator. This is what I am working with (basically):

$app['form.example'] = function ($app) {
    $constraints = new Assert\Collection(array(
        'date1' => new Assert\Date(),
        'date2' => new Assert\Date(),
    ));

    $builder = $app['form.factory']->createNamedBuilder('form', 'example', array(), array('validation_constraint' => $constraints));

    return $builder
        ->add('date1', 'date')
        ->add('date2', 'date')
        ->getForm();
};

I can put my own validation test in the 'process form' part, like: if ($form->isValid() && --my datetest--) but it doesnt feel right to me there.

Any help? Thanks!

lopsided
  • 2,160
  • 6
  • 25
  • 38

1 Answers1

7

I guess you can use form events for this kind of thing; certainly for Symfony2, so I assume Silex too? There's a cookbook article about using it to generate dynamic forms:

http://symfony.com/doc/current/cookbook/form/dynamic_form_generation.html

Some useful detail in another SO question:

Description of Symfony2 form events?

Could have sworn I had a SO discussion about this with someone before but I cannot find the question. I used BIND_CLIENT_DATA to calculate some form fields in some code a while back; I'll see if I can dig it out.

EDIT

Okay, I found something but I'm modifying this from Symfony code so I'm not 100% on this but it might be a starting point (I hope):

$builder->addEventListener(FormEvents::BIND_NORM_DATA, function($event) {
    // your form data
    $data = $event->getData();

    // get date objects - if you cannot dereference this way try getters
    $d1 = $data['date1'];
    $d2 = $data['date2'];

    // naive comparison :)
    $isCorrectDateOrder = $d1->getTimestamp() < $d2->getTimestamp();

    // check the comparison
    if (!$isCorrectDateOrder) {
        // trouble... create and add a FormError object to the form
        $event->getForm()->get('date1')->addError(new \Symfony\Component\Form\FormError('uh oh...'));
    }
});

Hope this helps :)

Community
  • 1
  • 1
Darragh Enright
  • 12,194
  • 6
  • 37
  • 44