Access id of paginator in controller - php

Hello guys I am new to Zendframework2.
I have the following line in view\partial\paginator.phtml
<a href="<?php echo $this->url($this->route);?>?page=<?php echo $page; ?>?id=<?php echo $this->id?>">
In browser it looks like http://new_project.localhost/districts?page=2?id=4
new_project is the name of my project, districts is route of controller and
in id=4, 4 is id which I want to access in controller.
I tried:
$_GET['id'];
$this->params()->fromRoute('id'); //also
$this->params()->fromQuery('id'); //also
But non of these works.
How I will access this id in controller?

I solve it, just by putting condition like below:
if (isset($_GET['id']))
{
// perform operation here.
}

Don't build your A element tag href yourself but use the framework like you should.
Url view helper:
// $this->url($routeName, $routeParams, $options, $reuseMatchedParams = false)
$this->url('my/route', ['id' => $object->getId()], ['query' => ['page' => $page]])
Controller plugin:
$this->params('id') // will take ID either from routeParameters or queryParameters.
$this->params()->fromRoute('id') // will take the id from the routeParameters
$this->params()->fromQuery('page') // will take the page from the route query
So when you've got a route with a routeParameter id but your query also has the id within it's query its best practice to keep on using the $this->params()->fromRoute('id') or $this->params()->fromQuery('id') so you always know where the value comes from instead of using $this->params('id').
As with the params plugin you can also define default values on the second argument, like: $this->params()->fromQuery('page', 1). So page will always be 1 if the user did not provide one. The default of the second argument is null. Hope this helps and makes you stop using $_GET['bla']

I think your url should look like this:
http://new_project.localhost/districts?page=2&id=4
^
not ?
Because of the mistake you made the parser probably doesn't parse the id in your url correctly meaning you cannot access it like you tried.
It would be better to use the url view helper for rendering the query parameters in the url then you wouldn't make such a mistake. You can check this post on StackOverflow for reference on how to add query parameters to a url using the url view helper. In your case it would look something like this:
<?php
$href = $this->url($this->route, [], ['query' => [
'page' => $page,
'id' => $id,
]]);
?>
<a href="<?php echo $href ?>">
Now you get the correct url:
http://new_project.localhost/districts?page=2&id=4
Meaning the parser also manages to parse the id correctly.
You should be able to access it now like you tried with:
$this->params()->fromQuery('id'); //returns your id from the url

Related

How to get a segment URL cakephp 3

Hi I got trouble in retrieve URL segment CAkephp3 in view. I want to get the ID from current URL.
Lets say my URL is http://localhost/admin/financial_agreements/edit/50
and I want redirect to http://localhost/admin/financial_agreements/do_print/50
simply :
var urlPrint = "<?=$this->Url->build(['controller' => 'financial_agreements', 'action' => 'do_print', 'I NEED ID FROM CURRENT'], true)?>";
I try debug
<?=debug($this->Url->build()); die();?>
But its produce : admin/financial_agreements/edit/50
whats called in 50 ? I need that 50 inside my "url->build" urlPrint
sorry for bad english.
Anyhelp will appreciate.
thanks.
You can use the Request object to get request data (including url parameters) within views.
Try this in your view:
$this->request->getParam('pass') //CakePHP 3.4+
$this->request->params['pass'] // CakePHP 3.3
That will return an array of all non-named parameters that were passed after the action's name in the URL. Example: /mycontroller/myaction/param1/param2. So in this example, $this->request->getParam('pass') will produce an array like: [0 => 'param1', 1 => 'param2'].
Bonus answer: you can also 'name' parameters in the URL, like: /mycontroller/myaction/some_name:some_value. To retrieve this kind of named parameters, you would do the same trick but using: $this->request->getParam('named') (Use the argument 'named' instead of 'pass').
More info:
https://book.cakephp.org/3.0/en/controllers/request-response.html
https://book.cakephp.org/3.0/en/development/routing.html#passed-arguments
Assuming that your edit function follows standard practices, you'll have something like this:
public function edit($id) {
$financialAgreement = $this->FinancialAgreements->get($id);
...
$this->set(compact('financialAgreement'));
}
Then in edit.ctp, you can get the id of the current record very simply as $financialAgreement->id, so your URL will be generated with
$this->Url->build(['controller' => 'financial_agreements', 'action' => 'do_print', $financialAgreement->id], true)

CakePHP redirect form post with querystring

I'm a Cake newbie, and I'm looking to post a querystring value into a controller method, but always reload the view with the querystring intact. Currently I have the below snippet.
public function something()
{
if($this->request->query !=null )
$date = $this->request->query["date"];
}
<?php echo $this->Form->create('setup',array('action' => 'something?date=2013','id'=>'setup-form','role'=>'form') ); ?>
Any advice on why something() doesn't redirect to something?date=2013 on its default render? Do I need to do some special routing?
In CakePHP 2, you can include query string parameters in $url parameters like so:
array('action' => 'something', '?' => array('date' => '2013'))
CakePHP will build the query string and append it to the matched URL in your routing configuration.
(Note: You may need to pass FormHelper::create an entire URL, generated from HtmlHelper::url, instead of using the "shorthand" technique.)

Going from, SELECT * FROM users WHERE url = "pretty url", to displaying 1 row from database with Lithium Framework

Hi I am new to php and mysql and jumped right into using the Lithium framework.....I know, bad idea.
BUT basically my question is, how do I go from;
$users = \app\models\Users::findByUrl($this->request->query['url']);
return array(
'users' => $users,
);
in my UsersController to actually echo'ing 1 specific row of data in my users/index.php.html page, according to the query string in my url?
My desired structure is localhost/users/"url", and "url" is a value in my mysql db labeled "url" in my Users table. e.g. localhost/users/Bob. "Bob" is "url" value.
My users/index.php.html page is using foreach ($users as $user) to echo the information like this;
<?=$user->firstname ?>
Snag and Confusion:
When I was using;
$users = \app\models\Users::find('all');
return array(
'users' => $users,
);
in my UsersController, the users/index.php.html page retrieved all the users in my database.
The content displays correctly, BUT I need the data from just the clicked-on user, so this is when I started using; $users = \app\models\Users::findByUrl($this->request->query['url']);
When linking to the users page this is how I do it;
<?php if( $user->avatar ):?>
<a href="/users/<?=$user->url?>">
<img class="img-responsive" src="/img/users/<?=$user->avatar?>" />
</a>
<?php else: ?>
Not sure if I need to add conditions to my controller, add something to my router, change my htaccess, or do something with params.... Pleease help, any direction would be greatly appreciated.
Finders return everything by default. If you want a single object, do:
Users::findFirstByUrl($this->request->query['url'])
...which is short-hand for:
Users::first(['conditions' => ['url' => $this->request->query['url']]]) or
Users::find('first', ['conditions' => ['url' => $this->request->query['url']]]).

How to createe a URL string based on a named route and keep parameters

I need to create urls for category switching, switching category should reset page to 1st and change cat name but keep rest of url params.
Example of url:
http://example.com/cat/fruits/page/3/q/testquery/s/date/t/kcal/mine/26/maxe/844/minb/9/mint/4/maxt/93/minw/7/minbl/6/maxbl/96
Urls can contain many different params but category name and page should be always first, category without page should work too and show 1st page.
Currently I have defined two routes and I'm using Zend's url helper with named route but it resets params and as end resuls I have /cat/cat_name/page/1 url.
$category_url = $view->url(array('category'=>$list_item['url'],'page'=>1),'category',FALSE)
resources.router.routes.category_main.route = "/cat/:category/*"
resources.router.routes.category_main.defaults.module = "ilewazy"
resources.router.routes.category_main.defaults.controller = "index"
resources.router.routes.category_main.defaults.action = "results"
resources.router.routes.category_main.defaults.category =
resources.router.routes.category_main.defaults.page = 1
resources.router.routes.category.route = "/cat/:category/page/:page/*"
resources.router.routes.category.defaults.module = "ilewazy"
resources.router.routes.category.defaults.controller = "index"
resources.router.routes.category.defaults.action = "results"
resources.router.routes.category.defaults.category =
resources.router.routes.category.defaults.page = 1
Do I need to create custom method for assembling url in this case?
Things I would try:
Add module, controller and action params in $urlOptions (it's the
first array you pass to the view helper)
instead of 'category' route name try null and see what that does for
you.
Try removing this line
"resources.router.routes.category.defaults.category = "
Please specify what version are of zf are you using.
Solution is very simple, one just have to pass all current request params to url helper
(and optionaly overwrite/add some of them, page and category in my case), last variable is set to FALSE to prevent route resetting.
$view->url(
array_merge(
$params,
array('category' => $list_item['url'],
'page' => 1)
),
'category_main',
FALSE
);

