0

我有一个表格,它在 cakephp 中添加了用户的名字和姓氏。这是代码

视图代码 ( 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');
?>

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

查看用户模型的代码 ( 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.'
      )
   );   
}
?>

这是我正在使用的代码,我也在 cakebook 上看到并使用了各种其他规则,但没有验证适用于我的表单。有人可以帮我看看可能是什么原因吗?提前致谢!

4

3 回答 3

5

您的模型文件名不正确。应该User.php不是UserModel.php

于 2013-04-16T06:38:58.067 回答
1

请将您的文件名更改为user.php如果您在 mysql 中使用表名作为用户而不是UserModel.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.'
      )
   );   
}
?>
于 2013-04-16T08:58:31.950 回答
0

您的模型名称应该是用户(因为您的表名称和控制器名称是用户)。所以在你的模型文件(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.'
  )

);
}

于 2013-04-16T06:40:57.983 回答