Tables side by side - php

How can I put two arrays side by side using twig ?
This is my input
{% for key, item in CompareArray %}
{% for x in item %}
<tr>
{% if key =='last' %}
<td> last</td>
{% endif %}
{% if key == 'primary' %}
<td> primary</td>
{% endif %}
</tr>
{% endfor %}
{% endfor %}
The desired output
table,td{
border: 1px solid black;
padding: 1px;
}
<table>
<tr>
<td> last.val1 </td>
<td> last.val2 </td>
<td> last.val3 </td>
<td> #### </td>
<td> primary.val1 </td>
<td> primary.val2 </td>
<td> primary.val3 </td>
</tr>
<tr>
<td> ... </td>
<td> ... </td>
<td> ... </td>
<td> ... </td>
<td> ... </td>
<td> ... </td>
<td> ... </td>
</tr>
<table>

Based on the shared information I see a couple of possible solutions.
But first confirm if I understand correctly what you're trying to achieve.
You want to have table where the item information of the last group is displayed first with a separator column and then the item information of the primary group on the left? And as seen in the screen shot of the array the number of items in the group isn't even necessarily the same?
First think to consider would be should we create two different tables one for primary group and one for last and style them through css to look as if they're in they are side by side.
{% for groupKey, items in CompareArray %}
<table>
{% for item in items %}
<tr>
<td>{{ groupKey }}.{{ item.prop1 }}</td>
<td>{{ groupKey }}.{{ item.prop2 }}</td>
<td>{{ groupKey }}.{{ item.prop3 }}</td>
</tr>
{% endfor %}
</table>
{% endfor %}
Second solution would be a complicated use of attribute this means that both arrays have to have same keys. Here you'd iterate over the largest group and then add the corresponding value from the other group. I'm using some macros to better separate the logic. The block named myTemplate is the code you'd insert where you wanted the data to be displayed.
{% block myTemplate %}
{% if CompareArray.last|length > CompareArray.primary|length %}
{{ _self.lastIsLonger(CompareArray.last, CompareArray.primary) }}
{% else %}
{{ _self.primaryIsLonger(CompareArray.last, CompareArray.primary) }}
{% endif %}
{% endblock %}
{% macro lastIsLonger(lastGroup, primaryGroup) %}
{% set primaryLenght = primaryGroup|length %}
<table>
{% for k,item in lastGroup %}
<tr>
{{ _self.buildElementData(item) }}
<td> #### </td>
{{ _self.buildElementData(loop.index <= primaryLenght ? attribute(primaryGroup, k) : {}) }}
</tr>
{% endfor %}
</table>
{% endmacro %}
{% macro primaryIsLonger(lastGroup, primaryGroup) %}
{% set lastGroupLength = lastGroup|length %}
<table>
{% for k,item in primaryGroup %}
<tr>
{{ _self.buildElementData(loop.index <= lastGroupLength ? attribute(lastGroup, k) : {}) }}
<td> #### </td>
{{ _self.buildElementData(item) }}
</tr>
{% endfor %}
</table>
{% endmacro %}
{% macro buildElementData(item) %}
<td>{{ item.prop1 ?? '' }}</td>
<td>{{ item.prop2 ?? '' }}</td>
<td>{{ item.prop3 ?? '' }}</td>
{% endmacro %}
If I understand what you're doing I think a third solution I think would be best. That is that from the PHP side you matched which items you wanted to compare so the data you'd insert would look something like this:
[
[
'last' => [
'prop1' => '...',
'prop2' => '...',
'prop3' => '...',
],
'primary' => [
'prop1' => '...',
'prop2' => '...',
'prop3' => '...',
],
], [
'last' => [
'prop1' => '...',
'prop2' => '...',
'prop3' => '...',
],
'primary' => [
'prop1' => '...',
'prop2' => '...',
'prop3' => '...',
],
]
];
This way you're not relying on dirty tricks and do most of the logic where it belongs. The corresponding generation template generation is thus much more pleasing.
{% block myTemplate %}
<table>
{% for row in CompareArray %}
<tr>
{{ _self.buildElementData(row.last ?? {}) }}
<td> #### </td>
{{ _self.buildElementData(row.primary ?? {}) }}
</tr>
{% endfor %}
</table>
{% endblock %}
{% macro buildElementData(item) %}
<td>{{ item.prop1 ?? '' }}</td>
<td>{{ item.prop2 ?? '' }}</td>
<td>{{ item.prop3 ?? '' }}</td>
{% endmacro %}

Related

PHP, symfony list data in table

This is a project for school!!!
Let's say that I want to store and show working hours in an HTML table.
I want something like, 'if' the date from DB which user added is equal to the date from the weekly calendar than show me an EDIT button else show me an ADD button?
I want to show Add for the rest of the users who didn't create any data in DB.
<table class="table" id="week">
<thead>
<tr>
<th scope="col">users</th>
{% for day in days %}
<th class="{{ day|date("D-d") }}">
<span>{{ day|date("D") }}</span>
<span>{{ day|date("d") }}</span>
</th>
{% endfor %}
</tr>
</thead>
<tbody>
{% for user in users %}
<tr class="days">
<th scope="row">{{ users.username }}</th>
{% for day in days %}
<td id="my_cell {{ day|date("d-m") }}">
{% for time in findTime %}
{% if d|date("d-m-Y") == time.date|date('d-m-Y') and users.id == time.getUser().id %}
{{ time.timeFrom|date("H:i") }} - {{ time.timeTo|date("H:i") }}
{% endif %}
{% endfor %}
</td>
{% endfor %}
</tr>
{% endfor %}
</tbody>
</table>
I am currently using DB doctrine ORM on symfony 3.4v
I don't have an idea how to solve this problem, I tried with different array function in PHP but I did not find solutions.
Thank you for understanding.

Doctrine - Create dynamical list in View

