Zend Form Dynamic Ajax City Loading
I'm working on a project using zend framework and I need a dynamic ajax city loading by the state selection.Each state is associated to cities in the database.
I have a form Create.php
class Application_Form_Create extends Zend_Form {
public function init() {
$this->setMethod('POST');
...
$state = new Zend_Form_Element_Select('state');
$state->setLabel('States:')
->addMultiOptions($DataBaseStatesArray);
$this->addElement($state);
$city = new Zend_Form_Element_Select('city');
$city->setLabel('Cities:')
->addMultiOptions($DataBaseCitiesArray);
$this->addElement($city);
$submit = new Zend_Form_Element_Submit('submit');
$this->addElement($submit);
}
the form is loaded to view on controller
...
function createAction()开发者_JS百科{
$this->view->form = new Application_Form_Create();
}
View
<?=$this->form;?>
How could i load the cities based on the selected state using zend framework resources?
Thanks
You could use that in the init method to your controller to change the nature of an action at runtime to an Ajax dedicated action which will automatically disable layout rendering.
Controller
public function init()
{
$ajaxContext = $this->_helper->getHelper('AjaxContext');
$ajaxContext->addActionContext('check', 'html');
$ajaxContext->initContext();
}
Action
public function checkAction()
{
// code to run upon ajax request
// ...
// ...
$this->_view->result = $result; // pass the result to the view
}
And you view file could be as easy as that
<?php echo $this->result; ?>
then you just have to make sure the content of the view in in whatever format you want, HTML, XML, JSON
More info at chapter 5 of the book Zend Framework in Action
精彩评论