You are here

class MappingForm in Bibliography & Citation 8

Same name and namespace in other branches
  1. 2.0.x modules/bibcite_entity/src/Form/MappingForm.php \Drupal\bibcite_entity\Form\MappingForm

Format mapping form.

Hierarchy

Expanded class hierarchy of MappingForm

1 string reference to 'MappingForm'
bibcite_entity.routing.yml in modules/bibcite_entity/bibcite_entity.routing.yml
modules/bibcite_entity/bibcite_entity.routing.yml

File

modules/bibcite_entity/src/Form/MappingForm.php, line 15

Namespace

Drupal\bibcite_entity\Form
View source
class MappingForm extends FormBase {

  /**
   * Configuration object.
   *
   * @var \Drupal\Core\Config\Config
   */
  protected $config;

  /**
   * Entity field manager service.
   *
   * @var \Drupal\Core\Entity\EntityFieldManagerInterface
   */
  protected $entityFieldManager;

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

  /**
   * Mapping form constructor.
   *
   * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
   *   Entity type manager service.
   * @param \Drupal\Core\Entity\EntityFieldManagerInterface $entity_field_manager
   *   Entity field manager service.
   */
  public function __construct(EntityTypeManagerInterface $entity_type_manager, EntityFieldManagerInterface $entity_field_manager) {
    $this->entityFieldManager = $entity_field_manager;
    $this->entityTypeManager = $entity_type_manager;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static($container
      ->get('entity_type.manager'), $container
      ->get('entity_field.manager'));
  }

  /**
   * {@inheritdoc}
   */
  public function getFormId() {
    return 'bibcite_entity_mapping';
  }

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state, $bibcite_format = NULL) {

    /** @var \Drupal\bibcite\Plugin\BibciteFormatInterface $bibcite_format */
    if (!$this->config) {
      $this
        ->initConfiguration($bibcite_format);
    }
    $form['types'] = [
      '#type' => 'table',
      '#caption' => $this
        ->t('Formats mapping'),
      '#header' => [
        $this
          ->t('Format type'),
        $this
          ->t('Reference type'),
      ],
    ];
    $type_options = $this
      ->getReferenceTypesOptions();
    $type_defaults = $this->config
      ->get('types');
    foreach ($bibcite_format
      ->getTypes() as $type) {
      $form['types'][$type]['format'] = [
        '#type' => 'item',
        '#markup' => $type,
        '#value' => $type,
      ];
      $form['types'][$type]['entity'] = [
        '#type' => 'select',
        '#options' => $type_options,
        '#empty_option' => $this
          ->t('- Select -'),
        '#default_value' => isset($type_defaults[$type]) ? $type_defaults[$type] : NULL,
      ];
    }
    $form['fields'] = [
      '#type' => 'table',
      '#caption' => $this
        ->t('Fields mapping'),
      '#header' => [
        $this
          ->t('Format field'),
        $this
          ->t('Reference field'),
      ],
    ];
    $field_options = $this
      ->getReferenceFieldOptions();
    $field_defaults = $this->config
      ->get('fields');
    foreach ($bibcite_format
      ->getFields() as $field) {
      $form['fields'][$field]['format'] = [
        '#type' => 'item',
        '#markup' => $field,
        '#value' => $field,
      ];
      $form['fields'][$field]['entity'] = [
        '#type' => 'select',
        '#options' => $field_options,
        '#empty_option' => $this
          ->t('- Select -'),
        '#default_value' => isset($field_defaults[$field]) ? $field_defaults[$field] : NULL,
      ];
    }
    $form['actions'] = [
      '#type' => 'actions',
    ];
    $form['actions']['submit'] = [
      '#type' => 'submit',
      '#value' => $this
        ->t('Save configuration'),
      '#button_type' => 'primary',
    ];
    return $form;
  }

  /**
   * Get array of Reference field options.
   *
   * @return array
   *   Array of fields options.
   */
  protected function getReferenceFieldOptions() {
    $fields = $this->entityFieldManager
      ->getBaseFieldDefinitions('bibcite_reference');
    $excluded_fields = [
      'id',
      'uuid',
      'langcode',
      'created',
      'changed',
      'revision_id',
      'revision_created',
      'revision_user',
      'revision_log_message',
      'status',
      'revision_default',
      'path',
      'metatag',
    ];
    $options = array_map(function ($field) {

      /** @var \Drupal\Core\Field\FieldDefinitionInterface $field */
      return $field
        ->getLabel();
    }, array_diff_key($fields, array_flip($excluded_fields)));

    // Sort options alphabetically.
    asort($options);

    // But 'Reference type' and 'Title' fields should go first.
    $options = [
      'type' => $options['type'],
      'title' => $options['title'],
    ] + $options;
    return $options;
  }

  /**
   * Get array of Reference types options.
   *
   * @return array
   *   Array of types options.
   */
  protected function getReferenceTypesOptions() {
    $storage = $this->entityTypeManager
      ->getStorage('bibcite_reference_type');
    $entities = $storage
      ->loadMultiple();
    return array_map(function ($entity) {

      /** @var \Drupal\bibcite_entity\Entity\ReferenceInterface $entity */
      return $entity
        ->label();
    }, $entities);
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    $types = array_map(function ($type_values) {
      return $type_values['entity'];
    }, $form_state
      ->getValue('types'));
    $this->config
      ->set('types', $types);
    $fields = array_map(function ($field_values) {
      return $field_values['entity'];
    }, $form_state
      ->getValue('fields'));
    $this->config
      ->set('fields', $fields);
    $this->config
      ->save();
    $this
      ->messenger()
      ->addStatus($this
      ->t('Your mapping has been saved.'));
  }

  /**
   * Init mapping configuration object.
   *
   * @param \Drupal\bibcite\Plugin\BibciteFormatInterface $bibcite_format
   *   Format plugin instance.
   */
  protected function initConfiguration(BibciteFormatInterface $bibcite_format) {
    $config_name = sprintf('bibcite_entity.mapping.%s', $bibcite_format
      ->getPluginId());
    $this->config = $this
      ->configFactory()
      ->getEditable($config_name);
  }

  /**
   * Mapping page title callback.
   *
   * @param \Drupal\bibcite\Plugin\BibciteFormatInterface $bibcite_format
   *   Format plugin.
   *
   * @return \Drupal\Core\StringTranslation\TranslatableMarkup
   *   Translatable title.
   */
  public static function formTitle(BibciteFormatInterface $bibcite_format) {
    return t('Mapping for @format format', [
      '@format' => $bibcite_format
        ->getLabel(),
    ]);
  }

}

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::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.
FormBase::validateForm public function Form validation handler. Overrides FormInterface::validateForm 62
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.
MappingForm::$config protected property Configuration object.
MappingForm::$entityFieldManager protected property Entity field manager service.
MappingForm::$entityTypeManager protected property Entity type manager service.
MappingForm::buildForm public function Form constructor. Overrides FormInterface::buildForm 1
MappingForm::create public static function Instantiates a new instance of this class. Overrides FormBase::create
MappingForm::formTitle public static function Mapping page title callback.
MappingForm::getFormId public function Returns a unique string identifying the form. Overrides FormInterface::getFormId
MappingForm::getReferenceFieldOptions protected function Get array of Reference field options.
MappingForm::getReferenceTypesOptions protected function Get array of Reference types options.
MappingForm::initConfiguration protected function Init mapping configuration object.
MappingForm::submitForm public function Form submission handler. Overrides FormInterface::submitForm
MappingForm::__construct public function Mapping form constructor.
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.