Cakephp validations not working - cakephp

Validations are working but form is not getting submitted and data is not inserted:
addgroup.ctp:
echo $form->create('Group', array('url' => array('controller' => 'admin', 'action' =>'addgroup'), 'onSubmit' => 'return Validate()'));
echo $form->input('name',array('label' => false));
<input type="submit" value="Submit"/>
<input type="button" value="Cancel"/>
Group Model:
var $validate = array(
'name' => array(
'isRequired' => array(
'rule' => 'required',
'message' => 'Enter group name.'
),
'isUnique' => array(
'rule' => 'isUnique',
'message' => 'This group name has already been taken.'
),
),
);
in controller:
$this->Group->save($this->data,array('validate' => true)
If I make any empty entry or duplicate entry it gives errormessge,
but if I make valid entries then also form gives error-message,
What m I missing here?

you need to close the form $this->Form->end('Submit'); and the save function: $this->Group->save($this->data); It will validate when it saves.

Related

how to inserting dynamic input fields value into mysql table using cakephp2.8.5

Please anyone help me, Thanks in advance,I am new to Cakephp. I am using Cakephp 2.8.5 version. In my project I have a form where I am selecting user from a combobox. On selecting user, below text boxes with Course name and price text boxes will appear. This is done through jquery.
But my problem is how to insert username,course name and price into mysql database as example
column 1 | column2 | column 3
ragith ITIL Foundation, CAPM $200,$400
My view page is add_price.ctp
Inside this page where you will find
<div class="form-group" id="divprice">
</div> where the Course name and Price textboxes are displaying through jquery
My full view page as below
<head>
<?php echo $this->Html->script('jquery.js'); ?>
<script>
$(document).ready(function(){
$('#user').change(function(){
var nameIdVal = $(this).val();
$.ajax({
type: "POST",
url: '/invl_exams/userprice',
cache: "false",
data: {userid:nameIdVal},
success : function(result){
//alert(result);
$('#divprice').html(result);
}
});
});
});
// using Ajax serialize to insert into DB
$(document).ready(function(){
$('.btn').click(function(event){
event.preventDefault();
$.ajax({
method: "POST",
url: "/invl_exams/submitprice",
cache: "false",
data: $('#addPriceForm').serialize(),
dataType: "text",
success: function(strMessage){
//alert(strMessage);
//console.log(strMessage);
//$('#msg').html(strMessage);
},
error: function(strMessage){
//alert('error');
console.log('error');
}
});
clearData();
});
});
function clearData()
{
$('#addPriceForm :input').each(function(){
$(this).val('');
});
}
</script>
</head>
<body>
<div id="content">
<div class="col-md-3">
<div id="msg"></div>
<form class="form-horizontal" role="form" accept-charset="utf-8" method="post" id="ExamAddExamForm" action="/invl_exams/users/priceSubmit">
<div style="display:none;"><input type="hidden" value="POST" name="_method"></div>
<div class="form-group">
<label for="ExamUsername">Users</label>
<select class="form-control" required="required" id="user" name="data[Exam][userid][]">
<option value="">-- Select --</option>
<?php foreach($users as $username): ?>
<option value="<?php echo $username['users']['id']?>"><?php echo $username['users']['username']?>
</option>
<?php endforeach; ?>
</select>
<label id="ExamUsername-error" class="error" for="ExamUsername"></label>
</div>
<!--On selecting username showing the Courses with price textboxes in this id here -->
<div class="form-group" id="divprice">
</div>
<div class="form-group">
<button class="btn btn-default">Submit</button>
</div>
</form>
</div><br class="clearall">
</div>
</body>
routes.php
Router::connect('/userprice', array('controller' => 'users', 'action' => 'showprice'));
Router::connect('/submitprice', array('controller' => 'users', 'action' => 'price_submit'));
Controller Page is UsersController.php
<?php
App::uses('CakeEmail', 'Network/Email');
class UsersController extends AppController
{
public function showprice()
{
$this->loadModel('Exam');
$id = $_POST['userid'];
//echo $id;
//die();
if($id!=0)
{
$allPrice = $this->Exam->query("select * from exams where username = $id");
$total_price = $allPrice[0]['exams']['exam'];
$price = explode(',',$total_price);
//This table will be displayed after selecting the user from combobox
echo "<table class='tblrow' width='450px'>";
for($i=0;$i<count($price);$i++)
{
//echo $price[$i];
echo "<tr>";
echo "<td><b>Course:</b><input type='' name='course[]' value='$price[$i]'></td>";
echo "<td><b>Price:</b><input type='text' name='price[]' value=''></td>";
echo "</tr>";
echo "<tr><td> </td></tr>";
}
echo "</table>";
}
else
{
echo "No results found";
}
die();
}
// This function is for inserting into the Mysql database table
public function price_submit()
{
// print_r($_POST);
if(isset($_POST['data']))
{
$this->loadModel('Price');
$priceData = $_POST['data'];
$this->Price->create();
if($this->Price->save($priceData))
{
echo "Data added successfully";
}
}
$this->loadModel('User');
//$userData = $this->User->find('all');
$userData = $this->User->query("select * from users where id!= 15 and id!= 8");
$this->set('users',$userData);
}
}
Model page is User.ctp
<?php
//App::uses ('AppModel','Model');
class User extends AppModel{
public $validate = array(
'username' => array(
'required' => array(
'rule' => 'notBlank',
'message' => 'Username is required'
),
'isUnique' => array(
'rule' => 'isUnique',
'message' => 'This username has already been taken')
),
'password' => array(
'required' => array(
'rule' => 'notBlank',
'message' => 'A password is required'
),
'isUnique' => array(
'rule' => 'isUnique',
'message' => 'Password has already been taken')
),
'full_name' => array(
'required' => array(
'rule' => 'notBlank',
'message' => 'Full name is required'
)
),
/*'role' => array(
'required' => array(
'rule' => 'notBlank',
'message' => 'Role is required'
)
) */
'email' => array(
array(
'rule' => array('email'),
'massage' => 'Please enter a valid email address',
),
),
'secondary_email' => array(
array(
'rule' => array('email'),
'massage' => 'Please enter a valid email address',
),
),
'phone' => array(
'required' => array(
'rule' => 'notBlank',
'message' => 'Phone is required'
)
),
'secondary_phone' => array(
'required' => array(
'rule' => 'notBlank',
'message' => 'Phone is required'
)
),
'location' => array(
'required' => array(
'rule' => 'notBlank',
'message' => 'Loacation is required'
)
),
'business_name' => array(
'required' => array(
'rule' => 'notBlank',
'message' => 'Business Name is required'
)
),
'document' => array(
'required' => array(
'rule' => 'notBlank',
'message' => 'Document is required'
)
),
'doc_file' => array(
'required' => array(
'rule' => 'notBlank',
'message' => 'Document is required'
)
),
'pname' => array(
'required' => array(
'rule' => 'notBlank',
'message' => 'Name is required'
)
),
'pemail' => array(
'required' => array(
'rule' => 'notBlank',
'message' => 'Please enter a Valid Email Id'
)
),
'pOfc_phone' => array(
'required' => array(
'rule' => 'notBlank',
'message' => 'Please enter a Phone Number'
)
),
'pdesignation' => array(
'required' => array(
'rule' => 'notBlank',
'message' => 'Designation is Required'
)
),
);
}
?>

cakephp form validation displaying default message instead of custom

Instead of my custom validation message being show upon submitting a form, the default "This field cannot be left blank" is being shown. Any ideas?
Here is my validation:
public $validate = array(
'id' => array(
'rule' => 'notEmpty'
),
'first_name' => array(
'rule' => 'notEmpty'
),
'last_name' => array(
'rule' => 'notEmpty'
),
'accused_of' => array(
'rule' => 'notEmpty'
),
'last_4_of_ssn' => array(
'rule' => '/^[0-9]{4}$/', // NEED TO DOUBLE CHECK THIS
'messsage' => 'Exactly 4 digits'
),
'date_of_accusation' => array(
'rule' => array('date', 'ymd'), // NEED TO DOUBLE CHECK THIS
'message' => 'Date must be in YYYY-MM-DD format.'
),
'monitoring' => array(
'rule' => 'notEmpty'
)
);
And here is my form:
echo $this->Form->create('Offender');
echo $this->Form->input('first_name', array('label' => 'First name:'));
echo $this->Form->input('last_name', array('label' => 'Last name:'));
echo $this->Form->input('accused_of', array('label' => 'Accused of:'));
echo $this->Form->input('monitoring', array('label' => 'Monitoring (enter as comma seperated list. ex: BAC, location):'));
echo $this->Form->input('last_4_of_ssn', array('label' => 'Last 4 digits of SSN:') );
echo $this->Form->input('date_of_accusation', array('label' => 'Date of accusation:'));
echo $this->Form->end('Save New Offender');
It appears for some fields you have not set any custom messages please go to this URL http://book.cakephp.org/2.0/en/models/data-validation.html
You can also create a custom validation for this purpose like in validation array do like this
'last_4_of_ssn' => array(
'rule' => array('digitValidate'),
'messsage' => 'Exactly 4 digits'
)
and in Model you can create a public function with the same name.
public function digitValidate() {
$pattern = '/^[0-9]{4}$/';
if (!preg_match($pattern,$this->data['last_4_of_ssn'])) {
return false;
}
return true;
}
I hope this will help you.

Controller validation in Cakephp

I wish to validate in controller in cakephp. Though my validations are working well in Models but instead of model I wish to validate it in controller as well.
What I did to validate in contrller.
$validates = array('email' => array(
'required' => array(
'rule' => array('notEmpty'),
'message' => 'A email is required'
),
'isUnique' => array(
'rule' => array('notEmpty'),
'message' => 'This email is already registered'
),
'email' => array(
'rule' => array('email'),
'message' => 'Enter valid mail address'
)
));
if ($this->User->validates($validates)) {
die("Action can be performed as validated !! Fields are correct");
} else {
die("Action can't be performed !! Fields are in-correct");
}
It always end me in correct condition no matters if field is correct or not. Please help
Setting $this->Model->validates = $validates; will work for you as suggested in the previous answer but you risk overwriting all other validation rules which may be set in the Model. It's much better to add, modify and remove validation rules on the fly like such:
$this->Model->validator()
->add('email', 'required', array(
'rule' => array('notEmpty'),
'message' => 'A email is required'
))
->add('email', 'isUnique', array(
'rule' => array('notEmpty'),
'message' => 'This email is already registered'
))
->add('email', 'email', array(
'rule' => array('email'),
'message' => 'Enter valid mail address'
));
I left your array exactly as you presented it, however I assume you have the wrong rule on isUnique
You can read more about binding rules here: http://book.cakephp.org/2.0/en/models/data-validation.html#dynamically-change-validation-rules
Try this -
$data = $this->request->data;
$this->ModelName->set($data);
if ($this->ModelName->validates()) {
// it validated logic
} else {
// didn't validate logic
$errors = $this->ModelName->validationErrors;
}
Suppose you want to validate a particular field in cakephp Controller, then for that below code will be use -
$this->ModelName->validationErrors['html_field_name'][] = 'Your Error Message goes here';
Edit your code:
$this->$Model->validate = array('email' => array(
'required' => array(
'rule' => array('notEmpty'),
'message' => 'A email is required'
),
'isUnique' => array(
'rule' => array('notEmpty'),
'message' => 'This email is already registered'
),
'email' => array(
'rule' => array('email'),
'message' => 'Enter valid mail address'
)
));
It work with me :)

