蛋糕PHP,避免和检测空字段和重复主键

时间:2015-02-26 21:39:56

标签: php mysql cakephp

我无法在Controller类中捕获字段为空时,或者当用户尝试添加具有重复主键的新行时。 这是我的模型验证数组:

public $validate = array(
    'username' => array(
        'notEmpty' => array(
            'rule' => 'notEmpty',
            'message' => 'username empty',
            'required' => true
        ),
        'alphaNumeric' => array(
            'rule' => 'alphaNumeric',
            'message' => 'not alphanumeric'
        ),
        'maxLength' => array(
            'rule' => array('maxLength', 50),
            'message' => 'too long'
        ),
        'minLength' => array(
            'rule' =>array('minLength', 1),
            'message' => 'too short'
        )
    ));

这是我在控制器中的添加操作:

if ($this->request->is('post')) {
        $this->Admin->set($this->request->data);
        $this->Admin->create();
            // it validated logic
            if ($this->Admin->save($this->request->data)) {
                $this->Session->setFlash(__('The admin has been saved.'));
                return $this->redirect(array('action' => 'index'));
            } else {
                $errors = $this->Admin->validationErrors;
                debug($errors);
                $this->Session->setFlash(__('The admin could not be saved. Please, try again.'));
            }
}

但是,

  • 如果我留空我的字段,我的自定义消息未显示,但显示空字段的默认cakephp消息

  • 如果我尝试将重复元素添加到我的数据库中(因此我违反了主键),也没有显示错误消息,并且我将automaticalli重定向到控制器的index()动作(默认情况下)显示数据库元素的索引操作)

1 个答案:

答案 0 :(得分:1)

要避免重复的主键,请在数据库表中将id设置为唯一键。

  

如果我留空我的字段,我的自定义消息不显示,但显示空字段的默认cakephp消息

显示验证消息的正确方法。

  

如果我尝试将重复元素添加到我的数据库中(因此我违反了主键),也没有显示错误消息,并且我将automaticalli重定向到控制器的index()动作(默认索引操作,显示数据库元素。)

如果提交的数据包含字段ID且该值存在于数据库中,则您的帖子将会更新。

我认为这条线是不必要的:

$this->Admin->set($this->request->data);

更新:

  

如果用户插入重复记录,我会显示一条消息。我不想显示默认的蛋糕php消息,但我的自定义消息被声明为规则。

public function add(){
if ($this->request->is('post')) {
        // 
        if(isset($this->request->data['ModelName']['id'])){
           $id = $this->ModelName->findById($this->request->data['ModelName']['id']);
           if($id){
              // my custom message here
           }
        }
        //
        $this->Admin->create();
            // it validated logic
            if ($this->Admin->save($this->request->data)) {
                $this->Session->setFlash(__('The admin has been saved.'));
                return $this->redirect(array('action' => 'index'));
            } else {
                $errors = $this->Admin->validationErrors;
                debug($errors);
                $this->Session->setFlash(__('The admin could not be saved. Please, try again.'));
            }
}
}