I want to have display-only fields to render data that’s never going to be changed nor submitted.
Similar to bootstrap’s static controls.
I need to show object data within a form without breaking the form structure or style. I want this data to use the same templates as all other inputs, but without rendering it as a dynamic input.
I thought of several ways to achieve this, some are plain hacks, some others seem more legitimate, but I wan’t to know if there is a more standard way to do this.
Here’s the list of options I have thought of in no particular order:
-
Use the read only property for fields: it does not feel very nice, I don’t want users to feel they can change something, but they are not allowed for some reason.
-
Hack the templates to output something other than input elements: seems very nasty to me, besides it would be necessary to handle server side the the missing fields on submits.
-
Extending field types to create display-only versions of them. I don’t think this would be safe.
-
Writing a custom fieldType to do the job. This option would be good to use as a base type for other fields.
I think the best solution is either option 3 or 4.
The only thing I still haven’t found is how to handle the missing fields on submit.
I think it’s important to have this type of fields because it allows reusing form types logic. Otherwise I end up writing twig templates that look like this:
<form>
{# This is the average writtable field #}
{{ form_row(form.field1) }}
{# This is the display-only field, notice I have to replicate
markup. Even if I wrote a macro, which I did, I would still
have to replicate markup in the macro.
#}
<label>Field 2</label>
<div>{{ the_object.field2 }}</div>
</form>
And finally, does anyone have a better idea or think that this approach is flawed altogether?
I finally used the read_only property and custom templates (a combination of options 1 and 2) to change the rendering of fields with the read_only property on.
Fields with the readonly property on are not expected to be sent (they are rendered with the disabled attribute, the same @elnur pointed out) and are rejected if present on POST, so all I had to do is change the templates to render differently.
Here is an example template:
Another way to do it would be using form extensions to create a new property for all fields, but the read_only property suit my needs.