You are here

class BehaviorForm in Synonyms 2.0.x

The behavior form for given entity type.

Hierarchy

Expanded class hierarchy of BehaviorForm

1 string reference to 'BehaviorForm'
synonyms.routing.yml in ./synonyms.routing.yml
synonyms.routing.yml

File

src/Form/BehaviorForm.php, line 20

Namespace

Drupal\synonyms\Form
View source
class BehaviorForm extends ConfigFormBase {
  use StringTranslationTrait, FormatWordingTrait;

  /**
   * The behavior configuration.
   *
   * @var \Drupal\synonyms\SynonymInterface
   */
  protected $config;

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

  /**
   * The entity type bundle info.
   *
   * @var \Drupal\Core\Entity\EntityTypeBundleInfoInterface
   */
  protected $entityTypeBundleInfo;

  /**
   * The behavior service.
   *
   * @var \Drupal\synonyms\SynonymsService\BehaviorService
   */
  protected $behaviorService;

  /**
   * Entity type that is being managed.
   *
   * @var \Drupal\Core\Entity\EntityTypeInterface
   */
  protected $entityType;

  /**
   * Bundle that is being managed.
   *
   * @var string
   */
  protected $bundle;

  /**
   * The renderer.
   *
   * @var Drupal\Core\Render\RendererInterface
   */
  protected $renderer;

  /**
   * Current 'status' form field name.
   *
   * @var string
   */
  protected $statusName;

  /**
   * Current 'wording' form field name.
   *
   * @var string
   */
  protected $wordingName;

  /**
   * The container.
   *
   * @var \Symfony\Component\DependencyInjection\ContainerInterface
   */
  protected $container;

  /**
   * BehaviorForm constructor.
   *
   * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
   *   The entity type manager.
   * @param \Drupal\Core\Entity\EntityTypeBundleInfoInterface $entity_type_bundle_info
   *   The entity type bundle info.
   * @param \Drupal\synonyms\SynonymsService\BehaviorService $behavior_service
   *   The behavior service.
   * @param Drupal\Core\Render\RendererInterface $renderer
   *   The renderer.
   * @param \Symfony\Component\DependencyInjection\ContainerInterface $container
   *   The container.
   */
  public function __construct(EntityTypeManagerInterface $entity_type_manager, EntityTypeBundleInfoInterface $entity_type_bundle_info, BehaviorService $behavior_service, RendererInterface $renderer, ContainerInterface $container) {
    $this->entityTypeManager = $entity_type_manager;
    $this->entityTypeBundleInfo = $entity_type_bundle_info;
    $this->behaviorService = $behavior_service;
    $this->renderer = $renderer;
    $this->container = $container;
    $this->entityType = $this
      ->getRequest()
      ->get('synonyms_entity_type')
      ->id();
    $this->bundle = $this
      ->getRequest()
      ->get('bundle');
  }

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

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

  /**
   * {@inheritdoc}
   */
  protected function getEditableConfigNames() {
    $config_names = [];
    foreach ($this->behaviorService
      ->getBehaviorServices() as $service_id => $service) {
      $config_names[] = $this
        ->getConfigName($service_id);
    }
    return $config_names;
  }

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {
    $replacements = [
      '#theme' => 'item_list',
      '#list_type' => 'ul',
      '#items' => [],
    ];
    foreach ($this
      ->formatWordingAvailableTokens() as $token => $token_info) {
      $replacements['#items'][] = Html::escape($token) . ': ' . $token_info;
    }
    $replacements = $this->renderer
      ->renderRoot($replacements);
    foreach ($this->behaviorService
      ->getBehaviorServices() as $service_id => $service) {
      $this
        ->setNames($service_id);
      $form[$this->statusName] = [
        '#type' => 'checkbox',
        '#title' => $this
          ->t('@service service', [
          '@service' => $service
            ->getTitle(),
        ]),
        '#default_value' => $this
          ->config($this
          ->getConfigName($service_id))
          ->get('status') ?: 0,
      ];
      if ($service instanceof WidgetInterface && $this
        ->showWordingForm()) {
        $form[$this->wordingName] = [
          '#type' => 'textfield',
          '#title' => $this
            ->t('@widget widget wording:', [
            '@widget' => $service
              ->getWidgetTitle(),
          ]),
          '#default_value' => $this
            ->config($this
            ->getConfigName($service_id))
            ->get('wording') ?: '',
          '#description' => $this
            ->t('Specify the wording with which @widget widget suggestions should be presented. Available replacement tokens are: @replacements If this field is left empty the @widget widget default wording will be used.', [
            '@widget' => $service
              ->getWidgetTitle(),
            '@replacements' => $replacements,
          ]),
          '#states' => [
            'visible' => [
              ':input[name="' . $this->statusName . '"]' => [
                'checked' => TRUE,
              ],
            ],
          ],
        ];
      }
    }
    return parent::buildForm($form, $form_state);
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    foreach ($this->behaviorService
      ->getBehaviorServices() as $service_id => $service) {
      $this
        ->setNames($service_id);
      $this
        ->config($this
        ->getConfigName($service_id))
        ->set('status', $form_state
        ->getValue($this->statusName))
        ->set('wording', $form_state
        ->getValue($this->wordingName))
        ->save();
      parent::submitForm($form, $form_state);
    }
  }

