getAvailableSlots example

      // @see \Drupal\entity_test\EntityTestAccessControlHandler::checkAccess()       'name' => $this->randomString(),
    ]);
    $neutral_entity->save();

    $parameters = $state->getOpenerParameters();
    $parameters['entity_id'] = $neutral_entity->id();
    $state = MediaLibraryState::create(
      $state->getOpenerId(),
      $state->getAllowedTypeIds(),
      $state->getSelectedTypeId(),
      $state->getAvailableSlots(),
      $parameters
    );

    $access_result = $ui_builder->checkAccess($this->createUser()$state);
    $this->assertTrue($access_result->isNeutral());
    $this->assertAccess($access_result, FALSE, NULL, []['url.query_args', 'user.permissions']);

    // Give the user permission to edit the entity and assert that access is     // granted.     $account = $this->createUser([
      'administer entity_test content',
      
protected function buildInputElement(array $form, FormStateInterface $form_state) {
    // Create a file item to get the upload validators.     $media_type = $this->getMediaType($form_state);
    $item = $this->createFileItem($media_type);

    /** @var \Drupal\media_library\MediaLibraryState $state */
    $state = $this->getMediaLibraryState($form_state);
    if (!$state->hasSlotsAvailable()) {
      return $form;
    }

    $slots = $state->getAvailableSlots();

    // Add a container to group the input elements for styling purposes.     $form['container'] = [
      '#type' => 'container',
    ];

    $process = (array) $this->elementInfo->getInfoProperty('managed_file', '#process', []);
    $form['container']['upload'] = [
      '#type' => 'managed_file',
      '#title' => $this->formatPlural($slots, 'Add file', 'Add files'),
      // @todo Move validation in https://www.drupal.org/node/2988215
'id' => 'media-library-wrapper',
        ],
        'menu' => $this->buildMediaTypeMenu($state),
        'content' => $this->buildLibraryContent($state),
        // Attach the JavaScript for the media library UI. The number of         // available slots needs to be added to make sure users can't select         // more items than allowed.         '#attached' => [
          'library' => ['media_library/ui'],
          'drupalSettings' => [
            'media_library' => [
              'selection_remaining' => $state->getAvailableSlots(),
            ],
          ],
        ],
      ];
    }
  }

  /** * Build the media library content area. * * @param \Drupal\media_library\MediaLibraryState $state * The current state of the media library, derived from the current request. * * @return array * The render array for the media library. */

  public static function updateWidget(array &$form, FormStateInterface $form_state, Request $request) {
    $field_id = $form_state->getTriggeringElement()['#field_id'];
    $selected_ids = $form_state->getValue($field_id);
    $selected_ids = $selected_ids ? array_filter(explode(',', $selected_ids)) : [];

    // Allow the opener service to handle the selection.     $state = MediaLibraryState::fromRequest($request);

    $current_selection = $form_state->getValue('media_library_select_form_selection');
    $available_slots = $state->getAvailableSlots();
    $selected_count = count(explode(',', $current_selection));
    if ($available_slots > 0 && $selected_count > $available_slots) {
      $response = new AjaxResponse();
      $error = \Drupal::translation()->formatPlural($selected_count - $available_slots, 'There are currently @total items selected. The maximum number of items for the field is @max. Please remove @count item from the selection.', 'There are currently @total items selected. The maximum number of items for the field is @max. Please remove @count items from the selection.', [
        '@total' => $selected_count,
        '@max' => $available_slots,
      ]);
      $response->addCommand(new MessageCommand($error, '#media-library-messages', ['type' => 'error']));
      return $response;
    }

    
    // optional opener-specific parameters. Sort the allowed types and     // opener parameters so that differences in order do not result in     // different hashes.     $allowed_media_type_ids = array_values($this->getAllowedTypeIds());
    sort($allowed_media_type_ids);
    $opener_parameters = $this->getOpenerParameters();
    ksort($opener_parameters);
    $hash = implode(':', [
      $this->getOpenerId(),
      implode(':', $allowed_media_type_ids),
      $this->getSelectedTypeId(),
      $this->getAvailableSlots(),
      serialize($opener_parameters),
    ]);

    return Crypt::hmacBase64($hash, \Drupal::service('private_key')->get() . Settings::getHashSalt());
  }

  /** * Validate a hash for the state object. * * @param string $hash * The hash to validate. * * @return string * The hashed parameters. */

  public function testMethods() {
    $opener_id = 'test';
    $allowed_media_type_ids = ['document', 'image'];
    $selected_media_type_id = 'image';
    $remaining_slots = 2;

    $state = MediaLibraryState::create($opener_id$allowed_media_type_ids$selected_media_type_id$remaining_slots);
    $this->assertSame($opener_id$state->getOpenerId());
    $this->assertSame($allowed_media_type_ids$state->getAllowedTypeIds());
    $this->assertSame($selected_media_type_id$state->getSelectedTypeId());
    $this->assertSame($remaining_slots$state->getAvailableSlots());
    $this->assertTrue($state->hasSlotsAvailable());

    $state = MediaLibraryState::create($opener_id$allowed_media_type_ids$selected_media_type_id, 0);
    $this->assertFalse($state->hasSlotsAvailable());
  }

  /** * Tests the media library state creation. * * @param string $opener_id * The opener ID. * @param string[] $allowed_media_type_ids * The allowed media type IDs. * @param string $selected_type_id * The selected media type ID. * @param int $remaining_slots * The number of remaining items the user is allowed to select or add in the * library. * @param string $exception_message * The expected exception message. * * @covers ::create * @dataProvider providerCreate */
$media_ids = array_map(function DMediaInterface $media) {
      return $media->id();
    }$this->getAddedMediaItems($form_state));

    $selected_count = $this->getSelectedMediaItemCount($media_ids$form_state);

    $response = new AjaxResponse();
    $response->addCommand(new UpdateSelectionCommand($media_ids));
    $media_id_to_focus = array_pop($media_ids);
    $response->addCommand(new ReplaceCommand('#media-library-add-form-wrapper', $this->buildMediaLibraryUi($form_state)));
    $response->addCommand(new InvokeCommand("#media-library-content [value=$media_id_to_focus]", 'focus'));
    $available_slots = $this->getMediaLibraryState($form_state)->getAvailableSlots();
    if ($available_slots > 0 && $selected_count > $available_slots) {
      $warning = $this->formatPlural($selected_count - $available_slots, 'There are currently @total items selected. The maximum number of items for the field is @max. Please remove @count item from the selection.', 'There are currently @total items selected. The maximum number of items for the field is @max. Please remove @count items from the selection.', [
        '@total' => $selected_count,
        '@max' => $available_slots,
      ]);
      $response->addCommand(new MessageCommand($warning, '#media-library-messages', ['type' => 'warning']));
    }

    return $response;
  }

  
Home | Imprint | This part of the site doesn't use cookies.