Jump to:

23376 Posts in 18214 Topics by 2867 members

General Questions

SilverStripe Forums » General Questions » displaying an array in a template

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

Page: 1
Go to End
Author Topic: 3749 Views
  • netnerd85
    Avatar
    Community Member
    42 Posts

    displaying an array in a template Link to this post

    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 %>

  • hello_world
    Avatar
    Community Member
    17 Posts

    Re: displaying an array in a template Link to this post

    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() .

  • swaiba
    Avatar
    Forum Moderator
    1785 Posts

    Re: displaying an array in a template Link to this post

    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 %>

  • netnerd85
    Avatar
    Community Member
    42 Posts

    Re: displaying an array in a template Link to this post

    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.

    3749 Views
Page: 1
Go to Top

Want to know more about the company that brought you SilverStripe? Then check out SilverStripe.com

Comments on this website? Please give feedback.