Programmatically update user field without duplicate entry

Public

Update an unlimited field for a user but not if the value is duplicated.

</> CopyGet raw version
php
  1. function api_add_contact_save() {
  2. global $user;
  3. $my_user = user_load($user->uid);
  4. $new_contact_uid = $_POST['contact_uid'];
  5. if($user->uid == $new_contact_uid) {
  6. drupal_set_message('You cant invite yourself.');
  7. } else {
  8. $contactUid = (int)$new_contact_uid;
  9. if(!empty($my_user->field_my_contacts)) {
  10. $duplicate = already_a_contact($user->uid, $contactUid);
  11. $contacts = $my_user->field_my_contacts;
  12. $new_contact = array('value' => $contactUid);
  13. if($duplicate == FALSE) {
  14. array_push($contacts['und'], $new_contact);
  15. } elseif($duplicate == TRUE) {
  16. drupal_set_message('Already a contact.');
  17. }
  18. } else {
  19. $contacts['und'][0]['value'] = $contactUid;
  20. }
  21.  
  22. $edit = array(
  23. 'field_my_contacts' => $contacts
  24. );
  25. user_save($my_user, $edit);
  26. }
  27.  
  28. $destination = 'transfer/new/users';
  29. drupal_goto($destination);
  30.  
  31. //return print_r($edit);
  32. }

Check for duplicate $uid's when entering the user data for the field.

</> CopyGet raw version
php
  1. function already_a_contact($uid, $contact_uid) {
  2. $duplicate = FALSE;
  3. $user = user_load($uid);
  4. $my_contacts = $user->field_my_contacts;
  5. $newArray = array();
  6.  
  7. if(!empty($my_contacts['und'])) {
  8. foreach ($my_contacts['und'] as $key => $value) {
  9. $newArray[] = $value['value'];
  10. }
  11. $duplicate = in_array($contact_uid, $newArray);
  12. }
  13.  
  14. // if($duplicate == TRUE) {
  15. // $output = 'True';
  16. // } elseif($duplicate == FALSE) {
  17. // $output = 'False';
  18. // }
  19.  
  20. return $duplicate;
  21. }