Passing an array to twig and displaying it - symfony

I have an array in my controller. I pass this to my twig view along with another array one
user_id = Array ( [0] => abc [1] => Def [2] => Hij )
data = [0] => HelpCenterBundle\Entity\New Object
(
[id:HelpCenterBundle\Entity\New:private] => 5
[userId:HelpCenterBundle\Entity\New:private] => 314
[comment:HelpCenterBundle\Entity\New:private] => 1
)
I want to print it in a table.
{% for countlist in data %}
<tr>
<td>{{ countlist.id }}</td>
</tr>
<tr>
<td> here i want to print first element of user_count </td>
</tr>
{% endfor %}
I tried with a for loop like
{% for first in user_id %}
<td>{{ first }}</td>
But it results in all the contents in a same line. Please help

seems you're trying to pass an array of objects to twig, which can still be done like so:
{% for key,value in array %}
{% value.objectProperty %}
{% endfor %}
if you want the count of something you can do this:
{% value|length %}
it might also help for building html using arrays in twig to dump your values to see what you work with:
{{ dump(array) }}
this shows a nice pretty format of data that's passed to your template.

Related

Accessing symfony form collection prototype attributes/properties inside twig block

I am trying to setup a custom symfony form collection prototype component of a form. I am referencing the proper documentation
https://symfony.com/doc/3.3/form/form_customization.html#how-to-customize-a-collection-prototype
The form collection is setup using the following
<table class="table table-bordered" data-prototype="{{ form_row(form.quoteItemDeliverables.vars.prototype)|e('html_attr') }}">
<caption>Deliverables</caption>
<tr>
<th>Quantity</th>
<th>Date Required</th>
</tr>
{% for itemDeliverable in form.quoteItemDeliverables %}
<tr>
<td>{{ form_widget(itemDeliverable.quantity) }}</td>
<td>{{ form_widget(itemDeliverable.dateRequired) }}</td>
</tr>
{% endfor %}
</table>
The twig block that is referencing the prototype is setup using the following
{% form_theme form _self %}
{% block _uniflytebundle_quoteitem_quoteItemDeliverables_entry_row %}
<tr>
{#<td>{{ form_widget(form.quoteItemDeliverables.vars.prototype.quantity) }}</td>#}
</tr>
{{ dump(form.children["quoteItemDeliverables"]) }}
{% endblock %}
The dump(); is returning the following error
Key "quoteItemDeliverables" for array with keys "quantity, dateRequired" does not exist.
What am I doing wrong?
If I dump(form); I get the form object displaying the children, the "quoteItemDeliverables" and the "prototype" elements
Can someone please point me in the right direction on how to access the various form properties? Trying to do what was done in the collection form for the prototype. Below being working form collection elements.
<td>{{ form_widget(itemDeliverable.quantity) }}</td>
<td>{{ form_widget(itemDeliverable.dateRequired) }}</td>
I would like the same for the prototype twig block but using something like
form_widget(itemDeliverable.prototype.dateRequired)
does not work. How can I do this?
Thank you in advance for your time and effort invested.
Inside the twig block, form does not refer to the "global" form but to the sub form corresponding to the entry of your collection. That is why the error produced by the dump call indicates that the array has quantity and dateRequired keys but no quoteItemDeliverables.
Thus what you should have is more likely to be something like:
{% block _uniflytebundle_quoteitem_quoteItemDeliverables_entry_row %}
<tr>
<td>{{ form_widget(form.quantity) }}</td>
<td>{{ form_widget(form.dateRequired}}</td>
</tr>
{% endblock %}

Field's Name Table [duplicate]

This question already has an answer here:
Getting column names in a doctrine2 entity
(1 answer)
Closed 5 years ago.
I was trying to display the field name from a database to be used in the table header to be displayed in the twig for admin section propose!
I have my database like this one
id | Gram | Height | Kilos |
1 | 27.1 | 126 cm | 29 kg |
and I want to get the field name "Gram, Height etc" and make it as table header, I was going to make a translation for this like English to Japanese and so on, "the problem is how do I get the data field name and display it like a text any advice for this on", Thank you in advance!
Code for controller
/**
* #Route("/ingredients/header-translation", name = "z_recipe_header_translation")
* #Template("NutritionMainBundle:Admin\create\recipe\ingredients:translate-headers.html.twig")
*/
public function headerTranslationAction(Request $request)
{
$em = $this->getDoctrine()->getManager();
$nutrients = $em->getRepository("NutritionAdminBundle:NutritionValue")->findAll();
return array(
'header' => $nutrients
);
}
Twig code
<table class="table" style="width:100%;">
<thead>
<tr>
<th>header</th>
{% for ii in 1..9 %}
<th>language {{ii}}</th>
{% endfor %}
</tr>
</thead>
<tbody>
{% for i in 1..10 %}
<tr>
<td>header label {{i}}</td>
{% for ii in 1..9 %}
<td><input type="text"/></td>
{% endfor %}
</tr>
{% endfor %}
</tbody>
</table>
Oh this is a duplicate question so sorry about that, i'll just make it as an example, The code below will be my final answer, Thank for the help!
controller code:
/**
* #Route("/ingredients/header-translation", name = "z_recipe_header_translation")
* #Template("NutritionMainBundle:Admin\create\recipe\ingredients:translate-headers.html.twig")
*/
public function headerTranslationAction(Request $request)
{
$em = $this->getDoctrine()->getManager();
$NutritionValueField = $em->getClassMetadata('NutritionAdminBundle:NutritionValue')->getFieldNames();
$languages = $em->getRepository("NutritionLanguageBundle:Language")->findAll();
$form = $this->createForm(new NutritionValueType());
$form->handleRequest($request);
return array(
'header' => $NutritionValueField,
'languages' => $languages,
'form' => $form->createView()
);
}
For my Twigs display
<table class="table" style="width:100%;">
<thead>
<tr>
<th>header</th>
{% for languages in languages %}
<th>{{languages.langLabel}}</th>
{% endfor %}
</tr>
</thead>
<tbody>
{% for header in header %}
<tr>
{% if header == 'NDB_NO'%}
{#do nothing#}
{% else %}
<td>{{ header|replace({'_':' '}) }}</td>
{% for languages in languages %}
<td><input id="{{header}}_{{ languages.id }}" type="text" value="{{header|replace({'_':' '})}}"/> </td>
{% endfor %}
{% endif %}
</tr>
{% endfor %}
</t
body>
You can use the database information schema:
SELECT `COLUMN_NAME`
FROM `INFORMATION_SCHEMA`.`COLUMNS`
WHERE `TABLE_SCHEMA` = 'databasename'
AND `TABLE_NAME` = 'tablename';
use sql sentence:desc tablename;

Sorting table by its column value in Twig

I created a method in Twig that will count and display results in table.But I want to sort the table based on results column
{% for island in islands %}
<tr>
<td>{{ island.id }}</td>
<td>{{ island.name }}</td>
<td>{{ number_votes(island.id) }}</td>
</tr>
{% endfor %}
results
id name result
1 name1 3000
2 name2 100
3 name3 5000
4 name4 90
As you can see it is sorted by default based on its id.How to sort based on its result column?
My twig filter
public function getFunctions()
{
return array(
new \Twig_SimpleFunction('number_votes', array($this, 'a'))
);
}
public function getName()
{
return 'app.extension';
}
public function a($id)
{
$qb=$this->em->createQueryBuilder();
$qb->select('count(v.id)')
->from('Bundle:Voters','v')
->join('v.city','c')
->join('c.province','p')
->join('p.region','r')
->join('r.island','i')
->where('i.id = :x')
->setParameter('x',$id);
$count = $qb->getQuery()->getSingleScalarResult();
return $count;
//I tried return sort($count)//not working
}
I also tried
{{ number_votes(island.id)|sort }}/throws an error
I'm afraid I have to create another Twig filter,is there any way to prevent this?
You could avoid a twig filter completely and do something like this so you have your islands and your vote counts in one result set:
$islandsAndVotes = $qb->select('i, count(v.id) as vote_count')
->from('Bundle:Voters','v')
->join('v.city','c')
->join('c.province','p')
->join('p.region','r')
->join('r.island','i')
->groupBy('i')
->orderBy('vote_count', 'DESC')
->getQuery()
->getResult()
;
Each element of $islandsAndVotes will contain an Island entity at index 0 and a vote count at index 1
E.g.
foreach ($islandsAndVotes as $islandVote) {
$island = array_shift($islandVote);
$votecount = array_shift($islandVote);
}
In twig you could use first & last to access the island or the vote count respectively as you iterate over the results.
{% for islandVote in islandsAndVotes %}
{% set island = islandVotes|first %}
{% set voteCount = islandVotes|last %}
<tr>
<td>{{ island.id }}</td>
<td>{{ island.name }}</td>
<td>{{ voteCount }}</td>
</tr>
{% endfor %}

How to get Pagination direction in twig for KNP paginator?

I am using knp paginator and it works well but when I want to use its sorting feature I have problem to get the sort direction in twig.
the following code is indicate how to get the sorted table header but not taking about how to get sorted table header direction.
{# total items count #}
<div class="count">
{{ pagination.getTotalItemCount }}
</div>
<table>
<tr>
{# sorting of properties based on query components #}
<th>{{ knp_pagination_sortable(pagination, 'Id', 'a.id') }}</th>
<th{% if pagination.isSorted('a.Title') %} class="sorted"{% endif %}>{{ knp_pagination_sortable(pagination, 'Title', 'a.title') }}</th>
</tr>
{# table body #}
{% for article in pagination %}
<tr {% if loop.index is odd %}class="color"{% endif %}>
<td>{{ article.id }}</td>
<td>{{ article.title }}</td>
</tr>
{% endfor %}
</table>
{# display navigation #}
<div class="navigation">
{{ knp_pagination_render(pagination) }}
</div>
I get this code from KnpPaginator documentation on following link:
https://github.com/KnpLabs/KnpPaginatorBundle
You should be able to just use {{ pagination.getDirection() }} in your twig template to find the current sort direction (if any) then set up your classes based on that.
{% set direction = pagination.getDirection() %}
<th{% if pagination.isSorted('p.id') %} class="sorted {{ direction }}"{% endif %}>
{{ knp_pagination_sortable(pagination, 'Id', 'p.id') }}
</th>
But... as of this post, KNP has not yet merged this fix:
https://github.com/sroze/KnpPaginatorBundle/commit/3105a38714c6f89c590e49e9c50475f7a777009d
When there is no direction parameter set, the current Paginator bundle throws an error.
So, until the above fix is merged, you can still get the direction with a bit more verbosity:
{% set directionParam = pagination.getPaginatorOption('sortDirectionParameterName') %}
{% set params = pagination.getParams() %}
{% set direction = params[directionParam] is defined ? params[directionParam] : null %}
<th{% if pagination.isSorted('p.id') %} class="sorted {{ direction }}"{% endif %}>
{{ knp_pagination_sortable(pagination, 'Id', 'p.id') }}
</th>
When you call {{ knp_pagination_sortable(pagination, 'Id', 'a.id') }}, bundle automatically generates link with a class holding an information about sort direction, which looks something like this: <a translationcount="" class="asc" href="?sort=a.id&direction=desc&page=1" title="Id">Id</a> So just put this class in your css file and style it with the arrow. If you, for some reason, need to get a sort direction inside a controller, just read it from request $request->query->get('direction').

Tables and forms in Twig

I have a table-form which I implemented this way:
<tr>
<td>Start Date:</td>
<td>{{ form_widget(form.start_date) }}</td>
</tr>
<tr>
<td>Previous Plan:</td>
<td>{{ form_widget(form.prev_plan) }}</td>
</tr>
Is there a way to make this using the ready theme form_table_layout.html.twig or at all in some more flexible and elegant way?
I tried this:
{% form_theme form 'form_table_layout.html.twig' %}
{{ form_errors(form) }}
{% for field in form %}
{{ form_row(field) }}
{% endfor %}
but it puts its own names in the left part of the table which are not the names I want. (For example instead of "Previous Plan: " in this way I got "Prev plan")
You can define your own labels when defining the form. Something like:
->add('prev_plan', 'text',array(
'label' => 'Previous Plan'
))
(I don't know the field type for prev_plan, I used 'text' but if it is a different field type just change that)

Resources