Theming: Alter the seven administrative theme in Drupal 8 - michaellenahan/blog GitHub Wiki

Some context

Hi, I'm Michael, a Drupal developer working on daskochrezept.de, a website showcasing delicious recipes. The site is based on thunder, a platform for professional publishing.

The requirement

In order to provide more context for our editors when they are on editing a Drupal node, we wanted to embed the main food picture in the right-hand-side of the node edit form, so it looks like this:

Node edit form with image below published block on right-hand-side

The code

Here's the code.

/**
 * Implements hook_form_BASE_FORM_ID_alter() for \Drupal\node\NodeForm.
 *
 * Display the main recipe picture on the node edit form.
 */
function dkr_theme_form_node_form_alter(&$form, FormState $form_state) {
  $node = $form_state->getFormObject()->getEntity();
  if ($node->hasField('field_recipe_images')) {
    $images = $node->get('field_recipe_images');
    if ($images->count() > 0) {
      $media_entity = $images[0]->entity;
      $view_builder = \Drupal::entityTypeManager()->getViewBuilder('media');
      // Go to admin/structure/display-modes/view to see available view modes.
      $view_mode = 'article_media';
      $render_array = $view_builder->view($media_entity, $view_mode);
      $markup = \Drupal::service('renderer')->renderRoot($render_array);
      $form['advanced']['recipe_image'] = array(
        'markup' => array(
          '#markup' => $markup,
        ),
      );
    }
  }
}

I confess I feel I'm cheating a little here, by firstly extracting the markup from the rendered media entity, and then placing the markup in the form's render array. If you can find a better way, please let me know by opening an issue here: https://github.com/michaellenahan/blog/issues