A formElement for accessing the media library via custom widgets.
Clone or download
Fetching latest commit…
Cannot retrieve the latest commit at this time.
Permalink
Type Name Latest commit message Commit time
Failed to load latest commit information.
src/Element
README.md
composer.json
media_library_element.info.yml

README.md

Purpose

This module provides a Drupal form Element that allows widgets to load the core Media library and select a media item from that library, or add a new media item.

Notes

  • The #target_bundles array element defines which media types are selectable via the media library
  • The value returned to the widget is nested in $value['image']['media_library_selection'] (see below)

Roadmap

  • Allow for multiple media items to be selected & passed back to the widget.

Sample implementation in a form widget:

  /**
   * {@inheritdoc}
   */
  public function formElement(FieldItemListInterface $items, $delta, array $element, array &$form, FormStateInterface $form_state) {
    $element['image'] = [
      '#type' => 'media_library_element',
      '#target_bundles' => ['image'],
      '#title' => t('Image'),
      '#default_value' => isset($items[$delta]->image) ? $items[$delta]->image : 0,
      '#description' => t('This image will fill the width of the region it is placed in.'),
    ];
    return $element;
  }

Sample retrieval of value from formElement (nested in 'media_library_selection')

  /**
   * {@inheritdoc}
   */
  public function massageFormValues(array $values, array $form, FormStateInterface $form_state) {
    // This loop is through (potential) field instances.
    foreach ($values as &$value) {
      if (isset($value['image']['media_library_selection'])) {
        // @see MediaLibraryElement.php
        $value['image'] = $value['image']['media_library_selection'];
      }
      else {
        $value['image'] = 0;
      }
    }
    return $values;
  }