farm_project_plan-1.x-dev/src/Form/ProjectAddLogActionForm.php

src/Form/ProjectAddLogActionForm.php
<?php

namespace Drupal\farm_project_plan\Form;

use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Form\ConfirmFormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Session\AccountInterface;
use Drupal\Core\TempStore\PrivateTempStoreFactory;
use Drupal\Core\Url;
use Drupal\plan\Entity\Plan;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\RedirectResponse;

/**
 * Provides a project add log confirmation form.
 */
class ProjectAddLogActionForm extends ConfirmFormBase {

  /**
   * The tempstore factory.
   *
   * @var \Drupal\Core\TempStore\SharedTempStore
   */
  protected $tempStore;

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

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

  /**
   * The entity type.
   *
   * @var \Drupal\Core\Entity\EntityTypeInterface
   */
  protected $entityType;

  /**
   * The logs to add.
   *
   * @var \Drupal\Core\Entity\EntityInterface[]
   */
  protected $entities;

  /**
   * Constructs a ProjectAddLogActionForm form object.
   *
   * @param \Drupal\Core\TempStore\PrivateTempStoreFactory $temp_store_factory
   *   The tempstore factory.
   * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
   *   The entity type manager.
   * @param \Drupal\Core\Session\AccountInterface $user
   *   The current user.
   */
  public function __construct(PrivateTempStoreFactory $temp_store_factory, EntityTypeManagerInterface $entity_type_manager, AccountInterface $user) {
    $this->tempStore = $temp_store_factory->get('project_add_log_confirm');
    $this->entityTypeManager = $entity_type_manager;
    $this->user = $user;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static(
      $container->get('tempstore.private'),
      $container->get('entity_type.manager'),
      $container->get('current_user')
    );
  }

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

  /**
   * {@inheritdoc}
   */
  public function getQuestion() {
    return $this->formatPlural(count($this->entities), 'Are you sure you want to add this @item to the project?', 'Are you sure you want to add these @items to the project?', [
      '@item' => $this->entityType->getSingularLabel(),
      '@items' => $this->entityType->getPluralLabel(),
    ]);
  }

  /**
   * {@inheritdoc}
   */
  public function getCancelUrl() {
    if ($this->entityType->hasLinkTemplate('collection')) {
      return new Url('entity.' . $this->entityType->id() . '.collection');
    }
    else {
      return new Url('<front>');
    }
  }

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

  /**
   * {@inheritdoc}
   */
  public function getConfirmText() {
    return $this->t('Add to plan');
  }

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {
    $this->entityType = $this->entityTypeManager->getDefinition('log');
    $this->entities = $this->tempStore->get($this->user->id());
    if (empty($this->entityType) || empty($this->entities)) {
      return new RedirectResponse($this->getCancelUrl()
        ->setAbsolute()
        ->toString());
    }

    $form['project'] = [
      '#type' => 'entity_autocomplete',
      '#title' => $this->t('Project'),
      '#description' => $this->formatPlural(count($this->entities), 'The project to add this @item to.', 'The project to add these @items to.', [
        '@item' => $this->entityType->getSingularLabel(),
        '@items' => $this->entityType->getPluralLabel(),
      ]),
      '#target_type' => 'plan',
      '#target_bundles' => ['project'],
      '#validate_reference' => TRUE,
      '#maxlength' => 1024,
      '#required' => TRUE,
    ];

    return parent::buildForm($form, $form_state);
  }

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

    // Filter out entities the user doesn't have access to.
    $inaccessible_entities = [];
    $accessible_entities = [];
    foreach ($this->entities as $entity) {
      if (!$entity->access('view', $this->currentUser())) {
        $inaccessible_entities[] = $entity;
        continue;
      }
      $accessible_entities[] = $entity;
    }

    // Create an observation log to group the assets.
    if ($form_state->getValue('confirm') && !empty($accessible_entities)) {

      $project_id = $form_state->getValue('project');
      $project = Plan::load($project_id);
      if (empty($project)) {
        $this->messenger()->addWarning($this->t('Could not load project.'));
      }

      /** @var \Drupal\Core\Field\EntityReferenceFieldItemListInterface $log_field */
      $log_field = $project->get('log');
      foreach ($accessible_entities as $log) {
        $log_field->appendItem($log);
      }

      // Validate the project before saving.
      $violations = $project->validate();
      if ($violations->count() > 0) {
        $this->messenger()->addWarning(
          $this->t('Could not update project plan: validation failed.'),
        );
        $this->tempStore->delete($this->currentUser()->id());
        $form_state->setRedirectUrl($this->getCancelUrl());
        return;
      }

      // Add success message.
      $this->messenger()->addMessage($this->formatPlural(count($accessible_entities), 'Added @count @item to <a href=":entity_link">%entity_label</a>.', 'Added @count @items to <a href=":entity_link">%entity_label</a>', [
        '@item' => $this->entityType->getSingularLabel(),
        '@items' => $this->entityType->getPluralLabel(),
        ':entity_link' => $project->toUrl()->setAbsolute()->toString(),
        '%entity_label' => $project->label(),
      ]));

      // Save the project.
      $project->save();
    }

    // Add warning message for inaccessible entities.
    if (!empty($inaccessible_entities)) {
      $inaccessible_count = count($inaccessible_entities);
      $this->messenger()->addWarning($this->formatPlural($inaccessible_count, 'Could not add @count @item because you do not have the necessary permissions.', 'Could not add @count @items because you do not have the necessary permissions.', [
        '@item' => $this->entityType->getSingularLabel(),
        '@items' => $this->entityType->getPluralLabel(),
      ]));
    }

    $this->tempStore->delete($this->currentUser()->id());
    $form_state->setRedirectUrl($this->getCancelUrl());
  }

}

Главная | Обратная связь

drupal hosting | друпал хостинг | it patrol .inc