2
votes

This should hopefully be a nice simple question.

On a form I have a number of checkboxes relating to selecting various users for a particular function. The checkbox is created like so

$this->Form->input("user_select", array(
  "type"   => "checkbox",
  "name"   => "data[Registration][User][]",
  "id"     => "UserId" . $user['User']['id'],
  "value"  => $user['User']['id'],
  "label"  => false
));

When this form is submitted it comes through to the registration controller but the request->data array contains the checkboxes that aren't selected too in the format:

array(
  'Registration' => array(
    'Users' => array(
      (int) 0 => '0',
      (int) 1 => '0',
      (int) 2 => '0',
      (int) 3 => '0',
      (int) 4 => '31',
      (int) 5 => '0',
      (int) 6 => '11'
    ),
)

Now there's nothing wrong with the data, its clear to see that user's 31 and 11 have been selected but I'd much prefer an array of the form:

array(
  'Registration' => array(
    'Users' => array(
      (int) 4 => '31',
      (int) 6 => '11'
    ),
)

This would make processing and validation much much easier.

So, Does CakePHP have a facility to prevent unselected checkboxes being shown in the request->data array?

2

2 Answers

4
votes

Try adding 'hiddenField' => false to your input() call:

$this->Form->input("user_select", array(
  "type"        => "checkbox",
  "name"        => "data[Registration][User][]",
  "id"          => "UserId" . $user['User']['id'],
  "value"       => $user['User']['id'],
  "label"       => false,
  "hiddenField" => false
));

CakePHP will automatically add a hidden field unless you tell it not to, presumably so that all of the form's keys are represented in $this->data->request. Check this page for more information.

1
votes

Commiting form will always return all checkboxes wheter they are checked or not, It's up to you to decide what to do with this data. As far as I know CakePHP has no such functionality you are asking for, but you can always use PHP to unset empty elements...

 foreach( $array as $key => $val ) {
   if( empty($val) ) {
     unset( $array[$key] );
   }
 }