How do I read the url parameters from a ZendFramework Controller - zend-framework

I have a ZendFramework controller whose view forms a framework similar to this:
http://foo.com/#/controler/someaction/state/city/address/
The action looks like this:
public function someactionAction()
{
$this->view->someaction = App_Model_WebService_Menu::getInstance()->getRows(array(
'address' => '1600 Pennsylvania Ave',
'returnRecordsLimit' => 1,
));
}
Is there a way where I can access state, city and address as parameters?

From Zend_Controller_Request documentation
$state = $this->getRequest()->getParam('state');
$city = $this->getRequest()->getParam('city');
$address = $this->getRequest()->getParam('address');

Ignoring the URL fragment part which I assume is reliant on some JavaScript configuration, that looks like it would be part of a custom route, ie
:controller/:action/:state/:city/:address
You will have to look into the route definition to discover the actual parameter names, after which you simply use (from your controller)
$state = $this->_getParam('state-param-name');

Related

how do you get a variable from a post address in zendframework 1

I am still new to Zend Framework and confused about a few concepts.
I have built a POST form and attached a unique Id to the URL at the end of the form. I now want to collect that Id when the form is submitted but I am unclear how to do that
I will show you want I have done:
Below is the function that renders the form from my controller page to the view. You will note that I have fed into the parameter, for the form, a return Action address with the ID
$action = "{$this->view->baseUrl()}/sample-manager/process-price/{$sampleId}";
$this->view->Form = $model= $this->_model->createForm($action);
The function to receive the post is below. However, I want to collect the Id that should have come back with the post return values, but I have no idea where to find it or how to attach it.
public function processPriceAction()
{
$this->requirePost();
if($this->_model->processTieredPriceForm($this->view->form, $this->getRequest()->getPost()))
{
$this->_helper->FlashMessenger('Changes saved');
return $this->_redirect("/product-ecommerce/{$this->_model->getProduct()->id}");
}
else
{
return $this->render('index');
}
}
In summary, when a post is returned, does the return address come with the post in Zend Framework?
Could you not supply the id into the construction of the form and assign it to a hidden element? For example, in your controller:
$action = "{$this->view->baseUrl()}/sample-manager/process-price";
$this->view->Form = $model= $this->_model->createForm($action, $sampleId);
In your form model (not provided so best guess here):
$sampleId = new Zend_Form_Element_Hidden('sampleId');
$sampleId->setValue($sampleId);
$form->addElement($sampleId);
Then once the form is posted, you should be able to get the sample id in your controller in the standard way:
$sampleId = $this->getParam('sampleId');
The answer depends a bit on how your routing is setup. If you're using the default setup, after the action name the default route allows for key/value pairs of additional data. So, you might have more luck with a URL like this:
{$this->view->baseUrl()}/sample-manager/process-price/id/{$sampleId}
That'll put your sampleId in a named parameter called 'id', which you can access in your controller action with $this->_getParam('id').

zend framework this->url get different url on the same page but different url

in application\modules\admin\layouts\scripts\layout.phtml
<?php echo $this->url(array('action'=>'logout','controller'=>'user','module'=>'admin'),null,true);?>
when I visited zfmul/public/admin-cate/ , It return
/zfmul/public/admin-cate/logout
but when I visited zfmul/public/admin/categories, It return
/zfmul/public/admin/user/logout
and the two url is render to the same module, same controller, same action, I wonder why it retrun different result?
I didi some configs in application.ini,
resources.router.routes.admincategories.route = "admin-cate/:action/:id"
resources.router.routes.admincategories.defaults.module = "admin"
resources.router.routes.admincategories.defaults.controller = "categories"
resources.router.routes.admincategories.defaults.action = "index"
resources.router.routes.admincategories.reqs.action = "save|edit|index|new"
resources.router.routes.admincategories.defaults.id = "1"
resources.router.routes.admincategories.reqs.id = "\d+"
When you use $this->url, you're in fact using function url from library/Zend/View/Helper/Url.php, whose 1st line is:
$router = Zend_Controller_Front::getInstance()->getRouter();
Since you declared a custom admincategories route, you now have 2 to access those particular module/controller/actions:
Default - accessible via zfmul/public/admin/categories;
Custom - accessible via zfmul/public/admin-cate/.
Depending on the URL you use to access, the $router variable value will change accordingly and so will the result of the $this->url call as you're experiencing.
Here are a few references to questions on SO that might help you work around that behaviour:
Zend Framework: How to disable default routing?;
Zend framework: Removing default routes.

Zend_Controller_Router_Route_Regex allow '?' in pattern

