I have two objects with a one to many relation (for example, a FAQ with categories and questions (a question can only have one category)).
I know how to create CRUD (with GII) for categories and questions, but what I would like to do is to have a link on each category (on the categories Gridview) to display only related questions (and not allow questions gridview if no category is specified).
I managed to create the link on the categories gridview :
Because you call ‘questions/admin’ action with a parameter named ‘category_id’ …
// in QuestionsController:
public function actionAdmin()
{
$model = new Questions('search');
$model->unsetAttributes();
if (isset($_GET['category_id']))
{
$model->category_id = (int)$_GET['category_id'];
}
if (isset($_GET['Questions']))
{
$model->attributes = $_GET['Questions'];
}
$this->render('admin', array('model' => $model));
}
Note that this is how the original admin action works:
[list=1]
[*]$model is an instance of Questions that holds the searching parameters for the grid.
[*]It is initially reset to empty, meaning that the grid initially displays all the questions.
[*]When the user input some searching parameters, then they are passed to the controller with $_GET[‘Questions’]. We set them to $model to filter the searching result.
[/list]
And now, we pass the category_id to the action with $_GET[‘category_id’].
You can write the action using the action parameter binding …
public function actionAdmin($category_id = null)
{
...
if ($category_id !== null)
{
$model->category_id = (int)$category_id;
}
...
}