I need display error message when user register end he input email which exist.I try this in my view:
<?php echo $form->errorSummary($model, NULL, NULL, array("class" => "standard-error-summary")); ?>
and this
if($model->hasErrors())
echo CHtml::errorSummary($model);
But it doesn't work.
There is my rules method of User model
public function rules()
{
return array(
array('status', 'numerical', 'integerOnly'=>true),
array('first_name, last_name, email, password', 'length', 'max'=>255),
array('email', 'unique', 'className' => 'User', 'attributeName' => 'email', 'message'=>'This Email is already in use'),
array('id, status, first_name, last_name, email, password', 'safe', 'on'=>'search'),
);
}
RegistrationForm Model:
public function rules()
{
return array(
array('first_name, repeat_password, last_name, password,email', 'required'),
array('email', 'email'),
array('password', 'compare','compareAttribute'=>'repeat_password'),
);
}
and my register action:
public function actionRegister()
{
$model = new RegistrationForm;
if(isset($_POST['RegistrationForm']))
{
$model->attributes = $_POST['RegistrationForm'];
if($model->validate())
{
$user = new User;
$user->first_name = $model->first_name;
$user->last_name = $model->last_name;
$user->password = $model ->password;
$user->email = $model->email;
$user->save();
}
}
$this->render('register',array('model'=>$model));
}
Such as you validate RegistrationForm model, you must have unique rule in it (not onlu in User model). So you can add this rule in your RegistrationForm model too:
public function rules()
{
return array(
array('first_name, repeat_password, last_name, password,email', 'required'),
array('email', 'email'),
// THIS RULE CHECKS EMAIL UNIQUE IN RegistrationForm MODEL
array('email', 'unique', 'className' => 'User', 'attributeName' => 'email', 'message'=>'This Email is already in use'),
array('password', 'compare','compareAttribute'=>'repeat_password'),
);
}
So not not necessary to add custom rule.
Thanks!
I found solution. I added this method in my RegisterationForm Model
public function uniqueEmail($attribute, $params)
{
if($user = User::model()->exists('email=:email',array('email'=>$this->email)))
$this->addError($attribute, 'Email already exists!');
}
and added
array('email', 'uniqueEmail','message'=>'Email already exists!'),
to the rules method
Related
I am new to yii1. In my project ,I have used TblExtendedGridView to display data in the table .The form shows the data in my local computer.But when the project is uloaded in server,the file is blank and doesnot show any error.
What is the problem?
'<?php
$uniqid=md5(uniqid());
$this->widget('bootstrap.widgets.TbExtendedGridView', array(
'id'=>'marketing-grid',
'dataProvider'=>$model->search(),
'filter'=>$model,
'type' => 'striped bordered',
'type' => 'striped bordered condensed',
'columns'=>array(
array(
'header'=>'#',
'value'=>'$this->grid->dataProvider->pagination->currentPage * $this->grid->dataProvider->pagination->pageSize + ($row+1)',
),
array(
'name'=>'client_id',
'header'=>'Company',
'value'=>'$data->clientName->client_name',
'htmlOptions' => array('style'=>'width:200px'),
),
array(
'name'=>'client_contact_id',
'header'=>'Contacted',
'value'=>'$data->contactPerson->contact_name',
'htmlOptions' => array('style'=>'width:180px'),
),
array(
'name'=>'visited_date',
'header'=>'Visit Date',
'htmlOptions' => array('style'=>'width:100px'),
),
array(
'name'=>'possibility',
'header'=>'Probability',
'htmlOptions' => array('style'=>'width:100px'),
),
'remarks',
array(
'name'=>'next_visited_date',
'header'=>'Next Contact Date',
'htmlOptions' => array('style'=>'width:100px'),
),
array(
'name'=>'follow_up_by',
'header'=>'Follow Up By',
'value'=>'$data->followPerson->user_name',
'htmlOptions' => array('style'=>'width:180px'),
),
),
),
),
)); ?>'
'My controller is:
<?php
class MarketingController extends Controller
{
public $layout='//layouts/column1';
public function actionIndex()
{
$this->actionAdmin();
}
// Uncomment the following methods and override them if needed
public function filters()
{
return array(
'accessControl', // perform access control for CRUD operations
'postOnly + delete', // we only allow deletion via POST request
);
}
public function accessRules()
{
return array(
array('allow', // allow all users to perform 'index' and 'view' actions
'actions'=>array('index','view','DynamicContact'),
'users'=>array('*'),
),
array('allow', // allow authenticated user to perform 'create' and 'update' actions
'actions'=>array('admin','delete','create','update','DynamicContact'),
'users'=>array('#'),
),
array('allow', // allow admin user to perform 'admin' and 'delete' actions
'actions'=>array('admin','delete','DynamicContact'),
'users'=>array('admin','#'),
),
array('deny', // deny all users
'users'=>array('*'),
),
);
}
protected function performAjaxValidation($model)
{
if(isset($_POST['ajax']) && $_POST['ajax']==='marketing-form')
{
echo CActiveForm::validate($model);
Yii::app()->end();
}
}
public function actionView($id)
{
EQuickDlgs::render('view',array('model'=>$this->loadModel($id)));
}
public function actionAdmin()
{
$model=new Marketing('search');
$model->unsetAttributes(); // clear any default values
if(isset($_GET['Marketing']))
$model->attributes=$_GET['Marketing'];
$this->render('admin',array(
'model'=>$model,
));
}
public function actionCreate()
{
$model=new Marketing;
// Uncomment the following line if AJAX validation is needed
$this->performAjaxValidation($model);
if(isset($_POST['Marketing']))
{
$model->attributes=$_POST['Marketing'];
//print_r($_POST['User']);
//die;
if($model->save())
{
EQuickDlgs::checkDialogJsScript();
$this->redirect(array('marketing/admin','id'=>$model->marketing_id));
}
}
EQuickDlgs::render('create',array(
'model'=>$model,
));
}
public function loadModel($id)
{
$model=Marketing::model()->findByPk($id);
if($model===null)
throw new CHttpException(404,'The requested page does not exist.');
return $model;
}
public function actionUpdate($id)
{
$model=$this->loadModel($id);
// Uncomment the following line if AJAX validation is needed
// $this->performAjaxValidation($model);
if(isset($_POST['Marketing']))
{
$model->attributes=$_POST['Marketing'];
if($model->save())
{
//$this->redirect(array('view','id'=>$model->user_id));
EQuickDlgs::checkDialogJsScript();
$this->redirect(array('marketing/admin','id'=>$model->marketing_id));
}
}
EQuickDlgs::render('update',array(
'model'=>$model,
));
}
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'));
}
}'
'And Model is :
<?php
class Marketing extends PMActiveRecord
{
/**
* #return string the associated database table name
*/
public function tableName()
{
return 'pm_mar_marketing';
}
public function rules()
{
return array(
array('client_id, client_contact_id, follow_up_by, visited_date, visit_type, next_visited_date, possibility, remarks', 'required'),
array('client_id, client_contact_id, follow_up_by, visit_type, crtd_by, updt_by, updt_cnt', 'numerical', 'integerOnly'=>true),
array('possibility', 'length', 'max'=>20),
// The following rule is used by search().
// #todo Please remove those attributes that should not be searched.
array('marketing_id, client_id, client_contact_id, follow_up_by, visited_date, visit_type, next_visited_date, possibility, remarks', 'safe', 'on'=>'search'),
);
}
public function relations()
{
return array(
'clientName' => array(self::BELONGS_TO, 'Client', 'client_id'),
'contactPerson' => array(self::BELONGS_TO, 'ClientContact', 'client_contact_id'),
'followPerson' => array(self::BELONGS_TO, 'User', 'follow_up_by'),
'visitType' => array(self::BELONGS_TO, 'CodeValue', 'visit_type')
);
}
/**
* #return array customized attribute labels (name=>label)
*/
public function attributeLabels()
{
return array(
'marketing_id' => 'Marketing',
'client_id' => 'Client',
// 'client_id'=> 'Client',
'client_contact_id' => 'Contact Person',
//'client_contact_id' => 'Contact Person',
'follow_up_by' => 'Follow Up By',
'visited_date' => 'Visited Date',
'visitType.code_lbl' => 'Visit Type',
'next_visited_date' => 'Next Contact Date',
'possibility' => 'Probability',
'remarks' => 'Remarks',
'crtd_by' => 'Crtd By',
'crtd_dt' => 'Crtd Dt',
'updt_by' => 'Updt By',
'updt_dt' => 'Updt Dt',
'updt_cnt' => 'Updt Cnt',
);
}
public function search()
{
// #todo Please modify the following code to remove attributes that should not be searched.
$criteria=new CDbCriteria;
$criteria->with = array('clientName','contactPerson','followPerson');
$criteria->compare('marketing_id',$this->marketing_id);
$criteria->compare('clientName.client_name',$this->client_id,true);
$criteria->compare('contactPerson.contact_name',$this->client_contact_id,true);
$criteria->compare('followPerson.user_name',$this->follow_up_by,true);
$criteria->compare('visited_date',$this->visited_date,true);
//$criteria->compare('visit_type',$this->visit_type);
$criteria->compare('next_visited_date',$this->next_visited_date,true);
$criteria->compare('possibility',$this->possibility,true);
$criteria->compare('remarks',$this->remarks,true);
$criteria->compare('crtd_by',$this->crtd_by);
$criteria->compare('crtd_dt',$this->crtd_dt,true);
$criteria->compare('updt_by',$this->updt_by);
$criteria->compare('updt_dt',$this->updt_dt,true);
$criteria->compare('updt_cnt',$this->updt_cnt);
//$criteria -> join = 'INNER JOIN pm_marketing_user followPerson on t.follow_up_by= followPerson.user_id';
return new CActiveDataProvider($this, array(
'criteria'=>$criteria,
));
}
public static function model($className=__CLASS__)
{
return parent::model($className);
}
}
'
If This happend only whit this view check for the lowercase/uppercase of the class code file (Marketing.php i guess)
If your development enviroment is windows and your produdction enviroment is Unix like, can happen yuo have marketing.php in your model and you referer to Marketing.php or to the contrary this work in windows/dos because in case insentisitve but not in Unix like O.S.
I have set up my website so only add and login are only accessible before the user log in. And when he log in, he is redirected to the home page.
But when the user tries to log in, the login page refreshes and it shows this message "Username or password is incorrect" which is from the action login of my controller.
I verified and it's "$this->Auth->login()" which is not working.
In my database, i used these fields for the user table: id, password, nom, prenom, username.
Here is the login function code from my controller UsersController:
public function login()
{
if ($this->request->is('post'))
{
if ($this->Auth->login())
{
return $this->redirect($this->Auth->redirectUrl());
}
else
{
$this->Session->setFlash(__('Username or password is incorrect'));
}
}
}
Here is the login view code:
<?php
echo $this->Session->flash('auth');
echo $this->Form->create('User');
echo $this->Form->input('username', array('label' => 'Votre pseudo: '));
echo $this->Form->input('password', array('label' => 'Votre mot de passe: '));
echo $this->Form->end('Se connecter');
?>
Here is User model code:
<?php
App::uses('AppModel', 'Model');
App::uses('SimplePasswordHasher', 'Controller/Component/Auth');
class User extends AppModel
{
public $hasMany = array('Compte','ComptesUtilisateur');
public function beforeSave($options = array()) {
Security::setHash('md5');
if(isset($this->data[$this->alias]['password']))
{
$passwordHasher= new SimplePasswordHasher();
$this->data[$this->alias]['password'] = $passwordHasher->hash($this->data[$this->alias]['password']);
}
return true;
}
}
?>
And here AppController.php code:
class AppController extends Controller {
var $components = array(
'Auth' => array(
'authError' => "Etes-vous sûr(e) d'avoir l'autorisation pour y accéder?",
'loginError' => "Votre pseudo ou votre mot de passe est incorrect",
'loginAction' => array(
'controller' => 'users',
'action' => 'login'
),
'loginRedirect' => array('controller' => 'pages', 'action' => 'home'),
'logoutRedirect' => array('controller' => 'users', 'action' => 'login'),
'authenticate' => array(
'Form' => array(
'fields' => array(
'username' => 'username',
'password' => 'password'
),
'passwordhasher' => array(
'className' => 'Simple',
'hashType' => 'md5'
)
)
)
),
'Session'
);
public function beforeFilter()
{
$this->Auth->allow('login');
}
public function beforeRender()
{
$this->set('auth', $this->Auth->loggedIn());
}
}
I searched the solution on forums but i found nothing.
Any indication?
Thanks,
Louberlu.
What i'm doing wrong?
<?php
public function login() {
$user_name = time();
User::create(array(
'name' => $user_name,
'email' => $user_name.'#test.com',
'password' => Hash::make('123123'),
));
$user = array(
'email' => $user_name.'#test.com',
'password' => '123123',
);
$m = User::where('email' , '=', $user_name.'#test.com')->first();
dd([
'Auth::attempt($user)',
Auth::attempt($user),
'Auth::check()',
Auth::check(),
'Hash::check($m->password, \'123123\')',
Hash::check($m->password, '123123')
]);
}
Result:
array(6) {
[0]=>
string(20) "Auth::attempt($user)"
[1]=>
bool(false)
[2]=>
string(13) "Auth::check()"
[3]=>
bool(false)
[4]=>
string(38) "Hash::check($user->password, '123123')"
[5]=>
bool(false)
}
Not sure what information should I add.
app/config/auth.php
'driver' => 'eloquent',
'model' => 'User',
'table' => 'users',
app/config/app.php
'key' => 'DMmiPAxSYz4O2jG44S92OcdPZN7ZsGGs',
'cipher' => MCRYPT_RIJNDAEL_256,
models/User.php
<?php
use Illuminate\Auth\UserTrait;
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableTrait;
use Illuminate\Auth\Reminders\RemindableInterface;
class User extends Eloquent implements UserInterface, RemindableInterface {
use UserTrait, RemindableTrait;
/**
* Validation rules
*/
public static $rules = array(
'name' => 'required',
'email' => 'email|required|unique',
'password' => 'min:6',
);
/**
* Validation rules
*/
public static $messages = array(
'name.required' => 'The name field is required',
'email.email' => 'The email field must contain properly formatted email.',
'email.required' => 'The email field is required',
'password.required' => 'The password field is required',
'password.min:6' => 'The password must be minimum 6 characters long',
);
protected $table = 'users';
protected $hidden = array('password', 'remember_token');
protected $guarded = array('id');
public function setPasswordAttribute($value) {
if ($value) {
$this->attributes['password'] = Hash::make($value);
}
}
}
Well here's some checks that you can do
Have you setup config/auth.php with driver, model and table?
Have you filled the fillable array of the User's model?
Have you change the key inside config/app.php ?
Also try to dd($m) in order to see what you got from that query.
I found what is wrong.
This part of code hash password for first time:
User::create(array(
'name' => $user_name,
'email' => $user_name.'#test.com',
'password' => Hash::make('123123'), // <---- first time
));
And this mutator in User model does hashing for second time before put password to database:
public function setPasswordAttribute($value) {
if ($value) {
$this->attributes['password'] = Hash::make($value); // <---- second time
}
}
So I just changed first block to this:
User::create(array(
'name' => $user_name,
'email' => $user_name.'#test.com',
'password' => '123123', // <---- no hashing here
));
In the registration form, used password field and confirm password field. After using this data cannot be updated.
Model
public function rules()
{
// NOTE: you should only define rules for those attributes that
return array(
array('name, password', 'required'),
array('password', 'compare', 'compareAttribute'=>'confirm_password'),
array('name', 'length', 'max'=>55),
// The following rule is used by search().
// Please remove those attributes that should not be searched.
array('id, name', 'safe', 'on'=>'search'),
);
}
Trying to update user model from index.php
`$post= User::model()->findByPk(1); $post->name='Abcdef'; $post->password='newpassword'; $post->save();`
The new data not updated? when it solve?
The update won't work because the confirmpassword has not been set. If the password is not required on update include a scenario for the password else it will always be checked.
public function rules()
{
// NOTE: you should only define rules for those attributes that
return array(
array('name', 'required'),
array('password', 'required','on'=>'create'),
array('password', 'compare', 'compareAttribute'=>'confirmpassword','on'=>'create'),
array('name', 'length', 'max'=>55),
// The following rule is used by search().
// Please remove those attributes that should not be searched.
array('id, name', 'safe', 'on'=>'search'),
);
public $confirmpassword;
public function rules()
{
// NOTE: you should only define rules for those attributes that
return array(
array('name, password, confirmpassword', 'required'),
array('password', 'compare', 'compareAttribute'=>'confirmpassword'),
array('name', 'length', 'max'=>55),
// The following rule is used by search().
// Please remove those attributes that should not be searched.
array('id, name', 'safe', 'on'=>'search'),
);
}
validation code is
return array(
array('firstname, lastname, confirm_email, education, email, password, occupation,location , birthdate, interest,gender,created, modified', 'required'),
array('email', 'email'),
array('password', 'length', 'max'=>20, 'min' => 5,'message' => "Incorrect fi (length between 5 and 20 characters)."),
array('firstname', 'match', 'pattern' => '/^[A-Za-z0-9_]+$/u','message' => UserModule::t("Incorrect symbols (A-z0-9).")),
array('email', 'unique'),
);
You may make your email unique in yii user model by the following rule as given in below.
public function rules() {
return array(
...
array('email', 'email'),
array('email', 'unique', 'className' => 'User',
'attributeName' => 'email',
'message'=>'This Email is already in use'),
...
); }
Here className is the name of your user model class, attributeName is your db email field name.
You may also check the below link.
http://www.yiiframework.com/forum/index.php/topic/32786-creating-my-own-model-cmodel-not-cactiverecord/
Thanks
public function rules()
{
return array(
...
array('email', 'email'),
array('email', 'unique'),
...
);
}
Try this:
As per your given code, It seems ok
You can verify using this url about validation:
http://www.yiiframework.com/doc/guide/1.1/en/form.model#declaring-validation-rules