Imagine situation, when the url should looks like
/catalog/sectionIdent?page=1
where page param is optional.
Of course, custom route should be defined. Consider the following code:
$route = new Zend_Controller_Router_Route_Regex(
'catalog/([-a-z]+)(?:\?page=([0-9]*))?',
array('controller'=>'catalog','action'=>'list','page'=>''),
array(1=>'section',2=>'page'),
'catalog/%s?page=%d'
);
$router->addRoute('catalog-section-page',$route);
But this route won't be triggered with '?' symbol in url.
Without '?' (for example, by adding escaped '!' symbol to pattern) everything works as it should.
Is there any way to achieve '?' presence in custom defined regex route? Maybe I'm doing something wrong in pattern?
P.S.: Don't offer to use '/' instead of '?', question is exactly about pattern restrictions in Zend_Controller_Router_Route_Regex implementation.
The ZF routing classes operate on the REQUEST_URI with the query string stripped off, so you may have a hard time get this working in the way you are expecting. However, I believe GET parameters are put into the request object by default, so you shouldn't need to cater for them in your routes. I'd suggest changing your route to remove the query string parts:
$route = new Zend_Controller_Router_Route_Regex(
'catalog/([-a-z]+)',
array('controller'=>'catalog','action'=>'list'),
array(1=>'section'),
'catalog/%s'
);
$router->addRoute('catalog-section-page',$route);
You should still be able to access the params in your controller as if they had been populated by the routes:
public function listAction()
{
echo $this->_getParam('page');
}
and you can use the same method to set a default:
public function listAction()
{
$page = $this->_getParam('page', 1); // defaults to 1 if no page in URL
}
You just may need to sanitise them there (make sure they are numeric).
Edit:
Example of URL helper with this route:
echo $this->url(array('section' => 'foo', 'page' => 2), 'catalog-section-page')

Setting routes in application.ini in Zend Framework

I'm a Zend Framework newbie, and I'm trying to work out how to add another route to my application.ini file.
I currently have my routes set up as follows:
resources.router.routes.artists.route = /artists/:stub
resources.router.routes.artists.defaults.controller = artists
resources.router.routes.artists.defaults.action = display
...so that /artists/joe-bloggs uses the "display" action of the "artists" controller to dipslay the profile the artist in question - that works fine.
What I want to do now is to set up another route so that /artists/joe-bloggs/random-gallery-name goes to the "galleries" action of the "artists" controller.
I tried adding an additional block to the application.ini file (beneath the block above) like so:
resources.router.routes.artists.route = /artists/:stub/:gallery
resources.router.routes.artists.defaults.controller = artists
resources.router.routes.artists.defaults.action = galleries
...but when I do that the page at /artists/joe-bloggs no longer works (Zend tries to route it to the "joe-bloggs" controller).
How do I set up the routes in application.ini so that I can change the action of the "artists" controller depending on whether "/:gallery" exists?
I realise I'm probably making a really stupid mistake, so please point out my stupidity and set me on the right path (no pun intended).
Try reversing the order of the routes. ZF matches routes in the opposite order they are added (so that the default route is the last to be matched)
If that doesn't work, you'll probably have to investigate regex routes with optional components.
Your second block needs to have a different route name, rename the 'artists' word to something similar to this for your new block:
resources.router.routes.artists-gal.route = /artists/:stub/:gallery
resources.router.routes.artists-gal.defaults.controller = artists
resources.router.routes.artists-gal.defaults.action = galleries
I usually setup my routes in application/Bootstrap.php (or wherever your Bootstrap.php file is)
add a method like the one below:
protected function _initRoutes()
{
$ctrl = Zend_Controller_Front::getInstance();
$router = $ctrl->getRouter();
$router->addRoute(
'artist_detail',
new Zend_Controller_Router_Route('artists/:stub',
array('controller' => 'artists',
'action' => 'display'))
);
$router->addRoute(
'artist_detail_gallery',
new Zend_Controller_Router_Route('artists/:stub/:gallery',
array('controller' => 'artists',
'action' => 'gallery'))
);
}
As far as checking weather an specific artist has a gallery, in the case of my example, i would have a galleryAction method in the ArtistsController
do a check if a gallery exists for the 'stub' request paramater, if it doesnt throw a 404:
throw new Zend_Controller_Action_Exception("Object does not exist", 404);
or redirect them to some other page:
return $this->_helper->redirector('index', 'index'); //redirect to index action of index controller
Hope this helps.

How to change the separation character of Zend Url?

I use Zend URL view helper for building my urls. Everythings works exactly as I'd like to, except one thing: The character used for replacing spaces in the url is a plus (+). I'd like it to be a 'min' (-). How can I change this?
Example:
Now: /nl/nieuws/bericht/3/title/nieuwe**+affiches
Wish: /nl/nieuws/bericht/3/title/nieuwe-**affiches
Thanks in advcance!
This isn't in the documentation anywhere, but it appears that the Zend URL view helper can take a parameter in it's $urlOptions array called chainNameSeparator. No guarantee that's what you're looking for, but trying playing with that and see if it changes anything.
This is likely happening because, by default, Zend_View_Helper_Url will urlencode() what you send it, which would translate spaces into +. My suggestion to you would be to create a new view helper for the type of URL in your code that needs the special inflection.
Something like:
class Default_View_Helper_SpecialUrl extends Zend_View_Helper_Abstract
{
public function specialUrl(array $opts = array(), $name = null, $reset = false, $encode = true)
{
if (!empty($opts['whatever'])) {
$opts['whatever'] = str_replace(' ', '-', $opts['whatever']);
}
$router = Zend_Controller_Front::getInstance()->getRouter();
return $router->assemble($opts, $name, $reset, $encode);
}
}
This way the spaces are changed for whatever necessary route parameters before URL encoding happens by the router.