Getting params from redirected request - php

I'm trying to redirect the user using this code:
return $this->redirect()->toRoute('application', array(
'controller' => 'Index',
'action' => 'connexion',
null,
array('e' => 'n'),
));
And getting from the layout the content of the e param this way:
$_REQUEST['e']
But doing that I don't catch anything. How do I to get it please?
Thanks in advance!

Matched Route params in view :
$this->getHelperPluginManager()
->getServiceLocator()
->get('Application')
->getMvcEvent()
->getRouteMatch()
->getParams()
Request Query/Post in view :
$this->getHelperPluginManager()
->getServiceLocator()
->get('Request')
->getQuery()->toArray()
$this->getHelperPluginManager()
->getServiceLocator()
->get('Request')
->getPost()->toArray()

As mentioned in the comments of your question, the way to go is: $this->params()->fromRoute(); mentioned by #Notuser. Will use it in a simple example for your use as you're passing the parameters to the view.
class ExampleController extends AbstractActionController
{
public function rerouteAction()
{
// Notice that 'param' is a route within our route.config.php and in there we
// define the controller and action, so we do not need to set the controller
// and action in the redirect. So param now points to paramAction of ExampleController.
return $this->redirect()->toRoute('param', array('e' => 'n'));
}
public function paramAction()
{
// Leaving fromRoute() blank will return all params!
$params = $this->params()->fromRoute();
$e = $params['e'];
return array('e' => $e);
}
}
So in your view.phtml you can now easily do <?php echo $this->e; ?> which should contain: n.
The route.config of the above example will look something like this:
return array(
'router' => array(
'routes' => array(
'reroute' => array(
'type' => 'segment',
'options' => array(
'route' => 'reroute',
'defaults' => array(
'controller' => 'Application\Controller\ExampleController',
'action' => 'reroute'
)
)
),
'param' => array(
'type' => 'segment',
'options' => array(
'route' => 'param',
'defaults' => array(
'controller' => 'Application\Controller\ExampleController',
'action' => 'param'
)
)
)
)
)
);

Related

zf2 phpunit scheme routes

We're using ZF2 for an web-application and want to test it with phpunit (v4.8.9). Within this application we've got a scheme-route, to be able to switch between http/https-context (Doesnt matter why...). The route looks like this:
'http' => array(
'type' => 'Scheme',
'options' => array(
'scheme' => 'http',
'defaults' => array(
'http' => true
)
),
'child_routes' => array(
'search' => array(
'type' => 'segment',
'options' => array(
'route' => '/search[/:keyword[/:page]]',
'constraints' => array(
'page' => '[1-9]+[0-9]*'
),
'defaults' => array(
'controller' => SearchController::class,
'action' => 'search',
),
),
),
),
),
'https' => array(
'type' => 'Scheme',
'options' => array(
'scheme' => 'https',
'defaults' => array(
'https' => true
)
),
'child_routes' => array(
'search' => array(
'type' => 'segment',
'options' => array(
'route' => '/search[/:keyword[/:page]]',
'constraints' => array(
'page' => '[1-9]+[0-9]*'
),
'defaults' => array(
'controller' => SearchController::class,
'action' => 'search',
),
),
),
),
),
The class of the test looks like this:
class SearchControllerTest extends SynHttpControllerTestCase
{
public function setUp()
{
$this->setApplicationConfig($this->getCurrentBootstrap()->getApplicationConfig());
parent::setUp();
$this->getApplicationServiceLocator()->setAllowOverride(true);
}
public function testSearchActionCanBeAccessed()
{
$this->dispatch('/search');
$this->assertResponseStatusCode(200);
$this->assertControllerName(SearchController::class);
$this->assertControllerClass('SearchController');
$this->assertActionName('search');
$this->assertMatchedRouteName('search');
}
}
FYI:
The "SynHttpControllerTestCase" is an extension from the original AbstractHttpControllerTestCase which comes with Zend-Test. It's modified to get the right bootstrap-file in our tests.
If we're running the tests, this error appears:
Fatal error: Call to a member function getParam() on null in C:\xampp\htdocs\git\xxx\vendor\zendframework\zend-test\src\PHPUnit\Controller\AbstractControllerTestCase.php on line 563
We looked into the AbstractControllerTestCase and this line is throwing the error:
$routeMatch = $this->getApplication()->getMvcEvent()->getRouteMatch();
Because the $routeMatch-Object is empty.
We've some other controllers and tests within our application, they're all fine and not affected from this problem, cause the routes to these controllers arent scheme-routes.
Do you have any ideas how to solve this? In advance: we're not able to use static https-routes in this case.
There is a lot of official documentation on how to write a proper controller test. In your setUp method you need to attach a Router instance to a RouteMatch instance which you attach to a MvcEvent in the controller.
protected function setUp()
{
$serviceManager = Bootstrap::getServiceManager();
$this->controller = new IndexController();
$this->request = new Request();
$this->routeMatch = new RouteMatch(array('controller' => 'index'));
$this->event = new MvcEvent();
$config = $serviceManager->get('Config');
$routerConfig = isset($config['router']) ? $config['router'] : array();
$router = HttpRouter::factory($routerConfig);
$this->event->setRouter($router);
$this->event->setRouteMatch($this->routeMatch);
$this->controller->setEvent($this->event);
$this->controller->setServiceLocator($serviceManager);
}
Then you can call dispatch.
UPDATE
Can you not set your route match object like this:
$routeParams = array('controller' => 'search', 'action' => 'search');
$routeMatch = new RouteMatch($routeParams);
$routerConfig = isset($config['router']) ? $config['router'] : array();
$router = HttpRouter::factory($routerConfig);
$event = new MvcEvent();
$event->setRouter($router);
$event->setRouteMatch($routeMatch);
$this->getApplication()->setMvcEvent($event);

