要使用表格输入,我们首先需要创建或填充一个模型实例数组,取决于我们是想插入还是更新数据。 然后我们从 $_post 变量中提取用户输入的数据并将其赋值到每个模型。和单模型输入稍有不同的一点就是: 我们要使用 $_post['modelclass'][$i] 提取输入的数据而不是使用 $_post['modelclass']。
public function actionbatchupdate() { // 假设每一项(item)是一个 'item' 类的实例, // 提取要通过批量模式更新的项 $items=$this->getitemstoupdate(); if(isset($_post['item'])) { $valid=true; foreach($items as $i=>$item) { if(isset($_post['item'][$i])) $item->attributes=$_post['item'][$i]; $valid=$valid && $item->validate(); } if($valid) // 如果所有项目有效 // ...则在此处做一些操作 } // 显示视图收集表格输入 $this->render('batchupdate',array('items'=>$items)); }
准备好了这个动作,我们需要继续 batchupdate 视图的工作以在一个 html 表格中显示输入项。
<p class="form"> <?php echo chtml::beginform(); ?> <table> <tr><th>name</th><th>price</th><th>count</th><th>description</th></tr> <?php foreach($items as $i=>$item): ?> <tr> <td><?php echo chtml::activetextfield($item,"[$i]name"); ?></td> <td><?php echo chtml::activetextfield($item,"[$i]price"); ?></td> <td><?php echo chtml::activetextfield($item,"[$i]count"); ?></td> <td><?php echo chtml::activetextarea($item,"[$i]description"); ?></td> </tr> <?php endforeach; ?> </table> <?php echo chtml::submitbutton('save'); ?> <?php echo chtml::endform(); ?> </p><!-- form -->
注意,在上面的代码中我们使用了 [$i]name 而不是 name 作为调用 chtml::activetextfield 时的第二个参数。
如果有任何验证错误,相应的输入项将会自动高亮显示,就像前面我们讲解的单模型输入一样。
以上就是yii框架官方指南系列20——使用表单:批量收集表格输入的内容。
