You are here

class LibraryCheckOutBulkForm in Library 8

Bulk checkout form.

@package Drupal\library\Form

Hierarchy

Expanded class hierarchy of LibraryCheckOutBulkForm

1 string reference to 'LibraryCheckOutBulkForm'
library.routing.yml in ./library.routing.yml
library.routing.yml

File

src/Form/LibraryCheckOutBulkForm.php, line 19

Namespace

Drupal\library\Form
View source
class LibraryCheckOutBulkForm extends FormBase {

  /**
   * {@inheritdoc}
   */
  public function getFormId() : string {
    return 'library_check_out_bulk_form';
  }

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state, $action = NULL) : array {
    if ($action == NULL) {
      $form_state
        ->setErrorByName('action', $this
        ->t('Required parameters missing'));
      return $form;
    }
    $form['action'] = [
      '#type' => 'value',
      '#value' => $action,
    ];
    for ($i = 0; $i < 6; $i++) {
      $form['item_' . $i] = [
        '#type' => 'textfield',
        '#title' => $this
          ->t('Item'),
        '#description' => $this
          ->t('Enter items by barcode'),
        '#maxlength' => 20,
        '#size' => 20,
      ];
    }
    $actionEntity = LibraryAction::load($action);
    if ($actionEntity
      ->action() == LibraryAction::CHANGE_TO_UNAVAILABLE) {
      $form['patron'] = [
        '#type' => 'entity_autocomplete',
        '#target_type' => 'user',
        '#title' => $this
          ->t('Patron'),
        '#required' => TRUE,
      ];
    }
    $form['notes'] = [
      '#type' => 'textarea',
      '#title' => $this
        ->t('Message'),
      '#required' => FALSE,
      '#maxlength' => 250,
      '#default_value' => '',
      '#description' => $this
        ->t('If you are reserving an item, make sure to include the date and time you would like it to be ready.'),
    ];
    $form['submit'] = [
      '#type' => 'submit',
      '#value' => $actionEntity
        ->label(),
    ];
    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function validateForm(array &$form, FormStateInterface $form_state) : void {
    parent::validateForm($form, $form_state);
    $data = $form_state
      ->getValues();
    foreach ($data as $key => $item) {
      if (strpos($key, 'item_') !== FALSE && !empty($item)) {
        $libraryItem = LibraryItemHelper::findByBarcode($item);
        if ($libraryItem) {
          $itemState = $libraryItem
            ->get('library_status')->value;
          $action = LibraryAction::load($data['action']);
          if ($action
            ->action() == LibraryAction::CHANGE_TO_AVAILABLE) {
            if ($itemState != LibraryItem::ITEM_UNAVAILABLE) {
              $form_state
                ->setErrorByName('item_' . $key, $this
                ->t('Item @item is already checked in.', [
                '@item' => $item,
              ]));
            }
          }
          if ($action
            ->action() == LibraryAction::CHANGE_TO_UNAVAILABLE) {
            if ($itemState != LibraryItem::ITEM_AVAILABLE) {
              $form_state
                ->setErrorByName('item_' . $key, $this
                ->t('Item @item is already checked out.', [
                '@item' => $item,
              ]));
            }
          }
          if ($libraryItem
            ->get('in_circulation')->value == LibraryItem::REFERENCE_ONLY) {
            $form_state
              ->setErrorByName('item_' . $key, $this
              ->t('Item @item cannot be checked out.', [
              '@item' => $item,
            ]));
          }
        }
      }
    }
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) : void {
    $data = $form_state
      ->getValues();
    foreach ($data as $key => $item) {
      if (strpos($key, 'item_') !== FALSE && !empty($item)) {
        $libraryItem = LibraryItemHelper::findByBarcode($item);
        if ($libraryItem) {
          $this
            ->processTransaction($libraryItem, $data);
        }
      }
    }
  }

  /**
   * Process a transaction.
   *
   * @param \Drupal\library\Entity\LibraryItem $item
   *   Item to process.
   * @param array $data
   *   Data context.
   */
  private function processTransaction(LibraryItem $item, array $data) {
    $transaction = LibraryTransaction::create();
    $transaction
      ->set('librarian_id', \Drupal::currentUser()
      ->id());
    $transaction
      ->set('nid', $item
      ->get('nid')
      ->getValue());
    if (isset($data['patron'])) {
      $transaction
        ->set('uid', $data['patron']);
    }
    $transaction
      ->set('library_item', $item
      ->id());
    $transaction
      ->set('action', $data['action']);
    $transaction
      ->set('due_date', LibraryItemHelper::computeDueDate($data['action'], $item
      ->get('nid')
      ->getValue()[0]['target_id']));
    $transaction
      ->set('notes', $data['notes']);
    $transaction
      ->save();
    LibraryItemHelper::updateItemAvailability($item
      ->id(), $data['action']);
    \Drupal::service('cache_tags.invalidator')
      ->invalidateTags([
      'node:' . $item
        ->get('nid')
        ->getValue()[0]['target_id'],
    ]);
    $node = Node::load($item
      ->get('nid')
      ->getValue()[0]['target_id']);
    $item_name = $node
      ->getTitle() . ' (' . $item
      ->get('barcode')->value . ')';
    $this
      ->messenger()
      ->addStatus($this
      ->t('Transaction processed for @item.', [
      '@item' => $item_name,
    ]));
    \Drupal::service('event_dispatcher')
      ->dispatch('library.action', new ActionEvent($transaction));
  }

}

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
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::create public static function Instantiates a new instance of this class. Overrides ContainerInjectionInterface::create 87
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.
LibraryCheckOutBulkForm::buildForm public function Form constructor. Overrides FormInterface::buildForm
LibraryCheckOutBulkForm::getFormId public function Returns a unique string identifying the form. Overrides FormInterface::getFormId
LibraryCheckOutBulkForm::processTransaction private function Process a transaction.
LibraryCheckOutBulkForm::submitForm public function Form submission handler. Overrides FormInterface::submitForm
LibraryCheckOutBulkForm::validateForm public function Form validation handler. Overrides FormBase::validateForm
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 protected property The messenger. 29
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.