Skip to content
Advertisement

Yii2: Controller action parameters with a dash?

If I have a URL like https://example.com/controller/action?customer-id=7414 how do I get customer-id in my action parameters? Since a dash is not allowed in variables names I cannot do the following!

public function actionContact($customer-id) {   //syntax error! :)
    // ...
}

Documentation is usually excellent but on this exact point it’s just silent. How do I solve this?

Advertisement

Answer

When yiiwebController calls action it only binds parameters which names match exactly. Dash cannot be used in variable name in PHP so there is no way it will ever match like that.

If you really want to have param in URL as customer-id=XXX then easiest thing you can do, is skip param in action method definition and get it during action itself:

public function actionContact() {
    $customerId = $this->request->get('customer-id');
    // or
    $customerId = Yii::$app->request->get('customer-id');

    // ...
}
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement