Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Symfony form read only field

How should I render read-only fields using Symfony form component?

This is how I am trying to do that to no avail:

Symfony 2

$builder
    ->add('descripcion', 'text', array(
        'read_only' =>'true'
    ));
}

Symfony 3

$builder
    ->add('descripcion', TextType::class, array(
        'read_only' => 'true'
    ));
}
like image 370
Bicu Avatar asked Oct 31 '12 13:10

Bicu


3 Answers

Provided answers all end up with this exception on Symfony 3:

Uncaught PHP Exception Symfony\Component\OptionsResolver\Exception\UndefinedOptionsException: "The option "read_only" does not exist.

The right way to do this is to take advantage of attr property on the field:

->add('descripcion', TextareaType::class, array(
    'attr' => array(
        'readonly' => true,
    ),
));

If you are after way to have a field with data not posted to the server during form submission, you should use disabled like:

->add('field', TextareaType::class, array(
    'disabled' => true,
));

on your form builder object.

like image 121
Pmpr.ir Avatar answered Oct 21 '22 07:10

Pmpr.ir


I believe the only secure method to present a form field as readonly and also prevent your form from accepting a new value in a request is the following.

$builder->add(
    'description',
    TextType::class,
    ['disabled' => true]
);

The other suggestion of using either ['attr' => ['readonly' => true]] or ['attr' => ['disabled' => true]] will leave you vulnerable to forged requests.

Both the latter options will set either readonly or disabled attributes on the field, but your Form will still accept a new value for this field if included in the request.

Only the first option above will both disable the form field and also prevent your Form from accepting a new value for the field in the request.

I have tested this with Symfony Form 3.4. I do not know if 4 behaves the same.

like image 16
Courtney Miles Avatar answered Oct 21 '22 05:10

Courtney Miles


You have declared your read only attribute to a string, it needs to be a boolean.

remove the quotes around true

like this:

->add('descripcion','text',array('read_only' => true))

true, without the quotes.

like image 9
Andrew Atkinson Avatar answered Oct 21 '22 05:10

Andrew Atkinson