I created a change password functionality to change the admin password.I used this toutorial.
Now I face a problem in $model->validate().
Can anyone help me??
Controller
public function actionIndex()
{
$id = 1;
$model = User::model()->findByAttributes(array('usertype' => $id));
$model->setScenario('changePwd');
if (isset($_POST['User'])) {
$model->attributes = $_POST['User'];
if ($model->validate()) {
$model->password = md5($model->new_password);
if ($model->save()) {
Yii::app()->user->setFlash('success', "Password Changed Successfully!");
}
} else {
Yii::app()->user->setFlash('error', "Change Password failed!");
}
}
$this->render('index', array('model' => $model));
}
Model
class User extends CActiveRecord
{
public $old_password;
public $new_password;
public $repeat_password;
/**
* #return string the associated database table name
*/
public function tableName()
{
return '{{user}}';
}
/**
* #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('usertype, firstname, lastname, email, password, mobile, gender, dob, country, area, city, address, street, housenumber, extradirection, createdon', 'required'),
array('usertype, country, area', 'numerical', 'integerOnly'=>true),
array('firstname, lastname, email, mobile, dob, city, street, housenumber', 'length', 'max'=>155),
array('password', 'length', 'max'=>225),
array('gender', 'length', 'max'=>6),
array('status', 'length', 'max'=>1),
array('updatedon', 'safe'),
// The following rule is used by search().
// #todo Please remove those attributes that should not be searched.
array('id, usertype, firstname, lastname, email, password, mobile, gender, dob, country, area, city, address, street, housenumber, extradirection, createdon, updatedon, status', 'safe', 'on'=>'search'),
array('old_password, new_password, repeat_password', 'required', 'on' => 'changePwd'),
array('old_password', 'findPasswords', 'on' => 'changePwd'),
array('repeat_password', 'compare', 'compareAttribute'=>'new_password', 'on'=>'changePwd'),
);
}
public function findPasswords($attribute, $params)
{
$user = User::model()->findByPk(Yii::app()->user->id);
//echo '<pre>';print_r($user);echo '</pre>';
if ($user->password != md5($this->old_password))
$this->addError($attribute, 'Old password is incorrect.');
}
Form
<div class="login_con_new">
<div class="form">
<?php
$form=$this->beginWidget('CActiveForm', array(
'id'=>'change-password-form',
//'action' => Yii::app()->createUrl('login/authenticate'),
// 'enableAjaxValidation' => FALSE,
'enableClientValidation' => true,
'clientOptions' => array('validateOnSubmit' => true,),
'htmlOptions' => array(
'class' => 'form',
)
));
?>
<div class="col-sm-6">
<h2 class="title">Change Password</h2>
<?php
foreach(Yii::app()->user->getFlashes() as $key => $message) {
echo '<div class="flash-' . $key . '">' . $message . "</div>\n";
}
?>
<div class="form-group">
<?php echo $form->labelEx($model,'Current_password'); ?>
<?php echo $form->passwordField($model,'old_password',array('class'=>'form-control login-field','size'=>60,'maxlength'=>222)); ?>
<?php echo $form->error($model,'old_password'); ?>
</div>
<div class="form-group">
<?php echo $form->labelEx($model,'new_password'); ?>
<?php echo $form->passwordField($model,'new_password',array('class'=>'form-control login-field','size'=>60,'maxlength'=>222)); ?>
<?php echo $form->error($model,'new_password'); ?>
</div>
<div class="form-group">
<?php echo $form->labelEx($model,'repeat_password'); ?>
<?php echo $form->passwordField($model,'repeat_password',array('class'=>'form-control login-field','size'=>60,'maxlength'=>222)); ?>
<?php echo $form->error($model,'repeat_password'); ?>
</div>
<div class="form-group">
<div class="col-lg-4" style="padding-left: 0px;">
<?php echo CHtml::submitButton('Change',array('class' => 'btn btn-success','style'=>'color:white')); ?></div>
</div>
</div>
<?php $this->endWidget(); ?>
</div> </div>
The $valid returns me false and entering the else part.
I think in this line $model = User::model()->findByAttributes(array('usertype' => $id)); you did the mistake for usertype. This is user id.
You can use senario for update. Like:
http://www.yiiframework.com/forum/index.php/topic/31357-priority-to-rules-with-a-scenario/
The best way to debug these kind of errors is to actually check why the validate is returning false.
This can be done by checking the errors on a model. You can either output all the errors in the flash message, so a user knows what to correct, or just put it in a var_dump to help you debug.
Change your controller part to have this:
if($valid)
{
$model->password = md5($model->new_password);
if($model->save())
{
Yii::app()->user->setFlash('success', "Password Changed Successfully!");
// $this->redirect(array('dashboard/index', 'id' => 1));
}
else
{
Yii::app()->user->setFlash('error', "Change Password failed!");
}
}
else
{
var_dump($model->errors);
die();
}
It will show you the validation error in an array. Displaying which attribute has which validation error.
If you only want to validate and save the password fields. You can pass them in the validate and save method.
$model->validate(array('password')) and $model->save(TRUE, array('password'))
I found a method I dont know whether the answer is in correct method or not.
I found that the problem occurs during validation.so created an another model called changepassword for this operation ,only validate the three attributes which I given in rules.
And it worked fine.
<?php
class Changepassword extends CActiveRecord
{
public $old_password;
public $new_password;
public $repeat_password;
/**
* #return string the associated database table name
*/
public function tableName()
{
return '{{user}}';
}
/**
* #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('usertype, firstname, lastname, email, password, mobile, gender, dob, country, area, city, address, street, housenumber, extradirection, createdon', 'required'),
// array('usertype, country, area', 'numerical', 'integerOnly'=>true),
// array('firstname, lastname, email, mobile, dob, city, street, housenumber', 'length', 'max'=>155),
// array('password', 'length', 'max'=>225),
// array('gender', 'length', 'max'=>6),
// array('status', 'length', 'max'=>1),
// array('updatedon', 'safe'),
// The following rule is used by search().
// #todo Please remove those attributes that should not be searched.
array('id, usertype, firstname, lastname, email, password, mobile, gender, dob, country, area, city, address, street, housenumber, extradirection, createdon, updatedon, status', 'safe', 'on'=>'search'),
array('old_password, new_password, repeat_password', 'required', 'on' => 'changePwd'),
array('old_password, new_password, repeat_password','length','max'=>225),
array('old_password', 'findPasswords', 'on' => 'changePwd'),
array('repeat_password', 'compare', 'compareAttribute'=>'new_password', 'on'=>'changePwd'),
);
}
public function findPasswords($attribute, $params)
{
$user = User::model()->findByPk(Yii::app()->user->id);
if ($user->password != md5($this->old_password))
$this->addError($attribute, 'Old password is incorrect.');
}
/**
* #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(
'events' => array(self::HAS_MANY, 'Events', 'createdby'),
'eventsJoinees' => array(self::HAS_MANY, 'EventsJoinee', 'userid'),
'eventsRatings' => array(self::HAS_MANY, 'EventsRating', 'userid'),
'usertype0' => array(self::BELONGS_TO, 'UserroleMaster', 'usertype'),
'area0' => array(self::BELONGS_TO, 'AreaMaster', 'area'),
'country0' => array(self::BELONGS_TO, 'CountryMaster', 'country'),
);
}
/**
* #return array customized attribute labels (name=>label)
*/
public function attributeLabels()
{
return array(
'old_password'=>'Current Password',
'new_password'=> 'New Password',
'repeat_password'=>'Confirm Password',
);
}
/**
* 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('usertype',$this->usertype);
$criteria->compare('firstname',$this->firstname,true);
$criteria->compare('lastname',$this->lastname,true);
$criteria->compare('email',$this->email,true);
$criteria->compare('password',$this->password,true);
$criteria->compare('mobile',$this->mobile,true);
$criteria->compare('gender',$this->gender,true);
$criteria->compare('dob',$this->dob,true);
$criteria->compare('country',$this->country);
$criteria->compare('area',$this->area);
$criteria->compare('city',$this->city,true);
$criteria->compare('address',$this->address,true);
$criteria->compare('street',$this->street,true);
$criteria->compare('housenumber',$this->housenumber,true);
$criteria->compare('extradirection',$this->extradirection,true);
$criteria->compare('createdon',$this->createdon,true);
$criteria->compare('updatedon',$this->updatedon,true);
$criteria->compare('status',$this->status,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 User the static model class
*/
public static function model($className=__CLASS__)
{
return parent::model($className);
}
}
?>
Friends if anyone get correct method please post it.
Related
I am new to Yii. I have a view which inputs host_start_date and host_end_date. While entering these dates, it must be validated. Validation Rules are as follows:
Both date_time must not be same
There can be two same start date but the time should be different
If start date_time is a and end_date_time is b, no other entries
must be permitted inside this limit
If an end_date_time is a
start_date_time of another entry, it must throw an error.
These are the validation Rules.
I am quiet new to custom validation. Please help me solving this.
My View:
<?php
/* #var $this NimsoftHostsDetailsController */
/* #var $model NimsoftHostsDetails */
$this->breadcrumbs=array(
'Nimsoft Hosts Details'=>array('index'),
$model->id,
);
$this->menu=array(
array('label'=>'List NimsoftHostsDetails', 'url'=>array('index')),
array('label'=>'Create NimsoftHostsDetails', 'url'=>array('create')),
array('label'=>'Update NimsoftHostsDetails', 'url'=>array('update', 'id'=>$model->id)),
array('label'=>'Delete NimsoftHostsDetails', 'url'=>'#', 'linkOptions'=>array('submit'=>array('delete','id'=>$model->id),'confirm'=>'Are you sure you want to delete this item?')),
array('label'=>'Manage NimsoftHostsDetails', 'url'=>array('admin')),
);
?>
<h1>View NimsoftHostsDetails - </h1><h3><?php echo "Host Name - ".$host_name;?></h3>
<?php
if(Yii::app()->user->hasFlash('error'))
{
echo Yii::app()->user->getFlash('error');
}
?>
<!--<a href="<?php //echo $this->createUrl('/NimsoftHostsDetails/create?id='.$host_id);?>" title="Add Date Entry" class="btn btn-primary circle_ok" style="text-decoration: none;" >Add Date Entry</a>-->
<a href="<?php echo $this->createUrl('/Nimsoft/search_host1?id='.$cust_id);?>" title="Back" class="btn btn-primary circle_ok" style="text-decoration: none;" >Back</a>
<?php /*$this->widget('zii.widgets.CListView', array(
'dataProvider'=>$dataProvider,
'itemView'=>'_view',
)); */?>
<div class="form">
<div class="row">
<div style="float:left;"> </div>
<?php
$host_id = $host_id;
$form=$this->beginWidget('CActiveForm', array(
'id'=>'nimsoft-hosts-details-form',
// Please note: When you enable ajax validation, make sure the corresponding
// controller action is handling ajax validation correctly.
// There is a call to performAjaxValidation() commented in generated controller code.
// See class documentation of CActiveForm for details on this.
'enableAjaxValidation'=>false,
)); ?>
<p class="note">Fields with <span class="required">*</span> are required.</p>
<div style="float:left;"> </div>
<div style="float:left;"><?php //echo $form->errorSummary($model); ?>
<?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' => $host_start_date,
),
));
?>
<?php echo $form->error($model,'host_start_date'); ?></div>
<div style="float:left;"> </div>
<div style="float:left;"><?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' => $host_end_date,
),
));
?>
<?php echo $form->error($model,'host_end_date'); ?>
</div>
</div>
<?php echo CHtml::submitButton($model->isNewRecord ? 'Create' : 'Save'); ?>
<?php $this->endWidget(); ?>
</div>
<?php
$obj=$this->widget('zii.widgets.grid.CGridView', array(
'dataProvider'=>$dataProvider,
////'afterAjaxUpdate'=>'\'changeTRColor()\'',
//'itemView'=>'_view',
'filter'=>$model,
'columns'=>array(
array( // display 'create_time' using an expression
'name'=>'host_start_date',
'value'=>'$data->host_start_date',
),
array(
'name'=>'host_end_date',
'value'=>'$data->host_end_date',
),
array(
'class'=>'CButtonColumn',
'template'=>'{update}{delete}',
)
),
));
?>
<?php //echo Yii::app()->user->getFlash('error'); ?>
My Model:
<?php
/**
* This is the model class for table "mst_nimsoft_hosts_details".
*
* The followings are the available columns in table 'mst_nimsoft_hosts_details':
* #property integer $id
* #property integer $host_id
* #property string $host_start_date
* #property string $host_end_date
*/
class NimsoftHostsDetails extends CActiveRecord
{
/**
* #return string the associated database table name
*/
public function tableName()
{
return 'mst_nimsoft_hosts_details';
}
/**
* #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_start_date','date_validate'),
array('host_start_date, host_end_date', 'date','format'=>array('yyyy-MM-dd H:m','yyyy-MM-dd H:m')),
array('host_end_date','compare','compareAttribute'=>'host_start_date','operator'=>'>', 'allowEmpty'=>false,'message'=>'{attribute} must be greater than "{compareValue}".'),
//array('host_start_date,host_end_date', 'unique','message'=>'HOST Date already exists!'),
// The following rule is used by search().
// #todo Please remove those attributes that should not be searched.
array('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(
'id' => 'ID',
'host_id' => 'Host',
'host_start_date' => 'Host Start Date',
'host_end_date' => 'Host End Date',
);
}
public function date_validate($attribute)
{
$host_start_date=$this->host_start_date;
$host_end_date=$this->host_end_date;
$model=new NimsoftHostsDetails;
$model->attributes=$_POST['NimsoftHostsDetails'];
$model->host_id=$id;
$date_details = NimsoftHostsDetails::model()->findAllByAttributes(array('host_start_date'=>$this->host_start_date,'host_end_date'=>$this->host_end_date,'host_id'=>$model->host_id));
if($date_details)
{
$this->addError($attribute, 'DATA already present, Please Enter different Date');
}
$date_details1 = NimsoftHostsDetails::model()->findAllByAttributes(array('host_start_date'=>$this->host_end_date,'host_id'=>$model->host_id));
if($date_details1)
{
$this->addError($attribute, "The End date ".$this->host_end_date." is already mentioned as a start date");
//$this->render('exist',array('message'=>"The End date ".$model->host_end_date." is already mentioned as a start date",'host_id'=>$model->host_id));
}
if($model->host_start_date == $model->host_end_date)
{
$this->addError($attribute, 'Both dates same, Please Enter different Date');
//$this->render('exist',array('message'=>"Both dates same, Please Enter different Date",'host_id'=>$model->host_id));
}
}
/**
* 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('host_id',$this->host_id);
$criteria->compare('host_start_date',$this->host_start_date,true);
$criteria->compare('host_end_date',$this->host_end_date,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 NimsoftHostsDetails the static model class
*/
public static function model($className=__CLASS__)
{
return parent::model($className);
}
}
My controller:
<?php
class NimsoftHostsDetailsController 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/ticket_console';
/**
* #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('admin'),
),
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)
{
$host_id=$id;
$model1=new NimsoftHostsDetails;
$detail = NimsoftHostsDetails::model()->findAllByAttributes(array('host_id'=>$id));
if(isset($_POST['NimsoftHostsDetails']))
{
$model1->attributes = $_POST['NimsoftHostsDetails'];
$model1->host_id=$id;
/*$model=new NimsoftHostsDetails;
$model->attributes=$_POST['NimsoftHostsDetails'];
$model->host_id=$id;
$criteria = new CDbCriteria;
$date_details = NimsoftHostsDetails::model()->findAllByAttributes(array('host_start_date'=>$model->host_start_date,'host_end_date'=>$model->host_end_date,'host_id'=>$model->host_id));
if($date_details)
{echo "Hi";
//Yii::app()->user->setFlash('error', "DATA already present, Please Enter different Date");
//$this->render('view',array('message'=>"DATA already present, Please Enter different Date",'host_id'=>$model->host_id));
die();
}
$criteria = new CDbCriteria;
$date_details = NimsoftHostsDetails::model()->findAllByAttributes(array('host_start_date'=>$model->host_end_date,'host_id'=>$model->host_id));
if($date_details)
{
Yii::app()->user->setFlash('a', "The End date ".$model->host_end_date." is already mentioned as a start date");
//$this->render('exist',array('message'=>"The End date ".$model->host_end_date." is already mentioned as a start date",'host_id'=>$model->host_id));
die();
}
if($model->host_start_date == $model->host_end_date)
{
Yii::app()->user->setFlash('s', "Both dates same, Please Enter different Date");
//$this->render('exist',array('message'=>"Both dates same, Please Enter different Date",'host_id'=>$model->host_id));
die();
}*/
if($model1->save())
$this->redirect(array('view','id'=>$model1->host_id));
}
$criteria = new CDbCriteria();
$criteria->condition = "host_id = '$id'";
$details = NimsoftHostsDetails::model()->findAll($criteria);
$model=new NimsoftHost;
$detail2 = NimsoftHost::model()->findAllByAttributes(array('host_id'=>$id));
foreach($detail2 as $val)
{
$name=$val->host_name;
$id=$val->host_id;
$cust_id=$val->host_customer_id;
}
$dataProvider=new CActiveDataProvider('NimsoftHostsDetails',array(
'criteria' => $criteria,));
$this->render('view',array(
'dataProvider'=>$dataProvider,
'host_name'=>$name,
'host_id'=>$id,
'cust_id'=>$cust_id,'model'=>$model1
));
}
/**
* Creates a new model.
* If creation is successful, the browser will be redirected to the 'view' page.
*/
public function actionCreate($id)
{
$model=new NimsoftHostsDetails;
$host_id=$id;
// Uncomment the following line if AJAX validation is needed
// $this->performAjaxValidation($model);
if(isset($_POST['NimsoftHostsDetails']))
{
$model->attributes=$_POST['NimsoftHostsDetails'];
$model->host_id=$id;
$criteria = new CDbCriteria;
$date_details = NimsoftHostsDetails::model()->findAllByAttributes(array('host_start_date'=>$model->host_start_date,'host_end_date'=>$model->host_end_date,'host_id'=>$model->host_id));
if($date_details)
{
$this->render('exist',array('message'=>"DATA already present, Please Enter different Date",'host_id'=>$model->host_id));
die();
}
$criteria = new CDbCriteria;
$date_details = NimsoftHostsDetails::model()->findAllByAttributes(array('host_start_date'=>$model->host_end_date,'host_id'=>$model->host_id));
if($date_details)
{
$this->render('exist',array('message'=>"The End date ".$model->host_end_date." is already mentioned as a start date",'host_id'=>$model->host_id));
die();
}
if($model->host_start_date == $model->host_end_date)
{
$this->render('exist',array('message'=>"Both dates same, Please Enter different Date",'host_id'=>$model->host_id));
die();
}
if($model->save())
$this->redirect(array('view','id'=>$model->host_id));
}
$this->render('create',array(
'model'=>$model,
'host_id'=>$host_id,
));
}
/**
* 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);
if(isset($_POST['NimsoftHostsDetails']))
{
$model->attributes=$_POST['NimsoftHostsDetails'];
if($model->save())
$this->redirect(array('view','id'=>$model->host_id));
}
$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('NimsoftHostsDetails');
$this->render('index',array(
'dataProvider'=>$dataProvider,
));
}
/**
* Manages all models.
*/
public function actionAdmin()
{
$model=new NimsoftHostsDetails('search');
$model->unsetAttributes(); // clear any default values
if(isset($_GET['NimsoftHostsDetails']))
$model->attributes=$_GET['NimsoftHostsDetails'];
$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 $id the ID of the model to be loaded
* #return NimsoftHostsDetails the loaded model
* #throws CHttpException
*/
public function loadModel($id)
{
$model=NimsoftHostsDetails::model()->findByPk($id);
if($model===null)
throw new CHttpException(404,'The requested page does not exist.');
return $model;
}
/**
* Performs the AJAX validation.
* #param NimsoftHostsDetails $model the model to be validated
*/
protected function performAjaxValidation($model)
{
if(isset($_POST['ajax']) && $_POST['ajax']==='nimsoft-hosts-details-form')
{
echo CActiveForm::validate($model);
Yii::app()->end();
}
}
}
in your model, you could add another set of rules using your own validations.
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_start_date, host_end_date', 'date','format'=>array('yyyy-MM-dd H:m','yyyy-MM-dd H:m')),
array('host_end_date','compare','compareAttribute'=>'host_start_date','operator'=>'>', 'allowEmpty'=>false,'message'=>'{attribute} must be greater than "{compareValue}".'),
//array('host_start_date,host_end_date', 'unique','message'=>'HOST Date already exists!'),
// The following rule is used by search().
// #todo Please remove those attributes that should not be searched.
array('host_start_date, host_end_date', 'safe', 'on'=>'search'),
array('host_start_date', 'unique'),//this will check if your entry is unique
array('host_start_date', 'checkEntry'),//this will call your custom validation
);
}
this will be your custom validation
public function checkEntry($attribute,$params)
{
if(condition)
$this->addError($attribute,"your error message");
}
How can i update, some field, forexample firstname or lastname or email without doing any change on password field
My model
public function rules()
{
// NOTE: you should only define rules for those attributes that
// will receive user inputs.
return array(
array('username, salt, password, firstname, lastname, email', 'required', 'on' ),
array('superuser, status', 'numerical', 'integerOnly'=>true),
array('username, password, salt', 'length', 'max'=>32),
array('firstname, lastname,image', 'length', 'max'=>80),
array('email', 'length', 'max'=>128),
array('id, username, password, salt, firstname, lastname, email, superuser, status', 'safe', 'on'=>'search'),
);
}
AND in model i have
public function beforeValidate()
{
$this->salt = '1294455567';
return parent::beforeValidate();
}
you can do like this also...
public function beforeSave()
{
if(!$this->getIsNewRecord())
unset($this->password);
return parent::beforeSave();
}
Hope it may help you..
You can use Yii scenarions. For example in your model you has next validation rules:
public function rules()
{
return array(
array('username, salt, password, firstname, lastname, email', 'required', 'on' => 'create'),
array('email, username, firstname, lastname', 'someValidationRuleOrMethod', 'on' => 'update'),
);
}
When you need to create new user, need to set validation scenario:
$model = new User('create');
//some code
$model->validate();
Or:
$model = new User();
$model->scenario = 'create';
//some code
$model->validate();
When you need update exists user - use update scenario instead create:
$model = User::model()->findByPk($someId);
$model->scenarion = 'update';
//some code
$model->validate();
Also, I found this receipt on Russian Yii blog.
UPD You can use static method to hash password, and can call it every where:
public static function hashPassword($password)
{
return CPasswordHelper::hashPassword($password);
}
Create a User model object for single user, then update by assigning new value for field:
...
$user = User::model()->find("`t`.`username` = :USER", array(':USER' => 'example.user'));
$user->firstname = 'New First Name';
$user->lastname = 'New Last Name';
$user->email = 'email#user.new';
# Now update User here
if($user->update()) {
echo 'Updated';
}
...
Hi all what i have done is here....
My controller ::
public function actionUpdate($id){
$model=$this->loadModel($id,'User');
$oldImage = $model->image;
// $old_password = $model->password;
$model->password = '';
// Uncomment the following line if AJAX validation is needed
// $this->performAjaxValidation($model);
if(isset($_POST['User']))
{
$model->attributes=$_POST['User'];
//If image not uploaded then set old image
if(!$this->uploadImage($model)){
$model->image = $oldImage;
}
if($model->save()){
Yii::app()->user->setFlash('success', "Data Updated successfully"); // Flash Message
$this->redirect(array('admin','id'=>$model->user_id));
}
}
$this->render('update',array(
'model'=>$model,
));
}
My Model
public function rules()
{
// NOTE: you should only define rules for those attributes that
// will receive user inputs.
return array(
array('first_name, last_name, password, email,repeat_password', 'required',"on"=>'create'),
array('first_name, last_name, email', 'required',"on"=>'update'),
array('first_name, last_name', 'length', 'max'=>100),
array('password', 'length', 'max'=>30,'min'=>6),
array('repeat_password', 'compare', 'compareAttribute' => 'password', 'message'=>'Confirm Password must be same as password'),
array('email', 'length', 'max'=>50),
array('email', 'unique'),
//array('image', 'file', 'types'=>'jpg, gif, png'),
array('image', 'safe'),
// The following rule is used by search().
// #todo Please remove those attributes that should not be searched.
array('user_id, first_name, last_name, email', 'safe', 'on'=>'search'),
);
}
public function beforeSave(){
if(!empty($this->password))
$this->password = md5($this->password);
else
unset($this->password);
return parent::beforeSave();
}
My View ::
<?php
// If user update profile or update data then don't show password
if( ((#Yii::app()->request->getParam('act')!=="profile") && empty($_GET["id"])) || #$_GET["act"]=='changepwd' )
{
?>
<div class="row">
<?php echo $form->labelEx($model,'password'); ?>
<?php echo $form->passwordField($model,'password',array('maxlength'=>20,'minlength'=>6)); ?>
<?php echo $form->error($model,'password'); ?>
</div>
<div class="row"><!-- Confirm password -->
<?php echo $form->labelEx($model,'Confirm Password'); ?>
<?php echo $form->passwordField($model,'repeat_password',array('maxlength'=>20,'minlength'=>6)); ?>
<?php echo $form->error($model,'repeat_password'); ?>
</div>
<?php } ?>
public function actionUpdate($id) {
$model=$this->loadModel($id);
if(isset($_POST['User']))
{
$password = $model->password;
$model->attributes=$_POST['User'];
if($password === $model->password) {
$model->password = $password;
} else {
$model->password = md5(SALT . $model->password);
}
if($model->save())
$this->redirect(array('view','id'=>$model->id));
}
$this->render('update',array(
'model'=>$model,
));
}
I am creating change password functionality, all things are working fine except the old password validation rule.here is my code
public function rules()
{
return array(
array('is_active', 'numerical', 'integerOnly'=>true),
array('first_name, joining_date,last_name, employee_code, username, password, role', 'required','on'=>array('create')),
array('employee_code', 'numerical', 'integerOnly'=>true),
array('username','email'),
array('username','valid_username','on'=>array('create')),
//array('username', 'contraints', 'readOnly'=>true, 'on'=>'update'),
array('currentPassword, newPassword, newPasswordRepeat', 'required','on'=>array('change')),
//array('newPassword', 'length', 'min' => 6, 'max'=>20, 'message'=>Yii::t("translation", "{attribute} is too short.")),
//array('newPassword','ext.SPasswordValidator.SPasswordValidator', 'preset' => 'strong', 'max' => 41),
array('newPassword', 'compare', 'compareAttribute'=>'newPasswordRepeat','on'=>array('change')),
array('currentPassword', 'equalPasswords','on'=>array('change')),
array('verifyCode', 'captcha', 'allowEmpty'=>!CCaptcha::checkRequirements(),'on'=>array('forgotPassword')),
array('joining_date', 'safe'),
array('user_id, first_name, last_name, employee_code, username, password, role, joining_date, pending_regular_leave, pending_medical_leave, allocated_regular_leave, allocated_medical_leave, is_active', 'safe', 'on'=>'search'),
);
}
My change password function is
public function equalPasswords($attribute, $params)
{
$user = Users::model()->findByPk(Yii::app()->user->id);
if ($user->password != md5($attribute))
{
$this->addError($attribute, 'Old password is incorrect.');
}
}
Update method
:
public function actionChange()
{
$model=new Users;
$model->setScenario('change');
if (isset($_POST['Users'])) {
$model->setAttributes($_POST['Users']);
if($model->validate())
{
$pass = md5($_POST['Users']['newPassword']);
$userModel = Users::model()->findByPk(Yii::app()->user->id);
$userModel->password = $pass;
$data = $userModel->update();
Yii::app()->user->setFlash('success',"Password changed successfully!");
}
}
$this->render('change_password', array('model'=>$model,true));
}
when i try to change password with all the correct parameters (correct old password,new password,retype password) it update the password but also shows me error that your old password does not correct .please help me to resolve this as i am new to Yii.
Thanks in advanced.
I'm not sure but you can try once.
$user = Users::model()->findByPk(Yii::app()->user->id);
if ($user->password != md5($this->attributes['currentPassword']))
{
$this->addError($attribute, 'Old password is incorrect.');
}
change md5($attribute) to md5($this->attributes['currentPassword']
And add this in your rules
public function rules()
{
public $currentPassword;
// your rules here
}
In the validator you receive the attribute name, not the value in $attribute. To get the value you'd have to:
$value = $this->$attribute;
problem defenition
i have one model called 'user.php'
i have some validation rules on the same as follows
i am now going to create a password reset form
in that form i have a text box name email (same email used in user model)
in password reset form i would like to check wheather this user is a registered one if it a registered one will send the password reset link
I DONT KNOW HOW TO VAIDATE THIS EMAIL FIELD , ANY HELP HIGHLY APPRECIABLE AS I AM NEW IN YII
user.php
class Users extends CActiveRecord
{
public $cpassword;
public static function model($className=__CLASS__)
{
return parent::model($className);
}
public function tableName()
{
return 'users';
}
public function rules()
{
// NOTE: you should only define rules for those attributes that
// will receive user inputs.
return array(
array('email, password, user_type , cpassword','required'),
array('email', 'length', 'max'=>200),
array('email', 'unique'),
array('email', 'email'),
array('password', 'length', 'max'=>300),
array('cpassword', 'length', 'max'=>300),
array('user_type', 'length', 'max'=>5),
array('cpassword', 'compare', 'compareAttribute' => 'password'),
// The following rule is used by search().
// Please remove those attributes that should not be searched.
array('id, email, password, user_type ', 'safe', 'on'=>'search'),
);
}
public function relations()
{
return array(
);
}
public function attributeLabels()
{
return array(
'id' => 'ID',
'email' => 'Email',
'password' => 'Password',
'user_type' => 'User Type',
'cpassword' => 'Confirm Password'
);
}
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('email',$this->email,true);
$criteria->compare('password',$this->password,true);
$criteria->compare('user_type',$this->user_type,true);
return new CActiveDataProvider($this, array(
'criteria'=>$criteria,
));
}
public function beforesave()
{
$this->password=md5($this->password);
return true;
}
}
You can check on the submit with something like:
$user = User::model()->find("email = '".trim($model->email)."'");
if (!empty($user)){
// users exists
} else {
// user does not exist
}
If you really want to use the model, you can setup a rule where email must be unique like so:
array('email', 'unique', 'message' => 'Email already in use'),
You can then check if the model validates on the submit, specifically the email field. If it doesnt validate the email address exists
Last, you can validate a single model attribute like so:
if($model->validate(array('attribute_name'))
// valid
}
Here is one way of doing the complete action (not the best way but the easiest to understand!)
public function actionResetpassword(){
$model = new User;
if(isset($_POST['User'])){
$model->attributes = $_POST['User']; // this is the form as completed by the user
$user = User::model()->find("email = '".trim($model->email)."'");
if (!empty($user)){
// send user their new email
$this->render("passwordreset"); // user exists, render confirmtion page
} else {
// user does not exist, render form and pass $error_message variable with messasge
$this->render("resetpassword",array(
"model" => $model,
"error_message" => "No such user found!",
));
}
} else {
// this will be rendered if the user has not submitted the form yet
$this->render("resetpassword",array(
"model" => $model,
));
}
}
public function rules() {
$action = Yii::app()->controller->action->id;
if($action == 'login'){
return array(array('username,password', 'required'), array('password', 'length', 'min'=>6, 'max'=>12), array('rememberMe', 'boolean'), array('password', 'authenticate'), array('id, jsid, email, username, password, status', 'safe', 'on'=>'search'));
}else{
return array( array('oldpassword,password1,password2', 'required'), array('password1,password2, oldpassword', 'length', 'min'=>6, 'max'=>12),array('password1', 'compare', 'compareAttribute'=>'password2'), array('id, jsid, email, username, password, status', 'safe', 'on'=>'search'),);
}
}
When a user registers for my application the following validation rules are called before submission:
public function rules()
{
return array(
array('email, firstName, lastName, password, passwordConfirm, telephone', 'required'),
array('club, email, firstName, lastName, level, password, telephone', 'length', 'max'=>45),
array('passwordConfirm', 'compare', 'compareAttribute'=>'password', 'on'=>'register'),
array('email', 'isUniqueEmailAddress'),
);
}
The first three validation rules complete successfully, but the fourth (a custom validation method) does not. It should call the function 'isUniqueEmailAddress' and perform the following:
/*
* Returns true if there doesn't exist a user in the database with the submitted email
*/
public function isUniqueEmailAddress($attribute, $params)
{
//if (User::model()->find('email=:email', array(':email'=>$this->email)) !== null)
//{
$this->addError('email', 'Email account already exists');
//}
}
As you can see, I've even commented out all logic to simply ensure that a validation error is sent back to the registration form, but no errors are returned on validation(). I've read Yii's Documentation and scoured the forums but cannot understand why my custom validation method is not being called?
I ran into this problem when attempting to set a flash message in a controller after calling $model->save(). It was a code formatting issue which caused a logic error.
For example, in the model I had something like this:
public function validateNumItems($attribute, $params) {
$this->addError($attribute, 'Validate Items Failed');
}
In theory this should have caused the form submission to fail every time for debugging purposes. But it never did.
My controller's update action looked like this:
public function actionUpdate($id) {
$model = $this->loadModel($id);
// Uncomment the following line if AJAX validation is needed
// $this->performAjaxValidation($model);
if (isset($_POST['Collection']))
{
$model->attributes = $_POST['Collection'];
if ($model->save())
Yii::app()->user->setFlash('success', "Data saved!");
$this->redirect(array('index'));
}
$this->render('update', array('model' => $model, ));
}
The missing brackets around the $model->save() test created by Gii caused a logic error when I added new lines. Putting the brackets in place fixed things.
public function actionUpdate($id) {
$model = $this->loadModel($id);
// Uncomment the following line if AJAX validation is needed
// $this->performAjaxValidation($model);
if (isset($_POST['Collection'])) {
$model->attributes = $_POST['Collection'];
if ($model->save()) {
Yii::app()->user->setFlash('success', "Data saved!");
$this->redirect(array('index'));
}
}
$this->render('update', array('model' => $model, ));
}
array('email', 'exist')
like this.
public function rules()
{
return array(
array('email, firstName, lastName, password, passwordConfirm, telephone', 'required'),
array('club, email, firstName, lastName, level, password, telephone', 'length', 'max'=>45),
array('passwordConfirm', 'compare', 'compareAttribute'=>'password', 'on'=>'register'),
array('email', 'exist')
);
}
I commented with some possible reasons your code isn't working (it looks right), but in this case you can just use the Unique validator.
array('email', 'unique') will do it.
try this, it's working fine -
public function rules()
{
return array(
array('email, firstName, lastName, password, passwordConfirm, telephone', 'required'),
array('email', 'email','message'=>"The email isn't correct"),
array('email', 'uniqueEmail'),
);
}
your custom function, write into same model -
public function uniqueEmail($attribute, $params)
{
if($user = User::model()->exists('email=:email',array(':email'=>$this->email)))
$this->addError($attribute, 'Email already exists!');
}