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.

How to alter the Inline Entity Form table fields - before
How to alter the Inline Entity Form table fields - before

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: https://git.drupalcode.org/project/inline_entity_form/blob/8.x-1.x/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: 

How to alter the Inline Entity Form table fields - after
How to alter the Inline Entity Form table fields - after

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();
}
Drupal Commerce 2 add SKU column
Drupal Commerce 2 add SKU column