Home >Backend Development >PHP Tutorial >Yii Framework Official Guide Series 20 - Using Forms: Batch Collecting Form Inputs

Yii Framework Official Guide Series 20 - Using Forms: Batch Collecting Form Inputs

黄舟
黄舟Original
2017-02-13 09:17:481170browse



#Sometimes we want to collect user input via batch mode. That is, users can enter information for multiple model instances and submit them all at once. We call this tabular input because these inputs are usually presented as HTML tables.

To use table input, we first need to create or populate an array of model instances, depending on whether we want to insert or update data. We then extract the user-entered data from the $_POST variable and assign it to each model. The slight difference from single model input is: we need to use $_POST['ModelClass'][$i] to extract the input data instead of using $_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));
}

Ready for this action, we need to continue the work of the batchUpdate view to update it in a The input items are displayed in an HTML table.


<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(&#39;Save&#39;); ?>
<?php echo CHtml::endForm(); ?>
</p><!-- form -->

Note that in the above code we used "[$i]name" Instead of "name" as the second parameter when calling CHtml::activeTextField.

If there are any validation errors, the corresponding input items will be automatically highlighted, just like the single model input we explained earlier.

The above is the Yii Framework Official Guide Series 20 - Using Forms: Batch collecting the content entered in the form. For more related content, please pay attention to the PHP Chinese website (www.php.cn)!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn