CakePHP: Dynamic select boxes with AJAX

Working with CakePHP1.2 I had to implement some AJAX techniques in the framework, mainly dealing with onChange behavior of the form components, here is a small example of how we can use multiple selectboxes.

Note: For simplicity reasons, I didn’t include queries, and just used option-arrays:

//inside controller
<?php
       class FooController extends AppController{
                var $name = 'Fooes';
                var $components = array('RequestHandler');
                var $helpers = array('Html','Form','Javascript','Ajax');
 
              function beforeRender(){
                          if($this->RequestHandler->isAjax()){
                                   Configure::write('debug',0);       
                                  //prevent useless warnings for Ajax
 
                          }
                          $this->set('foobar',null); 
                         // initiate an array of options (otherwise, you'll get a warning)
 
             }
             function updateDistricts(){
                                   $this->layout = 'ajax';
                                   $this->beforeRender();
                                   $this->render('updateDistricts/','ajax');
            }
 
      }
?>

This is just a simple layout for calling AJAX methods, without database, sofisticated layout handling, routes etc (for these reasons we got CakePHP API, and CakePHP GoogleGroup)

//inside viewer (test-data): foo/update_districts.ctp



The actual form would look like:

//this code was used as an element from /view/elements/*.ctp
 

As the result, once you change the default value of the first select box, the second one automatically calls the controller’s method, which renders the values (gets the option list from the view file) and renders it in AJAX manner

.

Related article: CakePHP Droppable helper with Dynamic select box