Chris 2pha Brown. Drupal developer Brisbane Australia

Chris Brown

Drupal, Javascript, Three.js, 3D

website blog
image for Changing the Inline Entity Form autocomplete field to a select list

Changing the Inline Entity Form autocomplete field to a select list

The Inline Entity Form module for Drupal is an awesome module. Most people probably have experienced using it with Drupal Commerce, but it can be used when ever an Entity Reference field is used. I have personally used it on many projects, most of which were not commerce related.

Sometimes though, the autocomplete field to select an existing entity is not appropriate, say if you only have a few entities that can be referenced.

Luckily though we can make use of the hook that the Inline Entity Form module provides which is HOOK_inline_entity_form_reference_form_alter(&$reference_form, &$form_state).

Below is an example of how to change all the autocomplete fields to select lists when the reference field references any type of node.

function MYMODULE_inline_entity_form_reference_form_alter(&$reference_form, &$form_state) {
  // change the entity reference 'add more' autocomplete into a select list
  if($reference_form['#entity_type'] == 'node') { // only change the forms that reference a node
    $field = field_info_field($reference_form['#parents'][0]);
    $nodes = node_load_multiple(array(), array('type' => reset($field['settings']['handler_settings']['target_bundles'])));
    $options = array();
    foreach($nodes as $node){
      $options[$node->title.' ('.$node->nid.')'] = $node->title;
    }
    $reference_form['entity_id']['#type'] = 'select';
    $reference_form['entity_id']['#options'] = $options;
  }
}

Add a comment

<b>, <i> and <code> tags are allowed.