Reputation: 77
I need to change the max value for the range validator in Symfony at runtime, while building the form with FormBuilder. Has anybody an idea how to do this?
Upvotes: 3
Views: 2679
Reputation: 77
As I wrote before in my comment I used a solution like this:
first part of the range:
class Entity {
//@Assert\NotBlank()
private $property;
}
second part of the range:
$formBuilder->get('property')->addEventListener(FormEvents::POST_SUBMIT,
function(FormEvent $event) use ($something) {
$property = $event->getForm()->getData();
if ($property > $something) {
$event->getForm()->addError(new FormError(...));
}
}
);
Hope this was helpful
Upvotes: 1
Reputation: 105908
Well, Symfony is designed so that the constraints are attached to the underlying object/data, not the form (type) itself.
However, you can add constraints directly to the form if the form is not mapped to a class.
http://symfony.com/doc/current/book/forms.html#adding-validation
Basically, you can define a constraints
option in the form builder which should be an array of constraint objects.
use Symfony\Component\Validator\Constraints\Range;
$builder->add('your_field', null, array(
new Assert\Range(array(
'min' => 10
, 'max' => $someDyanmicValue
, 'minMessage' => 'min error message'
, 'maxMessage' => 'max error message'
))
));
If your form is mapped to a class where the Range constraint is defined, you'll have to go about this a different way. Let me know.
Upvotes: 4