MediaForm.php in Lightning Media 8
File
src/Form/MediaForm.php
View source
<?php
namespace Drupal\lightning_media\Form;
use Drupal\Component\Utility\NestedArray;
use Drupal\Core\Form\FormStateInterface;
use Drupal\lightning_core\Form\BulkCreationEntityFormTrait;
use Drupal\lightning_media\MediaHelper as Helper;
use Drupal\media\MediaForm as BaseMediaForm;
class MediaForm extends BaseMediaForm {
use BulkCreationEntityFormTrait;
public function form(array $form, FormStateInterface $form_state) {
$form = parent::form($form, $form_state);
$entity = $this
->getEntity();
$field = Helper::getSourceField($entity);
if ($field && !$field
->isEmpty()) {
$widget_keys = [
$field
->getName(),
'widget',
0,
$field
->first()
->mainPropertyName(),
];
$widget =& NestedArray::getValue($form, $widget_keys);
$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;
}
public function renderPreview(array $element) {
$entity = $this
->getEntity();
return $element + Helper::getSourceField($entity)
->view('default');
}
public static function onChange(array &$form, FormStateInterface $form_state) {
$handler = $form_state
->getFormObject();
$entity = $handler
->getEntity();
$handler
->copyFormValuesToEntity($entity, $form, $form_state);
return Helper::getSourceField($entity)
->view('default');
}
}
Classes
Name |
Description |
MediaForm |
Adds dynamic preview support to the media entity form. |