Search code examples
phpdrupaldrupal-7

Unexpected Entity Reference Autocomplete behaviour


I'm using Entity API, Form API and Entity Reference Autocomplete in Drupal. I have a relationship between two types, clubs and courses, each club can have many courses so basically the table course contains a column called goclid which references the club id number like so:

// hook_schema()

$schema['course'] = array(
    // other fields...
'goclid' => array(
    'description' => 'Reference to the club',
    'type' => 'int',
    'unsigned' => TRUE,
    'not null' => TRUE,
  ),

// ... a few lines later...
'foreign key' => array(
  'related_club' => array( // join alias
    'table' => 'club',
    'columns' => array('goclid' => 'id'),
  ),
),
// etc.
);

Then I include a field like so in the course form:

$form['goclid'] = array(
    '#title' => t('Reference to the club'),
    '#type' => 'entityreference',
    '#era_entity_type' => 'club',
    '#default_value' => isset($course->goclid) ? $course->goclid : '',
    '#required' => FALSE,
);

Now, the autocomplete gives suggestions only when I type an id number, and then populates the field value with the label (name of the golf club). What I want is exactly the opposite: I want to get suggestions by typing the name of the club, and then when I choose one, the form field should be populated with the id number of that object.

Why is Entity Reference Autocomplete behaving in an unexpected way? What can I do to obtain the desired behaviour?


Solution

  • Salvador Molina, the author of the Entity Reference Autocomplete Module, gave me an answer on Drupal Answers which is worth sharing also here on Stackoverflow:

    I think you might have not specified the "label" column in the entity definition. That goes within the 'entity keys' array, like the 'id' key.

    $entity_info = array(
       .....
      'entity keys' array(
        'id' => 'primary key column...',
        'label' =>  'column holding the label'
      ),
    )
    

    Otherwise entityreference will not know which column to use for searching in the DB. That still makes it possible to show the label (as you're experiencing) after you reference the entity, because 'label' key is not mandatory, and you may have specified a "label callback" instead, which the Entity API will use when entity_label() is called to get the label of a specific entity.

    Salvador's hint worked flawlessly, after including label in the entity keys array I can search entities by typing their label.