Zend Form with Ajax and validation
Following "logical" Problem, i have an Controller with 2 Actions:
IndexAction: Display an Search Form, inside the view Script is an Div Tag to display search results.
The action validates the form:
public function indexAction()
{
$searchForm = new My_Form_Search();
$statsService = new My_Service_Statistics();
if ($this->getRequest()->isPost()) {
if ($searchForm->isValid($this->getRequest()->getParams())) {
$this->_forward('ajax-do-search');
} else {
//???
// i want to display the errors
exit();
}
}
$this->view->search = $searchForm;
}
public function ajaxDoSearchAction()
{
$this->view->result = array();
$searchForm = new My_Form_Search();
if ($this->getRequest()->isPost()) {
if ($searchForm->isValid($this->getRequest()->getParams())) {
$query = $searchForm->getValue('search');
$search = new My_Service_Search();
$hits = $search->find($query);
// more...
}
}
}
If valid it forwards to the Search action, and the view is rendered via Jquery.form in the defined div.
But what to do if the server side validation failed? without "exit();" the index action is displayed inside the result div.
I think the solution is simple, but to much code today :-)
I know i can prevent this开发者_开发技巧 with client side validation, but i thrust php :-
Your design is bad IMO.
Branch your code using $this->_request->isXmlHttpRequest().
Then echo either whole page (no-js fallback) or only the errors/results
if ($this->_request->isXmlHttpRequest()) {
if ($form->isValid($post)) {
$result = array('status'=>'ok', 'data' => $model->getResults());
$this->_json($result);
} else {
$result = array('status'=>'error', 'data' => $form->getErrors());
$this->_json($result);
}
} else {
//like you would without ajax
}
精彩评论