You are here

public function MediaForm::form in Lightning Media 8.4

Same name and namespace in other branches
  1. 8 src/Form/MediaForm.php \Drupal\lightning_media\Form\MediaForm::form()
  2. 8.2 src/Form/MediaForm.php \Drupal\lightning_media\Form\MediaForm::form()
  3. 8.3 src/Form/MediaForm.php \Drupal\lightning_media\Form\MediaForm::form()

Gets the actual form array to be built.

Overrides MediaForm::form

See also

\Drupal\Core\Entity\EntityForm::processForm()

\Drupal\Core\Entity\EntityForm::afterBuild()

File

src/Form/MediaForm.php, line 22

Class

MediaForm
Adds dynamic preview support to the media entity form.

Namespace

Drupal\lightning_media\Form

Code

public function form(array $form, FormStateInterface $form_state) {
  $form = parent::form($form, $form_state);

  /** @var \Drupal\media\MediaInterface $entity */
  $entity = $this
    ->getEntity();
  $field = Helper::getSourceField($entity);
  if ($field && !$field
    ->isEmpty()) {

    // Get the source field widget element.
    $widget_keys = [
      $field
        ->getName(),
      'widget',
      0,
      $field
        ->first()
        ->mainPropertyName(),
    ];
    $widget =& NestedArray::getValue($form, $widget_keys);

    // Add an attribute to identify it.
    $widget['#attributes']['data-source-field'] = TRUE;
    if (Helper::isPreviewable($entity)) {
      $widget['#ajax'] = [
        'callback' => [
          static::class,
          'onChange',
        ],
        'wrapper' => 'preview',
        'method' => 'html',
        'event' => 'change',
      ];
      $form['preview'] = [
        '#pre_render' => [
          [
            $this,
            'renderPreview',
          ],
        ],
        '#prefix' => '<div id="preview">',
        '#suffix' => '</div>',
      ];
    }
  }
  return $form;
}