0

I use the references module. I have a custom form, into which I capture names into a user reference field via the autocomplete widget. So, on the form, if a user types Joe, the following appears in the input box:

Joe [uid: 5]

Now, I do not want to insert this into my database as it is because my 'Name' field is expecting just the uid. So I need to pass '5' to the database, not the string Joe [uid: 5].

To accomplish this, before I write my record to the database I pass the string Joe [uid: 5] through this code:

// * Search for match (integer) to regular expression and put in $integer.
preg_match_all('!\d+!', $form_state['values']['name'], $integer);

// * Return string representation of array elements.
$name_uid = implode(' ', $integer[0]);

$name_uid now contains '5' and is ready to be inserted. Is there an existing function that already does this? or does anyone have a better way?

The downside of my method is that you cannot have numbers in names, like 'Joe 2'. I've looked in user_reference.module, but it's not obvious, to me, how they do it.

Thanks

1
  • Have a look at user_reference_autocomplete_value() and user_reference_autocomplete_validate(), that's how the user_reference module does it
    – Clive
    Commented May 30, 2013 at 12:34

1 Answer 1

0

I couldn't make user_reference_autocomplete_validate() work for me so I turned my own code into a function, which now solves my numbers in names problem. I can't see why it would ever fail, but if anyone has a better solution, please let me know.

/**
 * Search for regular expression matches and return the last match.
 */

function extract_id($subject) {
    preg_match_all('!\d+!', $subject, $matches);
    return end($matches[0]);
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.