How do you modify entity references on a form in a custom ajax action in Drupal 8?

1.6k views Asked by At

I have added a custom button to a form:

    $form['actions']['autotag_content'] = [
     '#type' => 'button',
     '#value' => 'Autotag Content',
     '#ajax' => [ 
       'callback' => ['\Drupal\taxonomy_migrate\taggerService', 'tagContent'],
       'wrapper' => ['block-adminimal-theme-content'],
       'progress' => [ 
         'type' => 'throbber',
         'message' => 'Tagging content',
       ],
     ],
   ];

Then in the callback I want to add or remove entities from an entity reference field on the form. This would then get sent back to the browser and rerendered. I don't want the changes to be save, I just want them populated in the form and then the user can accept the changes.

For the sake of this example, I have simplified this to just demonstrate the point. I would like to add two entity references to field_tax_subjects and have the frontend form rerender. Currently, the frontend form rerenders, but doesn't reflect the changes

public static function tagContent(array &$form, FormStateInterface &$form_state) {
  $node = $form_state->getFormObject()->getEntity();

  $node->field_tax_subjects[] = 12345;
  $node->field_tax_subjects[] = 23456;

  $form = \Drupal::service('entity.form_builder')->getForm($node);
  $form_state->setRebuild();

  return $form;
}
1

There are 1 answers

2
code.rider On

my answer is just for in case your ajax is working because in your question you have'nt full code of form also its not clear its node form or something else any way

If your ajax is working you only have to correct how to set value for entity reference field and term reference filed

for entity reference and term reference

public static function tagContent(array &$form, FormStateInterface &$form_state) {
  $node = $form_state->getFormObject()->getEntity();

  // for entity refrence
  $node->field_tax_subjects[]['target_id'] = 12345;
  $node->field_tax_subjects[]['target_id'] = 23456;

  // for term reference
  //$node->field_tax_subjects[]['tid'] = 12345;
  //$node->field_tax_subjects[]['tid'] = 23456;

  $form = \Drupal::service('entity.form_builder')->getForm($node);
  $form_state->setRebuild();

  return $form;
}

HOPE THIS HELP YOU

THANKS