Overriding symfony radio widget - php

Default radio widget creates a following structure:
<label>...</label>
<div id="...">
<div class="clearfix prettyradio labelright blue">
<input type="radio" id="..._0" name="..." value="..." style="display: none;">
...
</div>
I found the radio_widget block, but it contains only an input itself. So I can customize there only this part:
<input type="radio" id="..._0" name="..." value="1" style="display: none;">
But I can't understand how to change whole the structure of radio choice field?
Also, does anybody knows, why symfony adds display:none to the input?
Thanks.

if you're using Radio Field Type, you can customize only the input part of the radio_widget block by calling form_widget(form.yourField), all it displays is,
{% block radio_widget %}
{% spaceless %}
<input type="radio" {{ block('widget_attributes') }}{% if value is defined %} value="{{ value }}"{% endif %}{% if checked %} checked="checked"{% endif %} />
{% endspaceless %}
{% endblock radio_widget %}
But if you're using Choice Field Type to display Radio Fields (expanded => true and multiple => false). You'll then have to override the choice_widget block, which call for each child element the radio_widget block surrounded by a global div
How did you get the "display:none"? because there's no style such this in the default block.

If you specifically want to override the way an individual radio field is rendered - i.e. how each input field in the group is rendered - use this formula for the block name:
_<form name>_<field name>_entry_widget
Note this bit: _entry
If you're using an expanded choice field ..._entry_row and ..._entry_label won't work because they aren't used for the individual choices - well for radio buttons at least.
More generally you can find out a lot about which block Symfony intends to use during the next call to {{ form_widget(form) }} function call using this code:
{% for b in form.vars.block_prefixes %}
{{ dump(b) }}
{% endfor %}
or you might want to look at child in some situations:
{% for b in child.vars.block_prefixes %}
{{ dump(b) }}
{% endfor %}

Related

Symfony3 form builder form field in span instead of div

