Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Symfony2 disabled select

I'm trying to implement dynamic forms in Symfony2. The form is simple, first the user selects a broker, and then select an account according to that broker. Therefore, the account is disabled until the broker is selected.

In case of a text input, read_only => true could be a solution, but select has no attribute readonly. So, I made the select disabled, and then tried to enable the select with jQuery:

$('#form select').prop('disabled', false);

The problem is that on the server side, Symfony cannot handle the disabled form field. Its value is simply set to null.

I thought of possible solutions. First of all, I could manually set the field value in the controller, because I tested that the form field value is actually in the request parameter, Symfony just ignores to handle it and map it to the object. I think it would work, however it's not really nice solution.

Secondly, I can disable the select with some client side hacking, or add a hidden input to the form and manually set the value of it with Javascript.

Is there a standard solution here?

My form entity looks like this:

$builder->add('broker', 'entity', array(
    'class'         => 'MyBundle:Broker',
    'property'      => 'name',
    'query_builder' => function(BrokerRepository $br) {
                           return $br->getActiveBrokersQuery();
                       },
    'required'      => true,
    'empty_value'   => 'Choose a broker',
));

$builder->add('accountType', 'entity', array(
    'class'       => 'MyBundle:AccountType',
    'empty_value' => 'Choose a broker first',
    'disabled'    => true,
));

If I do not disable the select, everything works fine, Symfony handles the request perfectly.

like image 656
omgitsdrobinoha Avatar asked Dec 31 '13 11:12

omgitsdrobinoha


1 Answers

I managed to solve the problem, based on hakre's suggestions. So I needed to tell the form that the field is not disabled any more. Thus, I added a PRE_SUBMIT event to the form, in which i set the disabled value to false on the accountType field.

$builder->addEventListener(
            FormEvents::PRE_SUBMIT,
            function(FormEvent $event) {
                $event->getForm()->add('accountType', 'entity', array(
                    'class' => 'XXBundle:AccountType',
                    'empty_value' => 'Choose a broker first',
                    'disabled' => false
                ));
            }
        );

Thanks for your suggestions!

like image 93
omgitsdrobinoha Avatar answered Nov 18 '22 23:11

omgitsdrobinoha