O
O
Oleg Titarenko2015-02-21 12:58:20
Yii
Oleg Titarenko, 2015-02-21 12:58:20

Routing and URL Creation how to figure it out?

I can not figure out how to correctly create the page address. I read in the dock but I can not understand the logic of the work.
You need to create www.exemple.com/category_id
Where category_id = alies - where its name is stored in the database
How can I write in the controller and make it clear what needs to be put in the page alies category_id ?
Ps thanks in advance for your help

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander Makarov, 2015-02-25
@olegtytarenko2

Let's start with a little theory:
1. Inside the framework, the path is represented by an internal route: controller/action + an array of parameters.
2. The framework builds the URL and parses the URL based on the URLManager rules.
3. The rule defines the link pattern URL → internal route.
Now let's see what we have.
1. Let's say we have posts. Posts have a category_id.
2. List them PostController::actionCategory.
3. The parameter that is being passed is category_id.
Let's start with the controller:

class PostController extends Controller
{
    public function actionCategory($category_id)
    {
         $posts = Post::find()->where(['category_id' => $category_id])->all();
         return $this->render('category', ['posts' => $posts]);
    }
}

Next, we write the following rule in the config in components → urlManager → rules:
You can create a URL for this case like this:
echo Url::to(['post/category', 'category_id' => 42]);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question