Question

i have a problem to filter by a related object in my grid.

I have the follow two models:

Model Foo:
    id
    name
    create_date

Model Boss:
    id
    foo_id (FK to Foo Model)
    create_date

Now, i list all my Boss objects in this way:

<?php $this->widget('zii.widgets.grid.CGridView', array(
    'id'=>'boss-grid',
    'dataProvider'=>$model->search(),
    'filter'=>$model,
    'columns'=>array(
        'ID',
        array(
            'header'=>'Foo', //the header cell text.
            'name' => 'foo.name', //the attribute name of the data model.
            'value' => '$data->foo->Name',
            'filter' => CHtml::activeTextField(Foo::model(),'Name'),
        ),
        'CREATE_DATE',

    ),
)); ?>

The problem is that FK is numeric but the representation (label) is a text. So i need to know how to convert this object to filter in the grid.

Was it helpful?

Solution

you have to include the foreign key in search criteria in the model:

first :

   array(
        'header'=>'Foo',
        'name' => 'foo.name',
        'value' => '$data->foo->Name',
        'filter' => CHtml::textField('foreign',''), // change like this
    ),

then in model, search method:

$criteria->with('NameOfRlation');

$f = Yii::app()->request->getParam('foreign' , null);

if(!empty($f))
   $criteria->compare('t.Field' , $f , true);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top