yiiyii2

A list and a detail view


Could you, please, tell me how to do this:

https:///categories/ - a list of categories.

https:///categories/?id=1 - details about each category.

I've done:

class CategoriesController extends Controller 
{
    public function actionIndex($id=null)
    {
        if ($id) 
        {
           $category = Category::findOne($id);
           return $this->render("detail", compact("category"));
        } else
        {
           $categories = Category::find()->all();
            return $this->render("index", compact("categories"));        
        }
    }
}

The problem is that if I'm not mistaken in Yii world there exists a tradition to call a view after an action id. But here I have two views.

Could you tell how should it be done? If this code is ugly, how to do it better?


Solution

  • When using pretty URL's you need to make ID as part of path, so your second URL should be https://example.com/categories/1. Then you would map it into different controller actions. Please see documentation