drawde83
drawde83

Reputation: 139

output array to template

I'm trying to add a custom form with a series of radio buttons. I need to output a list into the template that I can loop over. but when I run this code nothing gets output. if I add text inside my loop it's only output once.

in my page_controller class

public function outputArray($array){
    $dl = DataList::create("DataObject");

    foreach ($array as $it) {
        $do = new DataObject();
        $do->Value = $it;
        $do->write();
        $dl->push($do);
    }

    return $dl;
}

public function NumList(){return $this->outputArray(array("0","1","2","3","4","5"));}

in my template

<% loop NumList() %>
    $Value
<% end_loop %>

Upvotes: 1

Views: 1006

Answers (1)

spekulatius
spekulatius

Reputation: 1499

You are almost there. That is how I would write it:

public function outputArray($array)
{
    $dl = new ArrayList();

    foreach ($array as $it) {
        $dl->add(array('Value' => $it));
    }

    return $dl;
}

and in the SilverStripe Template:

<% loop $NumList %>
    $Value
<% end_loop %>

If you use the Form class of SilverStripe you should have a look at this: http://api.silverstripe.org/3.1/class-SelectionGroup.html This would enable you to just set a key->value array on a object and get the radio buttons rendered by SilverStripe.

Upvotes: 3

Related Questions