Lack of array support for listbox, checkbox in CodeIgniter version 1.6.3


For those people still having one of your sites using CodeIgniter version 1.6.3 and below, you will certainly informed that CI doesn't support validation of listbox (select with multiple enabled) and checkbox for reselecting multiple values chosen. However, there is a decent hack available to enable such requirement, elaborated as below:

You should apply this patch ONLY IF you're using CI version 1.6.3 and below, CI version 1.7.0 and above uses a new form validation class and it does support array as field names.

1. Modify the core Validation.php located under system/libraries/Validation.php, then replace 2 sets of function called as "set_checkbox" and "set_select".

  1. function set_checkbox($field = '', $value = '')
  2. {
  3. if ($field == '' OR $value == '' OR ! isset($_POST[$field]))
  4. {
  5. return '';
  6. }
  7.  
  8. if(is_array($_POST[$field]))
  9. {
  10. if(in_array($value,$_POST[$field]))
  11. {
  12. return ' checked="checked"';
  13. }
  14. }
  15. elseif ($_POST[$field] == $value)
  16. {
  17. return ' checked="checked"';
  18. }
  19. }

  1. function set_select($field = '', $value = '')
  2. {
  3. if ($field == '' OR $value == '' OR ! isset($_POST[$field]))
  4. {
  5. return '';
  6. }
  7.  
  8. if(is_array($_POST[$field]))
  9. {
  10. if(in_array($value,$_POST[$field]))
  11. {
  12. return ' selected="selected"';
  13. }
  14. }
  15. elseif ($_POST[$field] == $value)
  16. {
  17. return ' selected="selected"';
  18. }
  19. }

 

2. Pay a closer attention on field name & id on listbox (select with multiple enabled) being displayed on the view file:

  1. <select id="business[]" name="business[]" size="10">
  2. </select>

Afterwards, $this->validation->set_select('business', $value) will be used to reselect the chosen values. At this point, if validation fails and the form is being reloaded to the user, then the multiple values previouly submitted will be reselected.

3. Last but not least, using $yourownvariable = $_POST["business"]; on the controller file will grab the array of submitted values and store it inside your own defined variable.




 Comments

reply this topic

Did you utilize a help of a media essay writing service for your great article? I opine that you have great good essay composing skillfulness. Thanks a lot for your stuff!