You are here

class TawkToExtraSettingsForm in Tawk.to - Live chat application (Drupal 8) 8

Same name and namespace in other branches
  1. 8.2 src/Form/TawkToExtraSettingsForm.php \Drupal\tawk_to\Form\TawkToExtraSettingsForm

Provides form for block instance forms.

Hierarchy

Expanded class hierarchy of TawkToExtraSettingsForm

1 string reference to 'TawkToExtraSettingsForm'
tawk_to.routing.yml in ./tawk_to.routing.yml
tawk_to.routing.yml

File

src/Form/TawkToExtraSettingsForm.php, line 19

Namespace

Drupal\tawk_to\Form
View source
class TawkToExtraSettingsForm extends ConfigFormBase {
  use StringTranslationTrait;

  /**
   * The condition plugin manager.
   *
   * @var \Drupal\Core\Condition\ConditionManager
   */
  protected $manager;

  /**
   * The language manager service.
   *
   * @var \Drupal\Core\Language\LanguageManagerInterface
   */
  protected $language;

  /**
   * The context repository service.
   *
   * @var \Drupal\Core\Plugin\Context\ContextRepositoryInterface
   */
  protected $contextRepository;

  /**
   * Constructs a TawkToExtraSettingsForm object.
   *
   * @param \Drupal\Core\Config\ConfigFactoryInterface $configFactory
   *   The factory for configuration objects.
   * @param \Drupal\Core\Executable\ExecutableManagerInterface $manager
   *   The ConditionManager for building the visibility UI.
   * @param \Drupal\Core\Plugin\Context\ContextRepositoryInterface $contextRepository
   *   The lazy context repository service.
   * @param \Drupal\Core\Language\LanguageManagerInterface $language
   *   The language manager.
   */
  public function __construct(ConfigFactoryInterface $configFactory, ExecutableManagerInterface $manager, ContextRepositoryInterface $contextRepository, LanguageManagerInterface $language) {
    parent::__construct($configFactory);
    $this->manager = $manager;
    $this->contextRepository = $contextRepository;
    $this->language = $language;
  }

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

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

  /**
   * {@inheritdoc}
   */
  protected function getEditableConfigNames() {
    return [
      'tawk_to.settings',
    ];
  }

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

