The problem I am having is that the validation rules are being fired on edit, but none of them are fired on create. Here are few of the validation rules, even though the problem is most probably not here:
var $validate = array(
'date' => array(
'notempty' => array(
'rule' => array('notEmpty'),
'message' => 'Choose a date'
)
),
'minutes' => array(
'rule'=>'minutes',
'message' => 'Minutes cannot exceed 60',
'allowEmpty' => true
)
And here are the forms (edit and add):
<?php echo $this->Form->create('Event');?>
<?php echo $this->Form->input('date', array('class'=>'datepicker', 'type'=>'text', 'label'=>__('Date*')));?>
<?php echo $this->Form->end(__('Save edit'));?>
<?php echo $this->Form->create('Event');?>
<?php echo $this->Form->input('date', array('class'=>'datepicker', 'type'=>'text', 'value'=>$date, 'label'=>__('Date*'))); ?>
<?php echo $this->Form->end(__('Save'));?>
And the validation is not disabled in any controller function as they are the same all over the app and work perfectly with every other model. I guess it has to be something simple, but I just cannot get it to work.
Any help is much appreciated.
Try this code in your EventsController.php file.
In your add() function:
Code:
if ($this->request->is('post')) {
$this->Event->set($this->request->data);
if($this->Event->validates()) {
if ($this->Event->save($this->request->data)) {
// Data saved and validated
}
}
}
I hope this code will help you..
Thank You!!
you just need to use validation rules in both actions on model table separately.
public function validationadd(Validator $validator){
->notEmpty('first_name');
return $validator;
}
public function validationedit(Validator $validator){
->notEmpty('first_name');
return $validator;
}
Related
I am new to CakePHP and have created a normal form to submit first name.
My table name is "registers. I have created a controller named RegistersController (RegistersController.php) and a model named Register (Register.php) . Each time i submit after entering first name, it still displays error (First name is must) which it should only if i submit it without entering anything. Next i added validation for having minimum 6 characters. That validation is also not working. I mean, cakephp is not validating that rule. Could anyone please tell me where i have done anything wrong?
Model:-
class Register extends AppModel {
//put your code here
//public $useTable = "registers";
public $validate = array(
'first'=>array(
'minLength' => array(
'rule' => array('minlength','6'),
'field' => 'first',
'message' => 'Minimum 6 characters required'
),
'required' => array(
'rule'=>array('notEmpty'),
'required' => true,
'message' => array('First name is must')
)
)
);
}
Controller:-
class RegistersController extends AppController {
public $uses = array("Register");
//put your code here
public function index() {
if($this->request->is('post')){
//echo "Data";
if($this->Register->validates()){
//$this->Register->create();
//echo "Data validated";
print_r($this->Register->validationErrors);
}else{
//echo "Data not validated";
print_r($this->Register->validationErrors);
}
}
}
My view is as follows:-
<?php
echo $this->Form->create('Register');
echo $this->Form->input('first');
echo $this->Form->end("Submit");
?>
You are missing this line
$this->Register->set($this->request->data);
Put it before the validation call, i.e.
$this->Register->validates()
In version 2.2.1 I could validate a form using rules and custom messages like below. But somehow the password rule isn't working as of version 2.3. Any help what I might be doing wrong here?
Model:
class User extends AppModel {
public $validate = array(
'password' => array(
'rule' => array ('between', 5, 10 ),
'message' => 'Password must between 5 and 10 characters long'
)
);
public function beforeSave($options = array()) {
$this->data['User']['password'] = Security::hash($this->data['User']['password'], 'sha1', true);
return true;
}
}
View:
<?php
echo $this->Form->create();
echo $this->Form->input('firstname', array('label' => 'First name'));
echo $this->Form->input('lastname', array('label' => 'Last name'));
echo $this->Form->input('adminrole', array('type' => 'checkbox', 'label' => 'Is admin?<br /><br />'));
echo $this->Form->input('email', array('label' => 'E-mail address'));
echo $this->Form->input('password', array('label' => 'Password'));
echo $this->Form->input('picturethumb', array('type' => 'file', 'label' => 'Profile picture'));
echo $this->Form->end('Save');
?>
Please bare in mind that this exact same code validates correctly in 2.2.1
Controller:
class UsersController extends AppController {
public function index() {
$users = $this->User->find('all');
$this->set('users', $users);
}
public function add() {
if ($this->request->is('post')) {
$this->User->save($this->request->data);
$this->redirect('/users');
}
}
}
Try this-
public function add() {
if ($this->request->is('post')) {
$this->User->create();
if($this->User->save($this->request->data)){
$this->redirect('/users');
}else{
$this->Session->setFlash('Opps... Something is wrong');
}
}
}
I don't work with cake sometime, but I remember had this problem before. The problem is, the cakephp will create a hash of password, so when Model get password is already big. What I did in time was make another validate, like password_tmp and use it like field and create the hash by myself in controller for the real field password.
I've installed Miles Johnson's Uploader plugin and set it up with one of my models and got it working perfectly. Very nice.
Then I went and set it up on another model with almost identical code [the only difference is the upload path] and it won't work on the second model. When I submit the form the plugin doesn't seem to notice; I get an SQL error from an attempt to insert the POST file array straight into the DB.
Here is the code. [Other than this the plugin is imported in the bootstrap]
public $actsAs = array(
'Uploader.Attachment' => array(
'photo' => array(
'name' => 'formatFileName',
'uploadDir' => '/uploads/uses/img/',
'dbColumn' => 'photo',
'maxNameLength' => 30,
'overwrite' => true,
'stopSave' => true,
'allowEmpty' => false,
'transforms' => array(
array('method' => 'resize', 'width' => 240, 'dbColumn' => 'photo_thumb'))
)
),
'Uploader.FileValidation' => array(
'fileName' => array(
'extension' => array('gif', 'jpg', 'png', 'jpeg'),
'required' => true
)
)
);
This is on the model that is not uploading and the only difference is the uploadDir.
Does the plugin only work on one model? Any clues? thnx :}
Edit for extra clarity
Here is my view code:
echo $this->Form->create('Use', array('type' => 'file'));
echo $this->Form->input('Use.photo', array('type' => 'file'));
echo $this->Form->input('Use.desc', array('rows' => '3', 'label' => 'Description'));
echo $this->Form->end('Add to Gallery');
And here is my controller code:
public function add() {
if ($this->request->is('post')) {
$this->Use->set('user_id', $this->Auth->user('id'));
if ($this->Use->save($this->request->data)) {
$this->Session->setFlash('Your Use has been saved.');
$this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash('Unable to add your Use.');
}
}
}
The plugin doesn't work in only one model. You can add more uploader into your site.
The model seems to be good, I suggest you to see into your form to see if you have create the form in the right way into your view (is imporant to put into your form: 'type' => 'file'
example:
echo $this->Form->create('Product', array ('class' => 'form', 'type' => 'file'));
echo $this->Form->input('ModelImage.filename', array('type' => 'file'));
echo $this->Form->submit('Add Image', array('id'=>'add_image'));
echo $this->Form->end();
Or the problem is the name Use try to change the name with another
After checking thru the code with Alessandro [thank you :)] I found the problem.
If you look in the View and Controller code you can see that the model is named 'Use'. This was the problem, as Use is a loaded word in PHP and I shouldn't have used it for a model name.
I renamed the model to Outcome and now the Uploader works perfectly.
How to get an input type file to validate for notempty in cake?
When you submit the form without adding a file the validation says it is empty even though $this->request->data shows the file.
// Model/Product.php
class Product extends AppModel {
public $validate = array(
'name' => array(
'rule' => 'notEmpty'
),
);
}
// Controller/ProductController.php
public function add() {
if ($this->request->is('post')) {
$this->Product->create();
if ($this->Product->save($this->request->data)) {
$this->Session->setFlash('Your product has been saved.');
} else {
$this->Session->setFlash('Unable to add your product.');
debug($this->request->data);
debug($this->Product->validationErrors);
}
}
}
// View/Products/add.ctp
echo $this->Form->create('Product', array('type' => 'file'));
echo $this->Form->input('name', array('type' => 'file'));
echo $this->Form->end('Save Post');
I don't think that you can actually use notEmpty on the -somewhat special- file field. The file field is handled differently than any other input field, as it returns the superglobal $_FILES as a result. As such, you should check it a little bit differently. There is actually quite a good example in the CakePHP Documentation.
Now this is for actually uploaded files, but you can easily change it by checking if the name key is not empty and actually set. Something like this as a custom validation rule in your Model should do the trick:
public function fileSelected($file) {
return (is_array($file) && array_key_exists('name', $file) && !empty($file['name']));
}
And then just set this as validation rule for your file field:
public $validate = array(
'name' => array(
'rule' => 'fileSelected'
),
);
Can anyone help me with a clear and complete example on how to set validations for 2 fields, say an email and password, with error messages?
From my understanding, the correct format is:
var $validate = array(
'password' => array(
'rule' => array('minLength', '8'),
'message' => 'Minimum 8 characters long'
),
'email_id' => array('email')
);
but I can’t seem to get it work (show a validation message, or halt the execution of the action) in my tests.
Validations work fine but no way for the custom messages to appear!
EDIT
The validations and page redirections work fine now. Only the specific messages do not appear. That is, if I enter a password less than 8 characters, the message "minimum 8 characters needed" should appear immediately or after I click the register button. Is there any method to do this?
EDIT 2
My view file
<!-- File: /app/views/forms/index.ctp -->
<?php
echo $javascript->link('prototype.js');
echo $javascript->link('scriptaculous.js');
echo $html->css('main.css');
?>
<div id="register">
<h3>Register</h3>
<?php
echo $form->create('User',array('action'=>'register'));
echo $form->input('User.name');
echo $form->input('User.email_id');
echo $form->input('User.password');
echo $form->end('Register');
?>
</div>
<div id="login">
<h3>Login</h3>
<?php
echo $form->create('User',array('action'=>'login'));
echo $form->input('User.email_id');
echo $form->input('User.password');
echo $form->end('Login');
?>
</div>
Controller:
<?php
class UsersController extends AppController
{
var $name = 'Users';
var $uses=array('Form','User','Attribute','Result');
var $helpers=array('Html','Ajax','Javascript','Form');
function register()
{
$userId=$this->User->registerUser($this->data);
$this->User->data=$this->data;
if (!$this->User->validates())
{
$this->Flash('Please enter valid inputs','/forms' );
return;
}
$this->Flash('User account created','/forms/homepage/'.$userId);
}
function login()
{
$userId=$this->User->loginUser($this->data);
$this->User->data=$this->data;
if (!$this->User->validates())
{
$this->Flash('Please enter valid inputs','/forms' );
return;
}
if($userId>0){
$this->Flash('Login Successful');
$this->redirect('/forms/homepage/'.$userId);
break;
}
else{
$this->flash('Username and password do not match.','/forms');
}
}
}
?>
Model:
<?php
class User extends AppModel {
var $name = 'User';
var $components=array('Auth');
var $validate = array(
'name' => array(
'rule' => VALID_NOT_EMPTY,
'message' =>'Name cannot be null.'
),
'password' => array(
'rule' => array('minLength', '6'),
'message' => 'Minimum 6 characters long.'
),
'email_id' => array(
'rule'=> array('email'),
'message'=>'Invalid email.'
)
);
function registerUser($data)
{
if (!empty($data))
{
$this->data['User']['name']=$data['User']['name'];
$this->data['User']['email_id']=$data['User']['email_id'];
$this->data['User']['password']=$data['User']['password'];
if($this->save($this->data))
{
$this->data['User']['id']= $this->find('all',array('fields' => array('User.id'),
'order' => 'User.id DESC'
));
$userId=$this->data['User']['id'][0]['User']['id'];
return $userId;
}
}
}
function loginUser($data)
{
$this->data['User']['email_id']=$data['User']['email_id'];
$this->data['User']['password']=$data['User']['password'];
$login=$this->find('all');
foreach($login as $form):
if($this->data['User']['email_id']==$form['User']['email_id'] && $this->data['User']['password']==$form['User']['password'])
{
$this->data['User']['id']= $this->find('all',array('fields' => array('User.id'),
'conditions'=>array('User.email_id'=> $this->data['User']['email_id'],'User.password'=>$this->data['User']['password'])
));
$userId=$this->data['User']['id'][0]['User']['id'];
return $userId;
}
endforeach;
}
}
?>
Here is a live example from my project..
This is how you set up your validation in your model: Article model
Ignore the fact that I'm initializing the validate array from constructor, you can keep doing it like you're doing it now if you don't plan on implementing I18n and L10n.
Handling validation errors in controller: Articles controller
From line 266 to 280 you can see validation and save errors being handled with setFlash() + return.
That's pretty much all you need to do, just don't forget you need to use the FormHelper for your forms for the messages to work as expected.
Common error: you must not do a $this->redirect() after failed validation.
Hopefully this will set you on the right track :)
Why dont you try $this->modelName->invalidFields(), which will return you an array with the fields that failed validation and the message to display.
http://book.cakephp.org/view/1182/Validating-Data-from-the-Controller