1

I have a rule in urlManager

    'rules' => [
        'products/<whatever:[-_0-9a-zA-Z]+>' => 'products/show',
    ],

and I have controller Products with actionShow()

public function actionShow($name)
{
    var_dump($name);
    echo 'actionShow is work';
}

But a have an Error: Bad Request (#400) Missing required parameters: name

How to transfer a product's $name to the controller, or how it can be obtained from the URL in the controller?

2
  • How do you call your controller? Commented Feb 6, 2018 at 16:18
  • added an answer for you see if that helps you out Commented Feb 6, 2018 at 20:18

2 Answers 2

1

The CORRECT and COMPLETE answer is that you have to use the rule like below.

'rules' => [
        'products/<name:[\-\w]+>' => 'products/show',
],

then in your products controller you don't need to pass $name in the parameter anymore that is why we defined in the rule and you have to use the Yii::$app->request->queryParams['name']; or Yii::$app->request->get('name') to get the name of the product, your action will look like below

public function actionShow()
{
   echo Yii::$app->request->get('name');
}

after doing all the settings above open brower and type

http://yourdomain.com/products/some-product

and it will show you

some-product

When you have to create a link to that page lets say in menu you have under products all products listed and you have to create a link to detail page for all of them i.e actionShow you would do it like below.

<?=Html::a($model->name, 
    Yii::$app->urlManager->createUrl([
        'products/show',
        'name'=>$model->slug
    ])
  );
?>
Sign up to request clarification or add additional context in comments.

Comments

1

I guess you should specify the name of your variable in the rule. You are calling it whatever, change it to name:

'rules' => [
        'products/<name:[-_0-9a-zA-Z]+>' => 'products/show',
    ],

2 Comments

Nearly. But in this case I would be obliged to write in the URL: products/namesamsung450z
nopes you are the wrong @yiier, although gmc is right but he hasnt given the complete answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.