0

我有一个生成复选框的循环,我让它在视图中工作,但我想将它移动到控制器中,然后将生成的字符串传递给视图。问题是 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;
4

1 回答 1

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;
于 2013-06-13T21:48:06.177 回答