Forum

Thread tagged as: Question, Problem, Forms

Looping through array in template

Trying to loop through an array in a form template but currently only able to output the first item in the array, although it does output as many times as there are items:

<?php
        PerchSystem::set_var('product_list', $itemList);
        perch_form('cart.html');
 ?>

Array content looks like this: Array ( [0] => 3 x Blackmagic Ursa Mini Pro 4.6k EF [1] => 1 x Go Pro Hero 3 Black Edition )

Template looks like this:

<perch:repeater id="product_list">
        <perch:forms id="product_list" encode="false" />
      </perch:repeater>

Output: 3 x Blackmagic Ursa Mini Pro 4.6k EF 3 x Blackmagic Ursa Mini Pro 4.6k EF

Rob Saunders

Rob Saunders 0 points

  • 3 years ago
Hussein Al Hammad

Hussein Al Hammad 105 points
Registered Developer

Hello Rob,

To render an array with a repeater tag your array should be made up of arrays like this:

$itemList = array();

$itemList[] = ['title' => '3 x Blackmagic Ursa Mini Pro 4.6k EF'];
$itemList[] = ['title' => '1 x Go Pro Hero 3 Black Edition'];
PerchSystem::set_var('product_list', $itemList);

Template:

<perch:repeater id="product_list">
<perch:forms id="title" encode="false" />
</perch:repeater>

Brill Thank you Hussein,

How would you perform that dynamically, as looping through adds each iteration into the array and I don't know the contents of the cart:

 <?php
        $cartItems = perch_shop_cart([
            'skip-template' => true
        ]);

        $Items = $cartItems['items'];
        $Item = $Items[0];

        $itemList = array();
        foreach($Items as $Item){
            $itemList[] = ($Item['qty']) ." x ".($Item['title']);
        };

        PerchSystem::set_var('product_list', $itemList);
        perch_form('cart.html');
      ?>

Magento Development Developers. Expand your online store with Magento developer tools, shopping cart and payment integration services worldwide. https://eminentcoders.com/magento-development-toronto/

Hussein Al Hammad

Hussein Al Hammad 105 points
Registered Developer

How would you perform that dynamically, as looping through adds each iteration into the array and I don't know the contents of the cart:

You need to assign keys to the array elements (so you can use the keys as IDs in the template):

$Items = $cartItems['items'];
$ItemList = array();

foreach($Items as $Item) {
    $product['qty'] = $Item['qty'];
    $product['title'] = $Item['title'];
    $ItemList[] = $product;
}

PerchSystem::set_var('product_list', $ItemList);
perch_form('cart.html');

In your case you can actually use:

$Items = $cartItems['items'];
PerchSystem::set_var('product_list', $Items);
perch_form('cart.html');

And in your form template:

<perch:repeater id="product_list">
    <perch:forms id="title" /> - <perch:forms id="qty" />
</perch:repeater>

Awesome thank you!!