You are here

private static function WidgetSubmit::processLibraryItems in Library 8

Process library items.

Parameters

\Drupal\Core\Field\FieldDefinitionInterface $field: Relevant field.

array $submittedValues: Submitted values.

\Drupal\Core\Entity\EntityInterface $parentEntity: Parent entity.

1 call to WidgetSubmit::processLibraryItems()
WidgetSubmit::doSubmit in src/WidgetSubmit.php
Submits the widget elements, saving and deleted entities where needed.

File

src/WidgetSubmit.php, line 79

Class

WidgetSubmit
Performs widget submission.

Namespace

Drupal\library

Code

private static function processLibraryItems(FieldDefinitionInterface $field, array $submittedValues, EntityInterface $parentEntity) {
  $fieldName = $field
    ->getName();
  $entriesChanged = FALSE;
  $savedReferences = $parentEntity
    ->get($fieldName)
    ->getValue();
  foreach ($submittedValues as $value) {
    if (isset($value['library']['item_id'])) {
      $itemEntity = LibraryItem::load($value['library']['item_id']);
    }
    else {
      $itemEntity = LibraryItem::create();
    }
    if ($field
      ->getSetting('barcode_generation') && empty($itemEntity
      ->get('barcode')->value)) {
      $itemEntity
        ->set('barcode', LibraryItemFieldWidget::findHighestBarcode() + 1);
    }
    else {
      $itemEntity
        ->set('barcode', $value['library']['barcode']);
    }
    if (!isset($value['library']['nid'])) {
      $itemEntity
        ->set('nid', [
        'target_id' => $parentEntity
          ->id(),
      ]);
    }
    $itemEntity
      ->set('library_status', $value['library']['library_status']);
    $itemEntity
      ->set('notes', $value['library']['notes']);
    $itemEntity
      ->set('in_circulation', $value['library']['in_circulation']);
    foreach ($savedReferences as $key => $reference) {
      if (isset($value['library']['item_id']) && $reference['target_id'] == $value['library']['item_id'] && $value['remove'] == 1) {
        unset($savedReferences[$key]);
        $entriesChanged = TRUE;
      }
    }
    if ($value['remove'] == 1) {
      $itemEntity
        ->delete();
    }
    else {
      $itemEntity
        ->save();
    }
    if (!isset($value['library']['item_id'])) {
      $savedReferences[] = [
        'target_id' => $itemEntity
          ->id(),
      ];
      $entriesChanged = TRUE;
    }
  }
  if ($entriesChanged == TRUE) {
    $parentEntity
      ->set($fieldName, $savedReferences);
    $parentEntity
      ->save();
  }
}