change CakePhp1.3 paginator destination url?

I'm new to cakephp...and I have a page with a url this:
http://localhost/books/filteredByAuthor/John-Doe
so the controller is ´books´, the action is ´filteredByAuthor´ and ´John-Doe´ is a parameter.. but the url looks ugly so i've added a Route like this:
Router::connect('/author/:name', array( 'controller' => 'books','action' => 'filteredByAuthor'), array('pass'=>array('name'),'name'=>".*"));
and now my link is:
http://localhost/author/John-Doe
the problem is that the view has a paginator and when i change the page (by clicking on the next or prev button).. the paginator won't consider my routing... and will change the url to this
http://localhost/books/filteredByAuthor/John-Doe/page:2
the code on my view is just:
<?php echo $this->Paginator->prev('<< ' . __('previous', true), array(), null, array('class'=>'disabled'));?>
the documentation doesn't say anything about avoiding this and i've spent hours reading the paginators source code and api.. and in the end i just want my links to be something like this: (with the sort and direction included on the url)
http://localhost/author/John-Doe/1/name/asc
Is it possible to do that and how?
hate to answer my own question... but this might save some time to another developper =) (is all about getting good karma)
i found out that you can pass an "options" array to the paginator, and inside that array you can specify the url (an array of: controller, action and parameters) that the paginator will use to create the links.. so you have to write all the possible routes in the routes.php file. Basically there are 3 possibilities:
when the "page" is not defined
For example:
http://localhost/author/John-Doe
the paginator will assume that the it's the first page. The corresponding route would be:
Router::connect('/author/:name', array( 'controller' => 'books','action' => 'filteredByAuthor'),array('pass'=>array('name'),'name'=>'[a-zA-Z\-]+'));
when the "page" is defined
For example:
http://localhost/author/John-Doe/3 (page 3)
The route would be:
Router::connect('/author/:name/:page', array( 'controller' => 'books','action' => 'filteredByAuthor'),array('pass'=>array('name','page'),'name'=>'[a-zA-Z\-]+','page'=>'[0-9]+'));
finally when the page and the sort is defined on the url (by clicking on the sort links created by the paginator).
For example:
http://localhost/author/John-Doe/3/title/desc (John Doe's books ordered desc by title)
The route is:
Router::connect('/author/:name/:page/:sort/:direction', array( 'controller' => 'books','action' => 'filteredByAuthor'),
array('pass'=>array('name','page','sort','direction'),
'name'=>"[a-zA-Z\-]+",
'page'=>'[0-9]*',
'sort'=>'[a-zA-Z\.]+',
'direction'=>'[a-z]+',
));
on the view you have to unset the url created by the paginator, cause you'll specify your own url array on the controller:
Controller:
function filteredByAuthor($name = null,$page = null , $sort = null , $direction = null){
$option_url = array('controller'=>'books','action'=>'filteredByAuthor','name'=>$name);
if($sort){
$this->passedArgs['sort'] = $sort;
$options_url['sort'] = $sort;
}
if($direction){
$this->passedArgs['direction'] = $direction;
$options_url['direction'] = $direction;
}
Send the variable $options_url to the view using set()... so in the view you'll need to do this:
View:
unset($this->Paginator->options['url']);
echo $this->Paginator->prev(__('« Précédente', true), array('url'=>$options_url), null, array('class'=>'disabled'));
echo $this->Paginator->numbers(array('separator'=>'','url'=>$options_url));
echo $this->Paginator->next(__('Suivante »', true), array('url'=>$options_url), null, array('class' => 'disabled'));
Now, on the sort links you'll need to unset the variables 'sort' and 'direction'. We already used them to create the links on the paginator, but if we dont delete them, then the sort() function will use them... and we wont be able to sort =)
$options_sort = $options_url;
unset($options_sort['direction']);
unset($options_sort['sort']);
echo $this->Paginator->sort('Produit <span> </span>', 'title',array('escape'=>false,'url'=>$options_sort));
hope this helps =)

Categories