开发者

In Yii, how can I have a form that loops through an array of objects?

I'm trying to create a Yii ActiveForm that edits values from a list of objects, presented in a table.

The classes involved:

class ResultForm extends CFormModel {

    /**
     * @var array[Result]
     */
    public $results; //Filled with an array of Result objects
}

class Result {  
    public $requiredArea;
}

My view:

<% $form = $this->beginWidget('CActiveForm'); %>
<table>
   ....
   <% $rowCounter = 0; foreach($resultForm->results as $result): %>
       ...
       <tr>
           ....
           <td>
               <!-- This doesn't work -->
               <% $form->textField($resultForm,
                   "results[$rowCounter]->requiredArea") %>

               <!-- Just displaying the value works -->
               <%= $resultForm->results[$rowCounter]->requiredArea %>
           </td>
           ...
       </tr>
       <% $rowCounter++; endforeach; %>
</table>
<% $this->endWidget(); %>

The text fields are rendered and Yii does not complain, but they do not contain the proper values.

Is there a way I can make this work, or is there a better approach of fo开发者_如何学Cr iterating through an array of objects in a form?


I think you want this instead of what you have:

<% $form->textField($result,"[$rowCounter]requiredArea") %>

What you want to do is pass the model you are iterating over ($result) instead of the parent/form model, and you want to pass in the name of that model's attribute in as the second parameter (along with the $i value/array index) instead of the actual attribute.

Review this page in the Yii guide for more info on tabular input: http://www.yiiframework.com/doc/guide/form.table

Also, check what the parameters are supposed to be for textfield(): http://www.yiiframework.com/doc/api/CHtml#activeTextField-detail

cheers!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