php - Is it posible to create a urlManager Rule which preloads an object based on ID? -
working yii 2.0.4, i'm trying use urlmanager rule preload object based on given id in url.
config/web.php
'components' => [ 'urlmanager' => [ [ 'pattern' => 'view/<id:\d+>', 'route' => 'site/view', 'defaults' => ['client' => client::findone($id)], ], [ 'pattern' => 'update/<id:\d+>', 'route' => 'site/update', 'defaults' => ['client' => client::findone($id)], ], ] ]
if works, not necessary manually find , object each time, crud actions:
class sitecontroller extends controller { public function actionview() { // using $client urlmanager rule // instead of using $client = client::findone($id); return $this->render('view', ['client' => $client]); } public function actionupdate() { // using $client urlmanager rule // instead of using $client = client::findone($id); if ($client->load(yii::$app->request->post()) && $client->save()) { return $this->redirect(['view', 'id' => $client->id]); } else { return $this->render('edit', ['client' => $client]); } } }
note: above snippets not working. they're idea of want get
is possible? there way achieve this?
if closer: nothing changes. still call client::findone($id);
doing in unexpected , inappropriate place, , if @ comment default
parameter says:
array default parameters (name => value) rule provides. when rule used parse incoming request, values declared in property injected $_get.
default parameter needed when want specify $_get
parameters rule. e.g.
[ 'pattern' => '/', 'route' => 'article/view', 'defaults' => ['id' => 1], ]
here specify article id = 1 default article when open main page of site e.g. http://example.com/ handled http://example.com/article/view?id=1
i can suggest add property clientmodel
in controller , in beforeaction()
method check if update or view action set
$this->clientmodel = client::findone($id);
and in action:
return $this->render('view', ['client' => $this->clientmodel]);
Comments
Post a Comment