Search code examples
yiicgridview

Add column from another table to CGridView


Hi I'm using yii crud and trying to add a column from another table to Admin view

This is my admin view CGridView widget code.

<?php $this->widget('zii.widgets.grid.CGridView', array(
    'id'=>'package-days-grid',
    'dataProvider'=>$model->search(),
    'filter'=>$model,
    'columns'=>array(
        'package_days_id',
        'package_days_description',    
                array(
                    'header' => 'Package Title',
                    'name' => 'package_days_package_id',
                    'value' => function ($data){
                        echo $data->packagePackagedays->package_title;
                    }
                ),
        array(
            'class'=>'CButtonColumn',
        ),
    ),
)); ?>

And this is relations function in 'PackageDays' model.

public function relations()
    {
        // NOTE: you may need to adjust the relation name and the related
        // class name for the relations automatically generated below.
        return array(
                    'packagePackagedays' => array(self::BELONGS_TO, 'Packages', 'package_days_package_id'),
        );
    }

This is search function in 'PackageDays' model.

public function search()
    {
        // @todo Please modify the following code to remove attributes that should not be searched.

        $criteria=new CDbCriteria;
                $criteria->with = "packagePackagedays";
        $criteria->compare('package_days_id',$this->package_days_id);
        $criteria->compare('packagePackagedays.package_title',$this->package_days_package_id);
        $criteria->compare('package_days_description',$this->package_days_description,true);

        return new CActiveDataProvider($this, array(
            'criteria'=>$criteria,
        ));
    }

I added the column successfully but I can't search values of newly added column.

It would be great if someone can looking to it


Solution

  • Make sure you added package_days_package_id as a public property of your Packages model. Otherwise $this->package_days_package_id doesn't exist

    class Packages extends CActiveRecord{

    public $package_days_package_id;

    ...

    Also Make sure you added package_days_package_id in your "safe" validation rule for the "search" scenario (also in your Packages model). Without this, the value you type in the text box won't be assigned to your $this->package_days_package_id

    public function rules(){

    return array(

    ...

    // The following rule is used by search()

    array('bunch, of, stuff, ..., package_days_package_id', 'safe', 'on'=>'search'),

    If you also want the grid column to be sortable on click, you'll also have to create a custom CSort and provide it to your CActiveDataProvider