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'];
}
}
Related
I have a form which have add more functionality. user can enter their multiple education. now I want to add a validation rule for the below condition
if user started their first education in 2006 and completed in 2008
then he can not enter second education starting date 2008 or before
that
here are my validation rules
/**
* Validation
*
* #var array
* #access public
*/
public $validate = array(
'degree_type_id' => array(
'notEmpty' => array(
'rule' => 'notEmpty',
'message' => 'This field cannot be left blank.',
'last' => true,
),
'is_unique_degree' => array(
'rule' => 'is_unique_degree',
'message' => 'You have added same course multiple time.',
'last' => true,
),
),
'college_hospital' => array(
'notEmpty' => array(
'rule' => 'notEmpty',
'message' => 'This field cannot be left blank.',
'last' => true,
),
'size' => array(
'rule' => array('maxLength', 255),
'message' => 'This field must be no larger than 255 characters long.'
),
),
'year_passing' => array(
'notEmpty' => array(
'rule' => 'notEmpty',
'message' => 'This field cannot be left blank.',
'last' => true,
),
),
'start_date' => array(
'notEmpty' => array(
'rule' => 'notEmpty',
'message' => 'This field cannot be left blank.',
'last' => true,
),
'dateRule' => array(
'rule' => array('date', 'ymd'),
'message' => 'Enter a valid date in MM/YYYY format.',
'allowEmpty' => true
),
'validateDuration' => array(
'rule' => 'validateDuration',
'message' => 'This field cannot be left blank.',
'last' => true,
),
),
'end_date' => array(
'notEmpty' => array(
'rule' => 'notEmpty',
'message' => 'This field cannot be left blank.',
'last' => true,
),
'dateRule' => array(
'rule' => array('date', 'ymd'),
'message' => 'Enter a valid date in MM/YYYY format.',
'allowEmpty' => true
),
'validateEndDate' => array(
'rule' => 'validateEndDate',
'message' => 'End date should be greater than start date.',
'allowEmpty' => true
)
),
);
This is what I try and got success only for validating future date condition
public function validateDuration() {
$startDate = $this->data['DoctorEducation']['start_date'];
$endDate = $this->data['DoctorEducation']['end_date'];
if (strtotime(date('Y-m-d')) < strtotime($startDate)) {
return __('Education duration will not be future date');
}
if (strtotime(date('Y-m-d')) < strtotime($endDate)) {
return __('Education duration will not be future date');
}
//pr($this->data);
return true;
}
let me know if you want any other information.
Assuming I understood your question correctly, you should have a User model with a hasMany association with DoctorEducation. One approach could be to define in the User model:
var $usedDates = array;
public function beforeValidate($options = array()) {
$this->usedDates = array();
}
then the validation rules for the DoctorEducation model could use it:
public function validateStart( $dataToValidate ) {
foreach($this->ParentModel->usedDates as $usedDate) {
// Perform whatever check you need to ensure periods
// don't overlap and return errors
}
$key = count($this->ParentModel->usedDates);
$this->ParentModel->usedDates[$key]['start_date'] = $dataToValidate['start_date'];
return true;
}
public function validateEnd( $dataToValidate ) {
foreach($this->ParentModel->usedDates as $usedDate) {
// Perform whatever check you need to ensure periods
// don't overlap and return errors
}
$key = count($this->ParentModel->usedDates) - 1;
$this->ParentModel->usedDates[$key]['end_date'] = $dataToValidate['end_date'];
return true;
}
The above assumes you will be saving the User model together with the DoctorEducation model.
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
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'm not sure why I keep receiving all the errors instead of just the invalid fields even when I fill out some of the required fields properly.
Submissions Controller:
public function submit() {
$this->set('title_for_layout', 'Submit - ');
if ($this->request->is('ajax')) {
if (!empty($this->request->data)) {
$this->Submission->set($this->request->data);
if ($this->Submission->invalidFields($this->request->data)) {
$formErrors = $this->Submission->validationErrors;
} else {
$formErrors = null;
}
} else {
$formErrors = null;
}
$this->set(compact('formErrors'));
}
/Submissions/json/submit.ctp:
<?php
$toReturn = array(
'formErrors' => $formErrors
);
echo json_encode($toReturn);
Submission model:
var $validate = array(
'title' => array(
'title' => array(
'rule' => 'notEmpty',
'required' => true,
'allowEmpty' => false,
'message' => 'Please enter a title'
),
'minLength' => array(
'rule' => array('minLength', 5),
'message' => 'Please make your title longer (e.g. IJL John F. Kennedy donated his presidential salary to charity)'
),
'maxLength' => array(
'rule' => array('maxLength', 300),
'message' => 'Your title needs to be shorter'
),
),
'description' => array(
'shortDescription' => array(
'rule' => array('shortDescription'),
'message' => 'Your description needs to be longer'
),
'longDescription' => array(
'rule' => array('longDescription'),
'message' => 'Your description needs to be shorter'
),
),
'source' => array(
'source' => array(
'rule' => 'notEmpty',
'required' => true,
'allowEmpty' => false,
'message' => 'Enter a valid source URL (e.g. http://en.wikipedia.org/wiki/Penguins)'
),
'website' => array(
'rule' => 'url',
'message' => 'Enter a valid source URL (e.g. http://en.wikipedia.org/wiki/Penguins)'
),
),
'category' => array(
'category' => array(
'rule' => 'notEmpty',
'required' => true,
'allowEmpty' => false,
'message' => 'Please choose a category'
)
)
);
Form values that are getting serialized and sent:
Errors I'm getting in a json response:
Pulling hair out over here :|
You seem to have got a little muddle up with validates() and invalidFields()
invalidFields() returns the invalid fields after a validates(), see: http://book.cakephp.org/2.0/en/models/data-validation/validating-data-from-the-controller.html
So your code should look something like this:
$this->Submission->set($this->request->data);
if (!$this->Submission->validates()) {
$formErrors = $this->Submission->invalidFields();
} else {
$formErrors = null;
}
First, set the data to the model:
$this->ModelName->set($this->request->data);
Then, to check if the data validates, use the validates method of the model, which will return true if it validates and false if it doesn’t:
if ($this->ModelName->validates()) {
// it validated logic
} else {
// didn't validate logic
$errors = $this->ModelName->validationErrors;
}
Validating Data from the Controller
This is the model file vechile_enquiry.php
<?php
class VechileEnquiry extends AppModel{
var $name ='VechileEnquiry';
var $validate = array('name' => array
('rule' => 'notEmpty',
'message' => 'Please type name')
);
}
?>
This is the view file vechile.ctp
<?php
echo $this->Form->input('name', array('label'=>false));
?>
At least one phone number is required:
<?php
echo $this->Form->input('mobile_phone', array('label'=>false));
echo $this->Form->input('work_phone', array('label'=>false));
echo $this->Form->input('home_phone', array('label'=>false));
?>
Validation is working in the name field but I'm not getting how to implement validation in mobile_phone,
work_phone, home_phone for the condition that at least one phone number is required.
This should do it for you:
var $validate = array(
'name' => array(
'rule' => 'notEmpty',
'message' => 'Please type name'
),
'mobile_phone' => array(
'check_phone' => array(
'rule' => array('hasPhone'),
'required' => false,
'allowEmpty' => true,
'message' => 'At least one phone number is required.'
)
),
'work_phone' => array(
'check_phone' => array(
'rule' => array('hasPhone'),
'required' => false,
'allowEmpty' => true,
'message' => 'At least one phone number is required.'
)
),
'home_phone' => array(
'check_phone' => array(
'rule' => array('hasPhone'),
'required' => false,
'allowEmpty' => true,
'message' => 'At least one phone number is required.'
)
)
);
function hasPhone($field){
if(!empty($this->data[$this->name]['mobile_phone']) || !empty($this->data[$this->name]['work_phone']) || !empty($this->data[$this->name]['home_phone'])){
return true;
} else {
return false;
}
}