Symfony2 errors on form field and parent - php

Is it possible to have validation on the form but keep it on the field at that same time? I am trying to have all my errors display at the top of the page but I would also like to have a red border around the error field. Also, each of my errors on the top should have a link that gives focus on the field that has that error.
If I use {{ form_errors(form.title) }}, I don't access to {{ form_errors(form) }}. If I use error_bubbling => true on the field then I don't access to {{ form_errors(form.title) }}. I was thinking of building my errors display in my controller, but if I do that, I'm losing Twig's functionality.

Customize your form_row block to not display error
{% block form_row %}
<div class="form-group{% if errors|length == 1 %} has-error{% endif %}">
{{ form_label(form, label|default(null)) }}
{{ form_widget(form, { 'attr' : { 'class' : 'form-control' } } ) }}
</div>
{% endblock form_row %}
Customize form_errors to be clickable. You can create a jQuery function to listen for clicks on li. In the function get the id of the clicked li remove RelatedField to get the field id
{% block form_errors -%}
{% if errors|length > 0 -%}
<ul id="allErrors">
{%- for error in errors -%}
<li id="RelatedField{{ error.id }}">{{ error.message }}</a></li>
{%- endfor -%}
</ul>
{%- endif %}
{%- endblock form_errors %}
References
How to Customize Form Rendering - http://symfony.com/doc/current/cookbook/form/form_customization.html

Here is the solution that I'm currenly using, I don't know if it's a good one. Personnaly I would rather do it all in Twig but I couldn't find a better way.
DefaultController.php : I'm passing the $errors to my view.
$errors = array();
if ($request->getMethod() == 'POST') {
$form->bind($this->getRequest());
if ($form->isValid()) {
...
} else {
foreach ($form->all() as $child) {
if (!$child->isValid()) {
$errors[$form->getName().'_'.$child->getName()] = substr($child->getErrorsAsString(),7);
}
}
}
}
template.html.twig
{% if errors|length > 0 %}
<ul>
{% for key, error in errors %}
<li>{{ error }}</li>
{% endfor %}
</ul>
{% endif %}
{% block form_widget_simple %}
{% spaceless %}
{% set type = type|default('text') %}
<input type="{{ type }}" {{ block('widget_attributes') }} {% if value is not empty %}value="{{ value }}" {% endif %} {% if errors|length > 0 %}class="error"{% endif %} />
{% endspaceless %}
{% endblock form_widget_simple %}
script.js
$('.errorClick').click(function() {
$('#'+$(this).attr('data-id')).focus();
});

Related

Twig show n keys of array or all

