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.

General Questions /

General questions about getting started with SilverStripe that don't fit in any of the categories above.

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

displaying an array in a template


Go to End


4 Posts   9166 Views

Avatar
jaybee

Community Member, 49 Posts

13 December 2010 at 11:21pm

How do you display an array of data in a template? I have some code that works but it seems extreme, is this really what I need to get it to work?

Controller code

function UKCities()
{
	$_list = array('Aberdeen
		', 'Armagh
		', 'Bangor
		', 'Bath
		', 'Belfast');

	$list = new DataObjectSet();
	foreach($_list as $key => $data) {
		$data = array('City' => $data);
		$list->push(new ArrayData($data));
	}
	return $list;
}

Template code
<% control UKCities %>
	<option>$City</option>
<% end_control %>

Avatar
hello_world

Community Member, 19 Posts

13 December 2010 at 11:46pm

Hi,
In Controller code use:

function UKCities() {
   $_list = array( 'Aberdeen', 'Armagh', 'Bangor', 'Bath', 'Belfast');


	$listoption = "Select your City";
	foreach($_list as $list) {
		
		$listoption .= "<option value=\"".$list."\">".$list."</option>";
		
	}
 
   return $listoption;
} 

And in Your template between <select></select> paste:


$UKCities

You can also use DropdownField() .

Avatar
swaiba

Forum Moderator, 1899 Posts

14 December 2010 at 12:16am

I would agree that DropDownField is the best option, but I'd disagree with writing '<option>' etc in the controller, to get your original version working I'd do the following... (note:untested!)

function UKCities()
{
$_list = array('Aberdeen', 'Armagh', 'Bangor', 'Bath', 'Belfast');

$list = new DataObjectSet();
foreach($_list as $data) {
$do=new DataObject();
$do->City = $data;
$list->push($do);
}
return $list;
}

Template code

<% control UKCities %> 
   <option>$City</option> 
<% end_control %>

Avatar
jaybee

Community Member, 49 Posts

14 December 2010 at 2:45am

Thanks guys, I thought there had to be a better way. I agree with swaiba about the HTML seperation and your code worked perfectly with just copy and paste.