1

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?

0

1 Answer 1

1

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,
];
1
  • Thanks that worked great! Helpful as always Clive
    – Amy
    May 18, 2022 at 21:39

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.