php - Zend framework 2: redirect toRoute shortcircuit not triggering
Get the solution ↓↓↓Solution:
The act of calling$this->redirect()
in your controller doesn't automatically redirect to a new location, it just returns aResponse
object which you then need to return from your controller action in order to short circuit the request.
Since you're returning the result of theredirect()
call from another function, you'll need to first test if the result of that call is aResponse
object and handle it in your controller action...
<?php
namespace Blog\Controller;
use Zend\Mvc\Controller\AbstractActionController;
use Zend\Mvc\Controller\Plugin\FlashMessenger as FlashMessenger;
use Zend\Stdlib\ResponseInterface as Response;
class PostController extends AbstractActionController
{
public function readAction()
{
$post_id = $this->params()->fromRoute('id');
$post = $this->validatePostId($post_id);
// check to see if post validation returned a Response
if ($post instanceof Response) {
// redirect...
return $post;
}
return array(
'post' => $post
);
}
/**
* Checks if $id from url is set and tries to find the corresponding post
*/
public function validatePostId($post_id)
{
if (!$post_id) {
$this->flashMessenger()->addErrorMessage('Invalid post id');
return $this->redirect()->toRoute('post');
}
$post = $this->getBlogService()->getPostById($post_id);
if ($post == NULL) {
$this->flashMessenger()->addErrorMessage('Invalid post id');
return $this->redirect()->toRoute('post');
}
return $post;
}
}
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: string literal contains an unescaped line break
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.