简体   繁体   中英

How can I do something like 'categoryname/seoname' in yii2?

I'm doing a project with Yii2. And I'm trying to do so with UrlManager. Like this;

'<CategoryID:\w+>/<SEO:\w+>'=>'soru/goster',

But Yii2 is showing "404 Not found". How do i?

You can use variables in url rules in config;

'<category>/<seo>'=>'soru/goster'

Then in your controller (I changed the name as I you didn't post your controller.;

public function actionGoster($seo) //you can also access $category
{
  if (isset($seo))
  { 
  //do your lookup 
  }
}

Access the url like this;

http://yourDomain/index.php/CATEGORY/SEO/

I do this to look up items in the database which allows for SEO friendly urls;

'plants/<name>'=>'catalog/viewSingle'

Controller;

public function actionViewSingle($name)
{
   if (isset($name)) 
   {
      $model = Plant::model()->findByAttributes(array('url_name'=>$name));

      if ($model)
      { //do stuff }
      else
      {
      //do matches and find similar plants that has these characters...
      $this->render('error_matches', array('matches'=>$matches));
      }
   }
   else
   { 
      //404
   }

Edit:

To avoid all URLs going to this make sure you include default rules;

'<controller:\w+>'=>'<controller>/',
'<controller:\w+>/<action:\w+>'=>'<controller>/<action>',

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM