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've moved the forum!

Please use forum.silverstripe.org for any new questions (announcement).
The forum archive will stick around, but will be read only.

You can also use our Slack channel or StackOverflow to ask for help.
Check out our community overview for more options to contribute.

Data Model Questions /

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

How to render an array in SS template using ArrayList [SOLVED]


Go to End


5 Posts   7298 Views

Avatar
Optic Blaze

Community Member, 190 Posts

9 July 2015 at 4:25pm

Hi,

Lets say i have an array called fruit in my Page controller class. How would i render it in a .ss template. Eg:

 class FruitPage_Controller extends Page_Controller {
		public function init() {
                parent::init();
		}
		public function myfruit() {
			$fruit = array( '0'=>'apple', '1'=>'pear', '2'=>'grape', '3'=>'peach' )
                        return $fruit;
		}
	}

And then in the .ss template
<% loop $myfruit %>
I like $fruit <br/>
<% end_loop %>

Avatar
Devlin

Community Member, 344 Posts

9 July 2015 at 7:55pm

Edited: 09/07/2015 8:02pm

public function myfruit() {
	$fruit = new ArrayList([
		new ArrayData(['fruit' => 'foo']), 
		new ArrayData(['fruit' => 'bar']),
	]);
	return $fruit;
}

Avatar
Optic Blaze

Community Member, 190 Posts

9 July 2015 at 8:47pm

Edited: 09/07/2015 8:48pm

Hi, Thanks for the feedback.

Is it possible to loop through the array using foreach to generate the new ArrayData. I have a checkbox field with comma delimited values that i use to populate the $fruit array with and i need to bring that into the template. So something like this maybe:

public function myfruit() {
$fruit = array( '0'=>'apple', '1'=>'pear', '2'=>'grape', '3'=>'peach' );
$fruitlist = new ArrayList([
		foreach($fruit as $id) {new ArrayData(['fruit' => '$id[]']), }
	]);

return $fruitlist;
}

Avatar
Devlin

Community Member, 344 Posts

9 July 2015 at 8:57pm

$fruits = array( '0'=>'apple', '1'=>'pear', '2'=>'grape', '3'=>'peach' );
$fruitlist = new ArrayList();
foreach($fruits as $item) {
    $fruitlist->push(
        new ArrayData(array('fruit' => $item))
    );
}
return $fruitlist;

Avatar
Optic Blaze

Community Member, 190 Posts

9 July 2015 at 9:06pm

Thanx Devlin!!!!!

That worked like a dream! I have been struggling with this for hours. Really appreciate the help.