Label is not displaying in Symfony form - symfony

I am facing a issue to display label.
Following is the code to generate form element.
$builder->add(
'hearAboutUs', 'choice', [
'choices' => ['Online Search'=>'Online Search',
'Email'=> 'Email',
'My Company' => 'My Company',
'Colleague or Friend'=>'Colleague or Friend',
'Existing Client' =>'Existing Client',
'Direct Mail' => 'Direct Mail',
'Other'=> 'Other',],
'label' => 'How did you hear about us?',
'required' => true,
'expanded'=> true,
'multiple' => false,
]
);
I am getting following output.
As like "Notes" label "How did you hear about us" label is not displaying.

You can try to override your form theme about choice widget.
You can do it like this :
1- Create a file named fields.html.twig in app/Resources/views/form/
2- In this file you have to extends default twig layout and override checkbox_widget adding <label> tag :
{% extends 'form_div_layout.html.twig' %}
{% block checkbox_widget %}
{% spaceless %}
<label>
<input type="checkbox" {{ block('widget_attributes') }}{% if value is defined %} value="{{ value }}"{% endif %}{% if checked %} checked="checked"{% endif %} />
</label>
{% endspaceless %}
{% endblock checkbox_widget %}
3- Finally, tell Symfony to use it in your view like this :
{% form_theme form 'form/fields.html.twig' %}

My View is looks like
My Updated Entity is

I have handled this using JQuery.
On Form Load I am appending Label and for required I have handled this on the controller.
But this is not proper solution, but by this way my problem solved.

Related

Symfony ChoiceType deep label customization

I want to customize my EntityType's choice labels highly, like creating a table with multiple attributes of my model.
So I want to access my choices class attributes. The choices are my entities of class MyClass through the EntityType. How can I do so in twig?
Currently I do it like this:
1. in my FormClass I json_encode all fields I need in my label
2. in my template I json_decode these information and display according
IN CODE:
1.
$builder
->add('field', EntityType::class, [
'class' => MyClass::class,
'multiple' => false,
'expanded' => true,
],
'choice_label' => function (MyClass $myClass) {
$data = [
'name' => $myClass->getName(),
'description' => $myClass->getDescription(),
];
return json_encode($data);
},
])
2.
{% block my_form_widget %}
...
{# form is my 'field' FormView of the EntityType #}
{% for child in form %}
{# child is a FormView, one choice of my EntityType #}
{# child.vars.data is boolean as its a checkbox #}
{% set data = child.vars.label|json_decode %}
create some complex html here, like tables
...
{% endfor %}
...
{% endblock %}
Working. But is there a better way?
Thanks,
Kim
In a Symfony form (or form field, which is just a form of its own) that is mapped to an entity, you always have access to the underlying data in form.vars.data. So in this case, form.vars.data would either be null or an instance of MyClass.
For ease of use in your template, you might do something like:
{% set my_object = form.field.vars.data %}
{% if my_object %}
{{ my_object.getName() }}
{{ my_object.getDescription() }}
{% endif %}
Thus there is no need to re-encode your entity data for the view layer, since it's always already available.
If you are working with an EntityType and want to access the properties of each choice's entity, they are available as well in the choices array:
{% for choice in form.field.vars.choices %}
{{ choice.data.getName() }}
{{ choice.data.getDescription() }}
{% endfor %}
A nice trick when you're trying to access any form data and aren't sure where to look is to temporarily add a line to your template like:
{{ dump(form.field) }}
This will allow you to look through the available data and see what all is available. Note that it requires the Twig debug extension to be enabled, and XDebug to be enabled in PHP in order to make the output look nice.
Ok I got it, here is an example of how to access the data of your EntityType's choices in twig. You can check the child.parent.vars.choices list.
{% block my_form_widget %}
...
{# form is my 'field' FormView of the EntityType #}
{% for child in form %}
{# child is a FormView, one choice of my EntityType #}
{# child.vars.data is boolean as its a checkbox #}
{% for choice in child.parent.vars.choices if choice.value == child.vars.value %}
{{ choice.data.name }} {# contains MyClass name #}
{{ choice.data.description }} {# contains MyClass description #}
{% endfor %}
...
{% endfor %}
...
{% endblock %}

Status of checkboxes submitted from symfony to twig

I'm searching for a way to submit the statsus of a checkbox from a symfony controller to the twig template. So that the User doesn't need to check again if the form was sumitted incomplete and some further input is needed.
For the reason that there will be more than one checkbox as an array, I'm stucking: There will be submitted an id ({{ usergroup.id }}) and I thought about using this number to check the status by this id like:
{% for usergroup in userGroups %}
<input type="checkbox" name="staffdata" value="{{ usergroup.id }}"{%if isChecked{{ usergroup.id }} %}checked="checked" >{& endif %}>{{ usergroup.name }}
{% endfor %}
Of course this is not working - like I expect :)
Can anyone give me a hint how to get this working?
EDIT: Here is the actual state:
The outputt looks like the script here: http://www.1stwebdesigns.com/blog/development/multiple-select-with-checkboxes-and-jquery . A selectbox with nested checkboxes.
Therefor, I need to get all values as a checkbox, not as a choice. Actually, I m doing this by giving the block_choice_widget a new layout :)
{% block choice_widget_collapsed -%}
//.....
{% if empty_value is not none -%}
<li><label><input type="checkbox" {% if required and value is empty %} checked="checked"{% endif %} name="staff-member-usergroup" value="{{ usergroup.id }}">{{ empty_value|trans({}, translation_domain) }}</label></li>
{%- endif %}
//......
{%- endblock choice_widget_collapsed %}
This is working but to me it seems not the best solutions. But as I'm new in symfony, it is a working solution:) Is there a better way or a possibility to get multiple checkboxes?
you need to use data option in form builder to set state of checkbox; here is a documentation.
sample code:
$builder->add('active', 'checkbox', array(
'label' => 'Is active?',
'required' => false,
'data' => $entity->getActive()
))

Directly access a form field's value when overriding widget in a twig template

What I want to do is get variables stored in form view.
{% form_theme edit_form _self %}
{% block field_widget %}
{% spaceless %}
{% set type = type|default('text') %}
<input type="{{ type }}" {{ block('widget_attributes') }} {% if value is not empty %}value="{{ value }}" {% endif %}/>
{# MY CODE #}
{% if type == "file" %}
<a class="BOpreview" href="{# NEED TO REPLACE VAR HERE #}">Aperçu</a>
{% endif %}
{# MY ATTEMPT #}
{{ form.title.get('value') }}
{{ form.vars.value.url }}
{% endspaceless %}
{% endblock field_widget %}
My form has properties like url, title, etc and I am trying to access them here to use it in the field widget block.
I searched for it and came on https://groups.google.com/forum/?fromgroups=#!topic/symfony2/onor9uFte9E that suggested:
{{ form.title.get('value') }}
{{ form.vars.value.url }}
which didn't work for me.
Note: If I do a var_dump on $form->createView() in my controller, I get:
object(Symfony\Component\Form\FormView)[331]
private 'vars' =>
array (size=15)
'value' =>
object(Panasonic\TestEtAvisBundle\Entity\Product)[168]
protected 'reviewArray' =>
object(Doctrine\ORM\PersistentCollection)[234]
...
protected 'testArray' =>
object(Doctrine\ORM\PersistentCollection)[221]
...
protected 'fbshareArray' =>
object(Doctrine\ORM\PersistentCollection)[317]
...
private 'id' => int 2
private 'name' => string 'Nom du produit' (length=14)
private 'title' => string '<span>Titre </span>' (length=19)
private 'image' => string 'bundles/testetavis/uploads/product/0d9d9550.png' (length=47)
private 'fbImage' => string 'bundles/testetavis/uploads/product/facebook//product_e928cd96.jpg' (length=65)
private 'description' => string '<span>Descriptif </span>' (length=24)
private 'url' => string 'http://www.google.com' (length=21)
private 'creationDate' =>
object(DateTime)[210]
...
private 'modificationDate' =>
object(DateTime)[209]
...
private 'isDeleted' => int 0
'attr' =>
array (size=0)
empty
'form' =>
&object(Symfony\Component\Form\FormView)[331]
'id' => string 'panasonic_testetavisbundle_producttype' (length=38)
'name' => string 'panasonic_testetavisbundle_producttype' (length=38)
'full_name' => string 'panasonic_testetavisbundle_producttype' (length=38)
I want to access that url for instance but can't seem to be able to do it after many variations. Including use of {{ value }}, {{ value.url }}
But inspite of vars, I can do {{ full_name }} and get panasonic_testetavisbundle_producttype.
Any ideas?
Edit2: I found out the real problem...
Edit3: Seeing that this question is quite popular I decided to clarify on what I attempted to do in case it helps someone in the same situation. If you rely strictly on what the question asks, as I stated from my research and that Besnik supported are indeed correct.
Now what I wanted to do is for every input type file, get url from object used to render form and append a preview link, using retrieved url, beside the input type file.
If you try to get the form var of an input type "file" like this "{{ form.vars.value.url }}" in my code, this doesn't work since, if I recall correctly, you receive a token instead of the url stored inside the object.
You can access the current data of your form via form.vars.value:
{{ form.vars.value.title }}
See Symfony2 Forms documentation: http://symfony.com/doc/current/book/forms.html#rendering-a-form-in-a-template
Dump vars by using dump function:
{{ dump(form.vars.value) }}
If you are using subforms or want to have a value of a specific field:
{{ form.FIELD.vars.VALUE }}
You can access values of the parent parent from a widget block using form.parent.vars
For example, we want to render the value from a type text field called primerNombre we will need
{{ form.vars.value.primerNombre }}
If we wanted to render the name of one of the children we will need
{% for hijo in form.hijos %}
<td><div align="left">{{ form_widget(hijo.vars.value.primerNombre) }}</div></td>
{% endfor %}
Good luck!
In Symfony > 3 you may use:
form.vars.value.Entity.someValue
Edit2:
Finally, I was indeed getting the value of the current row in {{ value }} here:
{% block field_widget %}
{% spaceless %}
{% set type = type|default('text') %}
<input type="{{ type }}" {{ block('widget_attributes') }} {% if value is not empty %}value="{{ **value** }}" {% endif %}/>
{# MY CODE #}
{% if type == "file" %}
<a class="BOpreview" href="{{ value }}">Aperçu</a>
{% endif %}
{% endspaceless %}
{% endblock field_widget %}
But in my case I get a token instead of the value since I am using input type file. This is due to a security measure in Symfony2.

Link in form label using route

In my registration form i have a checkbox "I accept the terms", and want to link the word "terms" to my terms page.
Is there a way to add a link to a form label, using a route? (preferably without injecting the container in the form)
As the solution above somehow didn't work for me I solved it using the solution suggested here: https://gist.github.com/marijn/4137467
OK, so here i how I did it:
{% set terms_link %}<a title="{% trans %}Read the General Terms and Conditions{% endtrans %}" href="{{ path('get_general_terms_and_conditions') }}">{% trans %}General Terms and Conditions{% endtrans %}</a>{% endset %}
{% set general_terms_and_conditions %}{{ 'I have read and accept the %general_terms_and_conditions%.'|trans({ '%general_terms_and_conditions%': terms_link })|raw }}{% endset %}
<div>
{{ form_errors(form.acceptGeneralTermsAndConditions) }}
{{ form_widget(form.acceptGeneralTermsAndConditions) }}
<label for="{{ form.acceptGeneralTermsAndConditions.vars.id }}">{{ general_terms_and_conditions|raw }}</label>
</div>
The best way is to overwrite the twig block used to render that specific label.
First, check the form fragment naming section of the docs. Then create a new block in your form template with the the appropriate name. Don't forget to tell twig to use it:
{% form_theme form _self %}
For the next step check the default form_label block.
You'll probably only need a portion of it, something like this (I'm leaving the default block name here):
{% block form_label %}
{% spaceless %}
<label{% for attrname, attrvalue in label_attr %} {{ attrname }}="{{ attrvalue }}"{% endfor %}>
{{ label|trans({}, translation_domain) }}
</label>
{% endspaceless %}
{% endblock %}
As an option, you can do so:
->add('approve', CheckboxType::class, [
'label' => 'Text part without link',
'help' => 'And download it',
'help_html' => true,
])
In Symfony 5.1 there are new form improvements.
HTML contents are allowed in form labels!
HTML contents are escaped by default in form labels for security reasons. The new label_html boolean option allows a form field to include HTML contents in their labels, which is useful to display icons inside buttons, links and some formatting in checkbox/radiobutton labels, etc.
// src/Form/Type/TaskType.php
namespace App\Form\Type;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Symfony\Component\Form\FormBuilderInterface;
class TaskType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
// ...
->add('save', SubmitType::class, [
'label' => ' Save',
'label_html' => true,
])
;
}
}
In your case you can set form label directly from template and pass the route there.
{{ form_widget(form.acceptTermsAndConditions, {
label: '' ~ "I accept ..."|trans ~ '',
label_html: true
})
}}
My solution was another:
form:
$builder
->add(
'agree_to_rules',
'checkbox',
[
'required' => true,
'label' => 'i_agree_to'
]
);
And html:
<span style="display:inline-block">
{{ form_widget(form.agree_to_rules) }}
</span>
<span style="display:inline-block">
rules
</span>
And looks the same :)
A very simple way to do it would be
{{ form_widget(form.terms, { 'label': 'I accept the terms and conditions' }) }}
You can also do this if you want to use translation
In your translation file for example messages.en.yml add
terms:
url: 'I accept the terms and conditions'
And in your view add
{{ form_widget(form.terms, { 'label': 'terms.url'|trans({'%url%': path('route_to_terms')}) }) }}

Adding "help" messages to fields

I'm trying to add some help messages after each field in form in symfony2.
I have read about one solution in official docs : http://symfony.com/doc/current/cookbook/form/form_customization.html#adding-help-messages
But this solution makes little sense, because we've need to create all form manually.
For example, it easy to define label: $formBuilder->add('myfieldname', 'text', array('label'=>'some my field label')); But how to pass help messages? (In other words, some custom variables)
A another method without another extension :
In your form builder class:
$builder->add('yourField',null, array('attr'=>array('help'=>'text help')))
In your form template rewrite:
{% block form_row %}
{% spaceless %}
{{ form_label(form) }}
{{ form_widget(form) }}
{% for attrname, attrvalue in attr %}
{% if attrname == 'help' %}
<span class="help-block">{{ attrvalue }}</span>
{% endif %}
{% endfor %}
{{ form_errors(form) }}
{% endspaceless %}
{% endblock form_row %}
$formBuilder->add('myFieldName', 'text', array('help' => 'My Help Message')); But it think you also need to add an extension that add this as a default option for all forms :
https://github.com/simplethings/SimpleThingsFormExtraBundle#helpextension
This makes you able to edit attributes directly from you FormTypes.
Since symfony 4.1 you can do :
$builder->add('email', null, [
'help' => 'Make sure to add a valid email',
]);
https://symfony.com/blog/new-in-symfony-4-1-form-field-help
You can use the solution in the official docs as you described.
But, the work is not complete yet. You have to create a Form Type Extention, based on this article: http://symfony.com/doc/current/cookbook/form/create_form_type_extension.html
After complete the Form Type Extention creation you can add Help Messages like this:
$form = $this->createFormBuilder()
->add('name', 'text', array(
'help' => 'this is a help message to user',
))
I think this is a native better solution.
Also, i recommend read this great article that shows you how to enable and set the help option in symfony2 forms:
http://toni.uebernickel.info/2012/11/03/how-to-extend-form-fields-in-symfony2.1.html
A little off topic but still useful if you're planning to use Bootstrap for your project then you can take advantage of some form helpers provided by the Mopa Bootstrap Bundle.
Demo: http://bootstrap.mohrenweiserpartner.de/mopa/bootstrap/forms/help_texts
GitHub: https://github.com/phiamo/MopaBootstrapBundle
Example:
<?php
$form = $this->get('form.factory')
->createNamedBuilder('form_name')
->setMethod('POST')
->add('testSelect', 'choice', [
'choices' => ['val1' => 'Value 1', 'val2' => 'Value 2'],
'required' => true,
'help_block' => 'Here some help text!!!'
])
->add('Save', 'submit')
->getForm();
return $form->createView();

Resources