I would like to set a query parameter when redirecting. I tried this:
$this->redirect()->toRoute('login/default', array('action' => 'forgotPassword', 'foo' => 'bar'));
It redirects to:
/login/forgotPassword
Instead of where I would like to redirect which is:
/login/forgotPassword?foo=bar
The query parameter belongs to the third parameter of the URL-Methods.
$this->redirect()->toRoute(
'login/default',
array(
'action' => 'forgotPassword'
),
array( 'query' => array(
'foo' => 'bar'
))
)
Plus.
To redirect a "access" or login, form you can use:
if (!$controller->identity()) {
$sm = $controller->getServiceLocator();
$router = $sm->get('router');
$request = $sm->get('request');
$routeMatch = $router->match($request);
$controller->redirect()->toRoute('login', array(),
array( 'query' =>
array('redir' => $routeMatch->getMatchedRouteName() ) ) );
}
Urls will be:
/login/?redir=current-route
Related
I would like to pass json to action, something similar to passing simple variable:
/** module.config.php
'mobileapplication-topup' => array(
'type' => 'segment',
'options' => array(
'route' => '/mob/topup[/:voucherID]',
'constraints' => array(
'voucherID' => '[a-zA-Z][a-zA-Z0-9_-]*',
),
'defaults' => array(
'controller' => 'Mob\Controller\Topup',
'action' => 'index',
),
),
and TopupController.php
public function indexAction()
{
echo ($this->params('voucherID'));
$result = new ViewModel();
$result->setTerminal(true);
return $result;
}
//** no layout //
$response = $this->getResponse();
$response->setStatusCode(200);
$response->setContent("Error");
return $response;
}
something similar to this, but just a json string instead of voucherID. What kind of constraints should be added to this json variable?
** Is there any way how to POST the form from other domain to ZF2?
I have found solution, but I don't think it is a perfect one...
What I was thinking that there is some way of passing variables using route
mvc.com/controller/param1/param2
and into this for example just pass a json and decode it in one of the controllers...
but at the moment I'm using basing _GET method
mvc.com/controller/param1/param2?"Json"={"p1":"value1","p2":"value2"}
Hello friends I am new in zf2. I stuck at one place. In my project I want to to call one view on many action.
My url is "baseurl/g/any-thing-from-from-database"
I want to call a view on "any-thing-from-from-database" action from another module or same.
My G module have this code on module.config.php
return array(
'controllers' => array(
'invokables' => array(
'G\Controller\G' => 'G\Controller\GController',
),
),
'router' => array(
'routes' => array(
'g' => array(
'type' => 'segment',
'options' => array(
'route' => '/g[/:action][/:id]',
'constraints' => array(
'action' => '[a-zA-Z][a-zA-Z0-9_-]*',
'id' => '[0-9]+',
),
'defaults' => array(
'controller' => 'G\Controller\G',
'action' => 'g',
),
),
),
),
),
'view_manager' => array(
'template_path_stack' => array(
'g' => __DIR__ . '/../view',
),
),
);
on GController.php
namespace G\Controller;
use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;
use Zend\Stdlib\RequestInterface as Request;
use Zend\Stdlib\ResponseInterface as Response;
use Zend\View\Renderer\PhpRenderer;
use Students\Form\StudentsForm;
use Students\Model\Students;
class GController extends AbstractActionController
{
public function dispatch(Request $request, Response $response = null)
{
$controller = $this->params('controller');
$nicname = $this->params('action');
if($nicname !== false){
$hosts = $this->getServiceLocator()->get('Manager\Model\HostsTable');
if(($data = $hosts->findByNicname($nicname)) !== null){
$captchaService = $this->getServiceLocator()->get('SanCaptcha');
$form = new StudentsForm($captchaService);
return array('from'=>$form);
}
}
return $this->redirect()->toRoute('home',array('controller'=>'application','action'=>'index'));
}
public function gAction()
{
return new ViewModel();
}
}
To get different actions from url I have used dispatch function that is working correctly. When i get this action from database I want to show a form with some content from different module named Students or G. But this code only showing header and footer and nothing else without any error.Please help me out.Thanks in advance.
I think overwriting dispatch method cannot be very good.
I'm sure you don't see anything, because you don't ever render a ViewModel, so no data are there. This is because you disabled default dispatch behaviour and overwrite the action argument in your route. So if you open http://my.website/g/foobar then foobarAction() would be called - if your dispatch will work correctly.
So what you could do is simple rename your action param to (for example) foo, take your logic to gAction() and do what ever you have to do with $this->param('foo').
Hello friends I am new in zf2. I am creating an action in controller, all things are working correctly. When the form is valid, i would like to pass some of the values to redirect page. how can i do this? Please help me out.
My controller action is
public function studenteditAction(){
$id = (int) $this->params()->fromRoute('id', 0);
if (!$id) {
return $this->redirect()->toRoute('manager', array(
'action' => 'students'
));
}
$form = new StudentsForm();
$request = $this->getRequest();
if ($request->isPost()) {
$students = new Students();
$form->setData($request->getPost());
if ($form->isValid()) {
$students->exchangeArray($form->getData());
$table = $this->getServiceLocator()->get('Students\Model\StudentsTable');
$table->profileStudents($students);
return $this->redirect()->toRoute('manager',array('controller'=>'manager','action'=>'student-view','id'=>$id,'status' => 'profile-ready'));
}
}
return array(
'id' => $id,
'form' => $form,
);
}
I am unable to get the passed status value on controller's view.
'status' => 'profile-ready'
Thanks in advance
You need to modify your routing configuration to accept both 'id' and 'status' values.
'manager' => array(
'type' => 'Segment',
'options' => array(
'route' => '/manager[/:id][/:status]',
'defaults' => array(
'controller' => 'Application\Controller\Manager',
'action' => 'studentView',
),
'constraints' => array(
'id' => '[0-9]*',
'status' => '[a-z-]*'
),
),
),
Controller:
public function studentViewAction()
{
$id = $this->params()->fromRoute('id');
$status = $this->params()->fromRoute('status');
return new ViewModel(array('id' => $id, 'status' => $status));
}
View
<?php
echo $this->id;
echo $this->status;
?>
This is how i pass the required values to another controller's action
I have the code to change the language of site. I would like to extend this functional. I want to make sure that the language parameter in the url is correct when I get the 404 page (or dispatch_error event).
My route example
'about' => array(
'type' => 'Segment',
'options' => array(
'route' => '/[:lang/]about',
'constraints' => array(
'lang' => '[a-zA-Z]{2}?',
),
'defaults' => array(
'controller' => 'Application\Controller\Index',
'action' => 'about',
'lang' => 'en',
),
),
),
If url param isn't correct (example.com/e/about or exampleDotcom//about), then makes redirect to the specific page (for example, example.com/why_did_it_happen). To make this, I create a function checkRedirect and attach it to EVENT_DISPATCH_ERROR . But how to get the LANG parameter from the url and then make a redirect, I don't know. I tried to do this many times, but could not. I've got - Call to a member function getParam () on a non-object. What code would I append to the checkRedirect function to get the LANG parameter from the url and then make a redirect in this function?
My code in Module.php
class Module implements
AutoloaderProviderInterface,
ConfigProviderInterface,
ViewHelperProviderInterface {
public function onBootstrap(MvcEvent $e) {
$eventManager = $e->getApplication()->getEventManager();
$moduleRouteListener = new ModuleRouteListener();
$moduleRouteListener->attach($eventManager);
$eventManager->attach(MvcEvent::EVENT_ROUTE, array($this, 'initLocale'), -100);
$eventManager->attach(MvcEvent::EVENT_DISPATCH_ERROR, array($this, 'checkRedirect'), -101);
$eventManager->attach(MvcEvent::EVENT_DISPATCH, array($this, 'preDispatch'), 100);
}
public function initLocale(MvcEvent $e) {
$translator = $e->getApplication()->getServiceManager()->get('translator');
$config = $e->getApplication()->getServiceManager()->get('Config');
$shotLang = $e->getRouteMatch()->getParam('lang'); //or $e->getApplication()->getMvcEvent()->getRouteMatch();
if (isset($config['languages'][$shotLang])) {
$translator->setLocale($config['languages'][$shotLang]['locale']);
} else {
$lang = array_shift($config['languages']);
$translator->setLocale($lang['locale']);
}
}
public function checkRedirect(MvcEvent $e) {
//code here
}
$e->getRouteMatch()->getParam('NAME')
This does work, but 'NAME', but be the name given in the routes.
'route' => '/[:lang/]about',
However, the above route does not match the route *example.com/why_did_it_happen*
Try changing your route to
'route' => '[/:lang]/about',
And you could always default, if a lang is not supplied, i.e.
$e->getRouteMatch()->getParam('lang', 'en');
I want to put a dropdown in my project which is made in zf2... I wasted all day but I only got a static dropdown, not dynamic. Can anyone help me with this problem??
UserForm.php
$this->add(array(
'name' => 'group_name',
'type' => 'select',
'attributes' => array(
'id'=>'group_name',
'class'=>'large',
'options' => array('1=>php','2'=>'java'),
),
'options' => array(
'label' => '',
),
));
Thanks in advance for your valuabe answer.
Try this:
$this->add(array(
'name' => 'group_name',
'type' => 'select',
'attributes' => array(
'id'=>'group_name',
'class'=>'large',
),
'options' => array(
'label' => '',
'value_options' => array(
'1' => 'php',
'2' => 'java'
),
),
));
This is what i did:
In my constructor for my form
$this->add(array(
'type' => 'Zend\Form\Element\Select',
'name' => 'color',
'options' => array(
'empty_option' => 'Select a Color',
'value_options' => self::getColors(),
'label' => 'Color',
),
));
In the form class yet, i created this method:
public static function getColors() {
// access database here
//example return
return array(
'blue' => 'Blue',
'red' => 'Red',
);
}
In my view script:
<div class="form_element">
<?php $element = $form->get('color'); ?>
<label>
<?php echo $element->getOption('label'); ?>
</label>
<?php echo $this->formSelect($element); ?>
</div>
Think about it from a abstract level.
You have one Form
The Form needs Data from the outside
So ultimately your Form has a Dependency. Since we've learned from the official docs, there's two types of Dependency-Injection aka DI. Setter-Injection and Constructor-Injection. Personally(!) i use one or the other in those cases:
Constructor-Injection if the dependency is an absolute requirement for the functionality to work
Setter-Injection if the dependencies are more or less optional to extend already working stuff
In the case of your Form, it is a required dependency (because without it there is no populated Select-Element) hence i'll be giving you an example for Constructor-Injection.
Some action of your controller:
$sl = $this->getServiceLocator();
$dbA = $sl->get('Zend\Db\Adapter\Adapter');
$form = new SomeForm($dbA);
That's all for the form. The population now happens inside your Form. This is only an example and may need some fine-tuning, but you'll get the idea:
class SomeForm extends \Zend\Form
{
public function __construct(\Zend\Db\Adapter\Adapter $dbA)
{
parent::__construct('my-form-name');
// Create all the form elements and stuff
// Get Population data
$popData = array();
$result = $dbA->query('SELECT id, title FROM Categories', $dbA::QUERY_MODE_EXECUTE)->toArray();
foreach ($result as $cat) {
$popData[$cat['id'] = $cat['title'];
}
$selectElement = $this->getElement('select-element-name');
$selectElement->setValueOptions($popData);
}
}
Important: I HAVE NO CLUE ABOUT Zend\Db the above code is only for how i think it would work going by the docs! This is the part that would need some optimization probably. But all in all you'll get the idea of how it's done.
In your controller you can do something like below;
On my first example assuming that you have a Group Table. Then we're going to fetchAll the data in group table;
We need the id and name to be display in select options;
public function indexAction()
{
$groupTable = new GroupTable();
$groupList = $groupTable->fetchAll();
$groups = array();
foreach ($groupList as $list) {
$groups[$list->getId()] = $list->getName();
}
$form = new UserForm();
$form->get('group_name')->setAttributes(array(
'options' => $groups,
));
}
OR
in this example the grouplist is hardcoded;
public function indexAction()
{
$groupList = array('1' => 'PHP', '2' => 'JAVA', '3' => 'C#');
$groups = array();
foreach ($groupList as $id => $list) {
$groups[$id] = $list;
}
$form = new UserForm();
$form->get('group_name')->setAttributes(array(
'options' => $groups,
));
}
Then in your view script;
<?php
$form = $this->form;
echo $this->formRow($form->get('group_name'));
?>
Or you can right a controller helper, you may check this link http://www.resourcemode.com/me/?p=327
Just came across the same problem and had to take a look into zf2 source.
Here's a more OOP solution:
Inside the form constructor:
$this->add(array(
'name' => 'customer',
'type' => 'Zend\Form\Element\Select',
'attributes' => array(
'options' => array(
0 => 'Kunde',
)
),
'options' => array(
'label' => 'Kunde'
)));
inside the controller:
$view->form = new SearchForm();
$customers = $view->form->get('customer')->getValueOptions();
$customers[] = 'Kunde1';
$customers[] = 'Kunde2';
$customers[] = 'Kunde3';
$customers[] = 'Kunde4';
$view->form->get('customer')->setValueOptions($customers);