learnosity-1.0.x-dev/src/Plugin/Field/FieldWidget/LearnosityActivityAuthoringWidget.php

src/Plugin/Field/FieldWidget/LearnosityActivityAuthoringWidget.php
<?php

namespace Drupal\learnosity\Plugin\Field\FieldWidget;

use Drupal\Component\Utility\NestedArray;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Field\FieldDefinitionInterface;
use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Field\WidgetBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\user\EntityOwnerInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\Validator\ConstraintViolationInterface;

/**
 * Plugin implementation of the 'learnosity_activity_authoring' widget.
 *
 * @FieldWidget(
 *   id = "learnosity_activity_authoring",
 *   label = @Translation("Embedded Authoring"),
 *   description = @Translation("Learnosity embedded activity authoring field."),
 *   field_types = {
 *     "learnosity_activity"
 *   }
 * )
 */
class LearnosityActivityAuthoringWidget extends WidgetBase {

  /**
   * Entity type manager service.
   *
   * @var \Drupal\Core\Entity\EntityTypeManagerInterface
   */
  protected $entityTypeManager;

  /**
   * Constructs a LearnosityActivityAuthoringWidget object.
   *
   * @param string $plugin_id
   *   The plugin_id for the widget.
   * @param mixed $plugin_definition
   *   The plugin implementation definition.
   * @param \Drupal\Core\Field\FieldDefinitionInterface $field_definition
   *   The definition of the field to which the widget is associated.
   * @param array $settings
   *   The widget settings.
   * @param array $third_party_settings
   *   Any third party settings.
   * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
   *   Entity type manager service.
   */
  public function __construct($plugin_id, $plugin_definition, FieldDefinitionInterface $field_definition, array $settings, array $third_party_settings, EntityTypeManagerInterface $entity_type_manager) {
    parent::__construct($plugin_id, $plugin_definition, $field_definition, $settings, $third_party_settings);
    $this->entityTypeManager = $entity_type_manager;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
    return new static(
      $plugin_id,
      $plugin_definition,
      $configuration['field_definition'],
      $configuration['settings'],
      $configuration['third_party_settings'],
      $container->get('entity_type.manager')
    );
  }

  /**
   * {@inheritdoc}
   */
  public static function defaultSettings() {
    return [
      'open' => FALSE,
      'button_label' => t('Create Activity'),
    ] + parent::defaultSettings();
  }

  /**
   * {@inheritdoc}
   */
  public function settingsForm(array $form, FormStateInterface $form_state) {
    $element = parent::settingsForm($form, $form_state);
    $element['button_label'] = [
      '#title' => $this->t('Button Label'),
      '#description' => $this->t('The button label to show users when creating the activity.'),
      '#required' => TRUE,
      '#type' => 'textfield',
      '#default_value' => $this->getSetting('button_label'),
    ];
    $element['open'] = [
      '#title' => $this->t('Show widget as open'),
      '#description' => $this->t('Show the wrapping fieldset as open by default.'),
      '#type' => 'checkbox',
      '#default_value' => $this->getSetting('open'),
    ];
    return $element;
  }

  /**
   * {@inheritdoc}
   */
  public function settingsSummary() {
    $summary = [];
    $open = ($this->getSetting('open')) ? $this->t('Yes') : $this->t('No');
    $summary[] = $this->t('Show widget as open: @open', ['@open' => $open]);
    $summary[] = $this->t('Button label: @label', ['@label' => $this->getSetting('button_label')]);
    return $summary;
  }

