Tuesday, 11 February 2014

How to set the country, state relationship in Yii

My Country table:

My state table:

Here i need to refer the country from state using the country_id relationship

So first i need to generate a Relationship in my State Model like below

public function relations()

return array(
'country'=>array(self::BELONGS_TO, 'Country', 'country_id'),


Country here is the country model
country_id is the reference key in state table to refer the country table

Ok so in CGrid view use the below format



And if we need filtering for countries in state admin?

Just use the compare setup like below

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

$criteria=new CDbCriteria;

$criteria->with = array('country');
$criteria->compare('country.id',$this->country_id, true);

return new CActiveDataProvider($this, array(

And in your Cgridview area have it like below

'filter'=>CHtml::listData(Country::model()->findall(),'id','name' ),

No comments:

Post a comment