I have a model: Categories. Any category may have subcategories. The model uses the tree behavior (Cakephp 2.0). I would like to create a form with two selection boxes. One with the categories and the other with the subcategories. When I choose one category, the box with the subcategories should be filled dynamically depending on my choice. For example if there are the categories Sports, Movies and the sub categories Football, Basketball and Comedy, SciFi if I select Movies in the first box, the second should be filled with Comedy and Scifi as options. Searching around I have found a solution but it does not work.
The solution is that in the form should be a script (Js) which observes the status of the first box. When it changes, it calls a function from the controller rendering the result in an element which populates the options of the second box.
So what I did.
Model
<?php
class Category extends AppModel {
var $name = 'Category';
var $actsAs = array('Tree');
}
?>
Model Fields: id, parent_id, lft, rght, name
Controller - Method
function ajax_categories() {
$this->set('options',
$this->Category->find('list',
array(
'conditions' => array(
'Category.parent_id' => $_GET['data']['Category']['id']
)
)
)
);
$this->render('/elements/ajax_dropdown', 'ajax');
}
It should find all the records in the table that have as father the chosen option (that means it finds the subcategories of the category chosen from the first box)
Element (ajax_dropdown)
<?php foreach($options as $key => $val) { ?>
<option value="<?php echo $key; ?>"><?php echo $val; ?></option>
<?php } ?>
View - Form
<?php
$this->Html->script('prototype', array('inline' => false));
echo $this->Form->create('Category');
echo $this->Form>input('Category.id',array('id'=>'Category.id','label'=>'Parent',
'empty' => '-- Pick a category --' ,'options' => $cats));
echo $this->Form->input('Subcategory',array('id' =>
'Subcategory','label'=>'Subcategory', 'empty' => '-- Pick a subcategory --' ));
echo $this->Form->input('name',array('label'=>'Name'));
echo $this->Form->end('Add');
$this->Js->get('#Category.id')->event(
'change', $this->Js->request(
array('controller'=>'categories','action'=>'ajax_categories'),
array('update' => '#Subcategory', 'dataExpression' => true, 'data'
=> '$("#Category.id").serialize()')
)
);
?>
where $cats is a var that contains the categories.
The problem is that nothing happens. When I choose a category, the second selection box is empty. I have included the Js helper and the RequestHandler and of course I load the jquery script, outputting the buffer (nappo reminded me that) What am I doing wrong?