Skip to main content

This site requires you to update your browser. Your browsing experience maybe affected by not having the most up to date version.

We're retiring the forums!

The SilverStripe forums have passed their heyday. They'll stick around, but will be read only. We'd encourage you to get involved in the community via the following channels instead:

Template Questions /

Moderators: martimiz, Sean, Ed, biapar, Willr, Ingo, swaiba

Iterating through a 2 dimensional array in a template


Go to End


3 Posts   2898 Views

Avatar
gwhizzl

Community Member, 3 Posts

20 September 2012 at 5:11am

Edited: 20/09/2012 5:11am

So I'm using a custom function in a page controller to get some data objects, and then display them in the template. Sounds simple, but I can't get it to work.

Here is my function in the page controller:

function getProducts() {
---$Products = array();
---$ProductIDs = array('10,'22','50');
---foreach ($ProductIDs as $key => $value) {
------$Products[$key] = $this->getProductByID($value);
---}
---return $Products;
}

And in the template...

<% control getProducts %>
---$Title
---$Image
---<hr>
<% end_control %>

But no data appears. However, if I put "return $Products[0]" in the function, it successfully returns a Product object and displays the $Title etc...

Avatar
martimiz

Forum Moderator, 1391 Posts

20 September 2012 at 10:49pm

The template engine expects the object passed to a control function to be either a DataObject or a DataObjectsSet, so in this case your function should preferrably return a 'DataObjectSet of DataObjectSets' (this is for version 2.4.x, v3 uses DataLists).

There are some usefull solutions in other posts on these forums (for instance: google 'silverstripe template array')

Avatar
Willr

Forum Moderator, 5523 Posts

22 September 2012 at 5:06pm

To clarify martimiz, your code must pass the template an instance of a ViewableData object (http://api.silverstripe.org/3.0/framework/view/ViewableData.html). This includes DataObjects or ArrayData objects. ArrayData is simply a wrapper around an array.

For 3.0 your function would look like

function getProducts() { 
$products = array();

foreach (array('10,'22','50') as $id) 
$products[] = $this->getProductByID($value); 
 
return new ArrayList($products); 
}

<% control $Products %>
..
<% end_control %>

(this should probably be documented so created http://open.silverstripe.org/ticket/7892)