Configuring the output of {{ field.input|raw }}
Created 6 years ago by cleancookie

I've made a form using the form module, but we've noticed {{ field.input|raw }} doesn't spit out IDs with the fields. That, along with other things we've resorted to doing:

<label for="{{ field.field }}" class="col-md-3 control-label">{{ field.label }}</label>
<div class="col-md-7">
    {{ form_text(
            id: field.field,
            class: 'form-control',
            required: 'true'
    ) }}

Is there a nicer / cleaner way of doing this? I couldn't find anything in the documentation, or video guides.

ryanthompson  —  6 years ago

Depends on why you need IDs I suppose. There is plenty in there for CSS selection 😄

I could add IDs but I think my intention was skipping them because they're mandate of being unique and potentially multiple forms but.. I could put in IDs I suppose of {{ field.input_name }} since that is supposed to be unique.

But for example if you have a field called header (maybe a dropdown for header style) that can easily collide with #header styles you have setup. Which is what I was trying to avoid. Hopefully that makes sense 😛

cleancookie  —  6 years ago

What I really meant was, suppose I wanted to add some data-test attributes, is there an easy way to add my own attributes?

ryanthompson  —  6 years ago

@cleancookie indeed - you can do something like this:

So that might look like this inline:

{{ form.fields.test_example.addAttribute('id', 'Foo bar').render|raw }}

Or if you override the form fields you can add attributes too:

    '*': '*', // All other fields
    'test_example: { 'attributes': { your attributes}}

Which is basically defining fields like you would on a form builder but in Twig syntax: