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) {
...
}
Related
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)
So I have a route defined in my web.php, like so....
Route::any('/items/{id}/{slug}', 'Items\ItemController#item')->name('items.item');
I am trying to make a function where I can get the string pattern for the URL, '/items/{id}/{slug}' from the route by calling it's name...
I assumed this would work.. but it doesn't (it tells me I'm missing the parameters id and slug).
// Should assign the string 'items/{id}/{slug}' to the variable.
$url_pattern = route('items.item');
I'm using Laravel 5.3.
You can access the Route's uri as follows:
$url_pattern = app('router')->getRoutes()->getByName('items.item')->uri;
var_dump($url_pattern);
// will return:
// "items/{id}/{slug}"
You can always create a faux route. When you are invoking route(), one has to assume you know the params it expects.
If you would like to get it as a string (to be used in JS for example), just pass the names of the params as the params. For example:
$url_pattern = route('items.item', ['id' => '{id}', 'slug' => '{slug}']);
// will generate:
// items/{id}/{slug}
you need to add the parameters in the router function, for example:
$url_pattern = route('items.item', ['id' => $id, 'slug' => $slug]);
https://laravel.com/docs/5.5/routing#named-routes
How can i configure a route connection to handle...
/users/{nameofuser_as_param}/{action}.json?limit_as_param=20&offset_as_param=20&order_as_param=created_at
in the routes.php file such that it calls my controller action like...
/users/{action}/{nameofuser_as_param}/{limit_as_param}/{offset_as_param}/{order_as_param}.json?
Note: Iam using Cakephp 2.X
to handle...
/users/{nameofuser_as_param}/{action}.json
That's pretty easy, and in the docs.
Assuming there is a call to parseExtensions in the route file, a route along the lines of this is required:
Router::connect(
'/users/:username/:action',
['controller' => 'users'],
[
'pass' => ['username'],
// 'username' => '[a-Z0-9]+' // optional param pattern
]
);
The pass key in the 3rd argument to Router::connect is used to specify which of the route parameters should be passed to the controller action. In this case the username will be passed.
For the rest of the requirements in the question it would make more sense for the action to simply access the get arguments. E.g.:
public function view($user)
{
$defaults = [
'limit_as_param' => 0,
'offset_as_param' => 0,
'order_as_param' => ''
];
$args = array_intersect_key($this->request->query, $defaults) + $defaults;
...
}
It is not possible, without probably significant changes or hacks, to make routes do anything with get arguments since at run time they are only passed the path to determine which is the matching route.
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']));
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.)