yii CActiveDataProvider or TbGridView do not work with pagination - php

I'm using Yii Booster TbGridView to show a DataProvider from CActiveDataProvider. It is functioning but not completely. I do not know what is going on with the pagination because when I select the other pages from the Grid, it does not return any record. It is strange because the pagination by default is 10 records, and the data is for example 33 records, the pagination creates 4 pages but I only can see the first 10 records and the others are not shown after I click on the number of the page I want to see. I only can see the first ten records.
Here's my code:
Action (Controller)
public function actionIndex() {
//Verificamos si es la primera vez que se corre la accion y asignamos fechas iniciales
if (!isset($_POST['FormGestionInformacion']['fechaDesde'])
&& !isset($_POST['FormGestionInformacion']['fechaDesde']) ){
$fechaHasta = date('Y-m-d');
$fechaDesde = date('Y-m-d',time()-(60*60*24*15));//Quince dias atras
} else {
$fechaHasta = $_POST['FormGestionInformacion']['fechaHasta'];
$fechaDesde = $_POST['FormGestionInformacion']['fechaDesde'];
}
//Verificamos si el usuario mando filtro, y armamos el WHERE a ver si esa palabra esta en alguna parte
$criteria = new CDbCriteria();
$criteria->alias = 's';
$criteria->select = 'c.fecha_creacion,
c.fecha_cierre,
s.caso_sistema_info,
s.sistema_informacion,
s.documentacion,
s.fecha_documentacion,
s.usuario,
s.tipo_documentacion,
s.tipo_protocolo';
$criteria->join = "INNER JOIN ".DB_USUARIOS.".soporte_casos c ON s.caso_sistema_info=c.caso_sistema_info";
$criteria->condition = "s.caso_sistema_info=c.caso_sistema_info and fecha_cierre>='"
.$fechaDesde." 00:00:00' and fecha_cierre<='".$fechaHasta." 23:59:59'";
$criteria->group = "s.caso_sistema_info";
$criteria->order = " s.caso_sistema_info";
$criteria->offset = 0;
if (isset($_POST['FormGestionInformacion']['filtro'])
&& $_POST['FormGestionInformacion']['filtro']!='') {
$filtro = $_POST['FormGestionInformacion']['filtro'];
$criteria->addCondition ("s.caso_sistema_info like '%$filtro%'
or s.sistema_informacion like '%$filtro%'
or s.usuario like '%$filtro%' or
s.tipo_documentacion like '%$filtro%'
or s.tipo_protocolo LIKE '%$filtro%'");
}
$dataProvider = new CActiveDataProvider('SoporteCasosDocumentacion', array(
'criteria' => $criteria,
'pagination' => array(
'pageSize' => 5,
),
)
);
$model = new FormGestionInformacion ();
$this->render('index', array(
'dataProvider' => $dataProvider,
'model'=> $model,
'fechaDesde'=>$fechaDesde,
'fechaHasta'=>$fechaHasta,
'filtro'=>$filtro,
)
);
}
Model:
class SoporteCasosDocumentacion extends CActiveRecord {
/**
* #return string the associated database table name
*/
public function tableName() {
return 'soporte_casos_documentacion';
}
/**
* #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('caso_sistema_info, sistema_informacion, usuario', 'required'),
array('fecha_documentacion, caso_sistema_info, sistema_informacion, usuario', 'length', 'max' => 45),
array('email, celular', 'length', 'max' => 50),
array('informacion_cliente_une', 'length', 'max' => 1),
array('archivo_adjunto, pro_det, sol_dad, ubi_fal, causa, ser_afe, con_aut, cor_ele', 'length', 'max' => 100),
array('tipo_documentacion, tipo_protocolo, tie_sol, tel_con, cel_con', 'length', 'max' => 10),
array('documentacion, error_oci', 'safe'),
// The following rule is used by search().
// #todo Please remove those attributes that should not be searched.
array('id_doc, fecha_documentacion, caso_sistema_info, sistema_informacion, documentacion, email, celular, informacion_cliente_une, usuario, archivo_adjunto, tipo_documentacion, tipo_protocolo, error_oci, pro_det, sol_dad, ubi_fal, causa, ser_afe, tie_sol, con_aut, cor_ele, tel_con, cel_con', '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();
}
/**
* #return array customized attribute labels (name=>label)
*/
public function attributeLabels() {
return array(
'id_doc' => 'Id Doc',
'fecha_documentacion' => 'Fecha Documentacion',
'caso_sistema_info' => 'Caso Sistema Info',
'sistema_informacion' => 'Sistema Informacion',
'documentacion' => 'Documentacion',
'email' => 'Email',
'celular' => 'Celular',
'informacion_cliente_une' => 'Informacion Cliente Une',
'usuario' => 'Usuario',
'archivo_adjunto' => 'Archivo Adjunto',
'tipo_documentacion' => 'Tipo Documentacion',
'tipo_protocolo' => 'Tipo Protocolo',
'error_oci' => 'Error Oci',
'pro_det' => 'Pro Det',
'sol_dad' => 'Sol Dad',
'ubi_fal' => 'Ubi Fal',
'causa' => 'Causa',
'ser_afe' => 'Ser Afe',
'tie_sol' => 'Tie Sol',
'con_aut' => 'Con Aut',
'cor_ele' => 'Cor Ele',
'tel_con' => 'Tel Con',
'cel_con' => 'Cel Con',
);
}
/**
* Retrieves a list of models based on the current search/filter conditions.
*
* Typical usecase:
* - Initialize the model fields with values from filter form.
* - Execute this method to get CActiveDataProvider instance which will filter
* models according to data in model fields.
* - Pass data provider to CGridView, CListView or any similar widget.
*
* #return CActiveDataProvider the data provider that can return the models
* based on the search/filter conditions.
*/
public function search() {
// #todo Please modify the following code to remove attributes that should not be searched.
$criteria = new CDbCriteria;
$criteria->compare('id_doc', $this->id_doc, true);
$criteria->compare('fecha_documentacion', $this->fecha_documentacion, true);
$criteria->compare('caso_sistema_info', $this->caso_sistema_info, true);
$criteria->compare('sistema_informacion', $this->sistema_informacion, true);
$criteria->compare('documentacion', $this->documentacion, true);
$criteria->compare('email', $this->email, true);
$criteria->compare('celular', $this->celular, true);
$criteria->compare('informacion_cliente_une', $this->informacion_cliente_une, true);
$criteria->compare('usuario', $this->usuario, true);
$criteria->compare('archivo_adjunto', $this->archivo_adjunto, true);
$criteria->compare('tipo_documentacion', $this->tipo_documentacion, true);
$criteria->compare('tipo_protocolo', $this->tipo_protocolo, true);
$criteria->compare('error_oci', $this->error_oci, true);
$criteria->compare('pro_det', $this->pro_det, true);
$criteria->compare('sol_dad', $this->sol_dad, true);
$criteria->compare('ubi_fal', $this->ubi_fal, true);
$criteria->compare('causa', $this->causa, true);
$criteria->compare('ser_afe', $this->ser_afe, true);
$criteria->compare('tie_sol', $this->tie_sol, true);
$criteria->compare('con_aut', $this->con_aut, true);
$criteria->compare('cor_ele', $this->cor_ele, true);
$criteria->compare('tel_con', $this->tel_con, true);
$criteria->compare('cel_con', $this->cel_con, true);
return new CActiveDataProvider($this, array(
'criteria' => $criteria,
));
}
/**
* #return CDbConnection the database connection used for this class
*/
public function getDbConnection() {
return Yii::app()->Usuarios;
}
/**
* Returns the static model of the specified AR class.
* Please note that you should have this exact method in all your CActiveRecord descendants!
* #param string $className active record class name.
* #return SoporteCasosDocumentacion the static model class
*/
public static function model($className = __CLASS__) {
return parent::model($className);
}
}
The Widget:
$this->widget('bootstrap.widgets.TbButton', array(
'buttonType' => 'button',
'type' => 'primary',
'label' => 'Consultar',
'size' => 'large',
'htmlOptions' => array(
'onClick' => '{ValidacionDatos()}',
'class' => 'btn'
),
));

Related

get limited numbers of data with yii2

I want to get limited numbers of data from database using Yİİ2. I fetched all the record by writing this:
$departures = ArrayHelper::map(
TourDeparture::find()->all(),
'id',
'tour_id'
);
I tried to use limit(5), so that I can get only 5 rows. But I could not. Still, I get the all the rows in the table. How can I achieve that?
Updated: Here is my tourdeparture model
class TourDeparture extends \yii\db\ActiveRecord
{
public static function tableName()
{
return 'tour_departure';
}
/**
* {#inheritdoc}
*/
public function rules()
{
return [
[['tour_id', 'start_date', 'end_date', 'price_1adult', 'price_2adult', 'price_3adult', 'price_child', 'price_baby', 'min_guests', 'max_guests', 'status', 'required_min_guest'], 'required'],
[['tour_id', 'min_guests', 'max_guests', 'status', 'required_min_guest'], 'integer'],
[['start_date', 'end_date'], 'safe'],
[['price_1adult', 'price_2adult', 'price_3adult', 'price_child', 'price_baby'], 'number'],
[['tour_id'], 'exist', 'skipOnError' => true, 'targetClass' => Tour::className(), 'targetAttribute' => ['tour_id' => 'id']],
];
}
/**
* {#inheritdoc}
*/
public function attributeLabels()
{
return [
'id' => 'ID',
'tour_id' => 'Tour ID',
'start_date' => 'Start Date',
'end_date' => 'End Date',
'price_1adult' => 'Price 1adult',
'price_2adult' => 'Price 2adult',
'price_3adult' => 'Price 3adult',
'price_child' => 'Price Child',
'price_baby' => 'Price Baby',
'min_guests' => 'Min Guests',
'max_guests' => 'Max Guests',
'status' => 'Status',
'required_min_guest' => 'Required Min Guest',
];
}
/**
* Gets query for [[Tour]].
*
* #return \yii\db\ActiveQuery
*/
public function getTour()
{
return $this->hasOne(Tour::className(), ['id' => 'tour_id']);
}
/**
* Gets query for [[TourReservations]].
*
* #return \yii\db\ActiveQuery
*/
public function getTourReservations()
{
return $this->hasMany(TourReservation::className(), ['tour_departure_id' => 'id']);
}
}
$departures = ArrayHelper::map( TourDeparture::find()->limit(5), 'id',
'tour_id' );
I wrote it like above. but ı got all the record
I'm surprised your code worked at all! You are passing the Query class into the map function. ArrayHelper::map is expecting an array and needs the query to be executed using the ->all(). ->limit(5) just adds a new term to the SQL query.
$departures = ArrayHelper::map( TourDeparture::find()->limit(5)->all(), 'id', 'tour_id' );
for retrieve the first 5 rows should be
TourDeparture::find()->orderBy("id")->limit(5)->all()
The code you shared didn't do the limit(5). Anyway, I believe it is caused by the array map,
you may try to simulate the changes as below
$q = TourDeparture::find()->select(['id', 'tour_id'])->limit(5)->asArray()->all();
\yii\helpers\VarDumper::dump($q, $depth = 10, $highlight = true);
For the above, records selected in array form, before array map.
After array map, from here you can compare the changes.
$departures = ArrayHelper::map(
$q,
'id',
'tour_id'
);
\yii\helpers\VarDumper::dump($departures, $depth = 10, $highlight = true);

Grid View Fetches all records in Yii

I am new to Yii. I have did a normal query operation by fixing a criteria in my action. My Grid view fetches particular records from the criteria query, but if I click on second page, it displays all the records again. Please help me in this. I have been stuck here so long. Thanks in advance.
My View:
<div class="form">
<?php $form=$this->beginWidget('CActiveForm', array(
'id'=>'nimsoft-alerts-form',
'enableAjaxValidation'=>false,
)); ?>
<h1>Missing Hosts List</h1>
<?php //echo $form->errorSummary($model); ?>
<div style="float:left;">
<div class="row">
<?php echo $form->labelEx($model,'host_start_date'); ?>
<?php
Yii::import('application.extensions.CJuiDateTimePicker.CJuiDateTimePicker');
$this->widget('CJuiDateTimePicker', array(
'attribute' => 'host_start_date',
'language' => '',
'model' => $model,
'options' => array(
'mode' => 'focus',
'dateFormat' => 'yy-mm-dd',
//'minDate'=>'0',
'showAnim' => 'slideDown',
),
'htmlOptions' => array(
'style'=>'height:20px;',
'value' => $model->host_start_date,
),
));
?>
<?php echo $form->error($model,'host_start_date'); ?>
</div>
</div><div style="float:left;"> </div>
<div style="float:left;">
<div class="row">
<?php echo $form->labelEx($model,'host_end_date'); ?>
<?php
Yii::import('application.extensions.CJuiDateTimePicker.CJuiDateTimePicker');
$this->widget('CJuiDateTimePicker', array(
'attribute' => 'host_end_date',
'language' => '',
'model' => $model,
'options' => array(
'mode' => 'focus',
'dateFormat' => 'yy-mm-dd',
//'minDate'=>'0',
'showAnim' => 'slideDown',
),
'htmlOptions' => array(
'style'=>'height:20px;',
'value' => $model->host_end_date,
),
));
?>
<?php echo $form->error($model,'host_end_date'); ?>
</div>
</div>
<div class="row buttons">
<?php echo CHtml::button('Search',array('submit' => array('Site/index')));?>
</div>
<?php $this->endWidget(); ?>
<?php //zii.widgets.grid.CGridView
$this->widget('zii.widgets.grid.CGridView', array(
'dataProvider'=>$dataProvider,
'enableSorting' => false,
'columns'=>array(
array( // display 'create_time' using an expression
'name'=>'alert_device',
'value'=>'$data->alert_device',
),
array( // display 'create_time' using an expression
'name'=>'alert_event_time',
'value'=>'$data->alert_event_time',
),
array( // display 'create_time' using an expression
'name'=>'alert_datetime',
'value'=>'$data->alert_datetime',
),
),
//'itemView'=>'_view',
));
?>
</div>
My Action:
public function actionIndex()
{
$model=new NimsoftAlerts;
if(isset($_POST['NimsoftAlerts']))
{
$model->attributes=$_POST['NimsoftAlerts'];
$params=array(
'host_start_date'=>$model->host_start_date,
'host_end_date'=>$model->host_end_date,
);
if($model->validate())
{
$criteria = new CDbCriteria();
$criteria->condition = "alert_datetime >= '$model->host_start_date' and alert_datetime <= '$model->host_end_date' and alert_itsm_ack_status IS NULL";
$details = NimsoftAlerts::model()->findAll($criteria);
$dataProvider=new CActiveDataProvider('NimsoftAlerts',array(
'criteria' => $criteria,
'pagination'=>array(
'params'=>$params,
),
'sort'=>array(
'params'=>$params,
'attributes'=>array('host_start_date','host_end_date'),
),
));
}
else
$dataProvider=new CActiveDataProvider('NimsoftAlerts');
}
else
$dataProvider=new CActiveDataProvider('NimsoftAlerts',array(
'pagination'=>array(
'params'=>$params,
),
'sort'=>array(
'params'=>$params,
'attributes'=>array('host_start_date','host_end_date'),
),
));
if($_REQUEST['isXLSDownload']=='1')
{
$xlsName='Missing_Host_Details_'.date('YmdHis').'.xls';
$sheetName='Missing Host Details';
$headerTxt='Host Details';
$arrTh=array(
'alert_device'=>array('label'=>'Alert Device'),
'alert_event_time'=>array('label'=>'Alert Event Time'),
'alert_datetime'=>array('label'=>'Alert Datetime'),
);
$this->generateCXLS($xlsName,$sheetName,$criteria,$model,$headerTxt,$arrTh);
}
$viewNimsoftTktSts = $model->dispNimsoftTktSts();
$this->render('index',array(
'viewNimsoftTktSts'=>$viewNimsoftTktSts,
'dataProvider'=>$dataProvider,
'model'=>$model,
));
}
My model:
<?php
/**
* This is the model class for table "mst_nimsoft_alerts".
*
* The followings are the available columns in table 'mst_nimsoft_alerts':
* #property string $alert_id
* #property string $alert_id_nimsoft
* #property string $alert_subject
* #property string $alert_message
* #property string $alert_severity
* #property string $alert_device
* #property string $alert_ip_address
* #property string $alert_status
* #property string $alert_monitor_type
* #property string $alert_instance
* #property string $alert_attribute
* #property string $alert_value
* #property string $alert_event_time
* #property string $alert_probe
* #property string $alert_datetime
* #property string $alert_itsm_ack
* #property string $alert_itsm_ack_status
* #property string $alert_itsm_ack_datetime
* #property string $alert_itsm_ticketnumber
*/
class NimsoftAlerts extends CActiveRecord
{
public $host_start_date;
public $host_end_date;
/**
* #return string the associated database table name
*/
public function tableName()
{
return 'mst_nimsoft_alerts';
}
/**
* #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('host_start_date,host_end_date', 'required'),
array('host_end_date','compare','compareAttribute'=>'host_start_date','operator'=>'>', 'allowEmpty'=>false,'message'=>'{attribute} must be greater than "{compareValue}".'),
array('alert_id_nimsoft, alert_ip_address, alert_probe', 'length', 'max'=>220),
array('alert_device, alert_status, alert_monitor_type, alert_instance, alert_attribute, alert_value, alert_event_time', 'length', 'max'=>250),
array('alert_itsm_ack', 'length', 'max'=>1),
array('alert_itsm_ack_status', 'length', 'max'=>4),
array('alert_itsm_ticketnumber', 'length', 'max'=>255),
//array('alert_subject, alert_message, alert_severity, alert_datetime, alert_itsm_ack_datetime,host_start_date,host_end_date', 'safe'),
// The following rule is used by search().
// #todo Please remove those attributes that should not be searched.
array('alert_id, alert_id_nimsoft, alert_subject, alert_message, alert_severity, alert_device, alert_ip_address, alert_status, alert_monitor_type, alert_instance, alert_attribute, alert_value, alert_event_time, alert_probe, alert_datetime, alert_itsm_ack, alert_itsm_ack_status, alert_itsm_ack_datetime, alert_itsm_ticketnumber,host_start_date,host_end_date', '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(
);
}
/**
* #return array customized attribute labels (name=>label)
*/
public function attributeLabels()
{
return array(
'alert_id' => 'Alert',
'alert_id_nimsoft' => 'Alert Id Nimsoft',
'alert_subject' => 'Alert Subject',
'alert_message' => 'Alert Message',
'alert_severity' => 'Alert Severity',
'alert_device' => 'Alert Device',
'alert_ip_address' => 'Alert Ip Address',
'alert_status' => 'Alert Status',
'alert_monitor_type' => 'Alert Monitor Type',
'alert_instance' => 'Alert Instance',
'alert_attribute' => 'Alert Attribute',
'alert_value' => 'Alert Value',
'alert_event_time' => 'Alert Event Time',
'alert_probe' => 'Alert Probe',
'alert_datetime' => 'Alert Datetime',
'alert_itsm_ack' => 'Alert Itsm Ack',
'alert_itsm_ack_status' => 'Alert Itsm Ack Status',
'alert_itsm_ack_datetime' => 'Alert Itsm Ack Datetime',
'alert_itsm_ticketnumber' => 'Alert Itsm Ticketnumber',
'host_start_date'=>'Start date',
'host_end_date'=>'End Date',
);
}
/**
* Retrieves a list of models based on the current search/filter conditions.
*
* Typical usecase:
* - Initialize the model fields with values from filter form.
* - Execute this method to get CActiveDataProvider instance which will filter
* models according to data in model fields.
* - Pass data provider to CGridView, CListView or any similar widget.
*
* #return CActiveDataProvider the data provider that can return the models
* based on the search/filter conditions.
*/
public function dispNimsoftTktSts()
{
$criteria = new CDbCriteria;
$criteria->select='alert_datetime,alert_itsm_ack_status,alert_itsm_ticketnumber,alert_itsm_ack_datetime';
$criteria->limit = 3;
$criteria->order='alert_datetime DESC';
$dispLimit=$this->findAll($criteria);
return $dispLimit;
}
public function searchForAutoTickets()
{
// #todo Please modify the following code to remove attributes that should not be searched.
$criteria=new CDbCriteria;
$criteria->compare('alert_id',$this->alert_id,true);
$criteria->compare('alert_id_nimsoft',$this->alert_id_nimsoft,true);
$criteria->compare('alert_subject',$this->alert_subject,true);
$criteria->compare('alert_message',$this->alert_message,true);
$criteria->compare('alert_severity',$this->alert_severity,true);
$criteria->compare('alert_device',$this->alert_device,true);
$criteria->compare('alert_ip_address',$this->alert_ip_address,true);
$criteria->compare('alert_status',$this->alert_status,true);
$criteria->compare('alert_monitor_type',$this->alert_monitor_type,true);
$criteria->compare('alert_instance',$this->alert_instance,true);
$criteria->compare('alert_attribute',$this->alert_attribute,true);
$criteria->compare('alert_value',$this->alert_value,true);
$criteria->compare('alert_event_time',$this->alert_event_time,true);
$criteria->compare('alert_probe',$this->alert_probe,true);
$criteria->compare('alert_datetime',$this->alert_datetime,true);
$criteria->compare('alert_itsm_ack',$this->alert_itsm_ack,true);
$criteria->compare('alert_itsm_ack_status',$this->alert_itsm_ack_status,true);
$criteria->compare('alert_itsm_ack_datetime',$this->alert_itsm_ack_datetime,true);
$criteria->compare('alert_itsm_ticketnumber',$this->alert_itsm_ticketnumber,true);
$criteria->limit = 10;
$criteria->order='alert_datetime DESC';
return new CActiveDataProvider($this, array(
'criteria'=>$criteria,
"pagination" => false
));
}
public function search()
{
// #todo Please modify the following code to remove attributes that should not be searched.
$criteria=new CDbCriteria;
$criteria->compare('alert_id',$this->alert_id,true);
$criteria->compare('alert_id_nimsoft',$this->alert_id_nimsoft,true);
$criteria->compare('alert_subject',$this->alert_subject,true);
$criteria->compare('alert_message',$this->alert_message,true);
$criteria->compare('alert_severity',$this->alert_severity,true);
$criteria->compare('alert_device',$this->alert_device,true);
$criteria->compare('alert_ip_address',$this->alert_ip_address,true);
$criteria->compare('alert_status',$this->alert_status,true);
$criteria->compare('alert_monitor_type',$this->alert_monitor_type,true);
$criteria->compare('alert_instance',$this->alert_instance,true);
$criteria->compare('alert_attribute',$this->alert_attribute,true);
$criteria->compare('alert_value',$this->alert_value,true);
$criteria->compare('alert_event_time',$this->alert_event_time,true);
$criteria->compare('alert_probe',$this->alert_probe,true);
$criteria->compare('alert_datetime',$this->alert_datetime,true);
$criteria->compare('alert_itsm_ack',$this->alert_itsm_ack,true);
$criteria->compare('alert_itsm_ack_status',$this->alert_itsm_ack_status,true);
$criteria->compare('alert_itsm_ack_datetime',$this->alert_itsm_ack_datetime,true);
$criteria->compare('alert_itsm_ticketnumber',$this->alert_itsm_ticketnumber,true);
return new CActiveDataProvider($this, array(
'criteria'=>$criteria,
));
}
/**
* Returns the static model of the specified AR class.
* Please note that you should have this exact method in all your CActiveRecord descendants!
* #param string $className active record class name.
* #return NimsoftAlerts the static model class
*/
public static function model($className=__CLASS__)
{
return parent::model($className);
}
}
This can be fixed using 'get' for form method instead of the 'post' method you seem to have used.
<div class="form">
<?php $form=$this->beginWidget('CActiveForm', array(
'method' => 'get',
'id'=>'nimsoft-alerts-form',
'enableAjaxValidation'=>false,
)); ?>
And in your action use the following instead of $_POST variables:
$_GET['NimsoftAlerts']

Css is not loading after changed the GetDbConnection() in Yii

I'm new to Yii Framwork, I have used the steps from Multiple-database support in Yii to connect different database , its helped me lot.
but Css is not loaded, normal HTML content is displaying in browser when I'm opening the index.php
What changes is require to load the CSS after changing the GetDbConnection() in modules.
my Ad.php code from models
<?php
class Ad extends MyActiveRecord
{
public $password;
public $repassword;
public function getDbConnection()
{
return self::getCCDbConnection();
}
public static function model($className=__CLASS__)
{
return parent::model($className);
}
....
}
Thanks in Advance
This does not solve your css problem, however, this is the right way to use multiple dbs in yii.
This is the right way to use multiple db's in yii mvc:
Let's say that i have multiple db's and I use them to store urls.
From time to time I need to change the db.
So, I have the model generated by using gii and on top of that I have class that extends and overwrites some of methods/functions.
UrlSlaveM extends UrlSlave wich extends CActiveRecord
as default, in UrlSlave I will connect to my first db
I always use UrlSlaveM when I insert new data, so that I can overwrite the following function:
public function getDbConnection() {
return Yii::app()->db1;
}
here is a full SlaveUrl model:
<?php
/**
* This is the model class for table "url".
*
* The followings are the available columns in table 'url':
* #property string $id
* #property integer $instance_id
* #property integer $website_id
* #property string $link
* #property string $title
* #property integer $created
* #property integer $updated
* #property integer $status
*/
class UrlSlave extends CActiveRecord {
/**
* Returns the static model of the specified AR class.
* #param string $className active record class name.
* #return UrlSlave the static model class
*/
public static function model($className = __CLASS__) {
return parent::model($className);
}
/**
* #return CDbConnection database connection
*/
public function getDbConnection() {
return Yii::app()->db1;
}
/**
* #return string the associated database table name
*/
public function tableName() {
return 'url';
}
/**
* #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('instance_id, website_id, link, title, created, updated, status', 'required'),
array('instance_id, website_id, created, updated, status', 'numerical', 'integerOnly' => true),
array('link, title', 'length', 'max' => 255),
// The following rule is used by search().
// Please remove those attributes that should not be searched.
array('id, instance_id, website_id, link, title, created, updated, status', '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(
);
}
/**
* #return array customized attribute labels (name=>label)
*/
public function attributeLabels() {
return array(
'id' => 'ID',
'instance_id' => 'Instance',
'website_id' => 'Website',
'link' => 'Link',
'title' => 'Title',
'created' => 'Created',
'updated' => 'Updated',
'status' => 'Status',
);
}
/**
* 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, true);
$criteria->compare('instance_id', $this->instance_id);
$criteria->compare('website_id', $this->website_id);
$criteria->compare('link', $this->link, true);
$criteria->compare('title', $this->title, true);
$criteria->compare('created', $this->created);
$criteria->compare('updated', $this->updated);
$criteria->compare('status', $this->status);
return new CActiveDataProvider($this, array(
'criteria' => $criteria,
));
}
}
and here is the full UrlSlaveM model:
<?php
class UrlSlaveM extends UrlSlave {
const ACTIVE = 1;
const INACTIVE = 0;
const BANNED = -1;
public static function model($className = __CLASS__) {
return parent::model($className);
}
public function rules() {
$parent_rules = parent::rules();
$rules = array_merge(
$parent_rules, array(
array('link', 'unique'),
));
return $rules;
}
public static $server_id = 1;
public static $master_db;
public function getDbConnection() {
//echo __FUNCTION__;
//die;
//echo 111;
self::$master_db = Yii::app()->{"db" . self::$server_id};
if (self::$master_db instanceof CDbConnection) {
self::$master_db->setActive(true);
return self::$master_db;
}
else
throw new CDbException(Yii::t('yii', 'Active Record requires a "db" CDbConnection application component.'));
}
}
now, by setting $server_id to 1 or 2 or 3 ... you are able to connect to another db
please set the value of $server_id as UrlSlaveM::$server_id = 2; before you add data!
public static $server_id = 1;
public static $master_db;
also, in the main config file, set like this:
'db' => array(
'connectionString' => 'mysql:host=localhost;dbname=dvc',
'emulatePrepare' => true,
'username' => 'root',
'password' => '',
'charset' => 'utf8',
),
'db2' => array(
'connectionString' => 'mysql:host=localhost;dbname=dvc2',
'username' => 'root',
'password' => '',
'charset' => 'utf8',
'tablePrefix' => '',
'class' => 'CDbConnection' // DO NOT FORGET THIS!
),
'db1' => array(
'connectionString' => 'mysql:host=localhost;dbname=dvc1',
'username' => 'root',
'password' => '',
'charset' => 'utf8',
'tablePrefix' => '',
'class' => 'CDbConnection' // DO NOT FORGET THIS!
),

Adding where close on Gii generated CRUD

I am beginner with Yii and I used GII to create a CURD table. Everything is working fine but I only want to fetch certain record from the database by putting a where clause (for example "where client gender is male). I cannot find where the data is fetched from the database in Gii's generated code and where I need to insert the WHERE clause in the code.
As you know the Gii generated Model, controller and view file. The model file is as below. My view used CGridView to generate the CRUD table.
public static function model($className = __CLASS__) {
return parent::model($className);
}
/**
* #return string the associated database table name
*/
public function tableName() {
return 'test_prefixtbl_client_local';
}
/**
* #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('client_id', 'required'),
array('client_id', 'length', 'max' => 15),
array('surname, forename', 'length', 'max' => 20),
array('title', 'length', 'max' => 6),
array('status', 'length', 'max' => 8),
array('dob', 'safe'),
// The following rule is used by search().
// Please remove those attributes that should not be searched.
array('client_id, surname, forename, title, status, dob', '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(
);
}
/**
* #return array customized attribute labels (name=>label)
*/
public function attributeLabels() {
return array(
'client_id' => 'Client ID',
'surname' => 'Surname',
'forename' => 'Forename',
'title' => 'Title',
'status' => 'Status',
'dob' => 'Date of birth (yyyy-mm-dd)',
'actions' => 'Actions',
);
}
/**
* 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('client_id', $this->client_id, true);
$criteria->compare('surname', $this->surname, true);
$criteria->compare('forename', $this->forename, true);
$criteria->compare('title', $this->title, true);
$criteria->compare('status', $this->status, true);
$criteria->compare('dob', $this->dob, true);
return new CActiveDataProvider($this, array(
'criteria' => $criteria,
'sort' => array(
'defaultOrder' => 'dob DESC',
),
));
}
You have two ways to do your query, one using Query Builder (tutorial here) like this:
$clientLocalArray = Yii::app()->db->createCommand()
->select()
->from("test_prefixtbl_client_local")
->where("gender = :gender", array(":gender"=>$gender))
->queryAll();
Or you can use the Active Record itself (tutorial here) like this:
$clientLocalArrayObjects = ClientLocal::model()->findAllByAttributes(array(
"gender" => $gender
));
Any doubts, just ask! :)

Yii Model extending / overloading

I have an Account Model which has some properties and relations, and i have an Reseller model.
The point is that a reseller is actually an account only it has the possibility to have accounts beneath it.
What is the best approach to implement this,
at first i had a special Reseller class with relations between them, but actually i just want an accounts class which if the account is a reseller uses the reseller class.
Account model
<?php
/**
* This is the model class for table "account".
*
* The followings are the available columns in table 'account':
* #property string $id
* #property string $reseller_id
* #property string $name
* #property string $invoice_id
* #property boolean $is_reseller
*
* The followings are the available model relations:
* #property Reseller $reseller
* #property Contact[] $contacts
* #property Domain[] $domains
* #property HostingAccount[] $hostingAccounts
* #property User[] $users
*/
class Account extends CActiveRecord {
/**
* Returns the static model of the specified AR class.
* #param string $className active record class name.
* #return Account 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 'account';
}
/**
* #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('name', 'required'),
array('id, reseller_id', 'length', 'max' => 40),
array('name', 'length', 'max' => 45),
array('invoice_id', 'length', 'max' => 10),
// The following rule is used by search().
// Please remove those attributes that should not be searched.
array('id, reseller_id, name, invoice_id', '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(
'reseller' => array(self::BELONGS_TO, 'Reseller', 'reseller_id'),
'contacts' => array(self::HAS_MANY, 'Contact', 'account_id'),
'domains' => array(self::HAS_MANY, 'Domain', 'account_id'),
'hostingAccounts' => array(self::HAS_MANY, 'HostingAccount', 'account_id'),
'users' => array(self::HAS_MANY, 'User', 'account_id'),
);
}
/**
* #return array customized attribute labels (name=>label)
*/
public function attributeLabels() {
return array(
'id' => 'ID',
'reseller_id' => 'Reseller',
'name' => 'Name',
'invoice_id' => 'Invoice',
);
}
/**
* 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, true);
$criteria->compare('reseller_id', $this->reseller_id, true);
$criteria->compare('name', $this->name, true);
$criteria->compare('invoice_id', $this->invoice_id, true);
return new CActiveDataProvider($this, array(
'criteria' => $criteria,
));
}
/**
* Adds UUID before the item is saved
*
*/
public function beforeSave() {
if ($this->isNewRecord)
$this->id = new CDbExpression('UUID()');
return parent::beforeSave();
}
}
Reseller Model
<?php
class Reseller extends Account
{
/**
* #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(
'reseller' => array(self::BELONGS_TO, 'Reseller', 'reseller_id'),
'contacts' => array(self::HAS_MANY, 'Contact', 'account_id'),
'domains' => array(self::HAS_MANY, 'Domain', 'account_id'),
'hostingAccounts' => array(self::HAS_MANY, 'HostingAccount', 'account_id'),
'users' => array(self::HAS_MANY, 'User', 'account_id'),
'accounts' => array(self::HAS_MANY, 'Account', 'reseller_id'),
'account' => array(self::BELONGS_TO, 'Account', 'account_id'),
);
}
}
First keep in mind that ActiveRecord != models its easy to get confused, beware!
Also check this post
Ok now, you can have some factory method that gives you the class you need, Account or Reseller, depending on your logic, if not all acounts can be resellers you may also need some way to determine this. like a "is_reseller" column or similar.
In the end i made a relation from accounts to itself and solved it.
/**
* #return array relational rules.
*/
public function relations() {
return array(
'reseller' => array(self::BELONGS_TO, 'Account', 'account_id'),
'users' => array(self::HAS_MANY, 'User', 'account_id'),
'accounts' => array(self::HAS_MANY, 'Account', 'account_id'),
);
}
I used a extended classes to a models to implemented a diferents methos and a unique prerequisite is add this function in a new class:
public static function model($className=__CLASS__){
return parent::model($className);
}

Categories