Description
Suppose you've several form fields (let's say "color") in different place around the app that require a JS component for better UX. For simplicity, this component will not require any additional option, just the value (the hex color #AEA1FF
) that coming from the underlying data. And of course, it must be reusable.
How to put custom code easily together with the color input? What's the shortest path to achieve it? Yeah "Form Theming" so let's move forward.
(Step 1) Create a new form type (let's name it ColorPickerType
) which will extend from TextType
and nothing more, almost empty! Why this step? -> because we need a global/reusable block name in our form themes template to render the JS component code under <input />
tag -> for each color form field regardless what form it belongs to, and it's what precisely I want improve here: "I want to remove this step":
class ColorPickerType extends AbstractType
{
public function getParent(): string
{
return TextType::class;
}
}
(Step 2) Create the form themes template form/fields.html.twig
with the customized block:
{% block color_picker_widget %}
{{ form_widget(form, {'attr': {'v-model': 'color', '@focus': 'open'}}) }}
{# custom code here #}
{% endblock %}
Great! we already have a new block prefix called color_picker
allowing easy customization. Now, I need to configure my color fields with my new ColorPickerType
.
BUT what if you want to configure this block prefix without adding a new form type? Yes, you can currently through the block_name
option, but most of the time it'll work only for individual fields as each one is prefixed at the same time with the parent block prefix, that's always happening in my case (using EasyAdminBundle or SonataAdminBundle) where the root form always has a name. (see related source code)
And here is where my proposal comes from:
What about add an exclusive block prefix that don't depend of the parent form?
I'm thinking in a new option, maybe block_prefix
or better (default null
) if set add this prefix to the list, just before the unique prefix:
Example (After):
(Step 1) Instead of create a new form type, configure the block_prefix
option e.g. color_picker
.
(Step 2) Same as before.
What do you think?
Cheers!