Codeigniter BUG?:表单验证类与数组混淆

时间:2012-01-17 14:52:32

标签: php codeigniter

我需要创建一个具有相同字段组的表单(数据来自数据库)

例如:

Group 1: Description field, Amount field, Others fields
Group 2: Description field, Amount field, Others fields
Group 3: Description field, Amount field, Others fields

所以在我看来,我循环数据库值:

$i = 0;

foreach ($data_from_db as $data) {

  $description = array(
    'name'  => 'description[]',
    'id'    => 'description_field['.$i.']',
    'value' => set_value('description[]', $data->description)
  );

  echo form_label(lang('reward_description'), 'description_field['.$i.']');
  echo form_textarea($description);
  echo form_error('description[]');

  // more fields generated here in similar ways

  $i++
}

在我的控制器中我有:

$this->form_validation->set_rules('description[]', 'lang:project_edit_description', 'required');

// more similar rules here

根据Codeigniter documentation,这是正确的方法,但它无法正常工作。

Codeigniter与验证消息混淆。

例如,如果我将故意其中一个描述字段清空并提交表单,我会在所有组中收到验证错误消息(我得到了“ “对于组1,2和3也需要说明字段”

1 个答案:

答案 0 :(得分:0)

只需为每个索引字段设置规则。以下摘录显示了一个有效的示例(根据需要进行改进):


测试控制器:

function index()
{
    if ($_POST)
    {
        foreach ($_POST as $key => $value)
        {
            if ($key == 'description' && is_array($value))
            {
                foreach ($value as $i => $vector)
                {
                    // set rule for each index
                    $this->form_validation->set_rules('description[' . $i . ']', 'description ' . ($i + 1), 'trim|required');
                }
            }
        }

        $this->form_validation->run();
    }

    $this->load->view('test');
}

测试视图views/test.php

<?php

echo form_open('');

$data_from_db = $_POST ? $_POST['description'] : array('aaa', 'bbb', 'ccc');
$i = 0;

foreach ($data_from_db as $data)
{
    $description = array(
        'name' => 'description[]',
        'value' => set_value('description[]', $data)
    );

    echo form_label('description ' . ($i + 1) . ':');
    echo form_textarea($description);
    echo '<br>';
    // set error for each index
    echo form_error('description[' . $i . ']');

    // more fields generated here in similar ways

    $i ++;
}

echo form_submit('mysubmit', 'Try it');
echo form_close();
?>

此代码仅在空字段中显示The description x field is required.