Status of checkboxes submitted from symfony to twig - symfony

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()
))

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 %}

Label is not displaying in Symfony form

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.

compare a input field value to a string or text symfony2

I was trying to learn about framework and Ill be starting under "Symfony", then i got this problem, I create a
{{ form_widget(form.type) }}
equivalent to
<input type="text" class="type" id="type"/>
this element "input" have a value that given by a tab or menu if i click on it, example jumping.how do i compare it to a text using "Symfony" if statement like the logic below.
{% if jumping == "text" %}
//it will do something
{% endif %}
as explained nicely in the symfony docs here you need to use the form.vars.value to get the input field's value
so for someting like {{ form_widget(form.name) }} you would access the values by doing {{ form.vars.value.name }}
in your case it would be
{% if form.vars.value.name == "text" %}
//do something
{% endif %}

How to reuse sonata Admin paginator with a custom crud controller

I have a custom CRUD controller with an action which retrieves a custom doctrine result set and passes it to a custom template. Is it possible to make use of Sonata Admin's pagination mechanism without reusing the standard list templates?
If so, what object format does the paginator expect? I could not see any mention of this in the documentation
The template I would need to populate with results would be base_results.html.twig:
{% block num_pages %}
{{ admin.datagrid.pager.page }} / {{ admin.datagrid.pager.lastpage }}
-
{% endblock %}
{% block num_results %}
{% transchoice admin.datagrid.pager.nbresults with {'%count%': admin.datagrid.pager.nbresults} from 'SonataAdminBundle' %}list_results_count{% endtranschoice %}
-
{% endblock %}
{% block max_per_page %}
<label class="control-label" for="{{ admin.uniqid }}_per_page">{% trans from 'SonataAdminBundle' %}label_per_page{% endtrans %}</label>
<select class="form-control per-page small" id="{{ admin.uniqid }}_per_page">
{% for per_page in admin.getperpageoptions %}
<option {% if per_page == admin.datagrid.pager.maxperpage %}selected="selected"{% endif %} value="{{ admin.generateUrl('list', {'filter': admin.datagrid.values | merge({'_page': 1, '_per_page': per_page})}) }}">
{{ per_page }}
</option>
{% endfor %}
</select>
{% endblock %}
If I want to add an additional constraint on the result set, how would I adapt the following code from Sonata's list action?
if (false === $this->admin->isGranted('LIST')) {
throw new AccessDeniedException();
}
$datagrid = $this->admin->getDatagrid();
$formView = $datagrid->getForm()->createView();
// set the theme for the current Admin Form
$this->get('twig')->getExtension('form')->renderer->setTheme($formView, $this->admin->getFilterTheme());
return $this->render($this->admin->getTemplate('list'), array(
'action' => 'list',
'form' => $formView,
'datagrid' => $datagrid,
'csrf_token' => $this->getCsrfToken('sonata.batch'),
));
The DatagridBundle is a work in progress in order to decouple the list, pagination and filtering mechanisms from the Admin for them to be reusable elsewhere. Hence it is not stable yet. I strongly recommend you use the pagination from the AdminBundle at the moment.
Regarding your main question, if you wish to understand fully how to use the pager, I recommend you take a look at the Datagrid::buildPager method (https://github.com/sonata-project/SonataAdminBundle/blob/master/Datagrid/Datagrid.php#L90).

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.

Resources