Trouble with URL parameters

I am working on a search form that I would like to post the searched by values in the url. I am having trouble getting the url to include the parameters however. They will post if I key in values in the view( if instead of $this->search_zip I key '12345'). Currently the search works as desired except for the url. I am currently getting the search terms from the form, would I need to change my controller setup to get them from the url instead? If this is the case how would I filter?
Ultimately I would like my url to read:
results/12345/otherparam
I am currently getting
results
No matter what variables I key into the form.
Module Config
return array(
'router' => array(
'routes' => array(
'home' => array(
'type' => 'segment',
'options' => array(
'route' => '/',
'constraints' => array(
'action' => '[a-zA-Z][a-zA-Z0-9_-]*',
),
'defaults' => array(
'controller' => 'Application\Controller\Index',
'action' => 'index',
),
),
'may_terminate' => true, //START OF CHILD ROUTES
'child_routes' => array(
'results' => array(
'type' => 'segment',
'options' => array(
'route' => 'results[/:search_zip][/:search_industry]',
'defaults' => array(
'controller' => 'Application\Controller\Index',
'action' => 'results',
Results view
$form->setAttribute('action', $this->url(
'home/results',
array(
'action' => 'results',
'search_zip'=> $this->search_zip,
'search_industry' => 'industry_name'
echo $this->formRow($form->get('industry_name'));//this is the form field
echo $this->formSubmit($form->get('submit'));
Controller
//beginning of the results action
$request = $this->getRequest();
$form = new SearchForm($dbAdapter);
if ($request->isPost()) {
$search = new MainSearch();
$form->setInputFilter($search->getInputFilter());
$form->setData($request->getPost());
if ($form->isValid()) {
At the end of my resultsAction I return the form and the results (per the album example)
return array(
'form' => $form,
'pros' => $fetchPros,
);
Thank you,
M
//This will give you an array containing your desired parameters
$params = $this->params()->fromRoute();
//Then you can simply use them like this
$search_zip = $params['search_zip'];
$search_industry = $params['search_industry'];

Pass custom variables in ZF2 routing config?

I'm thinking about the best way of implementing ACL. So - I need to protect certain routes. Some routes would be accessible only to users, some to guests and some to admins.
It seems like the best way of doing it would be by adding a $role variable in the routing config. So then I'd attach to post-route event, fetch the routeMatch and I would see if this user can enter this route.
How can I do that? Can I simply inject extra varibles like this:
'router' => array(
'routes' => array(
'route1' => array(
'type' => 'Zend\Mvc\Router\Http\Regex',
'options' => array(
'regex' => '/some/route/1',
'defaults' => array(
'controller' => 'Subscriber\Controller\View',
'action' => 'route1',
'role' => 'user', //extra
),
'spec' => '/some/route/1',
),
),
'route2' => array(
'type' => 'Zend\Mvc\Router\Http\Regex',
'options' => array(
'regex' => '/some/route/2',
'defaults' => array(
'controller' => 'Subscriber\Controller\View',
'action' => 'route2',
'role' => 'guest', //extra
),
'spec' => '/some/route/2',
),
),
//other routes....
),
),
Yes you can just add the router key like you have
'defaults' => array(
'controller' => 'Subscriber\Controller\View',
'action' => 'route1',
'role' => 'user', //extra
),
And then you can checkit like this
public function onBootstrap(MvcEvent $e) {
$application = $e->getApplication();
$eventManager = $application->getEventManager();
$eventManager->attach(MvcEvent::EVENT_ROUTE, function(MvcEvent $e) {
$e->getRouteMatch()->getParam('role');
});
}
There are however modules made for this
For example bjyoungblood/BjyAuthorize which works with ZfcUser
You should take a look at : ZfcRbac. It's well documented.

Can I have an action that doesn't load a template?

I got an answer to this question here, but now I have another concern\problem.
I have a subnav bar in my module created from a view partial via a helper.
Here is the config in module.config.php:
'navigation' => array(
'default' => array(
array(
'label' => 'Search',
'route' => 'mymodule\search',
),
array(
'label' => 'Log Off',
'route' => 'logout',
),
),
),
I have a LoginController with 2 actions: login and logout. After logging in I want the user to click the logout button, be redirected to the login page and have their session cleared.
Now if I have a login and logout action I need a template for each. This seems unnecessary for the logout action- I don't want another template to load for this action.
Here's my routing config:
'login' => array(
'type' => 'Zend\Mvc\Router\Http\Literal',
'options' => array(
'route' => '/login',
'defaults' => array(
'__NAMESPACE__' => 'Application\Controller',
'controller' => 'Application\Controller\Login',
'action' => 'login',
),
),
),
'logout' => array(
'type' => 'Zend\Mvc\Router\Http\Literal',
'options' => array(
'route' => '/login',
'defaults' => array(
'__NAMESPACE__' => 'Application\Controller',
'controller' => 'Application\Controller\Login',
'action' => 'logout',
),
),
),
Is there a correct way to have an action get called without loading a corresponding template?
You can return a response object instead:
public function logoutAction()
{
// do stuff
return $this->redirect()->toRoute('login');
}
then you don't need a template.
On zf2
public function Action(){
$vm = new ViewModel();
$vm->setTerminal(true);
return $vm;
}
EDIT:::
In case that you want to return a custom response you can do:
public function Action(){
return $this->getResponse()->setContent("Hello world!");
}

First optional routing segment acts as mandatory one for child routes

I have the following routing definition:
'admin_default' => array(
'type' => 'segment',
'options' => array(
'route' => '[/:lang]/administrator[/:module][/:action]',
'constraints' => array(
'lang' => '[a-zA-Z]{2}',
'module' => '[a-zA-Z0-9_-]*',
'action' => '[a-zA-Z0-9_-]*',
),
'defaults' => array(
'module' => 'Application',
'controller' => 'Admin',
'action' => 'index',
'lang' => 'ru'
),
),
'may_terminate' => true,
'child_routes' => array(
'wildcard' => array(
'type' => 'wildcard',
'may_terminate' => true,
'options' => array(
'key_value_delimiter' => '/',
'param_delimiter' => '/'
),
),
),
),
So, I can't get rid of segment [/:lang] in URL string
For example:
URL view helper $this->url('admin_default', array('module' => 'albums')) returns the following URL string:
/administrator/albums
while $this->url('admin_default/wildcard', array('module' => 'albums', 'action' => 'edit', 'id' => album_id_here)) returns:
/ru/administrator/albums/edit/id/album_id_here
How can I remove [/:lang] segment from URL string in second case?
so whats the matter with that "ru" ?
you have to extend the zend view helper URL to inject your current locale to the URL
look what i made for my current project :
<?php
namespace PatrickCore\View\Helper;
use Doctrine\ORM\EntityManager;
use Zend\View\Helper\Url;
class I18nUrl extends Url {
/**
* #var String
*/
protected $lang;
protected $router;
public function __construct($locale,$router) {
$arraylanguagemapping = array(
'en_US' => 'en',
'fa_IR' => 'fa'
);
$this->lang = $arraylanguagemapping[$locale];
$this->router = $router;
}
public function __invoke($name = null, array $params = array(), $options = array(), $reuseMatchedParams = false) {
$this->setRouter($this->router);
if (!array_key_exists('lang', $params)) {
$params['lang'] = $this->lang;
}
return parent::__invoke($name,$params,$options,$reuseMatchedParams);
}
}
?>

Categories