K
K
Ken Jee2016-08-30 21:06:59
Yii
Ken Jee, 2016-08-30 21:06:59

How to accept a number from a URL as a parameter to a controller action in Yii2?

Suppose there is a URL /site/view/1 where 1 is the post ID. How in Yii2 to make sure that 1 is passed to the actionView action of the SiteController controller as a parameter?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Andrew, 2016-08-30
@Machez

In the config, in the urlManager, add the rule:

'urlManager' => [
  'enablePrettyUrl' => true,
  'showScriptName' => false,
  'enableStrictParsing' => false,
  'rules' => [
    'site/view/<id:\d+>', // Если частный случай
    '<controller:\w+>/view/<id:\d+>', // Самое частое использование, для экшина view каждого контроллера
    '<controller:\w+>/<action:\w+>/<id:\d+>', // Если нужно преобразование для всех контроллеров и экшинов
  ]
]

id will automatically be added to the $_GET array, and you can get it from the action:
public function actionView($id)
{
    ....
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question