You are here

class ExtendMerciLineItem in MERCI (Manage Equipment Reservations, Checkout and Inventory) 8.2

Promotes a merci_line_item.

Plugin annotation


@Action(
  id = "merci_line_item_extend_action",
  label = @Translation("Extend item."),
  type = "merci_line_item"
)

Hierarchy

Expanded class hierarchy of ExtendMerciLineItem

File

modules/merci_line_item/src/Plugin/Action/ExtendMerciLineItem.php, line 25

Namespace

Drupal\merci_line_item\Plugin\Action
View source
class ExtendMerciLineItem extends ConfigurableActionBase implements ContainerFactoryPluginInterface {
  use ViewsBulkOperationsFormTrait;

  /**
   * User private temporary storage factory.
   *
   * @var \Drupal\user\PrivateTempStoreFactory
   */
  protected $tempStoreFactory;

  /**
   * The current user object.
   *
   * @var \Drupal\Core\Session\AccountInterface
   */
  protected $currentUser;
  use DependencyTrait;
  public function __construct(PrivateTempStoreFactory $tempStoreFactory, AccountInterface $currentUser, array $configuration, $plugin_id, $plugin_definition) {
    parent::__construct($configuration, $plugin_id, $plugin_definition);
    $this->tempStoreFactory = $tempStoreFactory;
    $this->currentUser = $currentUser;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
    return new static($container
      ->get('user.private_tempstore'), $container
      ->get('current_user'), $configuration, $plugin_id, $plugin_definition);
  }

  /**
   * Gets the current user.
   *
   * @return \Drupal\Core\Session\AccountInterface
   *   The current user.
   */
  protected function currentUser() {
    return $this->currentUser;
  }

  /**
   * {@inheritdoc}
   */
  public function execute($entity = NULL) {
    $extend_interval = $this->configuration['extend_interval'];
    $date_field = 'merci_reservation_date';
    $end_date = new DrupalDateTime($entity->{$date_field}
      ->getValue()[0]['end_value'] . ' ' . $extend_interval);
    $end_date_string = $end_date
      ->format(DATETIME_DATETIME_STORAGE_FORMAT);
    $date = $entity->{$date_field}
      ->getValue();
    $date[0]['end_value'] = $end_date_string;
    $entity->{$date_field}
      ->setValue($date);
    $entity
      ->save();
  }

  /**
   * {@inheritdoc}
   */
  public function buildPreConfigurationForm(array $form, array $values, FormStateInterface $form_state) {
    $form['validate_entities'] = [
      '#title' => $this
        ->t('Validate before processing'),
      '#type' => 'checkbox',
      '#default_value' => isset($values['validate_entities']) ? $values['validate_entities'] : '',
    ];
    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function defaultConfiguration() {
    return [
      'extend_interval' => '+1 days',
    ];
  }
  public function validateConfigurationForm(array &$form, FormStateInterface $form_state) {

    //    $form_state ->setErrorByName('extend_interval', t('Fix the errors or override validation.'));
  }

  /**
   * {@inheritdoc}
   */
  public function buildConfigurationForm(array $form, FormStateInterface $form_state) {
    $form_data = $form_state
      ->get('views_bulk_operations');
    $form['extend_interval'] = [
      '#type' => 'textfield',
      '#title' => t('Default checkin date and time.'),
      '#default_value' => $this->configuration['extend_interval'],
      '#required' => TRUE,
    ];
    $validation_errors = $this
      ->getTempstore($form_data['view_id'], $form_data['display_id'])
      ->get('validation_errors');
    if ($validation_errors) {
      foreach ($validation_errors as $entity_id => $violations) {
        $label = $violations
          ->getEntity()
          ->label();
        drupal_set_message(t('Errors for %label', [
          '%label' => $label,
        ]));
        foreach ($violations as $violation) {
          drupal_set_message($violation
            ->getMessage());
        }
      }
      $form['override_validation'] = [
        '#type' => 'checkbox',
        '#title' => t('Override Validation Errors'),
        '#default_value' => $form_state
          ->getValue('override_validation'),
      ];
      $this
        ->getTempstore($form_data['view_id'], $form_data['display_id'])
        ->delete('validation_errors');
    }
    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function submitConfigurationForm(array &$form, FormStateInterface $form_state) {
    $this->configuration['extend_interval'] = $form_state
      ->getValue('extend_interval');
    $violations = array();
    if ($form_data = $form_state
      ->get('views_bulk_operations') and $form_data['preconfiguration']['validate_entities'] and $form_state
      ->getValue('override_validation') == FALSE) {
      $form_data = $form_state
        ->get('views_bulk_operations');
      if (!$form_data) {
        return;
      }
      $entity_ids = array();
      foreach ($form_data['list'] as $item) {
        $entity_ids[] = $item[0];
      }
      $entities = \Drupal::entityTypeManager()
        ->getStorage('merci_line_item')
        ->loadMultiple($entity_ids);
      $extend_interval = $form_state
        ->getValue('extend_interval');
      $date_field = 'merci_reservation_date';
      foreach ($entities as $entity) {
        $end_date = new DrupalDateTime($entity->{$date_field}
          ->getValue()[0]['end_value'] . ' ' . $extend_interval);
        $end_date_string = $end_date
          ->format(DATETIME_DATETIME_STORAGE_FORMAT);
        $date = $entity->{$date_field}
          ->getValue();
        $date[0]['end_value'] = $end_date_string;
        $entity->{$date_field}
          ->setValue($date);
        $violation = $entity
          ->validate();
        if ($violation
          ->has(0) == TRUE) {
          $violations[$entity
            ->id()] = $violation;
        }
      }
    }
    if (count($violations)) {
      $this
        ->getTempstore($form_data['view_id'], $form_data['display_id'])
        ->set('validation_errors', $violations);
      $form_state
        ->setRebuild();
    }
  }

  /**
   * {@inheritdoc}
   */
  public function access($object, AccountInterface $account = NULL, $return_as_object = FALSE) {

    /** @var \Drupal\merci_line_item\NodeInterface $object */
    $access = $object
      ->access('update', $account, TRUE);
    return $return_as_object ? $access : $access
      ->isAllowed();
  }

}

Members

Namesort descending Modifiers Type Description Overrides
ActionBase::executeMultiple public function Executes the plugin for an array of objects. Overrides ActionInterface::executeMultiple 3
ConfigurableActionBase::calculateDependencies public function Calculates dependencies for the configured plugin. Overrides DependentPluginInterface::calculateDependencies 1
ConfigurableActionBase::getConfiguration public function Gets this plugin's configuration. Overrides ConfigurableInterface::getConfiguration
ConfigurableActionBase::setConfiguration public function Sets the configuration for this plugin instance. Overrides ConfigurableInterface::setConfiguration
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
DependencyTrait::$dependencies protected property The object's dependencies.
DependencyTrait::addDependencies protected function Adds multiple dependencies.
DependencyTrait::addDependency protected function Adds a dependency.
ExtendMerciLineItem::$currentUser protected property The current user object.
ExtendMerciLineItem::$tempStoreFactory protected property User private temporary storage factory.
ExtendMerciLineItem::access public function Checks object access. Overrides ActionInterface::access
ExtendMerciLineItem::buildConfigurationForm public function Form constructor. Overrides PluginFormInterface::buildConfigurationForm
ExtendMerciLineItem::buildPreConfigurationForm public function
ExtendMerciLineItem::create public static function Creates an instance of the plugin. Overrides ContainerFactoryPluginInterface::create
ExtendMerciLineItem::currentUser protected function Gets the current user.
ExtendMerciLineItem::defaultConfiguration public function Gets default configuration for this plugin. Overrides ConfigurableActionBase::defaultConfiguration
ExtendMerciLineItem::execute public function Executes the plugin. Overrides ExecutableInterface::execute
ExtendMerciLineItem::submitConfigurationForm public function Form submission handler. Overrides PluginFormInterface::submitConfigurationForm
ExtendMerciLineItem::validateConfigurationForm public function Form validation handler. Overrides ConfigurableActionBase::validateConfigurationForm
ExtendMerciLineItem::__construct public function Constructs a \Drupal\Component\Plugin\PluginBase object. Overrides ConfigurableActionBase::__construct
MessengerTrait::$messenger protected property The messenger. 29
MessengerTrait::messenger public function Gets the messenger. 29
MessengerTrait::setMessenger public function Sets the messenger.
PluginBase::$configuration protected property Configuration information passed into the plugin. 1
PluginBase::$pluginDefinition protected property The plugin implementation definition. 1
PluginBase::$pluginId protected property The plugin_id.
PluginBase::DERIVATIVE_SEPARATOR constant A string which is used to separate base plugin IDs from the derivative ID.
PluginBase::getBaseId public function Gets the base_plugin_id of the plugin instance. Overrides DerivativeInspectionInterface::getBaseId
PluginBase::getDerivativeId public function Gets the derivative_id of the plugin instance. Overrides DerivativeInspectionInterface::getDerivativeId
PluginBase::getPluginDefinition public function Gets the definition of the plugin implementation. Overrides PluginInspectionInterface::getPluginDefinition 3
PluginBase::getPluginId public function Gets the plugin_id of the plugin instance. Overrides PluginInspectionInterface::getPluginId
PluginBase::isConfigurable public function Determines if the plugin is configurable.
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.