Skip to main content

Drupal 8 Inline Entity Form: How to update dynamically the available options list based on the creared reference entities

Using the inline entity form module is very practical especially for all the times that you can't use the paragraphs module. I can only find one "small" issue on some cases where you want the user to add only one of the reference entities. So if for example you are making a projects list with various projects types and you only want the user to add one project type per node you need to modify the "options list" each type a new reference node is added.

This is how i did it.

use Drupal\Core\Form\FormStateInterface;

function mymodule_form_alter(&$form, FormStateInterface $form_state, $form_id) {

  $node_project_refs = ['node_project_form', 'node_project_edit_form'];

  if (in_array($form_id, $node_project_refs)) {
    //field_project_type is the entity reference field
    $entities_ref = $form['field_project_type']['widget']['entities'];

    foreach ($entities_ref as $key => $entity_ref) {

      if (is_numeric($key)) {
        $bundle_ref = $entity_ref['#entity']->bundle();
        $bundle_options = array_keys($form['field_project_type']['widget']['actions']['bundle']['#options']);
        $bundle_added = in_array($bundle_ref, $bundle_options);
        if ($bundle_added) {


php custom module