Get all parameters after action in Zend? - zend-framework

When I call a router like below in Zend:
coupon/index/search/cat/1/page/1/x/111/y/222
And inside the controller when I get $this->_params, I get an array:
array(
'module' => 'coupon',
'controller' => 'index',
'action' => 'search',
'cat' => '1',
'page' => '1',
'x' => '111',
'y' => '222'
)
But I want to get only:
array(
'cat' => '1',
'page' => '1',
'x' => '111',
'y' => '222'
)
Could you please tell me a way to get the all the params just after the action?

IMHO this is more elegant and includes changes in action, controller and method keys.
$request = $this->getRequest();
$diffArray = array(
$request->getActionKey(),
$request->getControllerKey(),
$request->getModuleKey()
);
$params = array_diff_key(
$request->getUserParams(),
array_flip($diffArray)
);

As far as I know, you will always get the controller, action and module in the params list as it is part of the default. You could do something like this to remove the three from the array you get:
$url_params = $this->getRequest()->getUserParams();
if(isset($url_params['controller']))
unset($url_params['controller']);
if(isset($url_params['action']))
unset($url_params['action']);
if (isset($url_params['module']))
unset($url_params['module']);
Alternatively as you don't want to be doing that every time you need the list, create a helper to do it for you, something like this:
class Helper_Myparams extends Zend_Controller_Action_Helper_Abstract
{
public $params;
public function __construct()
{
$request = Zend_Controller_Front::getInstance()->getRequest();
$this->params = $request->getParams();
}
public function myparams()
{
if(isset($this->params['controller']))
unset($this->params['controller']);
if(isset($this->params['action']))
unset($this->params['action']);
if (isset($this->params['module']))
unset($this->params['module']);
return $this->params;
}
public function direct()
{
return $this->myparams();
}
}
And you can simply call this from your controller to get the list:
$this->_helper->myparams();
So for example using the url:
http://127.0.0.1/testing/urls/cat/1/page/1/x/111/y/222
And the code:
echo "<pre>";
print_r($this->_helper->myparams());
echo "</pre>";
I get the following array printed:
Array
(
[cat] => 1
[page] => 1
[x] => 111
[y] => 222
)