  /**
   * {@inheritdoc}
   */
  public function formElement(FieldItemListInterface $items, $delta, array $element, array &$form, FormStateInterface $form_state) {
    $entity = $items->getEntity();
    $referenced_entities = $items->referencedEntities();
    $mappingsHandler = \Drupal::service('learnosity.mappings_handler');
    $trigger = $form_state->getTriggeringElement();
    $is_triggered = (isset($trigger) && $trigger['#name'] == 'add_learnosity_activity');

    // @todo: Resolve this bug.
    // This is a quick workaround to address an integration issue with inline
    // entity form.
    $post = \Drupal::request()->request->all();
    if (empty($referenced_entities) && !empty($post)) {
      $el0 = NestedArray::getValue($post, array_slice($element['#field_parents'], 0));
      if (isset($el0[$items->getName()][0]['target_id'])) {
        $referenced_entities[0] = $el0[$items->getName()][0]['target_id'];
      }
    }

    // If no content exists then show a "Create Activity" button. This is
    // useful for assisting with translations as well as migrations.
    if (!$is_triggered && empty($referenced_entities)) {
      $element['button'] = [
        '#type' => 'button',
        '#value' => $this->getSetting('button_label'),
        '#name' => 'add_learnosity_activity',
        '#limit_validation_errors' => [],
        '#ajax' => [
          'callback' => [get_class($this), 'loadAuthoringFormCallback'],
          'wrapper' => 'learnosity-authoring-widget',
        ],
      ];
      return $element;
    }

    $form_state->setCached(FALSE);

    // Append the match operation to the selection settings.
    $selection_settings = $this->getFieldSetting('handler_settings') + [
      'match_operator' => $this->getSetting('match_operator'),
      'match_limit' => $this->getSetting('match_limit'),
    ];

    /** @var \Drupal\user\Entity\User $user */
    $current_user = \Drupal::service('entity_type.manager')->getStorage('user')->load(\Drupal::currentUser()->id());
    $element += [
      '#type' => 'learnosity_activity_editor',
      // Leaving enabled in order for autocreate to work.
      '#target_type' => $this->getFieldSetting('target_type'),
      '#selection_handler' => $this->getFieldSetting('handler'),
      '#selection_settings' => $selection_settings,
      '#default_value' => isset($referenced_entities[$delta]) ? $referenced_entities[$delta] : NULL,
      '#context' => [
        'entity' => $entity,
        'entity_type' => $entity->getEntityTypeId(),
        'entity_id' => $entity->id(),
        'langcode' => $entity->language()->getId(),
      ],
      '#user' => [
        'id' => $mappingsHandler->get($current_user, 'id'),
        'email' => $mappingsHandler->get($current_user, 'email'),
        'firstname' => $mappingsHandler->get($current_user, 'firstname'),
        'lastname' => $mappingsHandler->get($current_user, 'lastname'),
      ],
    ];

    // Fetch the current supported editors.
    $editors = $this->getFieldSetting('editor');
    if (!empty($editors)) {
      $editor_entities = $this->entityTypeManager->getStorage('learnosity_activity_editor')->loadMultiple($editors);
      // Sort the entities by weight.
      uasort($editor_entities, 'Drupal\Core\Config\Entity\ConfigEntityBase::sort');
      $access = FALSE;
      foreach ($editor_entities as $editor) {
        if ($access = $editor->access('use', \Drupal::currentUser())) {
          $element['#editor'] = $editor->id();
          break;
        }
      }
      // If no access is found then use the fallback editor.
      if (!$access) {
        $fallback = \Drupal::config('learnosity.settings')->get('fallback_editor');
        $element['#editor'] = $fallback;
      }
    }

    $element['#autocreate'] = [
      'uid' => ($entity instanceof EntityOwnerInterface) ? $entity->getOwnerId() : \Drupal::currentUser()->id(),
    ];

    return ['target_id' => $element];
  }

  /**
   * Upload Widget settings form callback.
   *
   * @param array $form
   *   The form.
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   The form state.
   *
   * @return array
   *   The form element.
   */
  public static function loadAuthoringFormCallback(array &$form, FormStateInterface $form_state) {
    $button = $form_state->getTriggeringElement();
    // Go one level up in the form, to the widgets container.
    $element = NestedArray::getValue($form, array_slice($button['#array_parents'], 0, -2));
    return $element;
  }

  /**
   * {@inheritdoc}
   */
  public function form(FieldItemListInterface $items, array &$form, FormStateInterface $form_state, $get_delta = NULL) {
    $element = parent::form($items, $form, $form_state, $get_delta);
    $element['#type'] = 'details';
    $element['#title'] = $element['widget']['#title'];
    $element['#open'] = $this->getSetting('open');

    return $element;
  }

  /**
   * {@inheritdoc}
   */
  protected function formMultipleElements(FieldItemListInterface $items, array &$form, FormStateInterface $form_state) {
    $elements = parent::formMultipleElements($items, $form, $form_state);
    $elements['#prefix'] = '<div id="learnosity-authoring-widget">';
    $elements['#suffix'] = '</div>';
    return $elements;
  }

  /**
   * {@inheritdoc}
   */
  public function errorElement(array $element, ConstraintViolationInterface $error, array $form, FormStateInterface $form_state) {
    return $element['target_id'];
  }

  /**
   * {@inheritdoc}
   */
  public function massageFormValues(array $values, array $form, FormStateInterface $form_state) {
    foreach ($values as $key => $value) {
      // The form element returns an array when an entity
      // was "autocreated", so we need to move it up a level.
      if (isset($value['target_id']) && is_array($value['target_id'])) {
        unset($values[$key]['target_id']);
        $values[$key] += $value['target_id'];
      }
    }

    return $values;
  }

  /**
   * Returns the value of a setting for the selection handler.
   *
   * @param string $setting_name
   *   The setting name.
   *
   * @return mixed
   *   The setting value.
   */
  protected function getSelectionHandlerSetting($setting_name) {
    $settings = $this->getFieldSetting('handler_settings');
    return isset($settings[$setting_name]) ? $settings[$setting_name] : NULL;
  }

}

Главная | Обратная связь

drupal hosting | друпал хостинг | it patrol .inc