You are here

class KeywordSettingsForm in Alinks 8

Class KeywordSettingsForm.

@package Drupal\alinks\Form

Hierarchy

Expanded class hierarchy of KeywordSettingsForm

File

src/Form/KeywordSettingsForm.php, line 21

Namespace

Drupal\alinks\Form
View source
class KeywordSettingsForm extends ConfigFormBase {
  protected $entityTypeManager;
  protected $entityDisplayRepository;

  /**
   * {@inheritdoc}
   */
  public function __construct(ConfigFactoryInterface $config_factory, EntityTypeManager $entityTypeManager, EntityDisplayRepositoryInterface $entityDisplayRepository) {
    parent::__construct($config_factory);
    $this->entityTypeManager = $entityTypeManager;
    $this->entityDisplayRepository = $entityDisplayRepository;
  }

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

  /**
   * {@inheritdoc}
   */
  protected function getEditableConfigNames() {
    return 'alinks.settings';
  }

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

  /**
   * @param array $form
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   */
  public function addDisplay(array &$form, FormStateInterface $form_state) {
    if ($form_state
      ->getValue('entityType') && $form_state
      ->getValue('entityDisplay')) {
      $displays = $this
        ->configFactory()
        ->getEditable('alinks.settings')
        ->get('displays');
      $displays[] = [
        'entity_type' => $form_state
          ->getValue('entityType'),
        'entity_bundle' => $form_state
          ->getValue('entityBundle'),
        'entity_display' => $form_state
          ->getValue('entityDisplay'),
      ];
      $this
        ->configFactory()
        ->getEditable('alinks.settings')
        ->set('displays', $displays)
        ->set('vocabularies', $form_state
        ->getValue('vocabularies'))
        ->save();
    }
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    $this
      ->configFactory()
      ->getEditable('alinks.settings')
      ->set('vocabularies', array_filter($form_state
      ->getValue('vocabularies')))
      ->save();
  }

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {
    $form = parent::buildForm($form, $form_state);
    $form['display'] = array(
      '#type' => 'details',
      '#title' => $this
        ->t('Configure the displays on which alinks should be used'),
      '#open' => TRUE,
    );
    $form['display'] += $this
      ->buildTable($form_state);
    $form['display'] += $this
      ->buildAddNew($form_state);
    $vocabularies = $this
      ->configFactory()
      ->getEditable('alinks.settings')
      ->get('vocabularies');
    $form['settings'] = array(
      '#type' => 'details',
      '#title' => $this
        ->t('Replace taxonomy terms'),
      '#open' => TRUE,
    );
    $form['settings']['vocabularies'] = [
      '#type' => 'checkboxes',
      '#title' => $this
        ->t('Vocabularies'),
      '#default_value' => $vocabularies,
    ];
    $vocabularies = $this->entityTypeManager
      ->getStorage('taxonomy_vocabulary')
      ->loadMultiple();
    foreach ($vocabularies as $vocabulary) {
      $form['settings']['vocabularies']['#options'][$vocabulary
        ->id()] = $vocabulary
        ->label();
    }
    return $form;
  }

  /**
   * Fills forms.
   *
   * @param array $form
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *
   * @return mixed
   */
  public function populateEntitySettings(array &$form, FormStateInterface $form_state) {
    return $form['display']['entity'];
  }

