Codeigniter,在控制器中使用set_checkbox

时间:2013-06-12 22:27:40

标签: codeigniter codeigniter-2

我有一个生成复选框的循环,我在视图中工作,但我想将其移动到控制器中,然后将生成的字符串传递给视图。问题是set_checkbox()似乎不记得放在控制器中的值。但它似乎设置了默认值。

编辑:这只是验证失败时的问题,我希望复选框保留用户选择。否则代码按预期工作。我还有一个验证规则集。

    $languages_by_name = $this->event_model->get_spoken_languages_by_name();

    // Generate array from model data for form_dropdown()
    $i = 1; 
    $list_languages = '';
    foreach ($languages_by_name as $row) {
        $i == 1 ? $first = TRUE : $first = FALSE; // Check if this is the first radio and precheck it.
        $list_languages .= '<label>' . form_checkbox('spokenLanguages[]', $row->event_spoken_id, set_checkbox('spokenLanguages', $row->event_spoken_id, $first)) . ' ' . $row->name . '</label> ';
        $i++;
    }
    // Pass $list_languages to view
    $this->data['list_languages'] = $list_languages;

1 个答案:

答案 0 :(得分:1)

这是控制器的工作代码。可能有一种更优雅的方式来做到这一点。

    // Generate array from model data for form_dropdown()
    $i = 1; 
    $list_languages = '';
    foreach ($languages_by_name as $row) {
        // Check if there is post data
        if(!$this->input->post('spokenLanguages')) {
            // Set first element to checked
            $i == 1 ? $selection = TRUE : $selection = FALSE; // Check if this is the first radio and precheck it.
        } else {
            // Check if this input is checked
            if(in_array($row->event_spoken_id, $this->input->post('spokenLanguages'))) {
                $selection = TRUE;
            } else {
                $selection = FALSE;
            }   
        }

        $list_languages .= '<label>' . form_checkbox('spokenLanguages[]', $row->event_spoken_id, set_checkbox('spokenLanguages', $row->event_spoken_id, $selection)) . ' ' . $row->name . '</label> ';
        $i++;
    }
    // Pass $list_languages to view
    $this->data['list_languages'] = $list_languages;