CakePHP 3 构建规则,允许检查数据是否唯一并允许为空


cakephp 3 build rules that allows checks if data is unique and allows empty

我想允许用户在注册功能上将电子邮件和电话留空。我也想要任何添加的电子邮件或电话。独一无二。但是,构建规则中的 isUnique 函数正在阻止此操作,因为它看到空白字段已经存在。

public function buildRules(RulesChecker $rules)
{
    $rules->add($rules->isUnique(['username']));
    $rules->add($rules->isUnique(['email']));
    $rules->add($rules->isUnique(['phone']));
    return $rules;
}

我该如何补救?我已经在验证中尝试了 ->allowEmpty,但它不起作用。文件中没有任何关于此的内容。就这么具体。

要改进神圣的答案,您应该在用户实体中执行此操作

//Entity/User.php
protected function _setPhone($value)
{
      if($value == '') {
           $value = null;
       }
       return $value;
}

如果您仍然没有找到解决方案,我有一个。我今天遇到了同样的问题,我发现空字段的值为",不等于空。因此,您需要做的是,在add()和edit()函数中,或者您用于将手机写入数据库的任何函数中,您必须检查电话字段是否等于''。如果是这样,则只需为其分配 null。例如:

public function add()
{
    //todo: check for conflicting email and phone
    $user = $this->Users->newEntity();
    if ($this->request->is('post')) {
        $user = $this->Users->patchEntity($user, $this->request->data);
        //LOOK AT THESE TWO LINES
        if($user->phone == '') {
            $user->phone = null;
        }
        if ($this->Users->save($user)) {
            $this->Flash->success(__('The user has been saved.'));
            return $this->redirect(['action' => 'index']);
        } else {
            $this->Flash->error(__('The user could not be saved. Please, try again.'));
        }
    }
    $roles = $this->Users->Roles->find('list', ['limit' => 200]);
    $this->set(compact('user', 'roles'));
    $this->set('_serialize', ['user']);
}