I am using YII Framework but when i update my information excluding image , it throw error that image type is not valid , even i have valid iamge type .
it throw error that
Please fix the following input errors:
Image cannot be blank.
Please choose correct file format
public function actionUpdate($id) {
$model = $this->loadModel($id);
$oldImage = $model->image;
if (isset($_POST['Product'])) {
$model->attributes = $_POST['Product'];
$rnd = rand(0, 9999); // generate random number between 0-9999
$uploadedFile = CUploadedFile::getInstance($model, 'image');
if (!empty($uploadedFile)) {
$fileName = "{$rnd}" . time() . "{$uploadedFile}"; // random number + file name
$model->image = $fileName;
$uploadedFile->saveAs(Yii::app()->basePath . '/../images/product/' . $fileName);
#unlink(Yii::app()->basePath . "\\..\\images\\product\\" . $oldImage);
} else {
$model->image = $oldImage;
}
if ($model->save())
$this->redirect(array('view', 'id' => $model->id));
}
$this->render('update', array(
'model' => $model,
));
}
and my _form file is below
<div class="form">
<?php
$form = $this->beginWidget('CActiveForm', array(
'id' => 'product-form',
'enableAjaxValidation' => false,
'htmlOptions' => array('enctype' => 'multipart/form-data'),
));
?>
<p class="note">Fields with <span class="required">*</span> are required.</p>
<?php echo $form->errorSummary($model); ?>
<div class="row">
<?php echo $form->labelEx($model, 'title'); ?>
<?php echo $form->textField($model, 'title', array('size' => 60, 'maxlength' => 256)); ?>
<?php echo $form->error($model, 'title'); ?>
</div>
<div class="row">
<?php
echo $form->labelEx($model, 'slug');
echo $form->textField($model, 'slug', array('size' => 60, 'maxlength' => 256));
echo $form->error($model, 'slug');
?>
</div>
<div class="row">
<?php
echo $form->labelEx($model, 'image');
echo CHtml::activeFileField($model, 'image');
echo $form->error($model, 'image');
?>
</div>
<?php if ($model->isNewRecord != '1') {
?>
<div class="row">
<?php echo CHtml::image(Yii::app()->request->baseUrl . '/images/product/' . $model->image, "image", array("width" => 200)); ?>
</div>
<?php } ?>
<div class="row">
<?php
echo $form->labelEx($model, 'status');
echo $form->dropDownList($model, 'status', array('active' => 'Active', 'inactive' => 'InActive'), array('empty' => 'Select Status'));
echo $form->error($model, 'status');
?>
</div>
<div class="row buttons">
<?php echo CHtml::submitButton($model->isNewRecord ? 'Create' : 'Save'); ?>
</div>
<?php $this->endWidget(); ?>
and my model is below
<?php
class Product extends CActiveRecord {
public function tableName() {
return 'products';
}
public function rules() {
// NOTE: you should only define rules for those attributes that
// will receive user inputs.
return array(
array('title, image, status', 'required'),
array('image', 'file', 'types' => 'jpg, gif, png', 'message' => 'Please choose correct file format'),
array('created_by, modified_by', 'numerical', 'integerOnly' => true),
array('title', 'length', 'max' => 256),
array('slug', 'length', 'max' => 256),
array('status', 'length', 'max' => 8),
array('image, created_at, modified_at', 'safe'),
// The following rule is used by search().
// #todo Please remove those attributes that should not be searched.
array('id, title, slug, image, status, created_at, created_by, modified_at, modified_by', 'safe', 'on' => 'search'),
);
}
/**
* #return array relational rules.
*/
public function relations() {
return array(
'productitems' => array(self::HAS_MANY, 'Productitems', 'proid'),
);
}
/**
* #return array customized attribute labels (name=>label)
*/
public function attributeLabels() {
return array(
'id' => 'ID',
'title' => 'Title',
'slug' => 'Slug',
'image' => 'Image',
'status' => 'Status',
'created_at' => 'Created At',
'created_by' => 'Created By',
'modified_at' => 'Modified At',
'modified_by' => 'Modified By',
);
}
/**
* 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', $this->id);
$criteria->compare('title', $this->title, true);
$criteria->compare('slug', $this->slug, true);
$criteria->compare('image', $this->image, true);
$criteria->compare('status', $this->status, true);
$criteria->compare('created_at', $this->created_at, true);
$criteria->compare('created_by', $this->created_by);
$criteria->compare('modified_at', $this->modified_at, true);
$criteria->compare('modified_by', $this->modified_by);
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 Product the static model class
*/
public static function model($className = __CLASS__) {
return parent::model($className);
}
}
You are using a CFileValidator for the field image in your Product class, and you are restricting the formats that can be uploaded, as it is written in the following line:
array('image', 'file', 'types' => 'jpg, gif, png', 'message' => 'Please choose correct file format'),
The problem you are having is that CFileValidator does not allow file fields to be empty by default, so you have to explicitly set the allowEmpty attribute of the rule to true.
That said, your rule should be written as follows:
array('image', 'file', 'types' => 'jpg, gif, png', 'allowEmpty' => true, 'message' => 'Please choose correct file format'),
You can see more about Model Rules Validation in the following link:
http://www.yiiframework.com/wiki/56/#hh12
Hope it helps.
Related
I am beginner in Yii Framework.I have created the _form.php with Yii widget CActiveForm.I have made the Checkbox list for week of days.I have serialized checkbox values on actioncreate and save into database table.Actually problem is that When i calling the actionupdate then my checked values are not showing that i have insert on actioncreate.actioncreate and actionupdate using the same form _form.php.
I have written my code below
actioncreate
public function actionCreate()
{
$model=new CustomerAccounts;
if(isset($_POST['CustomerAccounts']))
{
$model->attributes=$_POST['CustomerAccounts'];
$model->DateCreated = date('Y-m-d H:i:s');
$model->DeliveryDay = serialize($_POST['CustomerAccounts']['DeliveryDay']);
if($model->save()) {
Yii::app()->user->setFlash('success', 'Customer Account create successfully.');
$this->redirect(array('admin'));
} else {
Yii::app()->user->setFlash('danger','An error occurred. Please try again.');
}
}
$this->render('create',array(
'model'=>$model,
));
}
actionupdate
public function actionUpdate($id)
{
$model=$this->loadModel($id);
if(isset($_POST['CustomerAccounts']))
{
$model->attributes=$_POST['CustomerAccounts'];
$model->DeliveryDay = serialize($_POST['CustomerAccounts']['DeliveryDay']);
$model->DateCreated = date('Y-m-d H:i:s');
if($model->save()) {
Yii::app()->user->setFlash('success', 'Customer Account update successfully.');
$this->redirect(array('admin'));
} else {
Yii::app()->user->setFlash('danger','An error occurred. Please try again.');
}
}
$this->render('update',array(
'model'=>$model,
));
}
_form.php
<?php $form=$this->beginWidget('CActiveForm', array(
'id'=>'customer-accounts-form',
'enableAjaxValidation'=>false,
<div class="row">
<div class="col-lg-12" style="padding-left: 34px;">
<?php echo $form->labelEx($model, 'DeliveryDay'); ?>
<?php echo $form->error($model, 'DeliveryDay'); ?>
<div id="checkbox" style="padding-left: 90px;">
<?php
$htmlOptions = array('template' => '<tr><td >{input}</td> <td> {label}</td> </tr', 'multiple' => true, 'checked' => 'checked');
echo $form->checkBoxList($model, 'DeliveryDay', Yii::app()->params['WeekDays'], $htmlOptions);
?>
</div></div></div>
<?php $this->endWidget(); ?>
Here my model
class CustomerAccounts extends CActiveRecord
{
public function tableName()
{
return 'customer_accounts';
}
public function rules()
{
return array(
array('DeliveryDay, Status, CustomerID, Employee_ID, PaymentModeID', 'required'),
array('CustomerID, Employee_ID, PaymentModeID, PcBottle, Bottle6Ltr, Bottle1500Ml, Bottle500Ml, TabStand, Pump, DispensirStatus, PCBottlesQuantity, PCBottleSecurity, DispensirQuantity, DispensirSerialNo, DispensirSecurity, TotalAmount, Status', 'numerical', 'integerOnly'=>true),
array('DateJoin', 'length', 'max'=>250),
array('Description', 'safe'),
array('CustomerAccountID, CustomerID, Employee_ID, PaymentModeID, DateJoin, PcBottle, Bottle6Ltr, Bottle1500Ml, Bottle500Ml, TabStand, Pump, DispensirStatus, PCBottlesQuantity, PCBottleSecurity, DispensirQuantity, DispensirSerialNo, DispensirSecurity, TotalAmount, DeliveryDay, Description, Status, DateCreated', 'safe', 'on'=>'search'),
);
}
public function relations()
{
return array(
'customer' => array(self::BELONGS_TO, 'Customer', 'CustomerID'),
'employee' => array(self::BELONGS_TO, 'Employee', 'Employee_ID'),
'paymentMode' => array(self::BELONGS_TO, 'PaymentMods', 'PaymentModeID'),
);
}
public function attributeLabels()
{
return array(
'CustomerAccountID' => 'Customer Account',
'CustomerID' => 'Customer',
//'Employee_ID' => 'Employee',
'Employee_ID' => 'Sale Person',
'PaymentModeID' => 'Payment Mode',
'DateJoin' => 'Date Join',
'PcBottle' => 'Pc Bottle',
'Bottle6Ltr' => 'Bottle6 Ltr',
'Bottle1500Ml' => 'Bottle1500 Ml',
'Bottle500Ml' => 'Bottle500 Ml',
'TabStand' => 'Tab Stand',
'Pump' => 'Pump',
'DispensirStatus' => 'Dispensir Status',
'PCBottlesQuantity' => 'Pcbottles Quantity',
'PCBottleSecurity' => 'Pcbottle Security',
'DispensirQuantity' => 'Dispensir Quantity',
'DispensirSerialNo' => 'Dispensir Serial No',
'DispensirSecurity' => 'Dispensir Security',
'TotalAmount' => 'Total Amount',
'DeliveryDay' => 'Delivery Day',
'Description' => 'Description',
'Status' => 'Status',
'DateCreated' => 'Date Created',
);
}
public function search()
{
$criteria=new CDbCriteria;
$criteria->compare('CustomerAccountID',$this->CustomerAccountID);
$criteria->compare('CustomerID',$this->CustomerID);
$criteria->compare('Employee_ID',$this->Employee_ID);
$criteria->compare('PaymentModeID',$this->PaymentModeID);
$criteria->compare('DateJoin',$this->DateJoin,true);
$criteria->compare('PcBottle',$this->PcBottle);
$criteria->compare('Bottle6Ltr',$this->Bottle6Ltr);
$criteria->compare('Bottle1500Ml',$this->Bottle1500Ml);
$criteria->compare('Bottle500Ml',$this->Bottle500Ml);
$criteria->compare('TabStand',$this->TabStand);
$criteria->compare('Pump',$this->Pump);
$criteria->compare('DispensirStatus',$this->DispensirStatus);
$criteria->compare('PCBottlesQuantity',$this->PCBottlesQuantity);
$criteria->compare('PCBottleSecurity',$this->PCBottleSecurity);
$criteria->compare('DispensirQuantity',$this->DispensirQuantity);
$criteria->compare('DispensirSerialNo',$this->DispensirSerialNo);
$criteria->compare('DispensirSecurity',$this->DispensirSecurity);
$criteria->compare('TotalAmount',$this->TotalAmount);
$criteria->compare('DeliveryDay',$this->DeliveryDay,true);
$criteria->compare('Description',$this->Description,true);
$criteria->compare('Status',$this->Status);
$criteria->compare('DateCreated',$this->DateCreated,true);
return new CActiveDataProvider($this, array(
'criteria'=>$criteria,
));
}
public static function model($className=__CLASS__)
{
return parent::model($className);
}
}
Would anyone Can tell me when i call the actionupdate How the checked values will be shows from database table ?
You have to unserialized checkbox values afterFind() function in your model file (i.e. models/CustomerAccounts.php) as follows:
public function afterFind() {
$this->DeliveryDay = unserialize($this->DeliveryDay);
parent::afterFind();
}
hi i am using yii framework but when i left image field blank while update , it will get oldfile from model like
$model = $this->loadModel($id);
$oldImage = $model->image;
but while updating it throw error that image type not valid , but old image type valid is save like my old image name is test.jpg .
But when i remove model rule
array('image', 'file', 'types' => 'jpg, gif, png', 'message' => 'Please choose correct file format','on'=>'insert'),
update work fine i am unable to understand where the problem is
Below is code of my actionUpdate
public function actionUpdate($id) {
$model = $this->loadModel($id);
$oldImage = $model->image;
if (isset($_POST['Product'])) {
$model->attributes = $_POST['Product'];
$rnd = rand(0, 9999); // generate random number between 0-9999
$uploadedFile = CUploadedFile::getInstance($model, 'image');
if (!empty($uploadedFile)) {
$fileName = "{$rnd}" . time() . "{$uploadedFile}"; // random number + file name
$model->image = $fileName;
$uploadedFile->saveAs(Yii::app()->basePath . '/../images/product/' . $fileName);
unlink(Yii::app()->basePath . "/../images/product/" . $oldImage);
} else {
$model->image = $oldImage;
}
if ($model->save())
$this->redirect(array('view', 'id' => $model->id));
else {
CVarDumper::dump($model->getErrors(), 10, 1);
exit;
}
}
$this->render('update', array(
'model' => $model,
));
}
and below is my _form view page
<div class="form">
<?php
$form = $this->beginWidget('CActiveForm', array(
'id' => 'product-form',
'enableAjaxValidation' => false,
'htmlOptions' => array('enctype' => 'multipart/form-data'),
));
?>
<p class="note">Fields with <span class="required">*</span> are required.</p>
<?php echo $form->errorSummary($model); ?>
<div class="row">
<?php echo $form->labelEx($model, 'title'); ?>
<?php echo $form->textField($model, 'title', array('size' => 60, 'maxlength' => 256)); ?>
<?php echo $form->error($model, 'title'); ?>
</div>
<div class="row">
<?php
echo $form->labelEx($model, 'slug');
echo $form->textField($model, 'slug', array('size' => 60, 'maxlength' => 256));
echo $form->error($model, 'slug');
?>
</div>
<div class="row">
<?php
echo $form->labelEx($model, 'image');
echo CHtml::activeFileField($model, 'image');
echo $form->error($model, 'image');
?>
</div>
<?php if ($model->isNewRecord != '1') {
?>
<div class="row">
<?php echo CHtml::image(Yii::app()->request->baseUrl . '/images/product/' . $model->image, "image", array("width" => 200)); ?>
</div>
<?php } ?>
<div class="row">
<?php
echo $form->labelEx($model, 'status');
echo $form->dropDownList($model, 'status', array('active' => 'Active', 'inactive' => 'InActive'), array('empty' => 'Select Status'));
echo $form->error($model, 'status');
?>
</div>
<div class="row buttons">
<?php echo CHtml::submitButton($model->isNewRecord ? 'Create' : 'Save'); ?>
</div>
<?php $this->endWidget(); ?>
and MOdel is below
<?php
class Product extends CActiveRecord {
/**
* #return string the associated database table name
*/
public function tableName() {
return 'products';
}
/**
* #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('title, image, status', 'required'),
// array('image', 'file', 'types' => 'jpg, gif, png', 'message' => 'Please choose correct file format'),
array('created_by, modified_by', 'numerical', 'integerOnly' => true),
array('title', 'length', 'max' => 256),
array('slug', 'length', 'max' => 256),
array('status', 'length', 'max' => 8),
array('image, created_at, modified_at', 'safe'),
// The following rule is used by search().
// #todo Please remove those attributes that should not be searched.
array('id, title, slug, image, status, created_at, created_by, modified_at, modified_by', '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(
'productitems' => array(self::HAS_MANY, 'Productitems', 'proid'),
);
}
/**
* #return array customized attribute labels (name=>label)
*/
public function attributeLabels() {
return array(
'id' => 'ID',
'title' => 'Title',
'slug' => 'Slug',
'image' => 'Image',
'status' => 'Status',
'created_at' => 'Created At',
'created_by' => 'Created By',
'modified_at' => 'Modified At',
'modified_by' => 'Modified By',
);
}
public function search() {
// #todo Please modify the following code to remove attributes that should not be searched.
$criteria = new CDbCriteria;
$criteria->compare('id', $this->id);
$criteria->compare('title', $this->title, true);
$criteria->compare('slug', $this->slug, true);
$criteria->compare('image', $this->image, true);
$criteria->compare('status', $this->status, true);
$criteria->compare('created_at', $this->created_at, true);
$criteria->compare('created_by', $this->created_by);
$criteria->compare('modified_at', $this->modified_at, true);
$criteria->compare('modified_by', $this->modified_by);
return new CActiveDataProvider($this, array(
'criteria' => $criteria,
));
}
public static function model($className = __CLASS__) {
return parent::model($className);
}
}
This is the view :
<?php
$this->renderPartial('_search', array(
'model' => $model
));
?>
This is the _search.php file:
<div class="wide form">
<?php
$form = $this->beginWidget('CActiveForm', array(
'action' => Yii::app()->createUrl($this->route),
'method'=>'get',
));
?>
<div class="row">
<?php echo $form->label($model,'month'); ?>
<?php echo $form->textField($model,'month'); ?>
</div>
<div class="row">
<?php echo $form->label($model,'year'); ?>
<?php echo $form->textField($model,'year'); ?>
</div>
<div class="row buttons">
<?php echo CHtml::submitButton('Filter'); ?>
</div>
<?php $this->endWidget(); ?>
</div>
The controller index function :
$user_id = Yii::app()->user->attributes->id;
$dataProvider = new CActiveDataProvider('Salaries', array(
'criteria'=>array(
'order'=>'id DESC'
),
'pagination'=>array(
'pageSize'=>20,
),
));
$model = new Salaries();
$this->render('index',array(
'dataProvider' => $dataProvider,
'model' => $model
));
And the model:
public function search()
{
// #todo Please modify the following code to remove attributes that should not be searched.
$criteria=new CDbCriteria;
$criteria->compare('id',$this->id);
$criteria->compare('first_name',$this->first_name,true);
$criteria->compare('last_name',$this->last_name,true);
$criteria->compare('month',$this->month);
$criteria->compare('year',$this->year);
return new CActiveDataProvider($this, array(
'criteria'=>$criteria,
));
}
When I press the filter button the url is generated and it looks like:
/index?Salaries[month]=2&Salaries[year]=&yt0=Filter
but it does not do anything. I don't understand why . What am I doing wrong? thx
UPDATE THIS IS THE TABLE:
$this->widget('GridView', array(
'id' => 'my-grid',
'dataProvider' => $dataProvider,
// 'filter'=>$model,
'ajaxUpdate'=>false,
'columns' => array(
...............
),
));
1) Make sure you have enabled rules for search on filterable fields.
[model]
public function rules() {
return array(
'id, first_name, last_name, /*...*/', 'safe', 'on' => 'search',
);
}
2) Don't call CActiveDataProvider in controller (you are not passing any filtering data there, bdw), use model's search() method (put ordering and pagination params there too).
[controller]
$model = new Salaries('search'); //pass scenario!
/*
* Will assign any filtering attributes to model attributes,
* if there is no filtering attributes than empty array will be
* assigned for attributes (default value)
*/
$model->attributes = Yii::app()->request->getParam('Scenario', []);
[view]
$this->widget('GridView', array(
'id' => 'my-grid',
'dataProvider' => $model->search(), // Where your filtering will take effect.
'filter' => $model,
I have Settings controller like
public function actionIndex()
{
$model = new SettingsForm;
if(isset($_POST['SettingsForm'])) {
if($model->validate()) {
//
}
}
$this->render('index', array('model' => $model));
}
and in settings view:
<?php
$form = $this->beginWidget(
'CActiveForm', array(
'id' => 'settings-form',
'enableClientValidation' => true,
'clientOptions' => array(
'validateOnSubmit' => true,
),
));
?>
<div class="form-group">
<?php echo $form->labelEx($model, 'meta_keywords'); ?>
<?php echo $form->textField($model, 'meta_keywords', array('class' => 'form-control', 'value' => Yii::app()->config->get('meta_keywords'), 'placeholder' => 'Ключевые слова и фразы через запятую')); ?>
<?php echo $form->error($model, 'meta_keywords', array('class' => 'text-danger')); ?>
</div>
<div class="form-group">
<?php echo $form->labelEx($model, 'main_page'); ?>
<?php echo $form->dropDownList($model, 'main_page', $model->getPages()); ?>
<?php echo $form->error($model, 'main_page', array('class' => 'text-danger')); ?>
</div>
function getPages in SettingsForm model:
public function getPages() {
return array(
0 => 'Nothing'
);
}
This code returns error:
Property "SettingsForm.main_page" is not defined.
But all previos elements Yii created successfully and don't return any error =\
In your SettingsForm model is main_page defined in the rules method? i.e.
public function rules()
{
// NOTE: you should only define rules for those attributes that
// will receive user inputs.
return array(
array( ... 'main_page', ...),
...
);
}
/**
* #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('site_name, charset, meta_description, meta_keywords', 'required'),
array('main_page', 'boolean')
);
}
Updated
class SettingsForm extends CFormModel
Still do it. Look at here and here (rus).
public function rules()
{
return array(
array('site_name, charset, meta_description, meta_keywords', 'required'),
array('main_page', 'boolean'),
array('site_name, charset, meta_description, meta_keywords, main_page', 'safe'),
);
}
Pfffff....
I just forgot call variable in model $main_page...
class SettingsForm extends CFormModel
{
public $site_name;
public $charset;
public $meta_description;
public $meta_keywords;
public $main_page;
..
}
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']