Cake PHP,避免并检测空字段和重复主键

Cake PHP, avoid and detect empty fields and duplicate primary key

我无法在 Controller class 中捕捉到字段为空或用户尝试添加具有重复主键的新行的情况。 这是我的模型验证数组:

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

但是,

为避免主键重复,请将 id 设置为数据库中的唯一键 table .

if i leave empty my field, my custom message is not showed, but is showed default cakephp message for empty field

这是显示验证消息的正确方式。

if i try to add a duplicate element into my database (so i violate primary key), no error message is showed too, and i'm redirect automaticalli to index() action of controller (the default index action that shows database elements).

如果提交的数据包含字段 ID 并且该值存在于数据库中,您的 post 将被更新。

我觉得这段话没有必要:

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

更新:

i would show a message if user insert duplicate record. i don't want show default cake php message, but my custom message declared into rule.

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