0

I want to allow users to leave the email and phone blank on the register function. I also want any added emails or phones no. to be unique. However the isUnique function in the build rules is stopping this because it sees that the blank field already exists.

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

How can I remedy this? I have already tried the ->allowEmpty in the validation but it doesn't work. There is nothing about this in the documents. As specific as this.

ndm
  • 59,784
  • 9
  • 71
  • 110
John Hogan
  • 996
  • 1
  • 13
  • 26
  • Normally comparing against `NULL` using ordinary comparision operators (which the unique rule does) should always be `NULL` (AFAIK this is at least the case in MySQL and Postgres), thus nothing being found, and consequently the unique check should pass. Reyling on this behavior is kinda ugly though, so this might be worth an enhancement for the core. Anyways, which DBMS are you using? What does the tables `CREATE TABLE` statement look like? And what does the data that you are trying to save look like? – ndm Mar 07 '16 at 10:41
  • I used wamp myadmin php with my sql. The table allows nulls for the entry. It is the strangest thing but it will allow the first null value but after that it won't allow a second. – John Hogan Mar 09 '16 at 06:33

2 Answers2

2

To improve on divinemaniac answer you should do this in the User Entity

//Entity/User.php

protected function _setPhone($value)
{
      if($value == '') {
           $value = null;
       }

       return $value;
}
artSir
  • 540
  • 1
  • 8
  • 29
0

If you still haven't found a solutions to this, I have one. I ran into the same problem today and what I found out was that empty fields have a value of '' which does not equal null. So, what you have to do is, in the add() and edit() function, or whichever function you are using to write the phone to the database, you must check if the phone field is equal to ''. If it does, then just assign null to it. For example:

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']);
}
divinemaniac
  • 267
  • 1
  • 9