How to use AJAX to fill in a date field from an entity selected using an entityref autocomplete field.
One of the things most startling about Drupal 8 is the lack of documentation or false documentation on many simple everyday tasks. I went looking for how to set a (date) field on an entity form when another entity was selected from an entity reference autocomplete field on that form. I found a slew of incorrect or incomplete answers including the official documentation on Drupal.org. Here is my solution:
I have a date field on an Event entity. I have a second entity (Request) form with an autocomplete entity reference field to those Events. When i select an event from the autocomplete; I want the Event's date to be used as the default value in the date field on the Request form.
at the top of my custom module:
use Drupal\node\Entity\Node; use Drupal\Core\Ajax\AjaxResponse; use Drupal\Core\Ajax\InvokeCommand;
in my form_alter I have this:
$form['field_my_autocomplete_entityref']['widget'][0]['target_id']['#ajax'] = [ 'callback' => '_mymodule_autofill_date', 'event' => 'autocompleteclose', ];
I then add the callback function in my custom module:
function _mymodule_autofill_date($form, $form_state) { $eid = $form_state->getValue('field_my_autocomplete_entityref')[0]['target_id']; $event = Node::load($eid); // set Request date fields as same value set in Event $start = $event->field_event_date->value; $end = $event->field_event_date->end_value; $response = new AjaxResponse(); $response->addCommand(new InvokeCommand('#edit-field-event-date-0-value-date', 'val', [$start])); $response->addCommand(new InvokeCommand('#edit-field-event-date-0-end-value-date', 'val', [$end])); return $response; }
Hope this helps someone else out.
Comments (5)
Add Comment