I'm trying to put html inside a form button with twig like:
{{ form_widget(form.jiraStatus, {
'label': '<i class="fa fa-bug"></i>Bug',
'attr':{'class': 'btn btn-large btn-default btn-block' }
}) }}
But doing this, the rendeded button shows like this:
<button type="submit" name="SolveTask[taskTypesFormObj][bugStatus]"
class="btn btn-large btn-default btn-block">
<i class="fa fa-bug"></i>Bug
</button>
As you can see, the html inside the button is encoded. I tried to use the raw filter, but the effect is the same. There is a way to do this?
Thanks!
Best Answer
Yes, but you'll have to customise your form theme.
A nice way to support icons in buttons is using form extensions. First create a form extension class that defines a new property icon that you can use in your forms:
Register this extension in your services.yml (or xml file). The alias must correspond with the string returned by the above
getExtendedType()
method.Next, override your
form_div_layout.html.twig
. (See link above) You can now useicon
as a variable in these themes. For buttons we override thebutton_widget
block:Finally, you can use the icon option in your template:
Or in your form classes:
Note: Is is generally better to add the icon in the template since icons are a matter of presentation, and your form classes should really be about buisness logic.
Make it even more generic:
By returning the FQCN of ButtonType in getExtendedType() we tell Symfony that we are extending all possible form elements that inherit from ButtonType such as SubmitType. Unfortunately there is no type we can use to target all possible form elements but we can add an extra extension that targets FormType. All form fields like input boxes and select elements inherit from this type. So if you want it to work with both form fields and buttons, I suggest the following:
Create an abstract class
abstract class AbstractIconExtension extends AbstractTypeExtension
with exactly the same content as above but leave out thegetExtendedType
method. Then create two classes that extend from this class (e.g.FieldTypeIconExtension
andButtonTypeIconExtension
) which only contain thegetExtendedType
method. One returning the FQCN ofFormType
and the other returning the FQCN ofButtonType
:Foo/BarBundle/Form/Extension/ButtonTypeIconExtension.php:
Foo/BarBundle/Form/Extension/FieldTypeIconExtension.php:
Register these two classes in you services using the corresponding alias:
Now you can use the
icon
variable in other places in your form themes as well. For instance, to add icons to labels you can override theform_label
block:And then add an icon to the label of that field in your form class: