如何在yii2中以url代替mysite / product / id => mysite / product / title输出?

时间:2019-01-20 11:54:56

标签: php yii2

我遇到了这样的问题,我想在我的网站上显示产品的所有ID,并在视图中显示其标题

这里是一个示例-http://本地主机/ yii-application /产品/ 1

进入ID为1的产品视图

我希望如此- http://本地主机/ yii-application / product / TestTitle

从产品的角度来看

1 个答案:

答案 0 :(得分:0)

您需要在配置文件中更改操作参数和urlmanager。通常,在查看操作中,我们将传递 id 作为参数,并使用ID获得产品信息。现在,我们正在更改而不是ID,我们通过产品的标题获得了产品信息

frontend / controllers / ProductController.php:

class ProductController extends Controller
{

     public function actionView($title)
     {
        //Based on title getting product information
        $productData = ProductModel::find ()->where(['title'=>$title])->asArray()->one();

        return $this->render('view',
          [
              'productData'=>$productData,
          ]);
     }
}

frontend / views / product / view.php:

your html code for display product view

frontend / config / main.php

在这里,我们将title作为视图acton的参数传递

'urlManager' => [
  'enablePrettyUrl' => true,
  'showScriptName' => false,
  'rules' => [
    'product/view/<title:\w+>'=>'product/view',
    -------------------------------------------
    -------------------------------------------
    '<controller:\w+>/<action:\w+>/<id:\d+>' => '<controller>/<action>',
    '<controller:\w+>/<action:\w+>/' => '<controller>/<action>',
  ]
]

希望有帮助