You are here

class AvatarKitEntityMappingForm in Avatar Kit 8.2

Configure Avatar Kit entity maps.

Hierarchy

Expanded class hierarchy of AvatarKitEntityMappingForm

1 string reference to 'AvatarKitEntityMappingForm'
avatars.routing.yml in ./avatars.routing.yml
avatars.routing.yml

File

src/Form/AvatarKitEntityMappingForm.php, line 18

Namespace

Drupal\avatars\Form
View source
class AvatarKitEntityMappingForm extends ConfigFormBase {

  /**
   * Storage for entity mapping configuration entities.
   *
   * @var \Drupal\Core\Entity\EntityStorageInterface
   */
  protected $entityMappingStorage;

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

  /**
   * AvatarKitEntityMappingForm constructor.
   *
   * @param \Drupal\Core\Config\ConfigFactoryInterface $config_factory
   *   The factory for configuration objects.
   * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entityTypeManager
   *   The entity type manager.
   * @param \Drupal\Core\Entity\EntityFieldManagerInterface $entityFieldManager
   *   The entity field manager.
   */
  public function __construct(ConfigFactoryInterface $config_factory, EntityTypeManagerInterface $entityTypeManager, EntityFieldManagerInterface $entityFieldManager) {
    parent::__construct($config_factory);
    $this->entityMappingStorage = $entityTypeManager
      ->getStorage('avatars_entity_mapping');
    $this->entityFieldManager = $entityFieldManager;
  }

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

  /**
   * {@inheritdoc}
   */
  protected function getEditableConfigNames() : array {
    return [];
  }

  /**
   * {@inheritdoc}
   */
  public function getFormId() : string {
    return 'avatars_entity_mapping_settings';
  }

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) : array {
    $form = parent::buildForm($form, $form_state);
    $avatar_field_types = [
      'file',
      'image',
    ];
    $headers = [
      'label' => $this
        ->t('Entity type'),
      'weight' => $this
        ->t('Bundle'),
      'field' => $this
        ->t('Field'),
      'field_settings' => $this
        ->t('Field settings'),
    ];
    $form['map'] = [
      '#type' => 'table',
      '#header' => $headers,
      '#empty' => $this
        ->t('No entity types with suitable avatar field targets found.'),
      '#default_value' => [],
    ];
    $fieldMap = $this->entityFieldManager
      ->getFieldMap();
    unset($fieldMap['avatars_avatar_cache']);
    $fieldsOptions = [];
    foreach ($fieldMap as $entityType => $fields) {
      foreach ($fields as $fieldName => $fieldInfo) {
        [
          'type' => $type,
          'bundles' => $bundles,
        ] = $fieldInfo;
        if (!in_array($type, $avatar_field_types)) {
          continue;
        }
        foreach ($bundles as $bundle) {
          $key = $entityType . ':' . $bundle;
          $fieldsOptions[$key][$fieldName] = $this
            ->t('@field_name (@field_type)', [
            '@field_name' => $fieldName,
            '@field_type' => $type,
          ]);
        }
      }
    }
    foreach ($fieldsOptions as $key => $options) {
      [
        $entityType,
        $bundle,
      ] = explode(':', $key);
      $id = $entityType . '.' . $bundle . '.default';
      $entityMap = $this->entityMappingStorage
        ->load($id);
      $entityMapFieldName = $entityMap ? $entityMap
        ->getFieldName() : NULL;
      $row = [];
      $row['entity_type']['#plain_text'] = $entityType;
      $row['bundle']['#plain_text'] = $bundle;
      $row['field'] = [
        '#type' => 'select',
        '#title' => $this
          ->t('Field'),
        '#title_display' => 'invisible',
        '#default_value' => $entityMapFieldName,
        '#options' => $options,
        '#empty_option' => $this
          ->t('- None -'),
      ];
      $row['field_settings'] = [];
      if ($entityMapFieldName) {
        $fieldConfigId = $entityType . '.' . $bundle . '.' . $entityMapFieldName;
        try {
          $url = Url::fromRoute('entity.field_config.' . $entityType . '_field_edit_form')
            ->setRouteParameter('field_config', $fieldConfigId);
          $row['field_settings']['link'] = [
            '#type' => 'link',
            '#title' => $this
              ->t('Settings'),
            '#url' => $url,
          ];
        } catch (RouteNotFoundException $exception) {

          // When field_ui is not enabled.
        }
      }
      $form['map'][$key] = $row;
    }
    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    parent::submitForm($form, $form_state);

    /** @var \Drupal\avatars\Entity\AvatarKitEntityMapInterface[] $entityMaps */
    $entityMaps = $this->entityMappingStorage
      ->loadMultiple();
    $map = $form_state
      ->getValue('map');
    foreach ($map as $key => $values) {
      [
        $entityType,
        $bundle,
      ] = explode(':', $key);
      $mapKey = $entityType . '.' . $bundle . '.default';

      // Check if a map exists already.
      $entityMap = $entityMaps[$mapKey] ?? NULL;
      $fieldName = $values['field'];
      if (!$fieldName) {
        continue;
      }
      unset($entityMaps[$mapKey]);
      if (!$entityMap) {

        // Otherwise create one.
        $entityMap = $this->entityMappingStorage
          ->create([
          'entity_type' => $entityType,
          'bundle' => $bundle,
        ]);
      }
      $entityMap
        ->set('field_name', $fieldName);
      $entityMap
        ->save();
    }

    // Delete any left over mappings.
    foreach ($entityMaps as $entityMap) {
      $entityMap
        ->delete();
    }
  }

}

Members

Namesort descending Modifiers Type Description Overrides
AvatarKitEntityMappingForm::$entityFieldManager protected property The entity field manager.
AvatarKitEntityMappingForm::$entityMappingStorage protected property Storage for entity mapping configuration entities.
AvatarKitEntityMappingForm::buildForm public function Form constructor. Overrides ConfigFormBase::buildForm
AvatarKitEntityMappingForm::create public static function Instantiates a new instance of this class. Overrides ConfigFormBase::create
AvatarKitEntityMappingForm::getEditableConfigNames protected function Gets the configuration names that will be editable. Overrides ConfigFormBaseTrait::getEditableConfigNames
AvatarKitEntityMappingForm::getFormId public function Returns a unique string identifying the form. Overrides FormInterface::getFormId
AvatarKitEntityMappingForm::submitForm public function Form submission handler. Overrides ConfigFormBase::submitForm
AvatarKitEntityMappingForm::__construct public function AvatarKitEntityMappingForm constructor. Overrides ConfigFormBase::__construct
ConfigFormBaseTrait::config protected function Retrieves a configuration object.
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::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.
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.