0

I'm trying to make an object to log user through oauth2. I need to put some conditionnal fields. Here is my code :

public function createUserLocally() {

    // Get user datas from api
    $user_infos = $this->getUserInfos();
    $user_society = $this->getUserSociety();
    $user_blabla_datas = $this->getUserBlaBlaInfos();

    // Create a list of user information.
    $user = array(
      'name'   => $this->username,
      'pass'   => $this->password,
      'mail'   => $user_infos['email'],
      'field_user_address' => array(
        LANGUAGE_NONE => array(
          0 => array(
            'first_name' => $user_infos['firstname'],
            'last_name' => $user_infos['lastname'],
            'phone_number' => $user_infos['phonenumber'],
            'country' => 'EN',
          ),
        ),
      ),
      'status' => 1,
      'init'   => $user_infos['email'],
      'roles'  => array(
        DRUPAL_AUTHENTICATED_RID => 'authenticated user',
      ),
    );

    if ($user_society) {
      $user = array(
        'field_user_society_id' => array(
          LANGUAGE_NONE => array(
            0 => array(
              'value' => $user_society['id'],
            ),
          ),
        ),
      );

    }
    if ($user_Blabla_datas) {
      $user = array(
        'field_user_blabla_locations' => array(
          LANGUAGE_NONE => array(
            0 => array(
              'lat' => $user_blabla_datas['Latitutde'],
              'lng' => $user_blabla_datas['Longitude'],
            ),
          ),
        ),
      );
    }

    // Save the new user.
    $user = user_save(NULL, $user);

Without the conditionnal fields, everything run smoothly but with some conditions (my two if), I'm getting this error message :

PDOException : SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '' for key 'name': INSERT INTO {users} (uid, created) 

Any idea on what I'm doing wrong ? I have to say that if I use a user without data in the "if" conditions, user is registered without problem.

  • 1
    You're replacing the $user object in the conditions, you need to alter it instead $user['field_user_society_id'] = array(... – Clive Apr 25 '18 at 21:07
  • What do you mean ? That's exactly what I did ? – Aporie Apr 25 '18 at 21:14
  • 1
    Your code is $user = array(, replacing the object – Clive Apr 25 '18 at 21:15
  • Ok gonna try this – Aporie Apr 25 '18 at 21:17

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.