When adding a record, I let user mark as many checkboxes and needed:
echo $this->Form->input('us_roles', array('label' => 'Roles:', 'type'=> 'select', 'multiple'=>'checkbox','options' => $arr_pr_role));
and store selected indexes to a string field on my bd without a problem. (it saves eg. 1,2,3)
However, when editing that record, the checkboxes are not populated -selected- accodingly. (based on the string text, for example, 1,2,3
How can I have my checkboxex reflect the values stored as a string on the db?
My edit view uses the same as my add view:
echo $this->Form->input('us_roles', array('label' => 'Roles:', 'type'=> 'select', 'multiple'=>'checkbox','options' => $arr_pr_role));
** More detail
When adding a new record, I implode the selections from the select into my data:
$this->request->data['User']['us_roles'] = implode(",", $this->request->data['User']['us_roles']);
Same thing when saving an edited record.
The issue isUpon retrieval, how can I translate the string into my us_roles input?
echo $this->Form->input('us_roles', array('label' => 'Roles:', 'type'=> 'select', 'multiple'=>'checkbox','options' => $arr_pr_role));
Can you help?
— update, fixed—
public function edit($id = null) {
$this->User->id = $id;
if (!$this->User->exists()) {
throw new NotFoundException(__('Invalid user'));
}
if ($this->request->is('post') || $this->request->is('put')) {
$this->request->data['User']['us_roles'] = implode(",", $this->request->data['User']['us_roles']);
if ($this->User->save($this->request->data)) {
...
} else {
$this->request->data = $this->User->read(null, $id);
$this->request->data['User']['us_roles'] = explode(",", $this->request->data['User']['us_roles']);
}
Now I understand…
You are looking for the opposite of implode().
That would be explode().
Or you can use the string class ( http://book.cakephp.org/2.0/en/core-utility-libraries/string.html#String::tokenize ):
should get you your array of values back.
But believe me, there are usually better ways of doing that.
You could make it another db table + model. You could use the ArrayDatasource, you could use some bitmasked solution like I do in such a case ( http://www.dereuromark.de/2012/02/26/bitmasked-using-bitmasks-in-cakephp/ ).
The advantage of the last approach is that you still use only a single field (and very small amount of space) while you have the full capabilities of an extra table: Full search on NOT, AND, OR, …