2

I have an entity class quote that has a field amount and this field should be less than a dynamic value which is set in the controller's newAction.

I am adding the amount field in the formtype class and My buildForm method in it is as follows

public function buildForm(FormBuilderInterface $builder, array $options)
{   
    $builder
        ->add('truckType')
        ->add('costPerTruck')
        ->add('amount');

    $builder->addEventSubscriber(new AddQuoteDetailFieldSubscriber());
}

My subscriber class is as follows

class AddQuoteDetailFieldSubscriber implements EventSubscriberInterface
{
    public static function getSubscribedEvents()
    {
        return array(FormEvents::PRE_SET_DATA => 'preSetData');
    }

    public function preSetData(FormEvent $event)
    {
        $product = $event->getData();
        $form = $event->getForm();

        if (null !== $product && null !== $product->getLimit()) {

            if($product->getLimit() > 0){
                $form->add('amount',null, array(
                    'data' => $product->getLimit(),
                    'constraints' => array(
                       new LessThanOrEqual(array('value' => $product->getLimit())),
                )));
            }
        }
    }
}

The issue is that the limit is correctly being set and displayed in the amount field but the constraint doesn't seem to be doing anything and is letting values greater than the limit go through.

If I add a limit in the buildForm method like

$builder
    ->add('truckType')
    ->add('costPerTruck')
    ->add('amount',null,array('constraints' => array(
       new LessThanOrEqual(array('value' => 10)),
    )));

Then the field is being constrained.

Been hitting my head against the wall with this one, does anybody have any clue what am I doing wrong? or any other way of achieving this?

Thanks!

user972616
  • 1,324
  • 3
  • 18
  • 38
  • Probably because the field has already been created. I suggest you to take a look at [Callback validation](http://symfony.com/doc/current/reference/constraints/Callback.html) chapter, it might be the right thing for you. – Artamiel Nov 17 '15 at 12:41
  • 1
    Yes, I also think calling `$form->remove('amount');` before `$form->add` should do the trick. (Be aware that custom View- and Modeltransformers are lost in that case. In order to reassign them you would have to create a custom FormType for your amount field.) – Atan Nov 17 '15 at 13:23

0 Answers0