Skip to content

Instantly share code, notes, and snippets.

@drubb
Last active July 14, 2022 08:25
Show Gist options
  • Save drubb/c5a4a4f09c7cee00b2e4f92cf35edb70 to your computer and use it in GitHub Desktop.
Save drubb/c5a4a4f09c7cee00b2e4f92cf35edb70 to your computer and use it in GitHub Desktop.
Update a Drupal text field using a media entity selected in a paragraph using entity browser.
script:
js:
js/script.js: {}
dependencies:
- core/drupal
- core/jquery
- core/once
<?php
use Drupal\Core\Ajax\AjaxResponse;
use Drupal\Core\Ajax\InvokeCommand;
use Drupal\media\Entity\Media;
/**
* @file
* Primary module hooks for Ajax module.
*/
/**
* Implements hook_form_BASE_FORM_ID_alter().
*
* @hook
*/
function ajax_form_node_form_alter(&$form, &$form_state, $form_id): void {
if ($form_id === 'node_page_form' || $form_id === 'node_page_edit_form') {
// Add a wrapper and an ajax behavior to the target field.
$form['field_label']['#prefix'] = '<div id="ajax-wrapper">';
$form['field_label']['#suffix'] = '</div>';
$form['field_label']['widget'][0]['value']['#ajax'] = [
'callback' => 'ajax_callback',
'event' => 'my-event',
];
// Add a hidden field to the form, to pass the current media id.
$form['mid'] = [
'#type' => 'hidden',
'#attributes' => [
'id' => 'mid',
],
];
// Add the custom JavaScript to the page.
$form['#attached']['library'][] = 'ajax/script';
}
}
/**
* Ajax callback
*
* @callback
*/
function ajax_callback($form, $form_state): AjaxResponse {
// Use the media id passed in the hidden form field to load the media entity.
$mid = $form_state->getValue('mid');
$media = Media::load($mid);
$text = $media ? $media->label() : 'Media entity not found';
// Update the target field using a custom JavaScript function.
$response = new AjaxResponse();
$response->addCommand(new InvokeCommand(NULL, 'updateLabel', [$text]));
return $response;
}
(function ($, Drupal, once) {
Drupal.behaviors.myModuleBehavior = {
attach: function () {
once('entitySelected', 'body').forEach(function (element) {
$(element).on('entities-selected', function (event, uuid, entities) {
if (entities.length > 0) {
$('#mid').val(entities[0][0]);
$("#ajax-wrapper input").trigger('my-event');
}
});
});
},
detach: function (context, settings) {
}
};
$.fn.updateLabel = function (argument) {
$('#edit-field-label-0-value').val(argument);
};
})(jQuery, Drupal, once);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment