1

我有一个带有两个输入文本字段的表单:

<input id="ModelName_test_0" name="ModelName[test][0]" type="text">
<input id="ModelName_test_1" name="ModelName[test][1]" type="text">

这些输入字段使用以下命令生成:

<?php echo $form->textField($model,'test[0]'); ?>
<?php echo $form->textField($model,'test[1]'); ?>

现在,当我提交表单时,我会看到 POST 请求中的值。但是,当表单提交失败时,我无法将值返回到输入字段中。打印模型显示 $test 没有值;- 这是因为 $test 是表单中的数组吗?

即使在验证之后,所有值仍然分配给变量:

if($model->validate()) {
   echo "<pre>";
   print_r($_POST);
   return;
}

这将返回:

[ModelName] => Array  
        (
            [test] => Array  
                (
                    [0] => myFirstInputField  
                    [1] => mySecondInputField
                )
        )

所以这些值在 POST 中,但在验证失败后它们消失了,我得到空变量:

[ModelName] => Array  
        (
            [test] => 
        )

变量test在验证规则中被声明为安全的。

我想要实现的是:
如果验证失败,将输入的值放回适当的输入文本字段中。

任何朝着正确方向的指针都会有所帮助:)

4

2 回答 2

0

问题是,CHtml::activeTextField需要一个模型及其属性之一作为参数。如果属性被命名test,那么 have $form->textField($model,'test');。提交表单后,要么test没有任何值,要么它是一个数组(选中此项以确认,要么回显它的值,要么执行print_ron $model->attributes)。

于 2012-06-13T05:29:15.613 回答
0

我在 yiiframework.com 网站上发现这篇文章帮助我解决了这个问题:http ://www.yiiframework.com/doc/guide/1.1/en/form.table

这是您将其放入控制器的示例代码:

public function actionBatchUpdate()
{
    // retrieve items to be updated in a batch mode
    // assuming each item is of model class '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=$item->validate() && $valid;
        }
        if($valid)  // all items are valid
            // ...do something here
    }
    // displays the view to collect tabular input
    $this->render('batchUpdate',array('items'=>$items));
}

这就是视图的样子:

<div 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(); ?>
</div><!-- form -->

两个代码片段均取自 yiiframework.com,您可以在其中找到有关如何使用“表格输入”的更多详细信息:http ://www.yiiframework.com/doc/guide/1.1/en/form.table

于 2012-06-13T14:03:58.853 回答