You are here

class EntityCloneForm in Entity Clone 8

Implements an entity Clone form.

Hierarchy

Expanded class hierarchy of EntityCloneForm

File

src/Form/EntityCloneForm.php, line 23

Namespace

Drupal\entity_clone\Form
View source
class EntityCloneForm extends FormBase {

  /**
   * The entity type manager.
   *
   * @var \Drupal\Core\Entity\EntityTypeManagerInterface
   */
  protected $entityTypeManager;

  /**
   * The entity ready to clone.
   *
   * @var \Drupal\Core\Entity\EntityInterface
   */
  protected $entity;

  /**
   * The entity type définition.
   *
   * @var \Drupal\Core\Entity\EntityTypeInterface
   */
  protected $entityTypeDefinition;

  /**
   * The string translation manager.
   *
   * @var \Drupal\Core\StringTranslation\TranslationManager
   */
  protected $stringTranslationManager;

  /**
   * Event dispatcher service.
   *
   * @var \Symfony\Component\EventDispatcher\EventDispatcherInterface
   */
  protected $eventDispatcher;

  /**
   * The messenger service.
   *
   * @var \Drupal\Core\Messenger\Messenger
   */
  protected $messenger;

  /**
   * The current user.
   *
   * @var \Drupal\Core\Session\AccountInterface
   */
  protected $currentUser;

  /**
   * The entity clone settings manager service.
   *
   * @var \Drupal\entity_clone\EntityCloneSettingsManager
   */
  protected $entityCloneSettingsManager;

  /**
   * The Service Provider that verifies if entity has ownership.
   *
   * @var \Drupal\entity_clone\Services\EntityCloneServiceProvider
   */
  protected $serviceProvider;

  /**
   * Constructs a new Entity Clone form.
   *
   * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
   *   The entity type manager.
   * @param \Drupal\Core\Routing\RouteMatchInterface $route_match
   *   The route match service.
   * @param \Drupal\Core\StringTranslation\TranslationManager $string_translation
   *   The string translation manager.
   * @param \Symfony\Component\EventDispatcher\EventDispatcherInterface $eventDispatcher
   *   The event dispatcher service.
   * @param \Drupal\Core\Messenger\Messenger $messenger
   *   The messenger service.
   * @param \Drupal\Core\Session\AccountProxyInterface $currentUser
   *   The current user.
   * @param \Drupal\entity_clone\EntityCloneSettingsManager $entity_clone_settings_manager
   *   The entity clone settings manager.
   * @param \Drupal\entity_clone\Services\EntityCloneServiceProvider $service_provider
   *   The Service Provider that verifies if entity has ownership.
   *
   * @throws \Drupal\Component\Plugin\Exception\PluginNotFoundException
   */
  public function __construct(EntityTypeManagerInterface $entity_type_manager, RouteMatchInterface $route_match, TranslationManager $string_translation, EventDispatcherInterface $eventDispatcher, Messenger $messenger, AccountProxyInterface $currentUser, EntityCloneSettingsManager $entity_clone_settings_manager, EntityCloneServiceProvider $service_provider) {
    $this->entityTypeManager = $entity_type_manager;
    $this->stringTranslationManager = $string_translation;
    $this->eventDispatcher = $eventDispatcher;
    $this->messenger = $messenger;
    $parameter_name = $route_match
      ->getRouteObject()
      ->getOption('_entity_clone_entity_type_id');
    $this->entity = $route_match
      ->getParameter($parameter_name);
    $this->entityTypeDefinition = $entity_type_manager
      ->getDefinition($this->entity
      ->getEntityTypeId());
    $this->currentUser = $currentUser;
    $this->entityCloneSettingsManager = $entity_clone_settings_manager;
    $this->serviceProvider = $service_provider;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static($container
      ->get('entity_type.manager'), $container
      ->get('current_route_match'), $container
      ->get('string_translation'), $container
      ->get('event_dispatcher'), $container
      ->get('messenger'), $container
      ->get('current_user'), $container
      ->get('entity_clone.settings.manager'), $container
      ->get('entity_clone.service_provider'));
  }

