ispim-1.0.x-dev/src/PreviewImage/AddForm.php
src/PreviewImage/AddForm.php
<?php
declare(strict_types=1);
namespace Drupal\ispim\PreviewImage;
use Drupal\Component\Utility\Xss;
use Drupal\Core\Entity\ContentEntityForm;
use Drupal\Core\Form\FormStateInterface;
use Drupal\user\EntityOwnerInterface;
class AddForm extends ContentEntityForm {
/**
* {@inheritdoc}
*
* @phpstan-param array<string, mixed> $form
*
* @return array<string, mixed>
*/
public function form(array $form, FormStateInterface $form_state): array {
$entityType = $this->entity->getEntityType();
$config = $this->getConfig();
$form = parent::form($form, $form_state);
if (!empty($config['help'])) {
$form['help'] = [
'#markup' => $config['help'],
'#allowed_tags' => Xss::getAdminTagList(),
'#weight' => -99,
'#theme_wrappers' => [
'container',
],
'#attributes' => [
'class' => [
'help-wrapper',
],
],
];
}
if ($this->entity instanceof EntityOwnerInterface) {
$form['author'] = [
'#type' => 'details',
'#title' => $this->t('Authoring information'),
'#group' => 'advanced',
'#weight' => 90,
'#optional' => TRUE,
];
$keyOwner = $entityType->getKey('owner');
if (isset($form[$keyOwner])) {
$form[$keyOwner]['#group'] = 'author';
}
if (isset($form['created'])) {
$form['created']['#group'] = 'author';
}
}
return $form;
}
/**
* @return array<string, mixed>
*
* @throws \Drupal\Component\Plugin\Exception\InvalidPluginDefinitionException
* @throws \Drupal\Component\Plugin\Exception\PluginNotFoundException
*/
protected function getConfig(): array {
$bundleEntityTypeId = $this->entity->getEntityType()->getBundleEntityType();
if ($bundleEntityTypeId) {
// @todo What if the $bundleEntityTypeId does not exists?
/* @noinspection PhpUnhandledExceptionInspection */
return $this
->entityTypeManager
->getStorage($this->entity->getEntityType()->getBundleEntityType())
->load($this->entity->bundle())
->toArray();
}
$configName = "ispim.{$this->entity->getEntityTypeId()}.settings";
return $this
->configFactory()
->get($configName)
->get();
}
/**
* {@inheritdoc}
*
* @phpstan-param array<string, mixed> $form
*
* @throws \Drupal\Core\Entity\EntityMalformedException
*/
public function save(array $form, FormStateInterface $form_state): int {
$result = parent::save($form, $form_state);
$this->saveSetMessage();
$form_state->setRedirectUrl($this->entity->toUrl('canonical'));
return $result;
}
protected function saveSetMessage(): static {
$args = [
'%label' => $this->entity->label(),
'@type' => $this->entity->getEntityType()->getLabel(),
];
$this->messenger()->addStatus($this->t('"%label" @type has been created', $args));
return $this;
}
}
