CRUD filter for related object

Hello,

I’m new to Yii and I have a simple problem :

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 :

‘buttons’=>array(

'records'=>array


    (


        'label'=>'Manage questions',


        'imageUrl'=>Yii::app()->request->baseUrl.'/images/questions.png',


        'url'=>'Yii::app()->createUrl("questions/admin",array('category_id"=>$data->id))',


    ),

),

But i don’t have any idea on how to handle this parameter to display only questions of the chosen catetgory on my questions CRUD.

Can you please help me ?

Thank you very much,

Frederic

Hi Frederic,

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;

    }

    ...

}



http://www.yiiframework.com/doc/guide/1.1/en/basics.controller#action

Hi,

just wanted to say thank you for this it helped solve a problem I have been struggling with.