  /**
   * {@inheritdoc}
   */
  public function getFormId() {
    return 'entity_clone_form';
  }

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {
    if ($this->entity && $this->entityTypeDefinition
      ->hasHandlerClass('entity_clone')) {

      /** @var \Drupal\entity_clone\EntityClone\EntityCloneFormInterface $entity_clone_handler */
      if ($this->entityTypeManager
        ->hasHandler($this->entityTypeDefinition
        ->id(), 'entity_clone_form')) {
        $entity_clone_form_handler = $this->entityTypeManager
          ->getHandler($this->entityTypeDefinition
          ->id(), 'entity_clone_form');
        $form = array_merge($form, $entity_clone_form_handler
          ->formElement($this->entity));
      }
      $entityType = $this
        ->getEntity()
        ->getEntityTypeId();
      if ($this->serviceProvider
        ->entityTypeHasOwnerTrait($this
        ->getEntity()
        ->getEntityType()) && $this->currentUser
        ->hasPermission('take_ownership_on_clone ' . $entityType . ' entity')) {
        $form['take_ownership'] = [
          '#type' => 'checkbox',
          '#title' => $this->stringTranslationManager
            ->translate('Take ownership'),
          '#default_value' => $this->entityCloneSettingsManager
            ->getTakeOwnershipSetting(),
          '#description' => $this->stringTranslationManager
            ->translate('Take ownership of the newly created cloned entity.'),
        ];
      }
      $form['actions'] = [
        '#type' => 'actions',
      ];
      $form['actions']['clone'] = [
        '#type' => 'submit',
        '#button_type' => 'primary',
        '#value' => $this->stringTranslationManager
          ->translate('Clone'),
      ];
      $form['actions']['abort'] = [
        '#type' => 'submit',
        '#value' => $this->stringTranslationManager
          ->translate('Cancel'),
        '#submit' => [
          '::cancelForm',
        ],
      ];
    }
    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function validateForm(array &$form, FormStateInterface $form_state) {
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {

    /** @var \Drupal\entity_clone\EntityClone\EntityCloneInterface $entity_clone_handler */
    $entity_clone_handler = $this->entityTypeManager
      ->getHandler($this->entityTypeDefinition
      ->id(), 'entity_clone');
    if ($this->entityTypeManager
      ->hasHandler($this->entityTypeDefinition
      ->id(), 'entity_clone_form')) {
      $entity_clone_form_handler = $this->entityTypeManager
        ->getHandler($this->entityTypeDefinition
        ->id(), 'entity_clone_form');
    }
    $properties = [];
    if (isset($entity_clone_form_handler) && $entity_clone_form_handler) {
      $properties = $entity_clone_form_handler
        ->getValues($form_state);
    }
    $duplicate = $this->entity
      ->createDuplicate();
    $this->eventDispatcher
      ->dispatch(EntityCloneEvents::PRE_CLONE, new EntityCloneEvent($this->entity, $duplicate, $properties));
    $cloned_entity = $entity_clone_handler
      ->cloneEntity($this->entity, $duplicate, $properties);
    $this->eventDispatcher
      ->dispatch(EntityCloneEvents::POST_CLONE, new EntityCloneEvent($this->entity, $duplicate, $properties));
    $this->messenger
      ->addMessage($this->stringTranslationManager
      ->translate('The entity <em>@entity (@entity_id)</em> of type <em>@type</em> was cloned.', [
      '@entity' => $this->entity
        ->label(),
      '@entity_id' => $this->entity
        ->id(),
      '@type' => $this->entity
        ->getEntityTypeId(),
    ]));
    $this
      ->formSetRedirect($form_state, $cloned_entity);
  }

  /**
   * Cancel form handler.
   *
   * @param array $form
   *   An associative array containing the structure of the form.
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   The current state of the form.
   */
  public function cancelForm(array &$form, FormStateInterface $form_state) {
    $this
      ->formSetRedirect($form_state, $this->entity);
  }

  /**
   * Sets a redirect on form state.
   *
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   The current state of the form.
   * @param \Drupal\Core\Entity\EntityInterface $entity
   *   The cloned entity.
   */
  protected function formSetRedirect(FormStateInterface $form_state, EntityInterface $entity) {
    if ($entity && $entity
      ->hasLinkTemplate('canonical')) {
      $form_state
        ->setRedirect($entity
        ->toUrl()
        ->getRouteName(), $entity
        ->toUrl()
        ->getRouteParameters());
    }
    else {
      $form_state
        ->setRedirect('<front>');
    }
  }

  /**
   * Gets the entity of this form.
   *
   * @return \Drupal\Core\Entity\EntityInterface
   *   The entity.
   */
  public function getEntity() {
    return $this->entity;
  }

}

Members

Namesort descending Modifiers Type Description Overrides
DependencySerializationTrait::$_entityStorages protected property An array of entity type IDs keyed by the property name of their storages.
DependencySerializationTrait::$_serviceIds protected property An array of service IDs keyed by property name used for serialization.
DependencySerializationTrait::__sleep public function 1
DependencySerializationTrait::__wakeup public function 2
EntityCloneForm::$currentUser protected property The current user.
EntityCloneForm::$entity protected property The entity ready to clone.
EntityCloneForm::$entityCloneSettingsManager protected property The entity clone settings manager service.
EntityCloneForm::$entityTypeDefinition protected property The entity type définition.
EntityCloneForm::$entityTypeManager protected property The entity type manager.
EntityCloneForm::$eventDispatcher protected property Event dispatcher service.
EntityCloneForm::$messenger protected property The messenger service. Overrides MessengerTrait::$messenger
EntityCloneForm::$serviceProvider protected property The Service Provider that verifies if entity has ownership.
EntityCloneForm::$stringTranslationManager protected property The string translation manager.
EntityCloneForm::buildForm public function Form constructor. Overrides FormInterface::buildForm
EntityCloneForm::cancelForm public function Cancel form handler.
EntityCloneForm::create public static function Instantiates a new instance of this class. Overrides FormBase::create
EntityCloneForm::formSetRedirect protected function Sets a redirect on form state.
EntityCloneForm::getEntity public function Gets the entity of this form.
EntityCloneForm::getFormId public function Returns a unique string identifying the form. Overrides FormInterface::getFormId
EntityCloneForm::submitForm public function Form submission handler. Overrides FormInterface::submitForm
EntityCloneForm::validateForm public function Form validation handler. Overrides FormBase::validateForm
EntityCloneForm::__construct public function Constructs a new Entity Clone form.
FormBase::$configFactory protected property The config factory. 1
FormBase::$requestStack protected property The request stack. 1
FormBase::$routeMatch protected property The route match.
FormBase::config protected function Retrieves a configuration object.
FormBase::configFactory protected function Gets the config factory for this form. 1
FormBase::container private function Returns the service container.
FormBase::currentUser protected function Gets the current user.
FormBase::getRequest protected function Gets the request object.
FormBase::getRouteMatch protected function Gets the route match.
FormBase::logger protected function Gets the logger for a specific channel.
FormBase::redirect protected function Returns a redirect response object for the specified route. Overrides UrlGeneratorTrait::redirect
FormBase::resetConfigFactory public function Resets the configuration factory.
FormBase::setConfigFactory public function Sets the config factory for this form.
FormBase::setRequestStack public function Sets the request stack object to use.
LinkGeneratorTrait::$linkGenerator protected property The link generator. 1
LinkGeneratorTrait::getLinkGenerator Deprecated protected function Returns the link generator.
LinkGeneratorTrait::l Deprecated protected function Renders a link to a route given a route name and its parameters.
LinkGeneratorTrait::setLinkGenerator Deprecated public function Sets the link generator service.
LoggerChannelTrait::$loggerFactory protected property The logger channel factory service.
LoggerChannelTrait::getLogger protected function Gets the logger for a specific channel.
LoggerChannelTrait::setLoggerFactory public function Injects the logger channel factory.
MessengerTrait::messenger public function Gets the messenger. 29
MessengerTrait::setMessenger public function Sets the messenger.
RedirectDestinationTrait::$redirectDestination protected property The redirect destination service. 1
RedirectDestinationTrait::getDestinationArray protected function Prepares a 'destination' URL query parameter for use with \Drupal\Core\Url.
RedirectDestinationTrait::getRedirectDestination protected function Returns the redirect destination service.
RedirectDestinationTrait::setRedirectDestination public function Sets the redirect destination service.
StringTranslationTrait::$stringTranslation protected property The string translation service. 1
StringTranslationTrait::formatPlural protected function Formats a string containing a count of items.
StringTranslationTrait::getNumberOfPlurals protected function Returns the number of plurals supported by a given language.
StringTranslationTrait::getStringTranslation protected function Gets the string translation service.
StringTranslationTrait::setStringTranslation public function Sets the string translation service to use. 2
StringTranslationTrait::t protected function Translates a string to the current language or to a given language.
UrlGeneratorTrait::$urlGenerator protected property The url generator.
UrlGeneratorTrait::getUrlGenerator Deprecated protected function Returns the URL generator service.
UrlGeneratorTrait::setUrlGenerator Deprecated public function Sets the URL generator service.
UrlGeneratorTrait::url Deprecated protected function Generates a URL or path for a specific route based on the given parameters.