How to alter Inline Entity Form table fields?

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

If I can be of assistance, please do not hesitate to contact me.

About the author

Goran Nikolovski is a highly experienced Drupal developer with an extensive skill set that includes PHP, MySQL, HTML, CSS and Javascript. He has experience with large Drupal sites and Drupal Commerce 2.x integration, and he is author of several Drupal modules.

You may also like

Drupal 8, nginx and Let's Encrypt

This site is powered by Drupal 8. I'm using Nginx as a web server and Let's Encrypt to add HTTPS encryption to my site. In this post, I will show you how my Nginx config file looks like.

2019 recap

As 2019 draws to a close, it’s time for a traditional recap post where I reflect on the best things that happened to me during the year.