I have a user entity reference field. When I type in a name, but the entity/user doesn't exist I would like to save the name as a plain text value. Is this possible?


  • 1
    what would be the use of the the same? The entity is always stored as id and not the name. – Mohammed Shameem Jan 31 '13 at 15:16
  • In this field I need to be able to enter users that are in the system as well as people that are not known within the system. But I guess it won't work if they are stored as ID. – Smos Jan 31 '13 at 15:36

Instead of adding an user entity field you can create a normal text field and then use formalter function to make it an auto complete.

The steps would be as follows.

Create a custom module.

First you would need to create a menu item to get the list of users to do that you can create a hook_menu function

function module_name_menu() {  
  $items['userlist/autocomplete'] = array(
    'page callback' => '_module_name_autocomplete',
    'access arguments' => array('you can define the permissions here'),
    'type' => MENU_CALLBACK
  return $items;

The next step would be to create the call back function.

function _module_name_autocomplete($string) {
  $matches = array();

  // Some fantasy DB table which holds cities
  $query = db_select('users', 'u');

  // Select rows that match the string
  $return = $query
    ->fields('u', array('name'))
    ->condition('c.name', '%' . db_like($string) . '%', 'LIKE')
    ->range(0, 10)

  // add matches to $matches  
  foreach ($return as $row) {
    $matches[$row->name] = check_plain($row->name);

  // return for JS

The last step would be to create a form alter function to

function module_name_form_page_node_form_alter(&$form, &$form_state, $form_id) {
  $form['field_name']['#autocomplete_path'] = 'userlist/autocomplete';

This would change your textfield into an autocomplete field. you would also be able to enter any other name as well.


Your Answer

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

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