  /**
   * @param array $form
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   */
  protected function buildAddNew(FormStateInterface $form_state) {
    $form = [];
    $entityTypes = [];
    foreach ($this->entityTypeManager
      ->getDefinitions() as $definition) {
      if ($definition instanceof ContentEntityTypeInterface) {
        $entityTypes[$definition
          ->id()] = $definition
          ->getLabel();
      }
    }
    asort($entityTypes);
    $form['entityType'] = [
      '#type' => 'select',
      '#title' => $this
        ->t('Entity type'),
      '#options' => $entityTypes,
      '#empty_value' => '',
      '#empty_option' => $this
        ->t('-- None --'),
      '#ajax' => [
        'callback' => array(
          $this,
          'populateEntitySettings',
        ),
        'wrapper' => 'entity-wrapper',
      ],
      '#group' => 'display',
    ];
    $form['entity'] = array(
      '#type' => 'container',
      '#prefix' => '<div id="entity-wrapper">',
      '#suffix' => '</div>',
      '#group' => 'display',
    );
    $form['entity']['entityBundle'] = array(
      '#type' => 'select',
      '#title' => $this
        ->t('Entity bundle'),
      '#empty_value' => '',
      '#empty_option' => $this
        ->t('-- None --'),
      '#options' => [],
    );
    $form['entity']['entityDisplay'] = array(
      '#type' => 'select',
      '#title' => $this
        ->t('Entity display'),
      '#empty_value' => '',
      '#empty_option' => $this
        ->t('-- None --'),
      '#options' => [],
    );
    $entityType = $form_state
      ->getValue('entityType');
    if ($entityType) {
      $bundleType = $this->entityTypeManager
        ->getDefinition($entityType)
        ->getBundleEntityType();
      if ($bundleType) {
        $bundles = $this->entityTypeManager
          ->getStorage($bundleType)
          ->loadMultiple();
        if ($bundles) {
          foreach ($bundles as $bundle) {
            $form['entity']['entityBundle']['#options'][$bundle
              ->id()] = $bundle
              ->label();
          }
        }
        asort($form['entity']['entityBundle']['#options']);
      }
      $options = $this->entityDisplayRepository
        ->getViewModeOptions($entityType);
      if ($options) {
        asort($options);
        $form['entity']['entityDisplay']['#options'] += $options;
      }
    }
    $form['actions']['addNew'] = array(
      '#type' => 'submit',
      '#value' => $this
        ->t('Add'),
      '#button_type' => 'primary',
      '#submit' => [
        '::addDisplay',
      ],
      '#group' => 'display',
    );
    return $form;
  }

  /**
   * @param array $form
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   * @return array
   */
  protected function buildTable(FormStateInterface $form_state) {
    $form = [];
    $form['display_table'] = array(
      '#type' => 'table',
      '#header' => array(
        t('Entity type'),
        t('Entity bundle'),
        t('Display'),
        t('Operations'),
      ),
    );
    $displays = $this
      ->configFactory()
      ->getEditable('alinks.settings')
      ->get('displays');
    foreach ($displays as $key => $display) {
      $form['display_table'][$key]['entity_type'] = array(
        '#plain_text' => $display['entity_type'],
      );
      $form['display_table'][$key]['entity_bundle'] = array(
        '#plain_text' => $display['entity_bundle'],
      );
      $form['display_table'][$key]['entity_display'] = array(
        '#plain_text' => $display['entity_display'],
      );
      $form['display_table'][$key]['operations'] = array(
        '#type' => 'operations',
        '#links' => array(
          'delete' => array(
            'title' => t('Delete'),
            'url' => Url::fromRoute('alinks.alinks_controller_delete', $display),
          ),
        ),
      );
    }
    return $form;
  }

}

Members

Namesort descending Modifiers Type Description Overrides
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
KeywordSettingsForm::$entityDisplayRepository protected property
KeywordSettingsForm::$entityTypeManager protected property
KeywordSettingsForm::addDisplay public function
KeywordSettingsForm::buildAddNew protected function
KeywordSettingsForm::buildForm public function Form constructor. Overrides ConfigFormBase::buildForm
KeywordSettingsForm::buildTable protected function
KeywordSettingsForm::create public static function Instantiates a new instance of this class. Overrides ConfigFormBase::create
KeywordSettingsForm::getEditableConfigNames protected function Gets the configuration names that will be editable. Overrides ConfigFormBaseTrait::getEditableConfigNames
KeywordSettingsForm::getFormId public function Returns a unique string identifying the form. Overrides FormInterface::getFormId
KeywordSettingsForm::populateEntitySettings public function Fills forms.
KeywordSettingsForm::submitForm public function Form submission handler. Overrides ConfigFormBase::submitForm
KeywordSettingsForm::__construct public function Constructs a \Drupal\system\ConfigFormBase object. Overrides ConfigFormBase::__construct
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.