I have Symfony3 app and I am making a simple form the code in the twig is as follows
{{ form_start(edit_form) }}
{{ form_widget(edit_form) }}
<input type="submit" value="Edit" />
{{ form_end(edit_form) }}
Pretty simple. What this code creates is a form and each form field is within it's own <div> which is fine, but if the type is date here is what the generated html looks like
<div>
<label class="required">Term</label>
<div id="appbundle_project_term">
<select id="appbundle_project_term_year" name="appbundle_project[term][year]"></select>
<select id="appbundle_project_term_year" name="appbundle_project[term][month]"></select>
<select id="appbundle_project_term_year" name="appbundle_project[term][day]"></select>
</div>
</div>
What bugs me is the inner div created for the date type field. Is there a way in the FormBuilder to keep the type date but remove this inner div without using javascript to handle it or in the twig template. Simply to say - "inner tag => span".
This is pretty generic question as I am looking for a way to usually change the auto generated tags, but if needed here is how this form field is created in form builder
add('term',DateType::class, array(
'widget' => 'choice',
'label'=>"Term",
'data'=>$project->getTerm()
))
You can override form rendering, there are few ways.
The simplest one is overriding form theme widget block (in this case date_widget) and setting form_theme to _self.
Basic example:
{% form_theme form _self %}
{% block date_widget %}
<span>
{% if widget == 'single_text' %}
{{ block('form_widget_simple') }}
{% else %}
{# rendering 3 fields for year, month and day #}
{{ form_widget(form.year) }}
{{ form_widget(form.month) }}
{{ form_widget(form.day) }}
{% endif %}
</span>
{% endblock %}
{% block content %}
{# ... form rendering #}
{{ form_row(form.someDateField) }}
{% endblock %}

How can I render an entity (choice <select>) field as a <ul> field in Twig?

Symfony renders an entity field type like a choice dropdown - a select, basically. However, the CSS framework that I'm using defines a sort of 'select' as a ul and li as the options. The Custom Field Type documentation gives no help on this scenario.
I'm converting my code from manual HTML rendering of the form dropdown to symfony form's version using twig and form_widget(). However, I want a ul and li instead of a select.
The manual way of creating my dropdown is:
<ul class='dropdown-menu'>
{% for locator in locators %}
<li>
<a href="#" data-id="{{locator.getId() }}">
{{ locator.getName() }}
</a>
</li>
{% endfor %}
</ul>
That's how I would render my dropdown manually before using symfony forms. It looks like this:
I like it. I think it looks awesome. Now, if I'm using Symfony forms, I can just use this instead:
{{ form_start(form) }}
{{ form_widget(form.locator) }} {# This is my locator dropdown #}
{{ form_widget(form.target) }} {# Ignore this #}
{{ form_end(form) }}
The problem is that this renders this instead:
I can't add my custom CSS here because this is rendered as a select instead of an unordered list and lis.
In case it may help, here's my form type being built:
/**
* {#inheritDoc}
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('target')
->add('locator', 'entity', [
'class' => 'Application\Model\Entity\Locator',
'query_builder' => function(EntityRepository $repo) {
return $repo->createQueryBuilder('e');
},
'empty_value' => 'Locator'
])
->add('save', 'submit', ['label' => 'Save']);
$builder->setAction($this->urlGenerator->generate('page_create_element', [
'suiteId' => $options['suiteId'], 'pageId' => $options['pageId']
]))->setMethod('POST');
}
The Question: Is there any way I can have the form commands above auto-generate my ul / li requirement instead of selects, or do I have to render this manually instead and ignore the symfony forms component for this?
Thanks to some of the posters above, there was some information from Form Theming, but it wasn't exactly enough to go along with so I had to do a little bit of digging on github.
According to the documentation, Symfony uses twig templates to render the relevant bits of a form and it's containing elements. These are just {% block %}s in twig. So the first step was to find where a select button is rendered within the symfony codebase.
Form Theming
Firstly, you create your own theme block in it's own twig file and you apply this theme to your form with the following code:
{% form_theme my_form_name 'form/file_to_overridewith.html.twig %}
So if I had overridden {% block form_row %} in the file above, then when I called {{ form_row(form) }} it would use my block instead of Symfony's default block.
Important: You don't have to override everything. Just override the things you want to change and Symfony will fall back to it's own block if it doesn't find one in your theme.
The Sourcecode
On github I found the source code for Symfony's "choice widget". It's a little complex but if you follow it through and experiment a little bit you'll see where it goes.
Within the choice_widget_collapsed block, I changed the select to uls and options to lis. Here's the theme file I created, note the minor differences described above:
{# Symfony renders a 'choice' or 'entity' field as a select dropdown - this changes it to ul/li's for our own CSS #}
{%- block choice_widget_collapsed -%}
{%- if required and empty_value is none and not empty_value_in_choices and not multiple -%}
{% set required = false %}
{%- endif -%}
<ul {{ block('widget_attributes') }}{% if multiple %} multiple="multiple"{% endif %}>
{%- if preferred_choices|length > 0 -%}
{% set options = preferred_choices %}
{{- block('choice_widget_options') -}}
{%- if choices|length > 0 and separator is not none -%}
<li disabled="disabled">{{ separator }}</li>
{%- endif -%}
{%- endif -%}
{%- set options = choices -%}
{{- block('choice_widget_options') -}}
</ul>
{%- endblock choice_widget_collapsed -%}
{%- block choice_widget_options -%}
{% for group_label, choice in options %}
{%- if choice is iterable -%}
<optgroup label="{{ group_label|trans({}, translation_domain) }}">
{% set options = choice %}
{{- block('choice_widget_options') -}}
</optgroup>
{%- else -%}
<li value="{{ choice.value }}"{% if choice is selectedchoice(value) %} selected="selected"{% endif %}>{{ choice.label|trans({}, translation_domain) }}</li>
{%- endif -%}
{% endfor %}
{%- endblock choice_widget_options -%}
Rendering
Now I can render my form with the following:
{{ form_widget(form.locator, {'attr': {'class': 'dropdown-menu'}}) }}
This uses my theme for the choice dropdown which contains ul and li tags instead of select and option ones. Pretty simple once you know where to look for the original code! The rendered HTML:
<ul id="elementtype_locator" name="elementtype[locator]" required="required" class="dropdown-menu">
<li value="1">id</li>
<li value="2">name</li>
<li value="3">xpath</li>
</ul>
I also had to remove one of the lines that put 'Locator' at the top of the dropdown as there were four dropdown choices (including the empty_data one) instead of three.

Customising form rows in a collection form field

I am trying to customise a specific form row in my form layout. From the symfony cookbook it tells me, if i understand correctly, that I can modify the form by adding a code block in my form theme file.
I am adding the field to the form like this:
->add('editions', 'collection',
array('type' => new EditionType(),
'allow_add' => true,
'allow_delete' => true,
'by_reference' => false,
)
)
I generate the form rows in the template in the following way, I need the data-prototype tag because the user needs to possibility to add an edition when viewing the form:
<div class="editions" data-prototype="{{ form_widget(form.editions.vars.prototype)|e }}">
{% for edition in form.editions %}
<section class="edition-container">
{{ form_label(edition.isbn) }}
{{ form_errors(edition.isbn) }}
{{ form_widget(edition.isbn) }}
</section>
{% endfor %}
</div>
To customise the rows for the 'editions' fields I tried the following:
<!-- Custom form theme for textarea label rows -->
{% block textarea_label %}
{% spaceless %}
<div {{ block('label_container_attributes') }}>
<label class="label">{{ label }}</label>
</div>
{% endspaceless %}
{% endblock %}
<!-- Custom form theme for edition field textarea label rows -->
{% block _booklist_editions_label %}
{% spaceless %}
<div {{ block('label_container_attributes') }}>
<label class="label">{{ label }}!</label>
</div>
{% endspaceless %}
{% endblock %}
Unfortunately the second block isn't working, the first block however does work. What I did notice is that the outer div from the editions field does not have an id attribute with the field name in it.
This makes me think that the solution to the problem could be one of these:
Custom form theme block has the wrong name, don't know what other name I should give it then.
The id's is not added to the outer div, therefor it's not 'linking' the custom form style.
Could someone explain me how I can add a custom form theme to my 'editions' field using an external form theme file or how I can achieve this in another way.

Add a css class on “form_widget” when errors happen

I would like add a CSS class on a form_widget() when errors (specific to field) happen.
For now, I have this code :
{{ form_widget(form.firstName, {'attr': {'class': 'text-input'}}) }}
It generates this HTML code :
<input type="text" id="userbundle_member_firstName" name="userbundle_member[firstName]" required="required" class="text-input" />
It's good but I want when error(s) happen (exemple the value is too short), a css class will added. So, I want to have something like that :
<input type="text" id="userbundle_member_firstName" name="userbundle_member[firstName]" required="required" class="text-input error-input" />
I tried searching solution on the doc (especially here), but I have not been able to do what I want.
Thank you for your help :D !
Tell Twig about your custom form's templates:
app/config/config.yml
twig:
debug: %kernel.debug%
strict_variables: %kernel.debug%
form:
resources:
- 'YourBundle::form.html.twig'
And override them (check vendor/symfony/symfony/src/Symfony/Bridge/Twig/Resources/views/Form):
src/YourBundle/Resources/views/form.html.twig
{% block form_widget_simple %}
{% if form.vars.errors|length > 0 %}
{% set class = attr.class is defined ? attr.class ~ ' error' : 'error' %}
{% set attr = attr|merge({'class': class}) %}
{% endif %}
{% spaceless %}
{% set type = type|default('text') %}
<input type="{{ type }}" {{ block('widget_attributes') }} {% if value is not empty %}value="{{ value }}" {% endif %}/>
{% endspaceless %}
{% endblock form_widget_simple %}
UPDATE
The method described above will change the rendering of all the form fragments, if you only need to change some form then you can do it locally, just read the docs (https://symfony.com/doc/current/book/forms.html#form-theming)

HTML in Symfony2 form labels instead of plain text

I am trying to implement something like this:
<div>
<input type="checkbox" name="checkbox" id="checkbox_id" />
<label for="checkbox_id">I agree to the Terms of Service</label>
</div>
The closest I've come to implement this is through:
<div>
{{ form_widget(form.agreeWithTos) }}
<label for="{{ form.agreeWithTos.vars.id }}">I agree to the Terms of Service</label>
</div>
Is there a better way? Having to specify {{ form.agreeWithTos.vars.id }} is inelegant. :)
Solved this problem using the following code in my form-theme:
{# ---- form-theme.html.twig #}
{% block checkbox_row %}
{% spaceless %}
<div>
{{ form_errors(form) }}
<label class="checkbox" for="{{ form.vars.id }}">
{{ form_widget(form) }}
{{ label|default(form_label(form)) | raw }}
</label>
</div>
{% endspaceless %}
{% endblock %}
in your Form-Template you can then use:
{% form_theme form '::form-theme.html.twig' %}
{{form_row(form.termsOfServiceAccepted, {
'label' : 'I have read and agree to the Terms and conditions'
})
}}
this way, the block from the form-theme would apply to any checkbox on the page. If you need to also use the default-theme, you can add a parameter to enable special-rendering:
{# ---- form-theme.html.twig #}
{% block checkbox_row %}
{% spaceless %}
{% if not useTosStyle %}
{{ parent() }}
{% else %}
{# ... special rendering ... #}
{% endif %}
{% endspaceless %}
{% endblock %}
which would be used like this:
{% form_theme form '::form-theme.html.twig' %}
{{form_row(form.termsOfServiceAccepted, {
'useTosStyle' : true,
'label' : 'I have read and agree to the Terms and conditions'
})
}}
Thanks to a recent commit to Symfony, you can use label_html from Symfony 5.1 onward:
{{ form_label(
form.privacy,
'I accept the privacy terms.',
{
'label_html': true,
},
) }}
I've been beating my head over this then had a eureka moment. The easiest way to do this–BY FAR–is to create a Twig extension.
Here's my Twig code:
{# twig example #}
{% block form_label %}
{% set label = parent() %}
{{ label|unescape|raw }}
{% endblock %}
and PHP:
<?php
new Twig_SimpleFilter('unescape', function($value) {
return html_entity_decode($value);
});
A couple notes:
This unescapes all previously escaped code. You should definitely re-escape afterwards as necessary.
This requires an extends tag for your target form theme in your own custom form theme which you can use in your subsequent forms. Put the twig code in a custom form theme and replace references to your other form theme/themes with this one.
Overall this is the fewest lines of code for the biggest and best outcome that I've been able to find. It's also ultra-portable and DRY: You can extend any form theme and the label will change without you changing the rest of your code.
Another very simple approach is to override the form theme directly in the template which renders the form. Using {% form_theme form _self %} it is as simple as this:
{% form_theme form _self %}
{% block form_label %}
{{ label | raw }}
{% endblock %}
{{ form_start(form) }}
See the corresponding section in the docs:
https://symfony.com/doc/current/form/form_customization.html#method-1-inside-the-same-template-as-the-form
The easiest way to customize the [...] block is to customize it directly in the template that's actually rendering the form.
By using the special {% form_theme form _self %} tag, Twig looks inside the same template for any overridden form blocks. [...]
The disadvantage of this method is that the customized form block can't be reused when rendering other forms in other templates. In other words, this method is most useful when making form customizations that are specific to a single form in your application. If you want to reuse a form customization across several (or all) forms in your application, read on to the next section.
Another approach is to use a simple Twig replacement:
{% set formHtml %}
{{ form(oForm) }}
{% endset %}
{{ formHtml|replace({'[link]': '', '[/link]': ''})|raw }}
In your form, you have something like this in order to make it work:
$formBuilder->add('conditions', CheckboxType::class, [
'label' => 'Yes, I agree with the [link]terms and conditions[/link].'
]
);
Of course, you may change [link] to anything else. Please note that you do not use HTML tags ;-)
I think you are looking for form theming. That way you are able to style each part of form, in an independent file, anyway you want and then just render it in "elegant" way, row by row with {{ form_row(form) }} or simply with {{ form_widget(form) }}. It's really up to you how you set it up.
Symfony 4.2
TWIG:
{% block main %}
....
{% form_theme form _self %}
...
{{ form_row(form.policy, {'label': 'security.newPassword.policy'|trans({"%policyLink%":policyLink, "%termsLink%":termsLink})}) }}
...
{% endblock %}
{% block checkbox_radio_label %}
<label{% with { attr: label_attr } %}{{ block('attributes') }}{% endwith %}>
{{- widget|raw }} {{ label|unescape|raw }}
</label>
{% endblock checkbox_radio_label %}
PHP:
use Twig\Extension\AbstractExtension;
use Twig\TwigFilter;
class AppExtension extends AbstractExtension
{
public function getFilters()
{
return [
new TwigFilter('unescape', function ($value) {
return html_entity_decode($value);
}),
];
}
}
So form theming is pretty complicated. The easiest thing I've found is to just suppress the field's label ('label'=> false in Symfony form class) and then just add the html label in the twig html.
You could leverage form theming in another way: you could move the <label> tag outside the form_label() function.
Create a custom form theme, and for checkboxes only move the <label> tag outside the form_label function:
{% block checkbox_row %}
<label>{{ form_label(form) }}</label>
{{ form_errors(form) }}
{{ form_widget(form) }}
{% endblock checkbox_row %}
{% block checkbox_label %}
{{ label }}
{% endblock checkbox_label %}
Now, in your teplate, override the label of your checkbox, and thus effectively inject HTML into the label function:
{% form_theme form 'yourtheme.html.twig' _self %}
{% block _your_TOS_checkbox_label %}
I agree with terms and conditions
{% endblock _your_TOS_checkbox_label %}

Categories