  /**
   * Title callback for 'behavior.entity_type.bundle'.
   */
  public function entityTypeBundleBehaviorsTitle() {
    if ($this->entityType == $this->bundle) {
      return $this
        ->t('Manage behaviors of @entity_type', [
        '@entity_type' => $this
          ->getRequest()
          ->get('synonyms_entity_type')
          ->getLabel(),
      ]);
    }
    $bundle_info = $this->entityTypeBundleInfo
      ->getBundleInfo($this->entityType);
    return $this
      ->t('Manage behaviors of @entity_type @bundle', [
      '@entity_type' => $this
        ->getRequest()
        ->get('synonyms_entity_type')
        ->getLabel(),
      '@bundle' => $bundle_info[$this->bundle]['label'],
    ]);
  }

  /**
   * Helper function to generate form element names.
   */
  public function setNames($service_id) {
    $this->statusName = $service_id . '_status';
    $this->wordingName = $service_id . '_wording';
  }

  /**
   * Helper function to generate form element names.
   */
  public function getConfigName($service_id) {
    return 'synonyms_' . $service_id . '.behavior.' . $this->entityType . '.' . $this->bundle;
  }

  /**
   * Helper function which return depends on wording type.
   *
   * @return bool
   *   Whether wording forms should be visible or hidden.
   */
  public function showWordingForm() {
    $wording_type = \Drupal::config('synonyms.settings')
      ->get('wording_type');
    return $wording_type == 'entity' || $wording_type == 'provider';
  }

}

Members

Namesort descending Modifiers Type Description Overrides
BehaviorForm::$behaviorService protected property The behavior service.
BehaviorForm::$bundle protected property Bundle that is being managed.
BehaviorForm::$config protected property The behavior configuration.
BehaviorForm::$container protected property The container.
BehaviorForm::$entityType protected property Entity type that is being managed.
BehaviorForm::$entityTypeBundleInfo protected property The entity type bundle info.
BehaviorForm::$entityTypeManager protected property The entity type manager.
BehaviorForm::$renderer protected property The renderer.
BehaviorForm::$statusName protected property Current 'status' form field name.
BehaviorForm::$wordingName protected property Current 'wording' form field name.
BehaviorForm::buildForm public function Form constructor. Overrides ConfigFormBase::buildForm
BehaviorForm::create public static function Instantiates a new instance of this class. Overrides ConfigFormBase::create
BehaviorForm::entityTypeBundleBehaviorsTitle public function Title callback for 'behavior.entity_type.bundle'.
BehaviorForm::getConfigName public function Helper function to generate form element names.
BehaviorForm::getEditableConfigNames protected function Gets the configuration names that will be editable. Overrides ConfigFormBaseTrait::getEditableConfigNames
BehaviorForm::getFormId public function Returns a unique string identifying the form. Overrides FormInterface::getFormId
BehaviorForm::setNames public function Helper function to generate form element names.
BehaviorForm::showWordingForm public function Helper function which return depends on wording type.
BehaviorForm::submitForm public function Form submission handler. Overrides ConfigFormBase::submitForm
BehaviorForm::__construct public function BehaviorForm constructor. Overrides ConfigFormBase::__construct
ConfigFormBaseTrait::config protected function Retrieves a configuration object.
DependencySerializationTrait::$_entityStorages protected property
DependencySerializationTrait::$_serviceIds protected property
DependencySerializationTrait::__sleep public function 2
DependencySerializationTrait::__wakeup public function 2
FormBase::$configFactory protected property The config factory. 3
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. 3
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.
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 72
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. 27
MessengerTrait::messenger public function Gets the messenger. 27
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. 4
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.