I am trying to display the information like this:
Controller:
public function index(RestaurantRepository $restaurantRepository)
{
$restaurant = $restaurantRepository->findAll();
return $this->render('restaurant/index.html.twig', [
'restaurant' => $restaurant
]);
}
twig:
{% for restaurants in restaurant %}
{{ restaurant.name }}
{% endfor %}
Error "Key" name "for array with keys" 0, 1, 2, ..... "does not exist. But if I type in twig restaurant [0] .name etc it will show me the name in the given index.
What am I doing wrong?
It is a problem of plurals.
In your controller, restaurant is a collection, you should replace
$restaurant by $restaurants and 'restaurant' => $restaurant
by 'restaurants' => $restaurants
In twig the problem is here {{ restaurant.name }} instead {{ restaurants.name }}
So you should replace
{% for restaurants in restaurant %}
{{ restaurant.name }}
{% endfor %}
by
{% for restaurant in restaurants %}
{{ restaurant.name }}
{% endfor %}
Related
{% form_theme form _self %}
{% block collection_entry_row %}
{% set fields = form.attributes.children[0].children %}
{% for key, field in fields %}
{{ form_widget(field) }}
{{ form_widget(fields[key]) }}
{% endfor %}
{% endblock %}
And I get this error:
Neither the property "attributes" nor one of the methods "attributes()", "getattributes()"/"isattributes()"/"hasattributes()" or "__call()" exist and have public access in class "Symfony\Component\Form\FormView".
But this
{% set fields = form.attributes.children[0] %}
{% for key, field in fields %}
{{ dump(field) }}
{% endfor %}
Produces this:
Symfony\Component\Form\FormView {#2150 ▼
+vars: array:33 [▶]
+parent: Symfony\Component\Form\FormView {#2203 ▶}
+children: []
-rendered: false
-methodRendered: false
}
And yet inside the form_start() I can do the following and render one field at a time:
{% set tempInput = form.children['attributes'].children[0].children['attributes'].children[0].children['pin'] %}
{{ form_widget(tempInput) }}
Thoughts?
just had the same questions as you about this subject, and since i didn't understands the way to use the "{% block collection_row %}" i've found this following workaround.
I find out that the problem i had was coming from the 2 last item of the form.children: "submit" and "_token".
Because, of course, they will not have the variable name you are searching in the other "real" forms childs.
So i just added a check to the length of the children array to exclude this "submit" and "_token" items.
(The test might certainly be different for your case).
{% for child in form.children %}
{% if not child.children | length != 4 %} // my array has 4 items, submit and _token have none
{{ form_widget(child.children.variableName) }}
{% endif %}
{% endfor %}
As you can see you can access your collection variable between the if like this:
{{ form_widget(child.children.variableName) }}
Peace.
How do I translate this in twig? I have this variable in twig that is an array:
$array = [
['number' => 7, 'name' => 'foo'],
['number' => 8, 'name' => 'bar'],
['number' => 10, 'name' => 'baz'],
// ... and so on and so forth
]
Would like it to be something like this:
The variables are 7 times for foo, 8 times for bar, and 10 times for baz.
Or
The variables are 7 times for foo and 10 times for baz.
Or
The variable is 7 times for foo.
Tried with something like this:
{% set last = array|last %}
{% set array = array|slice(0, array.length - 1) %}
{% trans %}
<p>The variables are
{% for i in array %}
{{ i.number }} times {{ i.name }},
{% endfor %}
, and {{ last.number }} number of {{ last.name }}
.</p>
{% endtrans %}
Thanks!
Try this
The variables are
{% for item in array %}
{% if array|length > 1 and loop.last %}
and
{% endif %}
{{ item.number }} times for {{ item.name }}{% if loop.last %}.{% elseif array|length > 2 %}, {% endif %}
{% endfor %}
i have a problem with twig syntax and merge function ... I have multiple object with 2 field category and price.
I need to create an array or hash (i guess hash is easier but ... i try both) with sum of prices for each category.
So i try many code, and my last is :
{% set test = [ {'category': 'description', 'price': '1'}, { 'category': 'abc', 'price': '2'}, { 'category':'description', 'price': '3'} ] %}
{% set listCategory={} %}
{% for line in test %}
{% set new_category = { 'category': line.category, 'price': line.price } %}
{% if loop.first %}
{% set listCategory = listCategory|merge([new_category]) %}
{% else %}
{% set flag = false %}
{% for category in listCategory %}
{% if line['category'] == new_category['category'] %}
{% set tmp = line['price'] + new_category['price'] %}
{# i try it too#}
{% set category = category|merge([tmp]) %}
{# or i try this#}
{% set category = category|merge({ (category.price) : category.price + new_category.price }) %}
{{ dump(listCategory) }}
{% endif %}
{% endfor %}
{% endif %}
{% endfor %}
I try it since 3 hours and i don't know where i make an error.
When i check my array, i test if the key 'name' exist
if yes, i want to add the price of element to the hash price
if no, i want to add a new array in hash with key = 'name'
Anyone have an idea ? thx for your reading.
I think you are looking for something similar to:
{% set test = [ {'category': 'description', 'price': 1}, { 'category': 'abc', 'price': 2}, { 'category':'description', 'price': 3} ] %}
{% set listCategory={} %}
{% for line in test %}
{% set key = line.category %}
{% if listCategory[key] is defined %}
{# notice here that the key is in brackets () because otherwise it will be interpreted as the string "key" %}
{% set listCategory = listCategory|merge({(key):listCategory[line.category]+line.price}) %}
{% else %}
{% set listCategory = listCategory|merge({(key):line.price}) %}
{% endif %}
{{ key }}: {{ listCategory[key] }}
{% endfor %}
For some reason, a variable I'm setting in one form template bloc is not available in a child form block.
I have an 'entity' field type to present a selection of checkboxes to allow the user to select related items...
$builder
->add( 'title' )
->add(
'apps',
'entity',
[
'class' => 'OurAdminBundle:App',
'choices' => $apps,
'property' => 'title',
'expanded' => true,
'multiple' => true
]
)
And here's the template that renders the form
// Effectively imported using the MopaBootstrapBundle
// {% form_theme form 'OurAdminBundle:Form:fields.html.twig %}
// Further in page theming
{% form_theme form _self %}
// Set variable when on the apps field, so it should be available to all child
// forms
{% block _gallery_apps_widget %}
{% set custom_checkboxes = 1 %}
{{ block('choice_widget') }}
{% endblock %}
// Attempt to retrieve the variable on the checkboxes within the apps entity
/ field
{% block checkbox_widget %}
{{ dump(custom_checkboxes|default(0) }} // Displays 0
{% endblock checkbox_widget %}
Here's the code from the fields.html.twig file (with minor debugging additions...
{% block choice_widget_expanded %}
{{ dump(custom_checkboxes|default(0)) }}
{% set custom_checkboxes = custom_checkboxes|default(0) %}
{{ dump(custom_checkboxes|default(0)) }}
{% spaceless %}
{% set label_attr = label_attr|merge({'class': (label_attr.class|default(''))}) %}
{% set label_attr = label_attr|merge({'class': (label_attr.class ~ ' ' ~ (widget_type != '' ? (multiple ? 'checkbox' : 'radio') ~ '-' ~ widget_type : ''))}) %}
{% if expanded %}
{% set attr = attr|merge({'class': attr.class|default(horizontal_input_wrapper_class)}) %}
{% endif %}
{% for child in form %}
{% if widget_type != 'inline' %}
<div class="{{ multiple ? 'checkbox' : 'radio' }}">
{% endif %}
<label{% for attrname, attrvalue in label_attr %} {{ attrname }}="{{ attrvalue }}"{% endfor %}>
{{ form_widget(child, {'horizontal_label_class': horizontal_label_class, 'horizontal_input_wrapper_class': horizontal_input_wrapper_class, 'attr': {'class': attr.widget_class|default('')}}) }}
{{ child.vars.label|trans({}, translation_domain) }}
</label>
{% if widget_type != 'inline' %}
</div>
{% endif %}
{% endfor %}
{% endspaceless %}
{% endblock choice_widget_expanded %}
... which successfully displays '1' on both counts.
I've racked my brains over this one, but can't for the life of me understand why I can't access the variable in the checkbox_widget block. Please help.
This is due to how Symfony renders form fields when calling form_widget() or any other form* family of functions.
Symfony creates a new separate scope which do not share the scope of the parent (in order to prevent scope polluting while rendering fields).
If you which to pass a variable to the checkbox widget, edit the form_widget call in the choice_widget_expanded to pass on the custom_checkboxes as so (added tabbing for clarity only):
{{ form_widget(child, {
'horizontal_label_class': horizontal_label_class,
'horizontal_input_wrapper_class': horizontal_input_wrapper_class,
'attr': {'class': attr.widget_class|default('')},
'custom_checkboxes': custom_checkboxes
}) }}
Im new to symfony and what im trying is next:
Select everything from the table and count the number of rows.
Access and display this informations in a twig template.
This is part from my code in the controler dedicated to fetch data from datatabase :
.
.
.
$em=$this->getDoctrine()->getManager();
$query=$em->createQuery('SELECT b,COUNT(b.id) FROM AcmeWebBundle:baza b ORDER BY b.id DESC');
$users = $query->getResult();
if (!$em) {
throw $this->createNotFoundException('Something went wrong!');
}
return $this->render('AcmeWebBundle:Default:index.html.twig',array('users'=>$users));
}
in the table named baza i have the fields: id,username,date..etc
And part from the twig file named index.html.twig
{% extends 'AcmeWebBundle:Default:master.html.twig' %}
{% block body %}
<h1> something</h1><br></br>
{% for user in users %}
{{ ...how to access to the number of rows and other data...}}
{% endfor %}
{% endblock %}
Queries:
$query = $this->createQueryBuilder()
->from('AcmeWebBundle:baza', 'b')
->getQuery();
$user = $query->select('b')
->getQuery()
->getResult();
$total = $query->select('COUNT(b)')
->getQuery()
->getSingleScalarResult();
.....
return $this->render('AcmeWebBundle:Default:index.html.twig',array('users' => $users, 'count' => $total));
Template:
{% extends 'AcmeWebBundle:Default:master.html.twig' %}
{% block body %}
<h1> something</h1><br></br>
{% for user in users %}
{{ user.id }}
{{ user.name }}
{% endfor %}
{% endblock %}
Total users: {{ count }}
Where id and name fields in your DB.
You could try the following:
{{ user.id }}
{{ user.username }}
{{ user.date }}
...etc...