Welcome Guest, Not a member yet? Register   Sign In
How can I pass an array of checkbox options from View to Controller?
#1

[eluser]duartix[/eluser]
This is probably more of a HTML question than CI, so I'm sorry for asking but I'm having some difficulty to come up with the better approach...

My problem is the following:
I need to show load a view which will have an undetermined number of checkboxes, like products for the user to choose from. What is the best way to show them?
After I submit the page, my controller will need to process all the checks without knowing which ones the user has checked. How do I go about reading them?

Is there anything as HTML arrays that can be stored in $_POST?
Any ideas on how to do this?

Thanks in advance.
#2

[eluser]CroNiX[/eluser]
Name the fields the same, but use brackets, [], to indicate it is an array.
Code:
<input type="checkbox" name="field[]" value="firstval" />
<input type="checkbox" name="field[]" value="secondval" />
In the controller, get that array by the name.
Code:
$fields = $this->input->post('field');
print_r($fields);
Array(
  0 => 'firstval',
  1 => 'secondval'
)
$fields is now an array of the checked values. Remember, in HTML, checkboxes don't get transmitted in a form unless they ARE checked. If "firstval" checkbox wasn't checked but "secondval" was, the array would only hold "secondval".
#3

[eluser]Unknown[/eluser]
Thank you CroNiX. This was very helpful. I didn't know all the name fields could be the same and that using square brackets will create an array. I'm glad I stumbled across this post late last night. It will help with a project I'm currently working on.
#4

[eluser]duartix[/eluser]
Sorry I didn't say thanks and marked as solution as I was in a hurry. I had voted it up though.
Thanks a million.




Theme © iAndrew 2016 - Forum software by © MyBB