2013-04-16 81 views
0

我有一個表單,它在cakephp中添加用戶的名字和姓氏。 這裏是代碼爲視圖蛋糕php表單驗證不適用於我

代碼UserController中(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'); 
?> 

代碼(UsersController.php),用於用戶模型(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.' 
    ) 
    ); 
} 
?> 

<?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'));    
       }    
      } 
    }  
?> 

視圖代碼這是我正在使用的代碼,我也在cakebook上看到過,並使用了各種其他規則,但沒有驗證正在爲我的表單工作。有些人可以幫我,可能是什麼原因? 在此先感謝!

回答

5

您的模型文件名是不正確的。它應該是User.php而不是UserModel.php

0

您的型號名稱應該是User(因爲您的表名和控制器名稱是用戶)。 那麼試試這個模型中的文件(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.' 
) 

);
}

1

請,如果你的MySQL中使用表名作爲用戶,而不是UserModel.php

更改文件名user.php和你的類名必​​須像下面

<?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.' 
    ) 
    ); 
} 
?>