How about this?
In controller:
$params = $this->getRequest()->getParams();
unset($params['module'];
unset($params['controller'];
unset($params['action'];
Pretty clunky; might need some isset() checks to avoid warnings; could jam this segment into its own method or helper. But it would do the job, right?

Related

Module Forms - Store Value of addField to a Variable

I have something like in my custom module:
$fieldset->addField('orderinfo', 'link', array(
'label' => Mage::helper('web')->__('Order Info'),
'style' => "",
'href' => Mage::helper('adminhtml')->getUrl('adminhtml/sales_order/view', array('order_id' => $order_id)),
'value' => 'Magento Blog',
'after_element_html' => '',
));
And as you can see from the code, I am trying to link that field to the Order Tab in the back-end. I'm having trouble getting the ID though. I'm planning to just save the Order ID in the database, and then using the addField I could have the correct url.
But how can I save an addField value to a variable?
I want to store the value in "$order_id".
Is it possible?
I am not sure in which context you are using this fieldset but if it is used for example for creating or editing object you can try something like that:
In controller:
public function editAction()
{
$id = $this->getRequest()->getParam('id');
$model = Mage::getModel('module/model')->load($id);
Mage::register('model_name', $model);
}
and then in the block:
protected function _prepareForm()
{
$model = Mage::registry('model_name');
// add fieldset to form
$fieldset->addField('orderinfo', 'link', array(
'label' => Mage::helper('web')->__('Order Info'),
'style' => "",
'href' => Mage::helper('adminhtml')->getUrl('adminhtml/sales_order/view', array('order_id' => $model->getOrderId())),
'value' => 'Magento Blog',
'after_element_html' => '',
));
//rest of the elements
}
Answering my own post again. (src: https://magento.stackexchange.com/questions/682/module-forms-store-value-of-addfield-to-a-variable)

Zend Controller Router : Define variables to point to a different action in one controller

I'm just new with Zend and I have a little trouble with Zend Routers. I've searched about it, but nothing found...
I want to be able to define a router for each defined variable at uri level to point to a different action in one controller.
I'm working with lang and modules so I defined at bootstrap application the next initRoutes function:
protected function _initRoutes()
{
$front = Zend_Controller_Front::getInstance();
$router = $front->getRouter();
$defaultRoute = new Zend_Controller_Router_Route(
':lang/:module/:controller/:action',
array(
'lang' => 'es',
'module' => 'default',
'controller' => 'index',
'action' => 'index'
),
array(
'lang' => '^(en|es)$',
'module' => '^(default|admin)$'
)
);
$router->addRoute('defaultRoute', $defaultRoute);
return $router;
}
I want to be able to access forum sections and forum topics by their defined action.
Something like :
mydomain/forum -> forum/index
mydomain/forum/section -> forum/sectionAction
mydomain/forum/section/topic -> forum/topicAction
and also with the lang and module defined at uri level like :
mydomain/lang/module/forum
mydomain/lang/module/forum/section
mydomain/lang/module/forum/section/topic
So I have this :
class ForumController extends Zend_Controller_Action
{
public function indexAction()
{
}
public function sectionAction()
{
}
public function topicAction()
{
}
Then I created the next routes inside the Default_Bootstrap :
$forumRoutes = new Zend_Controller_Router_Route(
':lang/:module/forum',
array(
'lang' => 'es',
'module' => 'default',
'controller' => 'forum',
'action' => 'index'
)
);
$sectionRoutes = new Zend_Controller_Router_Route(
':lang/:module/forum/:section',
array(
'lang' => 'es',
'module' => 'default',
'controller' => 'forum',
'action' => 'section',
'section' => ''
)
);
$topic = new Zend_Controller_Router_Route(
':lang/:module/forum/:section/:topic',
array(
'lang' => 'es',
'module' => 'default',
'controller' => 'forum',
'action' => 'topic',
'section' => '',
'topic' => ''
)
);
$router->addRoute('forumTopics', $topic);
$router->addRoute('forumSections', $section);
$router->addRoute('forum', $forumRoutes);
Now, this only works if I define the lang and module at uri level, but doesn't work if I defined like => mydomain/forum/section | section/topic. This also brings me another problem with my navigation->menu. If I define "forum" as a static variable at router definition, when I hover over at any label defined at navigatoin.xml, the uri level have the same value for every one of them.
I've tried to make a chain like this:
$forumRoutes = new Zend_Controller_Router_Route(
':lang/:module/forum',
array(
'lang' => 'es',
'module' => 'default',
'controller' => 'forum',
'action' => 'index'
)
);
$section = new Zend_Controller_Router_Route(
':section',
array(
'action' => 'section',
'section' => ''
)
)
$topic = new Zend_Controller_Router_Route(
':topic',
array(
'action' => 'topic',
'topic' => ''
)
)
$chainedRoute = new Zend_Controller_Router_Route_Chain();
$chainedRoute->chain($topic)
->chain($section)
->chain($forumRoutes);
$router->addRoute($chainedRoute);
But this doesn't work as I expected.
Any help would be appreciated, thanks.
You are new to Zend. You said it. So here are some explanations:
Ideally the URL on Zend application is:
example.com/controller/action/param-name/:param-value
So in which case, if there is an action called Edit under UsersController, it will be:
example.com/users/edit
if action is add, it will be :
example.com/users/add
when you specify first parameter as a variable, it will collide with controller requests. Example: if you say controller is User but first parameter accepts a value and puts it in emplyees then a request as example.com/employees and example.com/user will both point towards employees controller even if the usercontroller exists! which again is a theory!
What you might want to do is, leave the routes to only accept dynamic values rather routing! You do not want users to route your application but, route user to different sections of the application.
About language then you need to use Zend_Locale which will check for HTML language that is
<html lang="nl"> or <html lang = "en">
Hope things are clear! :)
Here's a quick example which should help you work with routes like that in ZF.
If you are using a default project structure like the one you get when starting a new project using Zend Tool go into the Application folder.
In your Bootstrap.php set up something like this:
protected function _initRouteBind() {
// get the front controller and get the router
$front = Zend_Controller_Front::getInstance();
$router = $front->getRouter();
// add each custom route like this giving them a descriptive name
$router->addRoute(
'addTheDescriptiveRouteNameHere',
new Zend_Controller_Router_Route(
'/:controller/:id/:action/:somevar',
array(
'module' => 'default',
'controller' => ':controller',
'action' => ':action',
'id' => ':id',
'somevar' => ':somevar'
)
)
);
}
My example above is just to illustrate how you would use a route where the controller, the action and a couple of parameters are set in the url.
The controller and action should be resolved without any additional work however to get the 'id' or 'somevar' value you can do this in your controller:
public function yourAction()
{
// How you get the parameters to pass in to a function
$id = $this->getRequest()->getParam('id');
$somevar = $this->getRequest()->getParam('somevar');
// Using the parameters
$dataYouWant = $this->yourAmazingMethod($id);
$somethingElse = $this->yourOtherAmazingMethod($somevar);
// Assign results to the view
$this->view->data = $dataYouWant;
$this->view->something = $somethingElse;
}
So while you will want to make sure your methods handle the parameters being passed in with care (after all it is user supplied info) this is the principle behind making use of the route parameter binding. You can of course do things like '/site' as the route and have it direct to a CMS module or controller, then another for '/site/:id' where 'id' is a page identifier.
Also just to say a nice alternative to:
$id = $this->getRequest()->getParam('id');
$somevar = $this->getRequest()->getParam('somevar');
which wasn't that nice itself anyway since it was assuming a parameter was going to be passed, using shorthand conditional statement in conjunction with action helpers is:
$id = ($this->_hasParam('id')) ? $this->_getParam('id') : null;
$somevar = ($this->_hasParam('somevar')) ? $this->_getParam('somevar') : null;
If you are not familiar with this, the
($this->_hasParam('id'))
is the conditional test which if true assigns the value of whatever is on the left of the ':' and which if false assigns the value of whatever is on the right of the ':'.
So if true the value assigned would be
$this->_getParam('id')
and null if false.
Does that help? :-D

How to create Zend_Navigation on some part of the site - ZF 1.11.11

I am very new with zend and I want to build a navigational menu on some part of my site - let's say I have 20 pages but i just want to create a menu of 5 items and visible only for 4 pages. This might be a silly question but Is there a way to make it on my controller and not in bootstrap? I just really cant find an example for this :(
Perhaps a view helper? This way it can be called from the view script on the 4 pages that you want it to be shown on:
<?php
class Default_View_Helper_ShortNav extends Zend_View_Helper_Abstract
{
/**
* Generate a Zend_Navigation object
* #return Zend_Navigation
*/
public function shortNav()
{
//psudo code
$pages = array();
$model = new Default_Model_Pages();
$rows = $model->fetchAll();
foreach($rows as $page)
{
$pages[] = array(
'label' => $page->title,
'module' => 'default',
'controller' => 'index',
'action' => 'page',
'params' => array('page' => $page->slug),
'containerClass' => 'page',
);
}
$nav =new Zend_Navigation();
$nav->addPage(
array(
'label' => 'Pages',
'route' => 'index', //route name
'params' => array(), //route parameters
'pages' => $pages
)
);
return $nav;
}
}
In the view script:
<?php
$nav = $this->shortNav();
echo $this->navigation($nav);
In the view helper you will need to change the fetch all to select ONLY the pages you want, and in the view script you will need to wrap the echo in an if statement to show only on the pages you want it to show.
Hope this is useful.

Hashing passwords and AuthComponent

I'm trying to login in my CakePHP 2.0 application but I always get the login error.
In the official documentation and the tutorial I've read how to hash the passwords, but I still get the login error, here is how I did it:
// Users Model
public function beforeSave ($options = array ()) {
$this->data['User']['password'] = AuthComponent::password($this->data['User']['password']);
return true;
}
// Users Controller
public $components = array ('Acl', 'Session',
'Auth' => array (
'authenticate' => array (
// login e logout sono di default i seguenti controller e views
// 'loginRedirect' => array ('controller' => 'users', 'action' => 'login'),
// 'logoutRedirect' => array ('controller' => 'users', 'action' => 'logout'),
'Form' => array (
'fields' => array (
// il valore default
'username' => 'email'
),
'scope' => array (
'User.active' => 1
)
)
),
'authError' => 'Login error message I get'
));
public function login () {
if ($this->request->is('post')) { // if the request came from post data and not via http (useful for security)
// the password is hashed in User Model in beforeSave method as read on documentation
// debug ($this->data);
if ($this->Auth->login()) {
$id = $this->Auth->user('id');
return $this->redirect(array('controller'=>'users', 'action'=>$id, $this->Auth->user('username')));
} else {
$this->Session->setFlash('Login error message', 'default', array(), 'auth');
}
}
}
In the view I have this:
// the view login.ctp
echo $this->Form->text('User.email', array('id'=>'email', 'value'=>'your#email.com'));
echo $this->Form->password('User.password', array('id'=>'password', 'value'=>'password'));
If I try to debug the data I get this:
// in the controller
debug($this->data);
// in the view
Array
(
[User] => Array
(
[email] => the#email.com
[password] => thepass // not hashed
)
)
I can't login because I get always the Login error message. How can I fix it?
Vitto,
(1) Which error message is displayed?
(2) Just for the record, be sure sessionFlash is printed at layout!
echo $this->Layout->sessionFlash();
(3) How did you set your Auth component? For example, in my AppController I've set this way:
public $components = array(
'Session',
'Cookie',
'Acl',
/**
* Default is authorize option is ActionsAuthorize.
* In this case, system uses AclComponent to check for permissions on an action level.
* learn more: http://book.cakephp.org/2.0/en/core-libraries/components/authentication.html#authorization
*/
'Auth'=> array(
'authorize' => array(
'Actions' => array('actionPath' => 'controllers')
),
'authenticate' => array(
'Form' => array(
'fields' => array('username' => 'email', 'password' => 'password')
)
)
)
);
(4) Finally, I believe (must be sure) there is no need to manually hash password to perform login. At least, after correct configuration, this code works for me:
if ($this->request->is('post')) {
if ($this->Auth->login()) {
// recirect stuffs

Zend Form Text value stays null

I've created a simple upload-form and got a little problem when submitting the data.
The file is uploaded correctly, but my little description field stays null.
Here's my form:
class Upload_Form_Uploadvideo extends Zend_Form{
public function init()
{
$this->setName('video')
->setAction('interface/videoupload')
->setMethod('post');
#id
$id = new Zend_Form_Element_Hidden('id');
$id->addFilter('Int');
#Textfield "Videofile"
$video = new Zend_Form_Element_File('videofile', array(
'label' => 'Videofile')
);
$video->setDestination(APPLICATION_PATH.'/upload/video/toConvert/');
#Textfield "Videofile"
$desc = new Zend_Form_Element_Text('videodescription', array(
'label' => 'Description')
);
$desc->setAttrib('value','The description is not optional!');
$desc->setAttrib('size','25');
#Submit
$submit = new Zend_Form_Element_Submit('submit', array('label' => 'Upload Video'));
$submit->setAttrib('id', 'submitbutton');
#bringing everything together
$this->addElements(array($id,$video,$desc,$submit));
}
}
the controller, giving it to the view:
public function videouploadAction()
{
#in production this code goes to the index()
if(!$this->getRequest()->isPost()){
return $this->_forward('index');
}
$form = $this->getForm();
$this->view->via_getpost = var_dump($this->_request->getPost());
$this->view->via_getvalues= var_dump($form->getValues());
}
Now, I var_dump $this->_request->getPost() and $form->getValues().
The output is the following:
array[$this->_request->getPost()]
'id' => string '0' (length=1)
'MAX_FILE_SIZE' => string '134217728' (length=9)
'videodescription' => string 'This is a test-video' (length=20)
'submit' => string 'Upload Video' (length=12)
array [$form->getValues()]
'id' => int 0
'videofile' => string 'swipeall.avi' (length=12)
'videodescription' => null
In addition, I set the "value"-attrib, without any effect. I intended to write something in the box, when the user loads the site.
I'm new to Zend, so I guess I'm just overseeing something stupid, though I can't find it.
Update:
I really had to get the $_POST-Data via
$formdata = $this->getRequest()->getPost();
use
$desc->setValue('The description is not optional!');
instead of
$desc->setAttrib('value','The description is not optional!');