Repopulating checkboxes in Codeigniter after Unsuccessful Form Validation

前端 未结 9 765
梦毁少年i
梦毁少年i 2021-02-04 16:18

I have a problem repopulating a set of checkboxes after an unsuccessful form validation returns the user back to the same form. Dropdown menus and text inputs could be repopulat

9条回答
  •  臣服心动
    2021-02-04 16:55

    In one of my projects, I have used it as follows:

    In the view I did:

    $checkbox_name = 'menu_type_id[]';
    $menu_type_attributes = array(
      'name'              => 'menu_type_id[]',
      'id'                => 'menu_type_id',
      'class'             => 'checkbox-custom rectangular',
      'value'             => $menu_type->get_id(), 
      'checked'           => set_checkbox('menu_type_id[]', $menu_type->get_id()),                 
      'aria-describedby'  => 'menuTypeIdHelp'
    );
    echo form_checkbox($menu_type_attributes);
    

    In the controller I have the validation (FYI, you will have to have form validation on the checkbox if you want to retain the checked status of the checkbox)

    $this->form_validation->set_rules('menu_type_id[]', 'Menu type(s)', 'required');
    

    Even though your business rule does not require you to have at least one checkbox checked, you will still need to put a validation for the checkbox. For eg, you could use

    $this->form_validation->set_rules('menu_type_id[]', 'Menu type(s)', 'trim'); etc.

    Hope this will help some one out there, b/c this information is not available in Code Igniter's documentation.

提交回复
热议问题