Welcome Guest, Not a member yet? Register   Sign In
Form validation and arrays - prevent callback from running for every value in array
#1

[eluser]drewbee[/eluser]
* I know all about the new form validation class, and this may even be proposed just for it*

I came across something very interesting when working with checkboxes. I wanted to do the standard callback function on a post-array of values coming from a checkbox group IE generated by checkboxes[].

I have a requirement to allow a maximum of three boxes to be checked, and I noticed something interesting with code igniter.

As expected, for each value passed in the checkbox array it calls the custom callback function for each value.

IE.

lets say we have an array of colors that were passed array('red', 'white', 'blue');

It will run callback_customFunction for each of these red, white, and blue.

Makes sense.

Now, however, say I want to make sure no more then three colors are selected
Code:
function customFunction($value)
{
  if ($this->input->post('colors') > 3)
  {
    $this->form_validation->set_message('_customFunction', 'Do not select more then three colors');
    return FALSE;
  }
}

As expected, this gets called as many times as there are values passed, but in this circumstance I really only need it called once.

Is their a way that I just have totally missed, or will this have to be a nice little core hack? Or is the performance degredation on this so negligible that I should just go on with my business?

Thanks for the insight on this.
#2

[eluser]beemr[/eluser]
Slightly off-topic, but checkboxes probably aren't the best way to communicate selection limits, for your controller or for your user. Select multiple boxes have been used in these cases. One pattern in particular, called option transfer, asks the user to transfer options from one selection box to another. In that case, you would only have to run a validation on the final selection box. An excellent jQuery variation on this is asmselect, but most all of these solutions require javascript.
#3

[eluser]drewbee[/eluser]
Right. That is a little bit over kill for what I am doing here.

The user has to select up to a maximum of three colors. I've never much liked multiple selection boxes. All the same though, regardless of whether I use javascript to pass it to another box though, the passed value will almost always be an array, unless I store it in a hidden field making it a string. Regardless of checkboxes or multi-box, the array comes through the same.

The form is basically a 'check what attributes match what you are submiting'. As such, this is why I felt a checkbox group was the best way to go.




Theme © iAndrew 2016 - Forum software by © MyBB