i have a database containing 3 tables, countries, cities and datacenters. country is the parent of city and city is the parent of datacenter. in the cities i have added a search dropdown of countries and its working fine. I have added cites search dropdown in datacenters and its also working fine but now i want countries search dropdown in datacenters, how to do it.
here is my datacenters/admin.php code for view
<?php
/* @var $this DataCentersController */
/* @var $model DataCenters */
$this->breadcrumbs=array(
'Data Centers'=>array('index'),
'Manage',
);
$this->menu=array(
array('label'=>'List DataCenters', 'url'=>array('index')),
array('label'=>'Create DataCenters', 'url'=>array('create')),
);
Yii::app()->clientScript->registerScript(‘search’, "
$(’.search-button’).click(function(){
$('.search-form').toggle();
return false;
});
$(’.search-form form’).submit(function(){
$.fn.yiiGridView.update('data-centers-grid', {
data: $(this).serialize()
});
return false;
});
");
?>
<h1>Data Centers</h1>
<?php $iHasFullAccess = $model->hasFullAccess(); if($iHasFullAccess) { ?> <a href="?r=datacenters/create" title="addnewdatacenter">Add New</a> <?php } ?>
<?php $this->widget(‘zii.widgets.grid.CGridView’, array(
'id'=>'data-centers-grid',
'dataProvider'=>$model->search(),
'filter'=>$model,
'columns'=>array(
'id',
'city.cityname'=>array('name'=>'cityid', 'value'=>'$data->city->cityname', 'filter'=>CHtml::listData(Cities::model()->findAll(array('order'=>'cityname')), 'id', 'cityname')),
'city.country.countryname'=>array('name'=>'city.country.id', 'value'=>'$data->city->countryid', 'filter'=>CHtml::listData(Countries::model()->findAll(array('order'=>'countryname')), 'id', 'countryname')),
'datacentername',
'datacentercode',
'lastupdatedon',
//array('name'=>'lastupdatedby', 'value'=>'$data->lastupdatedby0->fullname'),
'createdon',
array(
'class'=>'CButtonColumn',
'template'=> ($iHasFullAccess == 1 ? '{view}{update}' : '{view}') ,
),
),
)); ?>
model code for datacenters
==============================
<?php
/**
-
This is the model class for table "tbldatacenters".
-
The followings are the available columns in table ‘tbldatacenters’:
-
@property integer $id
-
@property string $datacentername
-
@property string $datacentercode
-
@property string $lastupdatedon
-
@property integer $lastupdatedby
-
@property string $createdon
-
The followings are the available model relations:
-
@property Tblusers $lastupdatedby0
-
@property Tblservers[] $tblservers
*/
class DataCenters extends CActiveRecord
{
/**
* Returns the static model of the specified AR class.
* @param string $className active record class name.
* @return DataCenters the static model class
*/
public static function model($className=__CLASS__)
{
return parent::model($className);
}
/**
* @return string the associated database table name
*/
public function tableName()
{
return 'tbldatacenters';
}
/**
* @return array validation rules for model attributes.
*/
public function rules()
{
// NOTE: you should only define rules for those attributes that
// will receive user inputs.
return array(
array('lastupdatedby, cityid', 'numerical', 'integerOnly'=>true),
array('datacentername, datacentercode', 'length', 'max'=>100),
array('lastupdatedon, createdon', 'safe'),
// The following rule is used by search().
// Please remove those attributes that should not be searched.
array('id, datacentername, cityid, datacentercode, lastupdatedon, lastupdatedby, createdon', 'safe', 'on'=>'search'),
);
}
/**
* @return array relational rules.
*/
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(
'lastupdatedby0' => array(self::BELONGS_TO, 'Users', 'lastupdatedby'),
'city' => array(self::BELONGS_TO, 'Cities', 'cityid'),
'servers' => array(self::HAS_MANY, 'Servers', 'datacenterid'),
);
}
/**
* @return array customized attribute labels (name=>label)
*/
public function attributeLabels()
{
return array(
'id' => 'ID',
'cityid'=>'City',
'datacentername' => 'Name',
'datacentercode' => 'Code',
'lastupdatedon' => 'Last Updated On',
'lastupdatedby' => 'Last Updated By',
'createdon' => 'Created On',
);
}
/**
* Retrieves a list of models based on the current search/filter conditions.
* @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
*/
public function search()
{
// Warning: Please modify the following code to remove attributes that
// should not be searched.
$criteria=new CDbCriteria;
$criteria->compare('id',$this->id);
$criteria->compare('cityid',$this->cityid);
$criteria->compare('datacentername',$this->datacentername,true);
$criteria->compare('datacentercode',$this->datacentercode,true);
$criteria->compare('lastupdatedon',$this->lastupdatedon,true);
$criteria->compare('lastupdatedby',$this->lastupdatedby);
$criteria->compare('createdon',$this->createdon,true);
return new CActiveDataProvider($this, array(
'criteria'=>$criteria,
));
}
public function hasFullAccess()
{
$objUsers = new Users();
return($objUsers->hasFullAccess());
}
public function checkDuplicateRecord($sDataCenterName, $iDataCenterId = 0)
{
$iIsDuplicate = 0;
$sSearch = "";
if($iDataCenterId > 0) $sSearch = " AND id <> '$iDataCenterId'";
if(Yii::app()->session['userid'])
{
$criteria=new CDbCriteria;
$criteria->select='id';
$criteria->condition = "datacentername='". $sDataCenterName . "'";
if($sSearch != "")
{
$criteria->condition = 'id <> '. $iDataCenterId . " AND datacentername='". $sDataCenterName . "'";
}
$sCities = DataCenters::model()->findAll($criteria);
if(count($sCities) > 0) return(1);
else return(0);
}
}
public function getCities()
{
if(Yii::app()->session['userid'])
{
$sQuery = "SELECT C.countryname countryname, C.countrycode countrycode, C2.id id, C2.cityname cityname, C2.citycode citycode FROM tblcountries AS C INNER JOIN tblcities AS C2 ON C2.countryid = C.id WHERE C2.citystatus = '1'";
$connection = Yii::app()->db;
$command = $connection->createCommand($sQuery);
$dataReader = $command->query();
$data = $dataReader->readAll();
$aCountries = array();
foreach($data as $row) $aCountries[$row['id']] = $row['countryname'] . ' => ' . $row['cityname'];
return($aCountries);
}
}
}
controller code for datacenters
================================
<?php
class DataCentersController extends Controller
{
/**
* @var string the default layout for the views. Defaults to '//layouts/column2', meaning
* using two-column layout. See 'protected/views/layouts/column2.php'.
*/
public $layout='//layouts/column1';
/**
* @return array action filters
*/
public function filters()
{
return array(
'accessControl', // perform access control for CRUD operations
'postOnly + delete', // we only allow deletion via POST request
);
}
/**
* Specifies the access control rules.
* This method is used by the 'accessControl' filter.
* @return array access control rules
*/
public function accessRules()
{
return array(
array('allow', // allow all users to perform 'index' and 'view' actions
'actions'=>array('index','view'),
'users'=>array('*'),
),
array('allow', // allow authenticated user to perform 'create' and 'update' actions
'actions'=>array('create','update'),
'users'=>array('*'),
),
array('allow', // allow admin user to perform 'admin' and 'delete' actions
'actions'=>array('admin','delete'),
'users'=>array('*'),
),
array('deny', // deny all users
'users'=>array('*'),
),
);
}
/**
* Displays a particular model.
* @param integer $id the ID of the model to be displayed
*/
public function actionView($id)
{
$this->render('view',array(
'model'=>$this->loadModel($id),
));
}
/**
* Creates a new model.
* If creation is successful, the browser will be redirected to the 'view' page.
*/
public function actionCreate()
{
$model = new DataCenters;
if(isset($_POST['DataCenters']))
{
foreach($_POST['DataCenters'] as $row=>$val)
{
if($row == 'datacentername')
{
$iIsDuplicate = $model->checkDuplicateRecord($val, 0);
if($iIsDuplicate) $this->redirect(array('create', 'error'=>-1));
}
$newPostedValues[$row] = $val;
}
$model->attributes = $newPostedValues;
if($model->save())
$this->redirect(array('view','id'=>$model->id, 'error'=>0));
}
$this->render('create',array(
'model'=>$model,
));
}
/**
* Updates a particular model.
* If update is successful, the browser will be redirected to the 'view' page.
* @param integer $id the ID of the model to be updated
*/
public function actionUpdate($id)
{
$model=$this->loadModel($id);
// Uncomment the following line if AJAX validation is needed
// $this->performAjaxValidation($model);
$newPostedValues = array();
if(isset($_POST['DataCenters']))
{
foreach($_POST['DataCenters'] as $row=>$val)
{
if($row == 'datacentername')
{
$iIsDuplicate = $model->checkDuplicateRecord($val, $_GET['id']);
if($iIsDuplicate) $this->redirect(array('update', 'id'=>$_GET['id'],'error'=>-1));
}
$newPostedValues[$row] = $val;
}
$model->attributes = $newPostedValues;
if($model->save())
$this->redirect(array('view','id'=>$model->id, 'error'=>1));
}
$this->render('update',array(
'model'=>$model,
));
}
/**
* Deletes a particular model.
* If deletion is successful, the browser will be redirected to the 'admin' page.
* @param integer $id the ID of the model to be deleted
*/
public function actionDelete($id)
{
$this->loadModel($id)->delete();
// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
if(!isset($_GET['ajax']))
$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
}
/**
* Lists all models.
*/
public function actionIndex()
{
$dataProvider=new CActiveDataProvider('DataCenters');
$this->render('index',array(
'dataProvider'=>$dataProvider,
));
}
/**
* Manages all models.
*/
public function actionAdmin()
{
$model=new DataCenters('search');
$model->unsetAttributes(); // clear any default values
if(isset($_GET['DataCenters']))
$model->attributes=$_GET['DataCenters'];
$this->render('admin',array(
'model'=>$model,
));
}
/**
* Returns the data model based on the primary key given in the GET variable.
* If the data model is not found, an HTTP exception will be raised.
* @param integer the ID of the model to be loaded
*/
public function loadModel($id)
{
$model=DataCenters::model()->findByPk($id);
if($model===null)
throw new CHttpException(404,'The requested page does not exist.');
return $model;
}
/**
* Performs the AJAX validation.
* @param CModel the model to be validated
*/
protected function performAjaxValidation($model)
{
if(isset($_POST['ajax']) && $_POST['ajax']==='data-centers-form')
{
echo CActiveForm::validate($model);
Yii::app()->end();
}
}
}