I have a twig extension function created that count the total prices of items:
public function getTotal($items)
{
$total = array();
foreach($items as $item){
$total[] = $item->getPrice() - $item->getDiscount() + $item->getValue();
}
return $total;
}
However when I display them i get error: array to string conversion
I am displaying like this:
{{getTotalTax(product)}}
I tried doing this which didnt help:
public function getTotal($items)
{
$totals = array();
foreach($items as $item){
$totals[] = $item->getPrice() - $item->getDiscount() + $item->getValue();
if(is_array($totals)) {
return '';
}
}
return $totals;
}
Your code is returning an array.
I assume you want to either:
.
function print_totals($totals){
foreach ($totals as $total){
echo $total;
}
}
it's hard to say exactly what you're trying to do from your question, as you have your 'display' calling getTotalTax(product)
where product seems to be a single item, but the function you pasted is called getTotal()
which assumes an array of $items
.
You might want to update a property on each item like so:
public function getTotal($items)
{
$total = array();
foreach($items as $item){
$item->total = $item->getPrice() - $item->getDiscount() + $item->getValue();
}
return true;
}
OR
.
public function getTotal($items)
{
$total = 0;
foreach($items as $item){
$total += $item->getPrice() - $item->getDiscount() + $item->getValue();
}
return $total;
}
You are indeed returning an array and it cannot be converted to string. Depending what exactly you want you can return for example
return print_r($totals, true);
Otherwise you can extract individual elements from your HTML template and output these.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.