Symfony form read only field

Bicu picture Bicu · Oct 31, 2012 · Viewed 45.1k times · Source

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'
    ));
}

Answer

Pmpr picture Pmpr · Jun 15, 2017

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.