    // Build visibility settings part.
    $form_state
      ->setTemporaryValue('gathered_contexts', $this->contextRepository
      ->getAvailableContexts());
    $form['#tree'] = TRUE;
    $form['visibility'] = $this
      ->buildVisibilityInterface([], $form_state);
    $form['user'] = $this
      ->buildUserInfoInterface([], $form_state);
    return parent::buildForm($form, $form_state);
  }

  /**
   * Helper function for building the visibility UI form.
   *
   * @param array $form
   *   An associative array containing the structure of the form.
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   The current state of the form.
   *
   * @return array
   *   The form array with the visibility UI added in.
   */
  protected function buildVisibilityInterface(array $form, FormStateInterface $form_state) {
    $form['visibility_tabs'] = [
      '#type' => 'vertical_tabs',
      '#title' => $this
        ->t('Visibility'),
      '#parents' => [
        'visibility_tabs',
      ],
    ];
    $visibility = $this
      ->config('tawk_to.settings')
      ->get('visibility');
    foreach ($this->manager
      ->getDefinitionsForContexts($form_state
      ->getTemporaryValue('gathered_contexts')) as $condition_id => $definition) {

      // Don't display the webform condition, causes problems.
      if ($condition_id == 'entity_bundle:webform_submission') {
        continue;
      }

      // Don't display the current theme condition.
      if ($condition_id == 'current_theme') {
        continue;
      }

      // Don't display the GTM Language condition, causes problems.
      if ($condition_id == 'gtag_language') {
        continue;
      }

      // Don't display the language condition until we have multiple languages.
      if ($condition_id == 'language' && !$this->language
        ->isMultilingual()) {
        continue;
      }

      /** @var \Drupal\Core\Condition\ConditionInterface $condition */
      $condition = $this->manager
        ->createInstance($condition_id, isset($visibility[$condition_id]) ? $visibility[$condition_id] : []);
      $form_state
        ->set([
        'conditions',
        $condition_id,
      ], $condition);
      $condition_form = $condition
        ->buildConfigurationForm([], $form_state);
      $condition_form['#type'] = 'details';
      $condition_form['#title'] = $condition
        ->getPluginDefinition()['label'];
      $condition_form['#group'] = 'visibility_tabs';
      $form[$condition_id] = $condition_form;
    }
    if (isset($form['node_type'])) {
      $form['node_type']['#title'] = $this
        ->t('Content types');
      $form['node_type']['bundles']['#title'] = $this
        ->t('Content types');
      $form['node_type']['negate']['#type'] = 'value';
      $form['node_type']['negate']['#title_display'] = 'invisible';
      $form['node_type']['negate']['#value'] = $form['node_type']['negate']['#default_value'];
    }
    if (isset($form['user_role'])) {
      $form['user_role']['#title'] = $this
        ->t('Roles');
      unset($form['user_role']['roles']['#description']);
      $form['user_role']['negate']['#type'] = 'value';
      $form['user_role']['negate']['#value'] = $form['user_role']['negate']['#default_value'];
    }
    if (isset($form['request_path'])) {
      $form['request_path']['#title'] = $this
        ->t('Pages');
      $form['request_path']['negate']['#type'] = 'radios';
      $form['request_path']['negate']['#default_value'] = (int) $form['request_path']['negate']['#default_value'];
      $form['request_path']['negate']['#title_display'] = 'invisible';
      $form['request_path']['negate']['#options'] = [
        $this
          ->t('Show for the listed pages'),
        $this
          ->t('Hide for the listed pages'),
      ];
    }
    if (isset($form['language'])) {
      $form['language']['negate']['#type'] = 'value';
      $form['language']['negate']['#value'] = $form['language']['negate']['#default_value'];
    }
    return $form;
  }

  /**
   * Helper function for building the user info UI form.
   *
   * @param array $form
   *   An associative array containing the structure of the form.
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   The current state of the form.
   *
   * @return array
   *   The form array with the visibility UI added in.
   */
  protected function buildUserInfoInterface(array $form, FormStateInterface $form_state) {
    $settings = $this
      ->config('tawk_to.settings');
    $form['user'] = [
      '#type' => 'fieldset',
      '#title' => $this
        ->t('User info settings'),
    ];
    $form['user']['show_user_name'] = [
      '#type' => 'checkbox',
      '#title' => $this
        ->t('Show user name in the widget'),
      '#default_value' => $settings
        ->get('show_user_name'),
    ];
    $form['user']['user_name'] = [
      '#type' => 'textfield',
      '#title' => $this
        ->t('User name in the widget'),
      '#description' => $this
        ->t('You can use tokens. E.g. [current-user:name].'),
      '#default_value' => $settings
        ->get('user_name'),
      '#states' => [
        'visible' => [
          ':input[name*=show_user_name]' => [
            'checked' => TRUE,
          ],
        ],
      ],
    ];
    $form['user']['show_user_email'] = [
      '#type' => 'checkbox',
      '#title' => $this
        ->t('Show user email in the widget'),
      '#default_value' => $settings
        ->get('show_user_name'),
    ];
    $form['user']['user_email'] = [
      '#type' => 'textfield',
      '#title' => $this
        ->t('User email in the widget'),
      '#description' => $this
        ->t('You can use tokens. E.g. [current-user:mail].'),
      '#default_value' => $settings
        ->get('user_email'),
      '#states' => [
        'visible' => [
          ':input[name*=show_user_email]' => [
            'checked' => TRUE,
          ],
        ],
      ],
    ];
    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    $this
      ->submitVisibility($form, $form_state);
    $this
      ->submitUserInfo($form, $form_state);
    return parent::submitForm($form, $form_state);
  }

  /**
   * Helper function to independently submit the visibility UI.
   *
   * @param array $form
   *   A nested array form elements comprising the form.
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   The current state of the form.
   */
  protected function submitVisibility(array $form, FormStateInterface $form_state) {
    $visibility = [];
    foreach ($form_state
      ->getValue('visibility') as $condition_id => $values) {

      // Allow the condition to submit the form.
      $condition = $form_state
        ->get([
        'conditions',
        $condition_id,
      ]);
      $condition
        ->submitConfigurationForm($form['visibility'][$condition_id], SubformState::createForSubform($form['visibility'][$condition_id], $form, $form_state));
      if ($condition instanceof ContextAwarePluginInterface) {
        $contextMapping = isset($values['context_mapping']) ? $values['context_mapping'] : [];
        $condition
          ->setContextMapping($contextMapping);
      }
      $conditionConfiguration = $condition
        ->getConfiguration();

      // Save the visibility conditions to config.
      $visibility[$condition_id] = $conditionConfiguration;
    }
    $this
      ->config('tawk_to.settings')
      ->set('visibility', $visibility)
      ->save();
  }

  /**
   * Helper function to independently submit the visibility UI.
   *
   * @param array $form
   *   A nested array form elements comprising the form.
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   The current state of the form.
   */
  protected function submitUserInfo(array $form, FormStateInterface $form_state) {
    $visibility = [];
    foreach ($form_state
      ->getValue('user')['user'] as $key => $value) {
      $this
        ->config('tawk_to.settings')
        ->set($key, $value)
        ->save();
    }
  }

  /**
   * {@inheritdoc}
   */
  public function validateForm(array &$form, FormStateInterface $form_state) {
    parent::validateForm($form, $form_state);
    $this
      ->validateVisibility($form, $form_state);
  }

  /**
   * Helper function to independently validate the visibility UI.
   *
   * @param array $form
   *   A nested array form elements comprising the form.
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   The current state of the form.
   */
  protected function validateVisibility(array $form, FormStateInterface $form_state) {

    // Validate visibility condition settings.
    foreach ($form_state
      ->getValue('visibility') as $conditionId => $values) {

      // All condition plugins use 'negate' as a Boolean in their schema.
      // However, certain form elements may return it as 0/1. Cast here to
      // ensure the data is in the expected type.
      if (array_key_exists('negate', $values)) {
        $form_state
          ->setValue([
          'visibility',
          $conditionId,
          'negate',
        ], (bool) $values['negate']);
      }

      // Allow the condition to validate the form.
      $condition = $form_state
        ->get([
        'conditions',
        $conditionId,
      ]);
      $condition
        ->validateConfigurationForm($form['visibility'][$conditionId], SubformState::createForSubform($form['visibility'][$conditionId], $form, $form_state));
    }
  }

}

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.
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.
TawkToExtraSettingsForm::$contextRepository protected property The context repository service.
TawkToExtraSettingsForm::$language protected property The language manager service.
TawkToExtraSettingsForm::$manager protected property The condition plugin manager.
TawkToExtraSettingsForm::buildForm public function Form constructor. Overrides ConfigFormBase::buildForm
TawkToExtraSettingsForm::buildUserInfoInterface protected function Helper function for building the user info UI form.
TawkToExtraSettingsForm::buildVisibilityInterface protected function Helper function for building the visibility UI form.
TawkToExtraSettingsForm::create public static function Instantiates a new instance of this class. Overrides ConfigFormBase::create
TawkToExtraSettingsForm::getEditableConfigNames protected function Gets the configuration names that will be editable. Overrides ConfigFormBaseTrait::getEditableConfigNames
TawkToExtraSettingsForm::getFormId public function Returns a unique string identifying the form. Overrides FormInterface::getFormId
TawkToExtraSettingsForm::submitForm public function Form submission handler. Overrides ConfigFormBase::submitForm
TawkToExtraSettingsForm::submitUserInfo protected function Helper function to independently submit the visibility UI.
TawkToExtraSettingsForm::submitVisibility protected function Helper function to independently submit the visibility UI.
TawkToExtraSettingsForm::validateForm public function Form validation handler. Overrides FormBase::validateForm
TawkToExtraSettingsForm::validateVisibility protected function Helper function to independently validate the visibility UI.
TawkToExtraSettingsForm::__construct public function Constructs a TawkToExtraSettingsForm object. Overrides ConfigFormBase::__construct
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.