w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
Zend framework 2: redirect toRoute shortcircuit not triggering

The act of calling $this->redirect() in your controller doesn't automatically redirect to a new location, it just returns a Response 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 the redirect() call from another function, you'll need to first test if the result of that call is a Response object and handle it in your controller action...

<?php

namespace BlogController;

use ZendMvcControllerAbstractActionController;
use ZendMvcControllerPluginFlashMessenger as FlashMessenger;

use ZendStdlibResponseInterface 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;
    }
}




© Copyright 2018 w3hello.com Publishing Limited. All rights reserved.