How to alter Inline Entity Form table fields?

By default, the Inline Entity Form widget will display very little information about referenced entities.

In my example, I have Article Group and Article content types. Article Group type has a reference to Articles, and IEF widget displays just two fields: Title and Status.

Image

Fortunately, adding a new field is really easy thanks to the hook inline entity form table fields alter hook. The details about this hook can be found here: inline_entity_form.api.php#L52

In the following example you can see how to add the Created date field: 

/**
 * Implements hook_inline_entity_form_table_fields_alter().
 */
function MY_MODULE_inline_entity_form_table_fields_alter(&$fields, $context) {
  if ($context['entity_type'] == 'node') {
    $fields['created_date'] = [
      'type' => 'callback',
      'label' => t('Created date'),
      'weight' => 100,
      'callback' => '_get_created_date',
    ];
  }
}

/**
 * Gets node created date.
 */
function _get_created_date($entity) {
  return date('d-m-Y', $entity->getCreatedTime());
}

And here's the final result: 

Image

This really comes in handy if you are using Drupal Commerce and you want to add the SKU column to the order items inline form. You can do it like this:

/**
 * Implements hook_inline_entity_form_table_fields_alter().
 */
function MY_MODULE_inline_entity_form_table_fields_alter(&$fields, $context) {
  if ($context['entity_type'] == 'commerce_order_item') {
    $fields['sku'] = [
      'type' => 'callback',
      'label' => t('SKU'),
      'weight' => 100,
      'callback' => '_get_sku',
    ];
  }
}

/**
 * Gets product variation SKU.
 */
function _get_sku($entity) {
  return $entity->getPurchasedEntity()->getSku();
}

And the final result will look like this: 

Image

About the Author

Goran Nikolovski is a web and AI developer with over 10 years of expertise in PHP, Drupal, Python, JavaScript, React, and React Native. He founded this website and enjoys sharing his knowledge.