I have an editor with a set of buttons, and I want to display only a set of buttons based on twig::render variables.
If I include all I want it to display are buttons available, if I include individual button keys I want to display only that ones.
echo TwigLoader::render('#ui/editor.html.twig'['toolbar'=>['all']]);
echo TwigLoader::render('#ui/editor.html.twig'['toolbar'=>['font','size']]);
For the template I'm using the following code:
{% set toolbar_tools = [
{'font':'<select class="ql-font"></select>'},
{'size':'<select class="ql-size"></select>'}]
%}
<div id="button-container">
<span class="ql-formats">
{% for tool, key in toolbar_tools %}
{{ tool.key|raw}}
{% endfor %}
</span>
</div>
I'm getting an empty container.
Is this a good strategy or there are better ways?
Seems you`re looking for something like this:
{% set toolbar_tools = {
'font':'<select class="ql-font"></select>',
'size':'<select class="ql-size"></select>'
}
%}
<div id="button-container">
<span class="ql-formats">
{% if toolbar|length > 0 %}
{% for t in toolbar %}
{% if t == 'all' %}
{# show all options #}
{% for tool in toolbar_tools %}
{{ tool|raw }}
{% endfor %}
{% else %}
{# show defined options #}
{{ attribute(toolbar_tools, t)|raw }}
{% endif %}
<br />
{% endfor %}
{% endif %}
</span>
</div>
Hope you will be fine with that.

is there a way to add violation to multiple paths in symfony2?

is it possible to add a violation to multiple paths? like:
$this->context->buildViolation($constraint->message)
->atPath('initialDate')
->atPath('finalDate')
->addViolation();
it only add to initialDate.
You can still add two violations with an empty message on the second
$this->context->buildViolation($constraint->message)
->atPath('phone')
->addViolation()
;
$this->context->buildViolation('')
->atPath('email')
->addViolation()
;
but you will have the error markup generated also in the second field
You can also override the form_errors block to adjust the markup if no message
{% block form_errors -%}
{% if errors|length > 0 -%}
{% if form.parent %}<span class="help-block">
{% else %}<div class="alert alert-danger">{% endif %}
<ul class="list-unstyled text-danger">
{%- for error in errors if error.message -%}
<li><span class="glyphicon glyphicon-exclamation-sign"></span>
{{ error.message }}
</li>
{%- endfor -%}
</ul>
{% if form.parent %}</span>{% else %}</div>{% endif %}
{%- endif %}
{%- endblock form_errors %}

Symfony2 Form Builder - Remove label, make it placeholder

I am playing with Symfony's form builder, and I can't find a way to not display a label. Further, I am interested in actually setting a placeholder for each input box. Is this possible? I have researched a bit and found nothing.
My form:
<form action="{{ path('searchPeople') }}" method="post" class="form-inline">
{{ form_errors(form) }}
{{ form_row(form.first_name) }}
{{ form_row(form.last_name) }}
{{ form_rest(form) }}
<br />
<button type="submit" class="btn btn-primary" /><i class="icon-search"></i>Search</button>
</form>
I know it's already answered, but might help somebody who is looking for a different solution for placeholders, if you don't want to change anything in your twig template:
$builder->add(
'name',
'text',
array(
'attr' => array(
'placeholder' => 'Your name',
),
'label' => false,
)
);
If you're outputting the field with form_rest you'll have to set the label for the the field to false in the form builder with something like
$builder->add('first_name', 'text', array(
'label' => false,
));
If you output the fields individually, you can omit the form_label for that field in the twig template, or set it to an empty string.
{{ form_label(form.first_name, '') }}
Convert label to placeholder
{% use 'form_div_layout.html.twig' with widget_attributes as base_widget_attributes %}
{% block widget_attributes %}
{% set attr = {'placeholder': label|trans({}, translation_domain)} %}
{{- block('base_widget_attributes') -}}
{% endblock widget_attributes %}
I did this recently! :) You'll want to create a new fields template, for form_row and one for form_widget. Then remove the form_label part, and add your placeholder.
http://symfony.com/doc/current/cookbook/form/form_customization.html
You can do it per field, or set it for all of them.
Or you can also skip the removing the form_label from the form_row template, and just do form_widget() where you're currently calling form_row()
for other that come across this label-question:
you could use form theme to override the form_row tag for every form you want. However I recommend to just set it invisible for page reader optimization. my example with bootstrap:
{% block form_row %}
{% spaceless %}
{{ form_label(form, null, {'label_attr': {'class': 'sr-only'}}) }}
{{ form_errors(form) }}
{{ form_widget(form) }}
{% endspaceless %}
{% endblock form_row %}
don't forget to include your formtheme in config.yml and template.
For those NOT using form_row, you can always add the placeholder as an attribute directly when adding the input to the builder. Like so:
$task = new Task();
$form = $this->createFormBuilder($task)
->add('first_name', 'text', array(
'required' => true,
'trim' => true,
'attr' => array('placeholder' => 'Lorem Ipsum')
)->getForm();
Symfony 2.8 & above
Remove form_label
{% block form_row %}
<div>
{{ form_errors(form) }}
{{ form_widget(form) }}
</div>
{% endblock form_row %}
Add placeholder attribute
{% block form_widget_simple %}
{% set type = type|default('text') %}
<input placeholder="{{ translation_domain is same as(false) ? label : label|trans({}, translation_domain) }}" type="{{ type }}" {{ block('widget_attributes') }} {% if value is not empty %}value="{{ value }}" {% endif %}/>
{% endblock form_widget_simple %}
Expanding on Léo's answer:
{% use 'form_div_layout.html.twig' %}
{% block widget_attributes %}
{% spaceless %}
{% set attr = attr|merge({'placeholder': label}) %}
{{ parent() }}
{% endspaceless %}
{% endblock widget_attributes %}
trans filter has been removed because it is included in the parent.
You must render the form manually.
Here's an example:
<form id="form-message" action="{{ path('home') }}" method="post" {{ form_enctype(form) }}>
{{ form_label(form.name) }}
{% if form_errors(form.name) %}
<div class="alert alert-error">
{{ form_errors(form.name) }}
</div>
{% endif %}
{{ form_widget(form.name) }}
{{ form_row(form._token) }}
<input type="submit" class="btn" value="Submit">
</form>
Related documentation
To sums it up:
Titi's answer is the most simple ;
Mick, Léo & Quolonel's answers are the most effective but are incomplete (for symfony > 2.6) :
If you use the label_format option in your *Type::configureOptions, their solution does not work. You need to add the content of the form_label block to handle all the label possibilities.
The full & most effective answer (code used w/ symfony 3.3) :
Remove form_label
{% block form_row %}
<div>
{{ form_errors(form) }}
{{ form_widget(form) }}
</div>
{% endblock form_row %}
Edit the widget_attribute block
{% block widget_attributes %}
{% spaceless %}
{% if label is not same as(false) -%}
{% if label is empty -%}
{%- if label_format is not empty -%}
{% set label = label_format|replace({
'%name%': name,
'%id%': id,
}) %}
{%- else -%}
{% set label = name|humanize %}
{%- endif -%}
{%- endif -%}
{% set attr = attr|merge({'placeholder': label}) %}
{%- endif -%}
{{ parent() }}
{% endspaceless %}
{% endblock widget_attributes %}
Notes :
Do not translate the labels into the widget_attributes block, otherwise they will appear as missing translations.
The solution does not work for checkboxes or radio buttons, you'll want to add something like :
{%- block checkbox_widget -%}
{{ parent() }}
{{- form_label(form) -}}
{%- endblock checkbox_widget -%}
Bootstrap Forms
In my case best is mix aswers of #Cethy and #Quolonel Questions
{% form_theme form _self %}
{% use 'bootstrap_4_layout.html.twig' %}
{% block widget_attributes %} {# set placeholder #}
{% spaceless %}
{% set attr = attr|merge({'placeholder': label}) %}
{{ parent() }}
{% endspaceless %}
{% endblock widget_attributes %}
{% block form_row %} {# remove label #}
<div class="form-group">
{{ form_errors(form) }}
{{ form_widget(form) }}
</div>
{% endblock form_row %}
It looks the following
It works with translations
You can also copy the labels into the placeholder attribute before rendering the form:
$formView = $form->createView();
foreach($formView->getIterator() as $item) {
/** #var $item FormView */
if ($item->vars['label']) {
$item->vars['attr']['placeholder'] =$item->vars['label'];
}
}

How to move "current" flag from <li> to <a> object in knpMenuBundle?

I have been looking at this twig code for a while, and tried a few trix to move the flag of the "current" item down to the link object (a) instead of the list item object (li) but I can't seem to get it right.
The output I get at the moment is
<ul>
<li class="current first">
Hem
</li>
The desired output is
<ul>
<li class="first">
<a class="current" href="/hemekonomi/web/app_dev.php/">Hem</a>
</li>
Here is the twig file (the standard twig template file for knpMenuBundle with irrelevant modifications to it).
{% macro attributes(attributes) %}
{% for name, value in attributes %}
{%- if value is not none and value is not sameas(false) -%}
{{- ' %s="%s"'|format(name, value is sameas(true) ? name|e : value|e)|raw -}}
{%- endif -%}
{%- endfor -%}
{% endmacro %}
{% block compressed_root %}
{% spaceless %}
{{ block('root') }}
{% endspaceless %}
{% endblock %}
{% block root %}
{% set listAttributes = item.childrenAttributes %}
{{ block('list') -}}
{% endblock %}
{% block list %}
{% if item.hasChildren and options.depth is not sameas(0) and item.displayChildren %}
<ul class="art-hmenu">
{{ block('children') }}
</ul>
{% endif %}
{% endblock %}
{% block children %}
{# save current variables #}
{% set currentOptions = options %}
{% set currentItem = item %}
{# update the depth for children #}
{% if options.depth is not none %}
{% set options = currentOptions|merge({'depth': currentOptions.depth - 1}) %}
{% endif %}
{% for item in currentItem.children %}
{{ block('item') }}
{% endfor %}
{# restore current variables #}
{% set item = currentItem %}
{% set options = currentOptions %}
{% endblock %}
{% block item %}
{% if item.displayed %}
{# building the class of the item #}
{%- set classes = item.attribute('class') is not empty ? [item.attribute('class')] : [] %}
{%- if item.current %}
{%- set classes = classes|merge([options.currentClass]) %}
{% set aFlag = ' class="active"' %}
{%- elseif item.currentAncestor %}
{%- set classes = classes|merge([options.ancestorClass]) %}
{%- endif %}
{%- if item.actsLikeFirst %}
{%- set classes = classes|merge([options.firstClass]) %}
{%- endif %}
{%- if item.actsLikeLast %}
{%- set classes = classes|merge([options.lastClass]) %}
{%- endif %}
{%- set attributes = item.attributes %}
{%- if classes is not empty %}
{%- set attributes = attributes|merge({'class': classes|join(' ')}) %}
{%- endif %}
{# displaying the item #}
<li{{ _self.attributes(attributes) }}>
{%- if item.uri is not empty and (not item.current or options.currentAsLink) %}
{{ block('linkElement') }}
{%- else %}
{{ block('spanElement') }}
{%- endif %}
{# render the list of children#}
{%- set childrenClasses = item.childrenAttribute('class') is not empty ? [item.childrenAttribute('class')] : [] %}
{%- set childrenClasses = childrenClasses|merge(['menu_level_' ~ item.level]) %}
{%- set listAttributes = item.childrenAttributes|merge({'class': childrenClasses|join(' ') }) %}
{{ block('list') }}
</li>
{% endif %}
{% endblock %}
{% block linkElement %}<a href="{{ item.uri }}"{{ _self.attributes(item.linkAttributes) }}>{{ block('label') }}</a>{% endblock %}
{% block spanElement %}<span{{ _self.attributes(item.labelAttributes) }}>{{ block('label') }}</span>{% endblock %}
{% block label %}{% if options.allow_safe_labels and item.getExtra('safe_label', false) %}{{ item.label|raw }}{% else %}{{ item.label }}{% endif %}{% endblock %}
Instead of moving the "current" class, I drilled down to the desired object with this css:
ul.mainmenu>li.current > a > div {
opacity:0.6;
}

How to get form variables in custom form field in symfony2

I have this custom form field
{# src/Acme/DemoBundle/Resources/views/Form/fields.html.twig #}
{% block gender_widget %}
{% spaceless %}
{% if expanded %}
<ul {{ block('widget_container_attributes') }}>
{% for child in form %}
<li>
{{ form_widget(child) }}
{{ form_label(child) }}
</li>
{% endfor %}
</ul>
{% else %}
{# just let the choice widget render the select tag #}
{{ block('choice_widget') }}
{% endif %}
{% endspaceless %}
{% endblock %}
This renders the checkboxes. But i am not able to find how can i get the value of checkbox
i.e child.form.value is not working.
Suppose i have entities which is named as tasks in the form.
how can i get the value of the taskid.
something like
child.form.vars.task.id
It seems to be in {{ choice.value }}
Have a look at this to see how the inheritance works.
<option value="{{ choice.value }}"{% if choice is selectedchoice(value) %} selected="selected"{% endif %}>{{ choice.label|trans({}, translation_domain) }}</option>

Categories