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.

General Questions /

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

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

displaying an array in a template


Reply


4 Posts   4148 Views

Avatar
netnerd85

Community Member, 42 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, 17 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, 1804 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
netnerd85

Community Member, 42 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.