0
votes

I have a view which interacts with more than one controller (post, comments, categories...)

In case the comment is not empty, it would go to the same action (comments/add) but in this case i manually redirect them again to the previous view with something like this:

$this->redirect(array('controller' => 'posts', 'action' => 'view', $this->request->data['Comment']['posts_id'], '#' => $this->Comment->id));

The thing is, when they try to post an empty comment, for example, the validation of Comment redirects it to comments/add (which is the route on the form action) but i don't want the redirection to do this. I want it to come back to the original view and i don't have anyway to change it on the controller or the model (as far as I know)

Is there any way to do this?

Thanks.

1

1 Answers

1
votes

The easiest way to do this is to make your form submit via AJAX. So you don't refresh the whole page on submit - you just get the form back, with errors (if there are any).

Obviously, that won't work for users without Javascript. So you can either not worry about those users, or you can make it so the add method of your comments controller uses the view that you want. Something like this:

if ($this->request->is('ajax')) {
    $this->render('/Elements/comment_form');
    return;  // return the form only
} else {
    $this->render('/Posts/view'); // Your post view.ctp would have the comment form on it.
}

Here's an example of a page where I've used that method: http://www.lintonmeagher.com/contact Try submitting either one of the forms with no data.

Let me know if you need any more info.