1

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 :-

1 Answer 1

2

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
}
Sign up to request clarification or add additional context in comments.

3 Comments

You are right, but now i have to use json to print the result (-:
no you don't have to ;) you can do $this->render('my-ajax-viewscript'); as well. This is just my best practice ;)
Hi, just changed the code yesterday exactly to your comment :-) Now i see things much clearer ! Thanks a lot!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.