You are here

class SettingsForm in Views Filter Harmonizer 1.0.x

Same name and namespace in other branches
  1. 8 src/Form/SettingsForm.php \Drupal\filter_harmonizer\Form\SettingsForm

Provides the from to edit Views Filter Harmonizer admin config settings.

Hierarchy

Expanded class hierarchy of SettingsForm

1 string reference to 'SettingsForm'
filter_harmonizer.routing.yml in ./filter_harmonizer.routing.yml
filter_harmonizer.routing.yml

File

src/Form/SettingsForm.php, line 12

Namespace

Drupal\filter_harmonizer\Form
View source
class SettingsForm extends ConfigFormBase {

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

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {
    $msg1 = $this
      ->t('The following views have paris of contextual and regular filters on the same fields.');
    $msg2 = $this
      ->t('You may select any of these views for harmonization.');
    $form['fh_views_with_paired_filters'] = [
      '#type' => 'details',
      '#open' => TRUE,
      '#title' => $this
        ->t('Harmonizable views'),
      '#description' => "{$msg1}<br/>{$msg2}",
    ];
    $eligible_view_info = [];
    foreach (Views::getAllViews() as $view) {
      $view_id = $view
        ->id();
      $view_label = $view
        ->get('label');
      if (views_view_is_disabled($view)) {
        $view_label .= ' (' . $this
          ->t('disabled') . ')';
      }
      if ($filter_pairs = filter_harmonizer_harmonize_and_record_filter_pairs($view
        ->getExecutable())) {
        if (self::viewHasFilterPair($view_id, $filter_pairs)) {
          $eligible_view_info[$view_id] = [
            'label' => $view_label,
            'displays' => $filter_pairs[$view_id],
          ];
        }
      }
    }
    $config = $this
      ->config('filter_harmonizer.settings');
    $harmonized_view_ids = $config
      ->get('filter_harmonizer_harmonized_view_ids') ?? [];
    foreach ($eligible_view_info as $view_id => $view_info) {
      $field_labels = [];
      foreach ($view_info['displays'] as $filter_pairs) {
        foreach (array_column($filter_pairs, 'field_label') as $label) {
          if (!in_array($label, $field_labels)) {
            $field_labels[] = $label;
          }
        }
      }
      $form['fh_views_with_paired_filters']['view_' . $view_id] = [
        '#type' => 'checkbox',
        '#title' => $this
          ->t('View %view_label: @field_labels', [
          '%view_label' => $view_info['label'],
          '@field_labels' => implode(', ', $field_labels),
        ]),
        '#default_value' => in_array($view_id, $harmonized_view_ids),
      ];
    }
    $form['fh_display_options'] = [
      '#type' => 'details',
      '#title' => $this
        ->t('Contextual and regular filter display options'),
      '#description' => '',
      '#open' => TRUE,
    ];
    $form['fh_display_options']['fh_contextual_args_in_exposed_form'] = [
      '#type' => 'checkbox',
      '#title' => $this
        ->t('Reflect contextual (URL) arguments on the regular filter form'),
      '#default_value' => $config
        ->get('filter_harmonizer_contextual_args_in_exposed_form'),
      '#description' => $this
        ->t('This helps to avoid confusion when the page was initially loaded with contextual arguments on the URL.<br/>Does not work when "Use AJAX" is ticked.'),
    ];
    $form['fh_display_options']['fh_regular_filter_values_in_address_bar'] = [
      '#type' => 'checkbox',
      '#title' => $this
        ->t('Reflect regular filter selections on the browser URL/address bar'),
      '#default_value' => $config
        ->get('filter_harmonizer_regular_filter_values_in_address_bar'),
      '#description' => $this
        ->t('This helps to avoid confusion after the page is re-submitted with new regular filter values.<br/>It also allows for easy sharing of a filtered page URL in emails and on social media, because the URL reflects the filter selection you made.<br/>Does not apply to Views UI admin pages. Does not work when "Use AJAX" is ticked.'),
    ];
    return parent::buildForm($form, $form_state);
  }

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

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    parent::submitForm($form, $form_state);
    $harmonized_view_ids = [];
    foreach ($form_state
      ->getValues() as $key => $value) {
      if ('view_' == substr($key, 0, 5) && $value == 1) {
        $harmonized_view_ids[] = substr($key, 5);
      }
    }
    $this
      ->config('filter_harmonizer.settings')
      ->set('filter_harmonizer_harmonized_view_ids', $harmonized_view_ids)
      ->set('filter_harmonizer_regular_filter_values_in_address_bar', $form_state
      ->getValue('fh_regular_filter_values_in_address_bar'))
      ->set('filter_harmonizer_contextual_args_in_exposed_form', $form_state
      ->getValue('fh_contextual_args_in_exposed_form'))
      ->save();
  }

  /**
   * {@inheritdoc}
   *
   * To allow saving of config settings in above submitForm().
   */
  protected function getEditableConfigNames() {
    return [
      'filter_harmonizer.settings',
    ];
  }

  /**
   * Returns if the View has a contextual and regular filter pair on a field.
   *
   * @param string $view_id
   *   The View id.
   * @param array $filter_pairs
   *   Array of filter pair information, indexed by display ID.
   *
   * @return bool
   *   TRUE if the View has at least one field with a filter pair.
   */
  public static function viewHasFilterPair($view_id, array $filter_pairs) {
    if (!empty($filter_pairs[$view_id])) {
      foreach ($filter_pairs[$view_id] as $field_info) {
        foreach ($field_info as $filters) {
          if (!empty($filters['contextual']) && !empty($filters['regular'])) {
            return TRUE;
          }
        }
      }
    }
    return FALSE;
  }

}

Members

Namesort descending Modifiers Type Description Overrides
ConfigFormBase::create public static function Instantiates a new instance of this class. Overrides FormBase::create 18
ConfigFormBase::__construct public function Constructs a \Drupal\system\ConfigFormBase object. 16
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.
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.
SettingsForm::buildForm public function Form constructor. Overrides ConfigFormBase::buildForm
SettingsForm::getEditableConfigNames protected function To allow saving of config settings in above submitForm(). Overrides ConfigFormBaseTrait::getEditableConfigNames
SettingsForm::getFormId public function Returns a unique string identifying the form. Overrides FormInterface::getFormId
SettingsForm::submitForm public function Form submission handler. Overrides ConfigFormBase::submitForm
SettingsForm::validateForm public function Form validation handler. Overrides FormBase::validateForm
SettingsForm::viewHasFilterPair public static function Returns if the View has a contextual and regular filter pair on a field.
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.