I am trying to build a section where we can add users with Role_ID=2
Role_ID is in some other table named as User_Details, and is linked with current user table id as foreign key.
Here is code for my UserController.php
function addUser(){
$this->set('setTab','addUser');
$this->set('parent_tab','Manage Users');
$this->set('tab','Add User');
// Super admin doesn't have an access of Manage user section
if($this->Session->read('User.access_rights') == 4){
$this->redirect('dashboard');
}
$this->layout = 'user';
$this->set('setTab','manageUsers');
$this->set('statusArray', $this->statusArray);
/*CREATE USER DROP DOWN ARRAY START*/
/*$userDrop['0']='Select Parent';
$getUsers = $this->User->generatetreelist('User.access_rights <> 4',null,'{n}.User.username','-');
if($getUsers) {
foreach ($getUsers as $key=>$value){
$userDrop[$key] = $value;
}
$this->set(compact('userDrop'));
}*/
/*CREATE USER DROP DOWN ARRAY END*/
if(!$this->Session->check('User')){
$this->redirect('login');
}
if($this->data){
$data = $this->data;
$this->User->set($data);
if ($this->User) {
// pr($this->data); die;
// because we like to send pretty mail
//Set view variables as normal
$this->set('userDetails', $data['User']);
//$this->User->recursive = 1;
if($this->User->saveAll($data)){
$this->Session->setFlash('User added successfully', 'default', array('class' => 'errMsgLogin'));
$this->redirect('manageUsers');
}
else {
echo "User not added";
}
}
else {
// do nothing
}
}
}//Ends here
Here is code for model user.php
<?php
class User extends AppModel{
var $name = "User";
var $validate = array(
'Username' => array(
'notempty' => array(
'rule' => array('notempty'),
'required' => false,
'message' => 'Username can not be empty!',
),
'maxLength'=> array(
'rule' => array('maxLength', 20),
'message' => 'Username can not be longer that 20 characters.'
)
),
'First_Name' => array(
'notempty' => array(
'rule' => array('notempty'),
'message' => 'First name can not be empty!',
)
),
/*'phone' => array(
'numeric' => array(
'rule' => 'numeric',
'message' => 'Numbers only'
),
'rule' => array('minLength', 10),
'message' => 'Phone number should be of 10 digits'
),*/
'Last_Name' => array(
'notempty' => array(
'rule' => array('notempty'),
'message' => 'Last name can not be empty!',
)
),
'Email_Id' => array(
'notempty' => array(
'rule' => array('email'),
'allowEmpty' => false,
'message' => 'Please Enter a valid Email Address'
)
)
/*'status'=> array(
'notempty' => array(
'rule' => array('notEmpty'),
'allowEmpty' => false,
'message' => 'Please Enter a Status'
)
),*/
);
Here is view code add_user.ctp
<h4 class="widgettitle">Add New User</h4>
<div class="widgetcontent">
<?php echo $this->Form->create('User',array('url'=>'addUser/', "enctype" => "multipart/form-data",'class'=>'stdform','id'=>'form1')); ?>
<div class="par control-group">
<label class="control-label" for="firstname">First Name*</label>
<div class="controls">
<?php echo $this->Form->input('First_Name',array('label'=>false, 'id'=>'firstname','class'=>'input-large')); ?>
</div>
</div>
<div class="control-group">
<label class="control-label" for="lastname">Last Name*</label>
<div class="controls">
<?php echo $this->Form->input('Last_Name',array('label'=>false,'id'=>'lastname','class'=>'input-large')); ?>
</div>
</div>
<div class="control-group">
<label class="control-label" for="username">Username*</label>
<div class="controls">
<?php echo $this->Form->input('Username',array('label'=>false,'id'=>'username','class'=>'input-large')); ?>
</div>
</div>
<div class="par control-group">
<label class="control-label" for="email">Email*</label>
<div class="controls">
<?php echo $this->Form->input('Email_Id',array('label'=>false,'id'=>'email','class'=>'input-xlarge')); ?>
</div>
</div>
<div class="par control-group">
<label class="control-label" for="location">Office Phone*</label>
<div class="controls">
<?php echo $this->Form->input('User_Phone1',array('label'=>false, 'maxlength'=>false,'id'=>'phone','class'=>'input-large')); ?>
</div>
</div>
<div class="par control-group">
<label class="control-label" for="location">Cell Phone*</label>
<div class="controls">
<?php echo $this->Form->input('User_Phone2',array('label'=>false, 'maxlength'=>false,'id'=>'phone','class'=>'input-large')); ?>
</div>
</div>
<div class="par control-group">
<label class="control-label" for="status">Status</label>
<div class="controls">
<?php echo $this->Form->input('Is_Active',array('type'=>'select', 'width' => 100, 'options'=>$statusArray, 'label' => false, 'class'=>'input-large')); ?>
</div>
</div>
<p class="stdformbutton">
<button class="btn btn-primary">Save</button>
</p>
<?php echo $this->Form->end(); ?>
</div><!--widgetcontent-->
After adding:
$this->User->bindModel(array('belongsTo'=>array('UserDetail'=>array('className' => 'UserDetail', 'foreignKey' => 'Role_ID', ))));
Got Error in query:
SQL Query: SELECT `User`.`User_ID`, `User`.`First_Name`, `User`.`Last_Name`, `User`.`Email_Id`, `User`.`Username`, `User`.`User_Password`, `User`.`User_Phone1`, `User`.`User_Phone2`, `User`.`Created_By`, `User`.`Created_Date`, `User`.`Is_Active`, `User`.`Is_Deleted`, `UserDetail`.`User_Detail_ID`, `UserDetail`.`User_ID`, `UserDetail`.`Role_ID`, `UserDetail`.`Unit_ID`, `UserDetail`.`Rank_ID`, `UserDetail`.`City_ID`, `UserDetail`.`State_ID`, `UserDetail`.`RSID`, `UserDetail`.`User_Address1`, `UserDetail`.`User_Address2`, `UserDetail`.`Zip_Code`, `UserDetail`.`User_Url`, `UserDetail`.`Created_By`, `UserDetail`.`Created_Date`, `UserDetail`.`Is_Active`, `UserDetail`.`Is_Deleted` FROM `national`.`users` AS `User` LEFT JOIN `national`.`user_details` AS `UserDetail` ON (`User`.`Role_ID` = `UserDetail`.`id`) WHERE 1 = 1 ORDER BY `User`.`User_ID` DESC
Any suggestions on how can I build this?
Please update User model Code :-
User Model User.php
<?php
class User extends AppModel{
var $name = "User";
/**
* Model associations: hasOne
*
* #var array
* #access public
*/
public $hasOne = array(
'UserDetail'
);
var $validate = array(
'Username' => array(
'notempty' => array(
'rule' => array('notempty'),
'required' => false,
'message' => 'Username can not be empty!',
),
'maxLength'=> array(
'rule' => array('maxLength', 20),
'message' => 'Username can not be longer that 20 characters.'
)
),
'First_Name' => array(
'notempty' => array(
'rule' => array('notempty'),
'message' => 'First name can not be empty!',
)
),
/*'phone' => array(
'numeric' => array(
'rule' => 'numeric',
'message' => 'Numbers only'
),
'rule' => array('minLength', 10),
'message' => 'Phone number should be of 10 digits'
),*/
'Last_Name' => array(
'notempty' => array(
'rule' => array('notempty'),
'message' => 'Last name can not be empty!',
)
),
'Email_Id' => array(
'notempty' => array(
'rule' => array('email'),
'allowEmpty' => false,
'message' => 'Please Enter a valid Email Address'
)
)
/*'status'=> array(
'notempty' => array(
'rule' => array('notEmpty'),
'allowEmpty' => false,
'message' => 'Please Enter a Status'
)
),*/
);
}
Then update controller code
Here is code for UserController.php
function addUser(){
$this->set('setTab','addUser');
$this->set('parent_tab','Manage Users');
$this->set('tab','Add User');
// Super admin doesn't have an access of Manage user section
if($this->Session->read('User.access_rights') == 4){
$this->redirect('dashboard');
}
$this->layout = 'user';
$this->set('setTab','manageUsers');
$this->set('statusArray', $this->statusArray);
/*CREATE USER DROP DOWN ARRAY START*/
/*$userDrop['0']='Select Parent';
$getUsers = $this->User->generatetreelist('User.access_rights <> 4',null,'{n}.User.username','-');
if($getUsers) {
foreach ($getUsers as $key=>$value){
$userDrop[$key] = $value;
}
$this->set(compact('userDrop'));
}*/
/*CREATE USER DROP DOWN ARRAY END*/
if(!$this->Session->check('User')){
$this->redirect('login');
}
if($this->data){
$data = $this->data;
$this->User->set($data);
if ($this->User) {
// pr($this->data); die;
// because we like to send pretty mail
//Set view variables as normal
$this->set('userDetails', $data['User']);
//$this->User->recursive = 1;
$data['UserDetail']['Role_ID'] = 2;
if($this->User->saveAll($data)){
$this->Session->setFlash('User added successfully', 'default', array('class' => 'errMsgLogin'));
$this->redirect('manageUsers');
}
else {
echo "User not added";
}
}
else {
// do nothing
}
}
}//Ends here
You can use bindModel functionality for associate or link two table like this
$this->User->bindModel(array('belongsTo'=>array('UserDetail'=>array('className' => 'UserDetail',
'foreignKey' => 'Role_ID',
))));
Now when you find the data of User table than it show the userdetail data also.
You can also use containable behaviour if you want particular field of userdetail model
First check table name of userdetail if your table name like userdetails than you can use class name in bindModel like this Userdetails
if you use the table name like this user_details than put class name like this UserDetails .Can You give a function where you find the user data and use bind model function in particular function .Model should be loaded
Please check table name
Related
I have tutor_students and users table. tutor_studentscontains id, tutor_id, student_id and created. users contain id, user_id, role_id, email, first_name, last_name. tutor_students table is connected table between tutor and student. so tutor can see their student list and can add new student too.
I succeeded to display student list and add new student to tutor student list. but when i want to search student, there will be an error:
Error: SQLSTATE[42S22]: Column not found: 1054 Unknown column
'User.email' in 'where clause'
SQL Query: SELECT TutorStudent.id, TutorStudent.tutor_id,
TutorStudent.student_id, TutorStudent.created FROM
virlen.tutor_students AS TutorStudent WHERE
TutorStudent.tutor_id IS NULL AND User.email LIKE
'%ka#mailinator.com%'
My controller:
public function admin_tutor_add_student($tutor_id = null)
{
$user_list = '';
$this->loadModel('TutorStudent');
$this->set('title_for_layout','User');
$this->User->bindModel(array(
'belongsTo'=>array(
'Standard'=>array(
'className'=>'Standard'
),
)
),false);
$this->User->id = $tutor_id;
/*form post and check conditions*/
// if ($this->request->is('post') || $this->request->is('put'))
if(!empty($this->request->data) && isset($this->request->data['User']['status1']))
{
// pr($this->request->data);die;
$action = $this->request->data['User']['pageAction'];
foreach ($this->request->data['User'] AS $value) {
if ($value != 0) {
$ids[] = $value;
}
}
// pr($ids);die;
if (!empty($this->request->data))
{
if (!isset($this->request->params['_Token']['key']) || ($this->request->params['_Token']['key'] != $this->request->params['_Token']['key']))
{
$blackHoleCallback = $this->Security->blackHoleCallback;
$this->$blackHoleCallback();
}
foreach($ids as $id)
{
if(!empty($id))
{
if($id != 1)
{
$shift = array();
$shift['TutorStudent']['tutor_id'] = $tutor_id;
$shift['TutorStudent']['student_id'] = $id;
$this->TutorStudent->save($shift);
$this->TutorStudent->id = false;
}
}
}
$this->Session->setFlash("Tutor has been added successfully", 'admin_flash_good');
$this->redirect(array('controller'=>'users', 'action'=>'subadmin_tutor',$tutor_id));
}
}
if (!isset($this->params['named']['page']))
{
$this->Session->delete('AdminSearch');
}
$email = '';
$first_name = '';
$role_id = '';
$status = '';
if (!empty($this->request->data))
{
$this->Session->delete('AdminSearch');
if (isset($this->request->data['User']['first_name']) && $this->request->data['User']['first_name'] != '')
{
$first_name = trim($this->request->data['User']['first_name']);
$this->Session->write('AdminSearch.first_name', $first_name);
}
if (isset($this->request->data['User']['email']) && $this->request->data['User']['email'] != '')
{
$email = trim($this->request->data['User']['email']);
$this->Session->write('AdminSearch.email', $email);
}
}
$filters = array('TutorStudent.tutor_id'=>$tutor_id);
if ($this->Session->check('AdminSearch'))
{
$keywords = $this->Session->read('AdminSearch');
foreach($keywords as $key=>$values)
{
if($key == 'email')
{
$email = $values;
$filters[] = array('User.'.$key.' LIKE'=>"%".$values."%");
}
if($key == 'first_name')
{
$first_name = $values;
$filters[] = array('User.'.$key.' LIKE'=>"%".$values."%");
}
}
}
$my_tutor_list = $this->TutorStudent->find('all',array('conditions'=>$filters));
if(!empty($my_tutor_list))
{
foreach($my_tutor_list as $key=>$value)
{
$user_list[] = $value['TutorStudent']['student_id'];
}
}
$this->paginate = array('User' => array(
'limit' =>Configure::read('App.PageLimit'),
'order' => array('User.id' => 'DESC'),
'conditions'=>array('User.id !='=>$user_list,'User.role_id'=>2),
)); //role_id 2 means student user
$student_list = $this->paginate('User');
// pr($student_list);die;
$this->loadModel('Standard');
$standards = $this->Standard->getStandardList();
$this->set(compact('standards'));
$this->set(compact('student_list','tutor_id','standard_id', 'User', 'email', 'first_name'));
$this->set('title_for_layout', __('User', true));
}
this is my view file:
<?php echo($this->Form->create('User', array('url'=>array('controller' => 'users', 'action' => 'tutor_add_student'))));?>
<div class="box-body table-responsive">
<div class="box box-danger">
<div class="full box-header">
<h3 class="box-title">Search</h3>
</div>
<div class="box-body">
<div class="row">
<div class="col-xs-2">
<label for="exampleInputPassword1">User Email</label>
<?php echo($this->Form->input('User.email', array('placeholder'=>"Tutor Email",'label' => false,'value'=>$email, 'div'=>false,'class'=>'form-control'))); ?>
</div>
<div class="col-xs-2">
<label for="exampleInputPassword1">First Name </label>
<?php echo($this->Form->input('User.first_name', array('placeholder'=>"First Name",'label' => false,'value'=>$first_name, 'div'=>false,'class'=>'form-control'))); ?>
</div>
<div class="col-xs-2" style="margin-top: 5px;">
<br /><?php echo($this->Form->submit('Search', array('div'=>false, 'class'=>'btn btn-primary pull-left')));?>
</div>
</div>
</div><!-- /.box-body -->
</div>
</div>
<?php echo($this->Form->end());?>
This is my app model for user:
<?php
/**
* Country
*
* PHP version 5
*
* #category Model
*
*/
// App::uses('AuthComponent', 'Controller/Component');
// App::uses('SessionComponent', 'Controller/Component');
App::uses('AppModel', 'Model');
class User extends AppModel{
//public $primaryKey = '_id';
/**
* Model name
* #var string
* #access public
*/
var $name = 'User';
/**
* Behaviors used by the Model
*
* #var array
* #access public
*/
var $actsAs = array(
'Multivalidatable'
);
var $validationSets = array(
'login'=> array(
'email'=>array(
'notEmpty' => array(
'rule' => 'notEmpty',
'message' => 'Email address is required'
),
'R2'=>array(
'rule'=>array('maxLength', 50),
'message'=>'Email can be maximum 50 characters long.'
),
'email' => array(
'rule' => 'email',
'message' => 'Please provide a valid email address.'
),
),
'password'=>array(
'R1'=>array(
'rule'=>'notEmpty',
'message' => 'Password is required.'
),
'R3'=>array(
'rule'=>array('minLength', 6),
'message'=>'Password must be at least 6 characters long.'
),
'R4'=>array(
'rule'=>array('maxLength', 20),
'message'=>'Password must be at least 20 characters long.'
),
),
),
'add'=> array(
'first_name'=>array(
'R1'=>array(
'rule'=>'notEmpty',
'message' => 'First name is required.'
),
'R2'=>array(
'rule'=>array('maxLength', 255),
'message'=>'First Name can be maximum 255 characters long.'
),
'characters' => array(
'rule' => array('custom', '/^[a-z]*$/i'),
'message' => 'Alphabet characters only'
)
),
'last_name'=>array(
'R1'=>array(
'rule'=>'notEmpty',
'message' => 'Last name is required.'
),
'R2'=>array(
'rule'=>array('maxLength',255),
'message'=>'Last name can be maximum 255 characters long.'
),
'characters' => array(
'rule' => array('custom', '/^[a-z]*$/i'),
'message' => 'Alphabet characters only'
)
),
'standard_id'=>array(
'R1'=>array(
'rule'=>'notEmpty',
'message' => 'Standard is required.'
)
),
'role_id'=>array(
'R1'=>array(
'rule'=>'notEmpty',
'message' => 'Role is required.'
)
),
'specilization'=>array(
'R1' => array(
'rule' => 'notEmpty',
'message' => 'Specilization is required.'
),
'R2'=>array(
'rule'=>array('maxLength', 255),
'message'=>'Specilization can be 255 characters long.'
),
),
'phone'=>array(
'R1' => array(
'rule' => 'notEmpty',
'message' => 'Phone number is required.'
),
'notEmpty' => array(
'rule' => 'numeric',
'message' => 'Phone number should be numeric'
),
'R2'=>array(
'rule'=>array('minLength', 8),
'message'=>'Phone number shuold be minimum 8 numbers long'
),
'R3'=>array(
'rule'=>array('maxLength', 12),
'message'=>'Phone number should be maximum 12 numbers long'
),
/* 'R4'=>array(
'rule'=>array('CheckPhoneVailidation'),
'message'=>'Phone no should be start with 82 to 87.'
), */
),
'email'=>array(
'notEmpty' => array(
'rule' => 'notEmpty',
'message' => 'Email address is required'
),
'R2'=>array(
'rule'=>array('maxLength', 50),
'message'=>'Email can be maximum 50 characters long.'
),
'isUnique' => array(
'rule' => 'isUnique',
'message' => 'Email already exists.'
),
'email' => array(
'rule' => 'email',
'message' => 'Please provide a valid email address.'
),
),
'new_password'=>array(
'R1'=>array(
'rule'=>'notEmpty',
'message' => 'Password is required.'
),
'R3'=>array(
'rule'=>array('minLength', 6),
'message'=>'Password must be at least 6 characters long.'
),
'R4'=>array(
'rule'=>array('maxLength', 20),
'message'=>'Password must be at least 20 characters long.'
),
),
'confirm_password'=>array(
'identicalFieldValues' => array(
'rule' => array('identicalFieldValues', 'new_password'),
'message' => 'Password and confirm password mismatch'
),
'R1' => array(
'rule' => 'notEmpty',
'message' => 'Confirm password is required.'
)
),
'image' => array(
'R1' => array(
'rule' => array('checkextension'),
'message' => 'Please upload only image files'
)
),
)
);
}
You need to contain the User model in your find query:-
$this->TutorStudent->find('all', array(
'conditions' => $filters,
'contain' => array('User')
);
The table User is not included in the query, you should try something like:
SELECT TutorStudent.id, TutorStudent.tutor_id, TutorStudent.student_id, TutorStudent.created
FROM virlen.tutor_students AS TutorStudent join
virlen.User as user
on user.id = tutorstudent.student_id
WHERE TutorStudent.tutor_id IS NULL AND User.email LIKE '%ka#mailinator.com%';
This assuming that the User table key used in tutor_student.student_id is id and not user_id, in which case you should change your code consequently to be it like: on user.user_id = tutorstudent.student_id
the from clause should be
virlen.tutor_students AS TutorStudent,virlen.users AS User
Then your query should be
SELECT TutorStudent.id, TutorStudent.tutor_id, TutorStudent.student_id, TutorStudent.created FROM virlen.tutor_students AS TutorStudent,virlen.users AS User WHERE TutorStudent.tutor_id IS NULL AND User.email LIKE '%ka#mailinator.com%'
Your code should be
$my_tutor_list = $this->TutorStudent->find('all',array('conditions'=>$filters,'contain' => array('User')));
if(!empty($my_tutor_list))
{
foreach($my_tutor_list as $key=>$value)
{
$user_list[] = $value['TutorStudent']['student_id'];
}
}
I'm going through the CakePHP tutorial and trying to test basic login functionality. I'm making slight tweaks along the way to match how my database needs to look (email and token instead of username and password as columns in the users table), I believe that I have messed something up when it comes to using Blowfish hashing. Can someone take a look and see if anything apparent pops out? Right now I can add new users, but their password in the database look to be plaintext. The token column is of type VARCHAR(75), is that enough space for Blowfish to work?
I'm getting the error:
**Warning (512): Invalid salt: pass for blowfish **
and then "Invalid username or password," when putting in a correct user/pass combo. When I put in incorrect credentials I only get the invalid user/pass error, so it looks like it is still getting through somewhere along the line.
app/Model/User.php
App::uses('AppModel', 'Model');
App::uses('BlowfishPasswordHasher', 'Controller/Component/Auth');
class User extends AppModel {
public $validate = array(
'email' => array(
'required' => array(
'rule' => array('notEmpty'),
'message' => 'An email is required'
)
),
'token' => array(
'required' => array(
'rule' => array('notEmpty'),
'message' => 'A password is required'
)
),
'group' => array(
'valid' => array(
'rule' => array('inList', array('user', 'admin', 'manager')),
'message' => 'Please enter a valid group role',
'allowEmpty' => false
)
)
);
public function beforeSave($options = array()) {
if (isset($this->data[$this->alias]['token'])) {
$passwordHasher = new BlowfishPasswordHasher();
$this->data[$this->alias]['token'] = $passwordHasher->hash(
$this->data[$this->alias]['token']
);
}
return true;
}
}
app/Controller/AppController.php
class AppController extends Controller {
//...
public $components = array(
'Session',
'Auth' => array(
'loginRedirect' => array(
'controller' => 'posts',
'action' => 'index'
),
'logoutRedirect' => array(
'controller' => 'pages',
'action' => 'display',
'home'
),
'authenticate' => array(
'Form' => array(
'passwordHasher' => 'Blowfish',
'fields' => array('username' => 'email', 'password' => 'token')
)
)
)
);
public function beforeFilter() {
$this->Auth->allow('index', 'view');
}
//...
}
add.ctp
<div class="users form">
<?php echo $this->Form->create('User'); ?>
<fieldset>
<legend><?php echo __('Add User'); ?></legend>
<?php echo $this->Form->input('email');
echo $this->Form->input('token');
echo $this->Form->input('group', array(
'options' => array('admin' => 'Admin', 'manager' => 'Manager', 'user' => 'User')
));
?>
</fieldset>
<?php echo $this->Form->end(__('Submit')); ?>
</div>
login.ctp
<div class="users form">
<?php echo $this->Session->flash('auth'); ?>
<?php echo $this->Form->create('User'); ?>
<fieldset>
<legend>
<?php echo __('Please enter your username and password'); ?>
</legend>
<?php echo $this->Form->input('email');
echo $this->Form->input('token');
?>
</fieldset>
<?php echo $this->Form->end(__('Login')); ?>
</div>
Check the blowfish salt to make sure it has the correct number of characters, and use the add / edit form to set the password initally.
You should also set the token length in the db to 256 chars
i am new in cakephp.
in View i have 2 form(login and Registration) in both form have email id then how to validate that both from same value in cake php please help and if you have example then please sent that type of information.
First of all define validate function in model
public $validate = array(
'username' => array(
'nonEmpty' => array('rule' => array('notEmpty'),
'message' => 'A username is required',
'allowEmpty' => false),),
'password' => array(
'required' => array(
'rule' => array('notEmpty'),
'message' => 'A password is required' ),
'min_length' => array(
'rule' => array('minLength', '6'),
'message' => 'Password must have a mimimum of 6 characters')),
'password_confirm' => array(
'required' => array(
'rule' => array('notEmpty'),
'message' => 'Please confirm your password' ), ),
'email' => array(
'required' => array(
'rule' => array('email', true),
'message' => 'Please provide a valid email address.' ),
),
);
Then in controller use
function register() {
if( isset($this->data) )
{
$this->User->create();
if($this->User->save($this->data))
{
$this->Session->setFlash( 'Thank you for registering!' );
}else
{
$this->Session->setFlash('An error occurred, try again!');
}
}
}
function login(){
if ($this->request->is('post')) {
$this->User->set($this->request->data);
if ($this->User->validates()) {
echo "This is valid!";
} else {
echo "This is invalid";
$errors = $this->User->validationErrors;
}
}
}
Registration ctp
<div class="users form">
<?php echo $this->Form->create('User');?>
<fieldset>
<legend><?php echo __('Add User'); ?></legend>
<?php echo $this->Form->input('username');
echo $this->Form->input('email');
echo $this->Form->input('password');
echo $this->Form->input('password_confirm', array('label' => 'Confirm Password *', 'maxLength' => 255, 'title' => 'Confirm password', 'type'=>'password'));
echo $this->Form->submit('Add User', array('class' => 'form-submit', 'title' => 'Click here to add the user') ); ?>
</fieldset>
<?php echo $this->Form->end(); ?>
</div>
login.ctp
<div class="users form">
<?php echo $this->Form->create('User');?>
<fieldset>
<legend><?php echo __('Add User'); ?></legend>
<?php echo $this->Form->input('email');
echo $this->Form->input('password');
echo $this->Form->submit('Login'); ?>
</fieldset>
<?php echo $this->Form->end(); ?>
</div>
I have some problem with Cakephp 2 validation.
I am trying to validate several fields on an Edit form. Some of them are a password and confirm password fields.
I want to validate both only if they are supplied. If they are empty I dont change the password, but if the user writes over them I would like to validate if they have a minLength or the passwords matchs.
Code:
'pwd' => array(
'length' => array(
'rule' => array('between', 8, 40),
'message' => 'Your password must be between 8 and 40 characters.',
'allowEmpty' => true
),
),
'pwd_repeat' => array(
'length' => array(
'rule' => array('between', 8, 40),
'message' => 'Your password must be between 8 and 40 characters.',
'allowEmpty' => true
),
'compare' => array(
'rule' => array('validate_passwords'),
'message' => 'The passwords you entered do not match.',
'allowEmpty' => true
),
I dont know if I have to define some rules on edit() function in the controller or it should be enough, but my code is not working.
Thanks!
Edit: (Controller Code)
public function edit($id = null) {
if (!$this->User->exists($id)) {
throw new NotFoundException(__('Usuario incorrecto'));
}
if ($this->request->is('post') || $this->request->is('put')) {
if ($this->User->save($this->request->data)) {
$this->Session->setFlash(__('El usuario ha sido actualizado.'));
return $this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash(__('El usuario no ha podido actualizarse. Por favor, inténtelo de nuevo.'));
}
unset($this->request->data['User']['pwd']);
unset($this->request->data['User']['pwd_repeat']);
} else {
$options = array('conditions' => array('User.' . $this->User->primaryKey => $id));
$this->request->data = $this->User->find('first', $options);
}
$roles = $this->User->Role->find('list');
$this->set(compact('roles'));
}
(View Code)
<div id="contenedor" class="users form">
<?php echo $this->Form->create('User', array('name' => 'form')); ?>
<fieldset>
<legend><?php echo __('Editar Usuario'); ?></legend>
<?php
echo $this->Form->input('id');
echo $this->Form->input('username', array('label' => __('Usuario')));
echo $this->Form->input('pwd', array('label' => __('Contraseña'), 'type' => 'password', 'name' => 'pass', 'onKeyUp' => 'habilita()', 'value' => ''));
echo $this->Form->input('pwd_repeat', array('label' => __('Repite Contraseña'), 'type' => 'password', 'name' => 'rpass', 'disabled' => 'disabled'));
echo $this->Form->input('firstname', array('label' => __('Nombre')));
echo $this->Form->input('lastname', array('label' => __('Apellidos')));
echo $this->Form->input('telephone', array('label' => __('Teléfono')));
echo $this->Form->input('email', array('label' => __('Email')));
echo $this->Form->input('role_id', array('label' => __('Rol')));
?>
</fieldset>
<?php echo $this->Form->end(__('Aceptar')); ?>
Make the validation rules like this
'pwd' => array(
'length' => array(
'rule' => array('between', 8, 40),
'message' => 'Your password must be between 8 and 40 characters.',
),
),
'pwd_repeat' => array(
'length' => array(
'rule' => array('between', 8, 40),
'message' => 'Your password must be between 8 and 40 characters.',
),
'compare' => array(
'rule' => array('validate_passwords'),
'message' => 'The passwords you entered do not match.',
)
)
And your validate_passwords function should be like this.
public function validate_passwords() {
return $this->data[$this->alias]['pwd'] === $this->data[$this->alias]['pwd_repeat']
}
I am new to CakePHP. When I am using Model Field Validations then it is showing error message infront of each required form field. I want to show it in a div at the top of the form. How I can implement it. Thanks in advance.
Here is my Code:
Model:
<?php
class User extends AppModel {
public $validate = array(
'username' => array(
'required' => array(
'rule' => array('notEmpty'),
'message' => 'A username is required'
),
array(
'rule' => array('minLength', 8),
'message' => 'Username must be at least 6 characters long'
)
),
'password' => array(
'required' => array(
'rule' => array('notEmpty'),
'message' => 'A password is required'
)
),
'city' => array(
'required' => array(
'rule' => array('notEmpty'),
'message' => 'A City is required'
)
),
'state' => array(
'required' => array(
'rule' => array('notEmpty'),
'message' => 'A State is required'
)
),
'role' => array(
'valid' => array(
'rule' => array('inList', array('admin', 'author')),
'message' => 'Please enter a valid role',
'allowEmpty' => false
)
)
);
}
UsersController.php
public function add() {
$this->set('states_options', $this->State->find('list', array('fields' =>array('id','name') )));
$this->set('cities_options', array());
if ($this->request->is('post')) {
$this->User->set($this->request->data);
if($this->User->validates())
{
$this->User->create();
if ($this->User->save($this->request->data)) {
$this->Session->setFlash(__('The user has been saved'));
$this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash(__('The user could not be saved. Please, try again.'));
}
}
else {
$errors = $this->User->validationErrors;
$this->set('ValidateAjay',$errors);
//pr($errors);die;
}
}
}
User View:
<!--<script src="http://code.jquery.com/jquery-1.7.2.js"></script>-->
<script>
$(document).ready(function(){
$('#UserState').change(function(){
var stateid=$(this).val();
$.ajax({
type: "POST",
url: "checkcity",
data:'stateid='+stateid+'&part=checkcity',
success: function(data) {
$("#city_div").html(data);
}
});
});
});
</script>
<div class="users form">
<?php
if(!empty($ValidateAjay)){
pr($ValidateAjay);
}
echo $this->Form->create('User'); ?>
<fieldset>
<legend><?php echo __('Add User'); ?></legend>
<?php
echo $this->Form->input('username');
echo $this->Form->input('password');
echo $this->Form->input('state', array('options' => $states_options , 'empty' => 'Select State' ));
?>
<div id="city_div">
<?php
echo $this->Form->input('city', array('options' => $cities_options, 'empty' => 'Select City' ));
?>
</div>
<?php
echo $this->Form->input('role', array(
'options' => array('admin' => 'Admin', 'author' => 'Author')
));
?>
</fieldset>
<?php echo $this->Form->end(__('Submit')); ?>
</div>
You can get all validation errors from the $this->validationErrors variable on the view. Then feel free to iterate through them and display as you like. They will be organized by model, like so:
array(
'User' => array(
'username' => 'This field cannot be empty.',
'password' => 'This field cannot be empty.'
)
);
Then you can iterate through them on the view and display them as such. This example displays them as an unordered list:
$errors = '';
foreach ($this->validationErrors['User'] as $validationError) {
$errors .= $this->Html->tag('li', $validationError);
}
echo $this->Html->tag('ul', $errors);
Lastly, you can hide the form helper's automatic error messages by hiding them with CSS or setting the FormHelper defaults to not show them.
CSS
.input.error {
display: none;
}
or
in the view
$this->Form->inputDefaults(array(
'error' => false
));
jeremyharris example makes a lot of sense, however if you don't want to manually set loop for every form field, you can try this:
$errors = '';
foreach($this->validationErrors as $assoc) {
foreach ($assoc as $k => $v) {
$errors .= $this->Html->tag('li', $v);
}
}
echo $this->Html->tag('ul', $errors);
So if your validation returns multiple errors, the output will looks like this:
- A username is required
- A password is required
Though this is a very old post, I'd like to answer my solution here as well.
To get Errors of Model Validations, just use the $model->getErrors();. This will return an array of errors with field key.
Example
$errors = $user->getErrors();