Entity Reference FAPI -- Is it Possible?

Posted by Lucas Hedding on December 11, 2013
Project Management
Strategy & Architecture

In a recent client project (most of my good ideas come from solving client problems), I had the dilemma of exposing an entity reference with-in a standard Drupal FAPI form. It needed to have auto complete functionality to search for a Commerce Product by SKU. I pieced together a solution from nuggets found in several blog and groups.drupal.org posts and from entityreference module.

As a requirement for this to work, an entityreference field to store the autocomplete data must exist. I only needed to store a single value (field cardinality of 1). However, someone could just as easily swap out for multiple values and replace 'single' with 'tags'. For this example, the FAPI code is super simple.

$form['product_line_item_ref'] = array(
  '#type' => 'textfield',
  '#title' => t('Product Line Item Reference'),
  '#description' => t('Enter the product line item.'),
  // The last 4 URL parameters are important.
  // 4: Use <NULL> as a placeholder in the URL when we don't have an entity.
  // 3: Bundle, in our case the specific type of commerce line item but for node, that could page, etc.
  // 2: Entity type, commerce line item in our example but node is also a valid type.
  // 1: Field name that is the entityreference field.
  '#autocomplete_path' => 'entityreference/autocompelete/single/commerce_product_line_item_ref/commerce_line_item/related_lines/NULL',
  '#size' => 60,
  '#maxlength' => 255,
  '#required' => FALSE,


Do want to keep your Drupal site running smoothly without worrying about maintenance? We can give your site a tune-up or help you keep it up-to-date for the long-term.

Write us about your project, and we’ll get back to you within 48 hours.

Entity Reference FAPI -- Is it Possible?