xtcentity-2.x-dev/src/Form/XtendedContentForm.php
src/Form/XtendedContentForm.php
<?php
namespace Drupal\xtcentity\Form;
use Drupal\Core\Entity\ContentEntityForm;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Routing\RouteMatchInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
/**
* Form controller for Xtended Content edit forms.
*
* @ingroup xtcentity
*/
class XtendedContentForm extends ContentEntityForm {
/**
* The current user account.
*
* @var \Drupal\Core\Session\AccountProxyInterface
*/
protected $account;
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container) {
// Instantiates this form class.
$instance = parent::create($container);
$instance->account = $container->get('current_user');
return $instance;
}
/**
* {@inheritdoc}
*/
public function getEntityFromRouteMatch(RouteMatchInterface $route_match, $entity_type_id) {
if ($route_match->getRawParameter($entity_type_id) !== NULL) {
$entity = $route_match->getParameter($entity_type_id);
}
else {
$values = [];
// If the entity has bundles, fetch it from the route match.
$entity_type = $this->entityTypeManager->getDefinition($entity_type_id);
if ($bundle_key = $entity_type->getKey('bundle')) {
if (($bundle_entity_type_id = $entity_type->getBundleEntityType()) && $route_match->getRawParameter($bundle_entity_type_id)) {
$values[$bundle_key] = $route_match->getParameter($bundle_entity_type_id);
}
elseif ($route_match->getRawParameter($bundle_key)) {
$values[$bundle_key] = $route_match->getParameter($bundle_key);
}
}
$entity = $this->entityTypeManager->getStorage($entity_type_id)->create($values);
}
return $entity;
}
/**
* {@inheritdoc}
*/
public function save(array $form, FormStateInterface $form_state) {
$entity = $this->entity;
$status = parent::save($form, $form_state);
switch ($status) {
case SAVED_NEW:
$this->messenger()->addMessage($this->t('Created the %label Xtended Content.', [
'%label' => $entity->label(),
]));
break;
default:
$this->messenger()->addMessage($this->t('Saved the %label Xtended Content.', [
'%label' => $entity->label(),
]));
}
$form_state->setRedirect('entity.xtended_content.canonical', ['xtended_content' => $entity->id()]);
}
}
