View source
<?php
namespace Drupal\media_entity;
use Drupal\Core\Form\FormStateInterface;
use Drupal\entity\Form\RevisionableContentEntityForm;
class MediaForm extends RevisionableContentEntityForm {
protected $settings;
protected $entity;
protected function prepareEntity() {
parent::prepareEntity();
$media = $this->entity;
if ($media
->isNew()) {
$media
->setPublisherId($this
->currentUser()
->id());
$media
->setCreatedTime(REQUEST_TIME);
}
}
public function form(array $form, FormStateInterface $form_state) {
$form = parent::form($form, $form_state);
if (isset($form['uid']) || isset($form['created'])) {
$form['author'] = [
'#type' => 'details',
'#title' => $this
->t('Authoring information'),
'#group' => 'advanced',
'#attributes' => [
'class' => [
'node-form-author',
],
],
'#attached' => [
'library' => [
'node/drupal.node',
],
],
'#weight' => 90,
'#optional' => TRUE,
];
}
if (isset($form['uid'])) {
$form['uid']['#group'] = 'author';
}
if (isset($form['created'])) {
$form['created']['#group'] = 'author';
}
$form['#attached']['library'][] = 'node/form';
$form['#entity_builders']['update_status'] = [
$this,
'updateStatus',
];
return $form;
}
protected function actions(array $form, FormStateInterface $form_state) {
$element = parent::actions($form, $form_state);
$media = $this->entity;
$element['publish'] = $element['submit'];
$element['publish']['#published_status'] = TRUE;
$element['publish']['#dropbutton'] = 'save';
if ($media
->isNew()) {
$element['publish']['#value'] = $this
->t('Save and publish');
}
else {
$element['publish']['#value'] = $media
->isPublished() ? $this
->t('Save and keep published') : $this
->t('Save and publish');
}
$element['publish']['#weight'] = 0;
$element['unpublish'] = $element['submit'];
$element['unpublish']['#published_status'] = FALSE;
$element['unpublish']['#dropbutton'] = 'save';
if ($media
->isNew()) {
$element['unpublish']['#value'] = $this
->t('Save as unpublished');
}
else {
$element['unpublish']['#value'] = !$media
->isPublished() ? $this
->t('Save and keep unpublished') : $this
->t('Save and unpublish');
}
$element['unpublish']['#weight'] = 10;
if ($media
->isPublished()) {
unset($element['unpublish']['#button_type']);
}
else {
unset($element['publish']['#button_type']);
$element['unpublish']['#weight'] = -10;
}
$element['submit']['#access'] = FALSE;
$element['delete']['#access'] = $media
->access('delete');
$element['delete']['#weight'] = 100;
return $element;
}
public function updateStatus($entity_type_id, MediaInterface $media, array $form, FormStateInterface $form_state) {
$element = $form_state
->getTriggeringElement();
if (isset($element['#published_status'])) {
$media
->setPublished($element['#published_status']);
}
}
}