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'
));
}
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With