0

I have a a form which adds first_name and last_name of user in cakephp. here is the code

code for view (add.ctp)

<?php 
echo $this->Form->create('User');
echo $this->Form->input('first_name',array('label'=>'First Name'));
echo $this->Form->input('last_name',array('label'=>'Last Name'));           
echo $this->Form->end('Add User');
?>

code for UserController (UsersController.php)

<?php
     public function add(){
          if($this->request->is('post')){
               $addData = $this->request->data;
               $this->User->create();       
               if($this->User->save($addData)){
                  $this->Session->setFlash('User has been added successfully');
                  $this->redirect(array('action'=>'index'));            
               }            
          }
     }    
?>

view code for User Model (UserModel.php)

<?php
  class UserModel extends AppModel{
   public $validate = array(
     'first_name' => array(
          'rule'    => 'notEmpty',
          'message' => 'first name should not be empty.'
      ),
     'last_name' => array(
         'rule'    => 'notEmpty',
         'message' => 'last name should not be empty.'
      )
   );   
}
?>

This is the code I am using, I have seen on cakebook as well and used various other rules, but no validation is working for my form. Can some please help me what could be the reason ? Thanks in advance!

3 Answers 3

5

Your model filename is incorrect. It should be User.php not UserModel.php

Sign up to request clarification or add additional context in comments.

Comments

1

please change your file name to user.php if your using table name in mysql as users instead of UserModel.php

and your classname must be like below

<?php
  class User extends AppModel{

    var $name = 'User';

   public $validate = array(
     'first_name' => array(
          'rule'    => 'notEmpty',
          'message' => 'first name should not be empty.'
      ),
     'last_name' => array(
         'rule'    => 'notEmpty',
         'message' => 'last name should not be empty.'
      )
   );   
}
?>

Comments

0

Your model name should be User (as your table name and controller name is users). So try this in your model file(User.php)

<?php
App::uses('AppModel', 'Model');
class User extends AppModel{
public $validate = array(
 'first_name' => array(
      'rule'    => 'notEmpty',
      'message' => 'first name should not be empty.'
  ),
 'last_name' => array(
     'rule'    => 'notEmpty',
     'message' => 'last name should not be empty.'
  )

);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.