Multiple checkboxes in CakePHP - how to set which are checked?

user198003 picture user198003 · Aug 29, 2012 · Viewed 33.8k times · Source

I have multiple checkboxes in CakePHP's Add/Edit view, created with:

echo $this->Form->input('email_warning_chb', array('type'=>'select', 'multiple'=>'checkbox', 'label'=> __('Email notice'), 'class'=>'multiple-chb', 'options'=> array('title...'=>array( '5'=>'5 days', '15'=>'15 days', '30'=>'30 days', '60'=>'60 days');

My question is how to set which one are checked by default (ie. in thi example, 5, 15 and 60)?

Thank you in advance!

Answer

Pent picture Pent · Apr 5, 2013

As said in other answers, you should set the 'selected' option. What some people don't mention is that your selected array should only contain the id in each element. Example:

$selectedWarnings = $this->Warning->find('list', array(
  'fields' => array('id')
));


echo $this->Form->input('email_warning_chb', array(
    'label' => 'Email Notice',
    'type' => 'select',
    'multiple' => 'checkbox',
    'options' => $warnings,
    'selected' => $selectedWarnings
  ));