I am trying to create a view for display the total sales for all the suppliers and customers of a shop.
The total sales for a customer are easy to obtain, the problem is when I have to create the columns with the brands, I have been looking through this site, doctrine, etc, But I cannot find any solution.
SaleController.php
/**
* #Route("/widget/summarize")
*
* #return Render
*/
public function widgetSummarizeAction()
{
$suppliers = $this->getDoctrine()->getEntityManager()->createQueryBuilder()
->select(['su.name AS name'])
->from('AppBundle:Supplier', 'su')
->getQuery()
->getArrayResult()
;
$data = $this->getDoctrine()->getManager()->createQueryBuilder()->groupBy('c.name')
->select([
's.id AS id',
's.invoiceDate AS invoiceDate',
'c.name AS customer',
'SUM(ROUND(s.amount * s.price, 2)) AS totalSales',
'su.name AS supplier',
])
->from('AppBundle:Sale', 's')
->leftJoin('s.supplierCustomer', 'sc')
->leftJoin('sc.customer', 'c')
->leftJoin('sc.supplier', 'su')
->getQuery()
->getArrayResult()
;
return $this->render('AppBundle::home_widget.html.twig', [
'title' => 'Total Sales',
'icon' => 'money',
'urlList' => $this->generateUrl($this->getUrlList()),
'rowRoute' => $this->getUrlEdit(),
'data' => $data,
'columns' => [
'customer' => 'customer',
'totalSales' => 'Total Sales'
]
]);
home_widget.html.twig
<div class="panel panel-default home-widget">
<div class="panel-heading">
<h2 class="panel-title pull-left">
{% if icon is defined and icon is not empty %}<i class="fa fa-{{ icon }}"></i>{% endif %}
{{ title }}
</h2>
{% if urlList %}
<a class="btn btn-primary pull-right" href="{{ urlList }}">See All</a>
{% endif %}
<div class="clearfix"></div>
</div>
<div class="panel-body">
{% if data is not empty and data is iterable %}
<table class="table table-bordered table-striped">
<thead>
<tr>
{% for column in columns %}
<td>{{ column }}</td>
{% endfor %}
</tr>
</thead>
<tbody>
{% for row in data %}
{% set href = url(rowRoute, {'id': row.id}) %}
<tr>
{% for key,column in columns %}
<td>
<a href="{{ href }}">
{{ row[key] | raw }}
</a>
</td>
{% endfor %}
</tr>
{% endfor %}
</tbody>
</table>
{% endif %}
</div>
</div>
Maybe try get colulmns name by:
$em = $this->getDoctrine()->getManager();
$columns = $em->getClassMetadata(your_entity_name::class)->getFieldNames();
and loop through the columns in twig template.
<thead>
<tr>
{% for column in columns %}
<td>{{ column }}</td>
{% endfor %}
</tr>
</thead>

Get key name of array value in twig for loop

I'm trying to have twig to output the key name(column name from mysql data).
What I want to do is basicly: <a class="listquestions" href="#" id="{{ key }}"...
Current codebase:
<table id="listquestions" class="table table-striped table-bordered table-hover" cellspacing="0" width="100%">
<thead>
<tr>
{% for key, answer in answers[0] %}
<th>{{ key }}</th>
{% endfor %}
</tr>
</thead>
<tbody>
{% for key,answer in answers %}
<tr>
<td>{{ answer.a_id }}</td>
<td>
<a class="listquestions" href="#" data-name="a_text" data-type="text" data-pk="{{ answer.a_id }}" data-url="{{ path_for('qa.edit') }}" data-title="enter attribute name">
{{ answer.a_text }}
</a>
</td>
<td>
<a class="listquestions" href="#" data-name="a_attribute_name" data-type="text" data-pk="{{ answer.a_id }}" data-url="{{ path_for('qa.edit') }}" data-title="enter attribute name">
{{ answer.a_attribute_name}}
</a>
</td>
</tr>
{% endfor %}
</tbody>
PHP function var_export($data,true) outputs:
array (
0 =>
array (
'a_id' => '1',
'a_text' => 'text',
'a_attribute_name' => 'attr',
),
1 =>
array (
'a_id' => '2',
'a_text' => 'text',
'a_attribute_name' => 'attr',
),
2 =>
array (
'a_id' => '3',
'a_text' => 'text',
'a_attribute_name' => 'attr',
),
)
I tried adding a TwigExtension that does key($answer.a_text) but key() does not work with twig for-loops.
So what am I missing? I can output the key name inside <thead> as you see but I'd like to do this with the second for-loop.
<table id="listquestions" class="table table-striped table-bordered table-hover" cellspacing="0" width="100%">
<thead>
<tr>
{% for key, answer in answers[0] %}
<th>{{ key }}</th>
{% endfor %}
</tr>
</thead>
<tbody>
{% for key,answer in answers %}
{% for field, value in answer %}
<tr>
{% if field == 'a_id' %}
<td>{{ answer.a_id }}</td>
{% else %}
<td>
<a class="listquestions" href="#" data-name="{{ field }}" data-type="text" data-pk="{{ answer.a_id }}" data-url="path_for('qa.edit')" data-title="enter attribute name">
{{ value }}
</a>
</td>
{% endif %}
</tr>
{% endfor %}
{% endfor %}
</tbody>
</table>

Twig if/else not working

I'm not sure why my code isn't executing. I know that it should be working this way but all that happens now is that it doesn't do the else portion.
In debugging I know descriptions is not null and descriptions show for those that have it.
{% if descriptions is not null %}
{{ dump(descriptions) }}
{% for description in descriptions %}
<td>{{ description.productDesciption }}</td>
{% endfor %}
{% else %}
<td>
Create a Description for this Product
</td>
{% endif %}
You can simplify using the The else Clause of the for statement:
{% for description in descriptions %}
<td>
{{ description.productDesciption }}
</td>
{% else %}
<td>
Create a Description for this Product
</td>
{% endfor %}
Hope this help
You can use if into for loop.
{% for description in descriptions if descriptions is not null %}
<td>
{{ description.productDesciption }}
</td>
{% else %}
<td>
Create a Description for this Product
</td>
{% endfor %}

Twig doesn't approximate number

I have a strange situation. My code is :
{% set total_amount=0 %}
{% for result in a_result %}
<tr>
<td>{% set total_amount=total_amount+("%.2f"|format(result.tva*result.prix_ht)) %}
{{ "%.2f"|format(result.tva*result.prix_ht) }}
</td>
/tr>
{% endfor %}
<tr>
<td colspan="5">Total</td>
<td>{{ total_amount }}</td>
</tr>
As result I have :
15.98, 25.49, 25.49
And Total = 65 but total should be equal with 65.96. I don't understand where is the problem. Can you help me please ?
I suggest you to use the round and number_format filter as follow:
{% set total_amount=0 %}
{% for result in a_result %}
{% set value = (result.tva* result.prix_ht)|round(2) %}
{% set total_amount=total_amount+value %}
<tr>
<td>
{{ value|number_format(2, '.', ',') }}
</td>
/tr>
{% endfor %}
<tr>
<td colspan="5">Total</td>
<td>{{ total_amount|number_format(2, '.', ',') }}</td>
</tr>
A running example with sample data in this twigfiddle files
Hope this help

Categories