Flash messages doesn't show up cakephp

I know this question has been asked many times but none of the answers are fixing my problem. First of all let me show where I have setFlash and echo $this->Session->flash().
This is my add function:
if(!empty($this->request->data))
{
$friend_id = $this->request->data['User']['id'];
$user_id = $this->Auth->User('id');
$already_friends = $this->Group->findByIdAndFriend($user_id, $friend_id);
if($already_friends)
{
$this->Session->setFlash(__('You are already friends', true));
}
else
{
$this->Group->create();
$data = array($user_id, $friend_id);
if($this->Group->save($data))
{
$this->Session->setFlash(__('You are now friends', true));
}
else {
$this->Session->setFlash(__('Failed to add friend. Please try again', true));
}
}
$this->redirect(array('action' => 'index'));
This is my layout, the necessary part of it:
<div id="header">
<?php echo $this->Html->image('connect.jpg', array('alt' => 'My Image', 'id' => 'headerImage')) ?>
<div id="headerNavMenu">
<div name="navTab" class="menuTab">
<?php echo $this->Html->link('Me', array('controller' => 'users', 'action' => 'view', CakeSession::read("Auth.User.id")), array('class' => 'tabName')) ?>
</div>
<div name="navTab" class="menuTab">
<?php echo $this->Html->link('My Schedule', array('controller' => 'newSchedules', 'action' => 'index'), array('class' => 'tabName')) ?>
</div>
<div name="navTab" class="menuTab">
<?php echo $this->Html->link('My Group', array('controller' => 'groups', 'action' => 'index'), array('class' => 'tabName')) ?>
</div>
<div name="navTab" class="menuTab">
Settings
</div>
</div>
<div id="login">
<?php echo CakeSession::read("Auth.User.firstName").' '.CakeSession::read("Auth.User.lastName").' ' ?>
<?php echo $this->Html->link('logout', array('controller' => 'users', 'action' => 'logout')) ?>
</div>
</div>
<div id="mainContent">
<?php echo $this->Session->flash(); ?>
<?php echo $this->Session->flash('auth'); ?>
<?php echo $this->fetch('content') ?>
</div>
</div>
Besides the fact that no flash messages show up, it also seems like the validation criteria is not being checked for models since specific messages don't show up either.
I am new at cakePHP but I have been following the blog tutorial to do most of my work. The flash messages used to work, but now it doesn't work for even models it used to.
Here are my validations:
public $validate = array(
'first_name' => array(
'required' => array(
'rule' => array('notempty'),
'message' => 'First Name cannot be blank',
'allowEmpty' => false,
'required' => true
)
),
'last_name' => array(
'required' => array(
'rule' => array('notempty'),
'message' => 'Last Name cannot be blank',
'allowEmpty' => false,
'required' => true
)
),
'email' => array(
'required' => array(
'rule' => array('notEmpty'),
'message' => 'Email cannot be blank',
'allowEmpty' => false,
'required' => true
),
'valid' => array(
'rule' => array('email', true),
'message' => 'This is not a valid email',
'required' => true
),
'unique' => array(
'rule' => array('isUnique'),
'message' => 'This email already exists',
'required' => true
)
),
'password' => array(
'required' => array(
'rule' => array('notempty'),
'message' => 'Password cannot be blank',
'allowEmpty' => false,
'required' => true
),
'valid' => array(
'rule' => array('minlength', 6),
'message' => 'Password has to be at least 6 characters',
'required' => true
),
'password_has_to_be_alphanumeric' => array(
'rule' => 'alphanumeric',
'message' => 'Password has to be alphanumeric',
'required' => true
)
)
);
I can't add comments so I have to answer, but in line 4 of your add function You should write user in lower case
$this->Auth->user('id');.
Theme check to have added Session component to your $components array in AppController

cakephp Custom validation rule message

I have a custom validation rule to check if two passwords entered are the same, and if they arent I wish to have a message that says "Passwords do not match".
The rule works, however, when the passwords don't match it simply displays the normal error message, what's going on?
var $validate=array(
'passwd2' => array('rule' => 'alphanumeric',
'rule' => 'confirmPassword',
'required' => true,
'allowEmpty'=>false));
function confirmPassword($data)
{
$valid = false;
if ( Security::hash(Configure::read('Security.salt') .$data['passwd2']) == $this->data['User']['passwd'])
{
$valid = true;
$this->invalidate('passwd2', 'Passwords do not match');
}
return $valid;
}
It says "This field cannot be left blank"
EDIT:
The strange thing is, if I leave one of the password fields blank, both error messages say "This field cannot be left blank"
However, if I put something in both, then it correctly says "Passwords do not match"
I think you made it too complex. Here is how I do it:
// In the model
public $validate = array(
'password' => array(
'minLength' => array(
'rule' => array('minLength', '8')
),
'notEmpty' => array(
'rule' => 'notEmpty',
'required' => true
)
),
'confirm_password' => array(
'minLength' => array(
'rule' => array('minLength', '8'),
'required' => true
),
'notEmpty' => array(
'rule' => 'notEmpty'
),
'comparePasswords' => array(
'rule' => 'comparePasswords' // Protected function below
),
)
);
protected function comparePasswords($field = null){
return (Security::hash($field['confirm_password'], null, true) === $this->data['User']['password']);
}
// In the view
echo $form->input('confirm_password', array(
'label' => __('Password', true),
'type' => 'password',
'error' => array(
'comparePasswords' => __('Typed passwords did not match.', true),
'minLength' => __('The password should be at least 8 characters long.', true),
'notEmpty' => __('The password must not be empty.', true)
)
));
echo $form->input('password', array(
'label' => __('Repeat Password', true)
));
You should use the 'message' key in your $validate array to specify the message:
'message' => 'Your passwords do not match'
Further reading: http://book.cakephp.org/view/1143/Data-Validation
And then you can access the fields and the messages by $this->modelName->invalidFields(), which will return you the fields that didn't pass the validation and the message that you have setted for them...
In the controller I mean...
http://book.cakephp.org/view/1182/Validating-Data-from-the-Controller

Resources