Score:1

How to add new fields to the 'edit media' dialog box on media embeds

cn flag

I'm attempting to add a new select box to the dialog box that pops up when choosing 'edit media' on a media embed in a WYSIWYG. I'm referring to the dialog box that presents options like 'caption' and 'alignment'

I was able to make the field appear by using

function mymodule_form_alter(array &$form, FormStateInterface $form_state, string $form_id)  {
if($form_id=='editor_media_dialog'){
  $form['size'] = [
    '#title' => t('Size'),
    '#type' => 'select',
    '#options' => [
      '' => t('Default'),
      '-small' => t('Small'),
      '-medium' => t('Medium'),
      '-large' => t('Large'),
    ],
  ];
 }
}

but I can't seem to be able to make that value save in anyway. When saving and reopening the dialog box there is no reference to the new value in $form_state.

What would be the proper way to add fields to the 'edit media' dialog box of embedded media entities in a WYSIWYG?

Score:1
cn flag

These dialogs work like so:

  • When you save the form, everything inside attributes in the form state is added as a literal HTML attribute to the <drupal-media> element which the modal was launched for. So the data gets saved in the markup itself.
  • When you load the form again, all of the HTML attributes currently on the element are passed through to the form, so the inputs can be populated.

So all you need to do is:

  1. Get your form element into the attributes array, so it will be applied to the markup automagically. You can do this by setting the #parents on the element.
  2. Set the #default_value to the one passed in from the editor. Those values are available from the user input, rather than the form state values.

Your final code might look like this:

$size = $form_state->getUserInput()['editor_object']['attributes']['size'] ?? '';

$form['size'] = [
  '#title' => t('Size'),
  '#type' => 'select',
  '#options' => [
    '' => t('Default'),
    '-small' => t('Small'),
    '-medium' => t('Medium'),
    '-large' => t('Large'),
  ],
  '#parents' => ['attributes', 'size'],
  '#default_value' => $size,
];
Matt avatar
cn flag
Thanks that worked great! Helpful as always Clive
mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.