Yii2 render url with query parameters - php

I need to add some parameter to url by using render in a Yii2 controller action. For example add cat=all parameter to following url:
localhost/sell/frontend/web/index.php?r=product/index
and this is my index action :
return $this->render('index', [
'product' => $product,
]);

You can create URL like below:
yii\helpers\Url::toRoute(['product/index', 'cat' => 'all']);
You can redirect in controller like below:
$this->redirect(yii\helpers\Url::toRoute(['product/index', 'cat' => 'all']));
Then render your view.

To generate url using the Yii2 yii\helpers\Url to() or toRoute() method:
$url = yii\helpers\Url::to(['product/index', 'cat' => 'all']);
or:
$url = yii\helpers\Url::toRoute(['product/index', 'cat' => 'all']);
And you can then redirect in controller:
return $this->redirect($url);
Also note that the controller redirect() method is merely a shortcut to yii\web\Response::redirect(), which in turn passes it's first argument to: yii\helpers\Url::to(), so you can feed your route array in directly like so:
return $this->redirect(['product/index', 'cat' => 'all']);
Please Note: the other answer by #ali-masudianpour may have been correct in earliest versions of Yii2, but in later versions of Yii2 (including latest - 2.0.15 at time of writing), the Url helper methods only accept unidimensional arrays, which are in turn passed into yii\web\UrlManager methods like createUrl.

You can make redirect route into your controller like this:
$this->redirect(yii\helpers\Url::toRoute(['product/index', 'cat' => 'all']));

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)

Link with parameters

I am new in prestashop (version 1.6) and I have some problem about a link.
I want to add another login link with extra parameters so that I can hide registration part from connexion page.
So in nav.tpl, I added extra parameters :
$link->getPageLink('my-account', true, NULL, ['params' => 'myTest'])|escape:'html':'UTF-8'}
When I click on that link, It completely disappear and in AuthController (initContent) Tools:getValue('params') returns null. I don't know how to figure it out. Thanks
You should work with Smarty.
The parameter you should pass the file AuthController in function initContent.
Edit this:
$this->context->smarty->assign(array(
'inOrderProcess' => true,
'PS_GUEST_CHECKOUT_ENABLED' => Configuration::get('PS_GUEST_CHECKOUT_ENABLED'),
'PS_REGISTRATION_PROCESS_TYPE' => Configuration::get('PS_REGISTRATION_PROCESS_TYPE'),
'sl_country' => (int)$this->id_country,
'countries' => $countries
));
Alternative method
In the same function you can do another change
Of prestashop you can use the GET and POST using the function:
$param = (int) (Tools::getValue ('myTest'));
The Array that you have passed to getPageLink function seems wrong, please try the following:
{$params = ['params' => 'myTest']}
$link->getPageLink('my-account', true, NULL, $params)|escape:'html':'UTF-8'}
That is because when a FrontController is protected (such as MyAccountController) the user is redirected to the login page and the query params are lost. To fix it, change /classes/controller/FrontController.php:
Tools::redirect('index.php?controller=authentication'.($this->authRedirection ? '&back='.$this->authRedirection : ''));
to:
Tools::redirect('index.php?controller=authentication'.($this->authRedirection ? '&back='.$this->authRedirection.'&'.$_SERVER['QUERY_STRING'] : ''));
That should preserve the additional query params on the login page.

Laravel 5.1 add Query strings in url

I've declared this route:
Route::get('category/{id}{query}{sortOrder}',['as'=>'sorting','uses'=>'CategoryController#searchByField'])->where(['id'=>'[0-9]+','query'=>'price|recent','sortOrder'=>'asc|desc']);
I want to get this in url: http://category/1?field=recent&order=desc
How to achieve this?
if you have other parameters in url you can use;
request()->fullUrlWithQuery(["sort"=>"desc"])
Query strings shouldn't be defined in your route as the query string isn't part of the URI.
To access the query string you should use the request object. $request->query() will return an array of all query parameters. You may also use it as such to return a single query param $request->query('key')
class MyController extends Controller
{
public function getAction(\Illuminate\Http\Request $request)
{
dd($request->query());
}
}
You route would then be as such
Route::get('/category/{id}');
Edit for comments:
To generate a URL you may still use the URL generator within Laravel, just supply an array of the query params you wish to be generated with the URL.
url('route', ['query' => 'recent', 'order' => 'desc']);
Route::get('category/{id}/{query}/{sortOrder}', [
'as' => 'sorting',
'uses' => 'CategoryController#searchByField'
])->where([
'id' => '[0-9]+',
'query' => 'price|recent',
'sortOrder' => 'asc|desc'
]);
And your url should looks like this: http://category/1/recent/asc. Also you need a proper .htaccess file in public directory. Without .htaccess file, your url should be look like http://category/?q=1/recent/asc. But I'm not sure about $_GET parameter (?q=).

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.)

CakePHP 3.0 query string parameters vs passed parameters

In CakePHP 3.0 named parameters have been removed (thank god) in favour of standard query string parameters inline with other application frameworks.
What I'm still struggling to get my head around though is that in other MVC frameworks, for example ASP.NET you would pass the parameters in the ActionResult (same as function):
Edit( int id = null ) {
// do stuff with id
}
And that method would be passed the id as a query string like: /Edit?id=1 and you'd use Routing to make it pretty like: /Edit/1.
In CakePHP however anything passed inside the function parameters like:
function edit( $id = null ) {
// do stuff with $id
}
Must be done as a passed parameter like: /Edit/1 which bypasses the query string idea and also the need for routing to improve the URL.
If I name the params in the link for that edit like:
$this->Html->link('Edit', array('action' => 'edit', 'id' => $post->id));
I then have to do:
public function edit() {
$id = $this->request->query('id');
// do stuff with $id
}
To get at the parameter id passed. Would of thought it would pick it up in the function like in ASP.NET for CakePHP 3.0 but it doesn't.
I prefer to prefix the passed values in the edit link instead of just passing them so I don't have to worry about the ordinal as much on the other end and I know what they are etc.
Has anyone played with either of these ways of passing data to their methods in CakePHP and can shed more light on the correct ways of doing things and how the changes in version 3.0 will improve things in this area...
There are a few types of request params in CakePHP 3.0. Let's review them:
The Query String: are accessed with $this->request->query(), are not passed to controller functions as arguments and in order to make a link you need to do Html->link('My link', ['my_query_param' => $value])
Passed arguments: The special type of argument is the one that is received by the controller function as an argument. They are accessed either as the argument or by inspecting $this->request->params['pass']. You Build links with passed args depending on the route, but for the default route you just add positional params to the link like Html->link('My link', ['action' => view, $id, $secondPassedArg, $thirdPassedArg])
Request Params: Passed arguments are a subtype of this one. A request param is a value that can live in the request out of the information that could be extracted from the route. Params can be converted to other types of params during their lifetime.
Consider this route:
Router::connect('/articles/:year/:month/:day', [
'controller' => 'articles', 'action' => 'archive'
]);
We have effectively created 3 request params with that route: year, month and day and they can be accessed with $this->request->year $this->request->month and $this->request->day. In order to build a link for this we do:
$this->Html->link(
'My Link',
['action' => 'archive', 'year' => $y, 'month' => $m, 'day' => $d]
);
Note that as the route specify those parameters, they are not converted as query string params. Now if we wanted to convert those to passed arguments, we connect this route instead:
Router::connect('/articles/:year/:month/:day',
['controller' => 'articles', 'action' => 'archive'],
['pass' => ['year', 'month', 'day']]
);
Our controller function will now look like:
function archive($year, $month, $day) {
...
}

Categories