Related
I am trying to "merge" add and edit function so to speak, into one "save" function, which will, whether $id of the model is provided, update or add a new instance of the model. By starting to code this, I realised that this idea brings more complications than built in CakePHP add and edit methods, thing is, my mentor insists that I merge this so I shall try it, even if i personally think this is not the best approach.
ItemTypesController.php
class ItemTypesController extends AppController {
public function save($id = null) {
if($this->request->is(array('post', 'put'))){
$this->ItemType->set($this->request->data);
//if i put an exit() funct here, it exits on this spot
if($this->ItemType->validates()){
if(!$id){
$this->ItemType->create();
if ($this->ItemType->save($this->request->data)) {
$this->Flash->success(__('The item type has been saved.'));
return $this->redirect(array('action' => 'index'));
} else {
$this->Flash->error(__('The item type could not be saved. Please, try again.'));
}
}
else{
if ($this->ItemType->save($this->request->data)) {
$this->Flash->success(__('The item type has been saved.'));
return $this->redirect(array('action' => 'index'));
} else {
$this->Flash->error(__('The item type could not be saved. Please, try again.'));
}
}
} else {
$this->Flash->warning($this->ItemType->validationErrors, array(
'key' => 'negative'
));
}
} else {
$options = array('conditions' => array('ItemType.' . $this->ItemType->primaryKey => $id));
$this->request->data = $this->ItemType->find('first', $options);
}
$this->set('classes', $this->ItemType->classes);
}
}
So basically the function will enter if block if $id is not provided, which is the case if i enter a link for a new ItemType. And it works fine for create, but, when I try to update it it always requires that any field must be changed, because of "isUnique" rule, i set that rule to be only for create, but CakePHP prolly thinks of its create function, albeit here is used my save() funct and it probably thinks it needs to enter that rule for my funct.
ItemType.php
class ItemType extends AppModel {
public $classes = array(
'product' => 'Proizvod',
'kit' => 'Kit (bundle)'
);
public $validate = array(
'code' => array(
'required' => array(
'rule' => 'notBlank',
'message' => 'A code is required'
),
'alphanum' => array(
'rule' => 'alphanumeric',
'message' => 'A code must be an alphanumeric value'
),
'unique' => array(
'rule' => 'isUnique',
'message' => 'This code already exists!',
'required' => 'create'
),
'between' => array(
'rule' => array('lengthBetween', 3, 7),
'message' => 'Code must be between 3 and 7 characters long'
)
),
'name' => array(
'required' => array(
'rule' => 'notBlank',
'message' => 'A name is required'
),
'unique' => array(
'rule' => 'isUnique',
'message' => 'This name already exists!',
'required' => 'create'
),
'between' => array(
'rule' => array('lengthBetween', 3, 30),
'message' => 'Name must be between 3 and 30 characters long'
)
),
'class' => array(
'valid' => array(
'rule' => array('inList', array('product', 'material', 'kit', 'semi_product', 'service_product', 'service_supplier','consumable','inventory','goods','other')),
'message' => 'Please enter a valid class',
'allowEmpty' => false
)
),
'tangible' => array(
'bool' => array(
'rule' => 'boolean',
'message' => 'Incorrect value for the checkbox'
)
),
'active' => array(
'bool' => array(
'rule' => 'boolean',
'message' => 'Incorrect value for the checkbox'
)
)
);
public $hasMany = array(
'Item' => array(
'className' => 'Item',
'foreignKey' => 'item_type_id',
'dependent' => false,
'conditions' => '',
'fields' => '',
'order' => '',
'limit' => '',
'offset' => '',
'exclusive' => '',
'finderQuery' => '',
'counterQuery' => ''
)
);
}
This is the view from which I am entering a new one or updating one:
index.ctp
<div class="itemTypes index">
<h2><?php echo __('Item Types'); ?></h2>
<table cellpadding="0" cellspacing="0">
<thead>
<tr>
<th><?php echo $this->Paginator->sort('id'); ?></th>
<th><?php echo $this->Paginator->sort('code'); ?></th>
<th><?php echo $this->Paginator->sort('name'); ?></th>
<th><?php echo $this->Paginator->sort('class'); ?></th>
<th><?php echo $this->Paginator->sort('tangible'); ?></th>
<th><?php echo $this->Paginator->sort('active'); ?></th>
<th><?php echo $this->Paginator->sort('created'); ?></th>
<th><?php echo $this->Paginator->sort('modified'); ?></th>
<th class="actions"><?php echo __('Actions'); ?></th>
</tr>
</thead>
<tbody>
<?php foreach ($itemTypes as $itemType): ?>
<tr>
<td><?php echo h($itemType['ItemType']['id']); ?> </td>
<td><?php echo h($itemType['ItemType']['code']); ?> </td>
<td><?php echo h($itemType['ItemType']['name']); ?> </td>
<td><?php echo h($itemType['ItemType']['class']); ?> </td>
<td><?php if($itemType['ItemType']['tangible']) echo "Yes"; else echo "No" ?></td>
<td><?php if($itemType['ItemType']['active']) echo "Yes"; else echo "No" ?></td>
<td><?php echo h($itemType['ItemType']['created']); ?> </td>
<td><?php echo h($itemType['ItemType']['modified']); ?> </td>
<td class="actions">
<?php echo $this->Html->link(__('View'), array('action' => 'view', $itemType['ItemType']['id'])); ?>
<?php echo $this->Html->link(__('Edit'), array('action' => 'save', $itemType['ItemType']['id'])); ?>
<?php echo $this->Form->postLink(__('Delete'), array('action' => 'delete', $itemType['ItemType']['id']), array('confirm' => __('Are you sure you want to delete # %s?', $itemType['ItemType']['id']))); ?>
</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
<p>
<?php
echo $this->Paginator->counter(array(
'format' => __('Page {:page} of {:pages}, showing {:current} records out of {:count} total, starting on record {:start}, ending on {:end}')
));
?> </p>
<div class="paging">
<?php
echo $this->Paginator->prev('< ' . __('previous'), array(), null, array('class' => 'prev disabled'));
echo $this->Paginator->numbers(array('separator' => ''));
echo $this->Paginator->next(__('next') . ' >', array(), null, array('class' => 'next disabled'));
?>
</div>
</div>
<div class="actions">
<h3><?php echo __('Actions'); ?></h3>
<ul><li><?php echo $this->Html->link(__('New Item Type'), array('action' => 'save')); ?>
</li>
</ul>
</div>
save.ctp
<div class="itemTypes form">
<?php echo $this->Form->create('ItemType'); ?>
<fieldset>
<legend><?php echo __('Add Item Type'); ?></legend>
<?php
echo $this->Form->input('code');
echo $this->Form->input('name');
echo $this->Form->input('class', array('options' => $classes));
echo $this->Form->input('tangible');
echo $this->Form->input('active');
?>
</fieldset>
<?php echo $this->Form->end(__('Submit')); ?>
</div>
<div class="actions"><h3><?php echo __('Actions'); ?></h3><ul><li><?php echo $this->Html->link(__('List Item Types'), array('action' => 'index')); ?></li></ul></div>
Function save is not coded well, because id of the model was never set, so it did not knew whether it was updating or not.
public function save($id = null) {
if($this->request->is(array('post', 'put'))){
if($id){
$this->request->data['ItemType']['id'] = $id;
}
$this->ItemType->set($this->request->data);
if($this->ItemType->validates()){
if(!$id){
$this->ItemType->create();
}
if ($this->ItemType->save($this->request->data)) {
$this->Flash->success(__('The item type has been saved.'));
return $this->redirect(array('action' => 'index'));
} else {
$this->Flash->error(__('The item type could not be saved. Please, try again.'));
}
} else {
$this->Flash->warning($this->ItemType->validationErrors, array(
'key' => 'negative'
));
}
} else {
$options = array('conditions' => array('ItemType.' . $this->ItemType->primaryKey => $id));
$this->request->data = $this->ItemType->find('first', $options);
}
$this->set('classes', $this->ItemType->classes);}
Now, this is how function should look.
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 a very simple model User, and it's associated table users with fields 'id', 'username', 'password', 'role', 'created', 'modified'.
The view add.ctp contains:
<div class="users form">
<?= $this->Form->create('user'); ?>
<fieldset>
<legend><?= __('Add user');?></legend>
<?= $this->Form->input('user.username'); ?>
<?= $this->Form->input('password'); ?>
<?= $this->Form->input('role', array('options' => array('admin' => 'Admin', 'customer' => 'Customer'))); ?>
</fieldset>
<?= $this->Form->end(__('Submit')); ?>
</div>
The model is set up according to http://book.cakephp.org/2.0/en/tutorials-and-examples/blog-auth-example/auth.html:
class User extends AppModel {
public $validate = array(
'username' => array(
'required' => array(
'rule' => array('notEmpty'),
'message' => 'You must specify a username'
)
),
'password' => array(
'required' => array(
'rule' => array('notEmpty'),
'message' => 'You must specify a password'
)
),
'role' => array(
'valid' => array(
'rule' => array('inList', array('admin','customer')),
'message' => 'You must specify a valid role',
'allowEmpty'=> false
)
)
);
}
And lastly, the controller simply has:
public function add() {
if($this->request->is('post')) {
$this->User->create();
if ($this->User->save($this->request->data)) {
$this->set('stuff', $this->User->data);
$this->Session->setFlash(__('The user has been saved.'));
//return $this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash(__('The user could not be saved. Please try again.'));
}
}
}
I've commented out the redirect on success to be able to show the INSERT query on submit (if I allow the redirect, the only query being shown is SELECT's)
So, quite simple, the problem is, when the form is submitted, it generates this query:
INSERT INTO `mytable`.`users` (`modified`, `created`) VALUES ('2014-02-21 13:03:11', '2014-02-21 13:03:11')
How can I determine why it won't insert the submitted fields? And how can I make it?
use this <?= $this->Form->create('User'); ?> instead of <?= $this->Form->create('user'); ?>
and use this <?= $this->Form->input('User.username'); ?> instead of <?= $this->Form->input('user.username'); ?>
CakePHP is case sensitive model name must be in CamalCase
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();