You are here

class WidgetForm in Search API Sorts Widget 1.x

Provides a Search API Sorts Widget form.

Hierarchy

Expanded class hierarchy of WidgetForm

File

src/Form/WidgetForm.php, line 16

Namespace

Drupal\search_api_sorts_widget\Form
View source
class WidgetForm extends FormBase {
  use ConfigIdEscapeTrait;

  /**
   * The search api sorts widget storage.
   *
   * @var \Drupal\Core\Entity\EntityStorageInterface
   */
  protected $searchApiSortsWidgetStorage;

  /**
   * Constructs the DisplaySortsForm object.
   *
   * @param \Drupal\search_api\Display\DisplayPluginManagerInterface $display_plugin_manager
   *   The search_api display plugin manager.
   * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
   *   The entity manager.
   * @param \Drupal\Core\Language\LanguageManagerInterface $languageManager
   *   The language manager.
   * @param \Drupal\Core\Extension\ModuleHandlerInterface $moduleHandler
   *   The module handler.
   */
  public function __construct(EntityTypeManagerInterface $entity_type_manager) {
    $this->searchApiSortsWidgetStorage = $entity_type_manager
      ->getStorage('search_api_sorts_widget');
  }

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

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

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state, $content = NULL, $derivative_plugin_id = NULL) {
    if (!$content || !$derivative_plugin_id) {
      return $content;
    }
    $config_id = $this
      ->getEscapedConfigId($derivative_plugin_id);
    $settings = $this->searchApiSortsWidgetStorage
      ->load($config_id);
    if (empty($settings) || !$settings
      ->get('status')) {
      return $content;
    }
    $links = $content['links'];
    $new_items = [];
    $default = '';
    $sort_fields = array_column($links['#items'], '#sort_field');
    foreach ($settings
      ->get('sorts') as $name => $setting) {
      $key = array_search($name, $sort_fields);
      if (!empty($links['#items'][$key])) {
        $link = $links['#items'][$key];
        if (!empty($setting['label_asc'])) {
          $new_items[$name . '|asc'] = $setting['label_asc'];
        }
        if (!empty($setting['label_desc'])) {
          $new_items[$name . '|desc'] = $setting['label_desc'];
        }
        if ($link['#active']) {
          $default = $name . '|' . ($link['#order'] == 'asc' ? 'desc' : 'asc');
        }
      }
    }
    $form_state
      ->set('links', $links);
    $form['sort_by'] = array(
      '#type' => 'select',
      '#options' => $new_items,
      '#default_value' => $default,
    );
    if ($settings
      ->get('autosubmit')) {
      $form['sort_by']['#attributes']['onChange'] = 'this.form.submit();';
    }
    $form['actions'] = [
      '#type' => 'actions',
    ];
    $form['actions']['submit'] = [
      '#type' => 'submit',
      '#value' => $this
        ->t('Sort'),
    ];
    if ($settings
      ->get('autosubmit_hide')) {
      $form['actions']['submit']['#attributes']['style'] = [
        'display: none;',
      ];
    }
    return $form;
  }

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

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    $links = $form_state
      ->get('links');
    [
      $key,
      $order,
    ] = explode('|', $form_state
      ->getValue('sort_by'));
    foreach ($links['#items'] as $link) {
      $name = $link['#sort_field'];
      if ($name == $key) {
        $url = $link['#url'];
        $url_info = parse_url($url);
        parse_str($url_info['query'], $query);
        $query['order'] = $order;
        $url_info['query'] = UrlHelper::buildQuery($query);
        $url = $url_info['path'] . '?' . $url_info['query'];
        $form_state
          ->setRedirectUrl(Url::fromUserInput($url));
      }
    }
  }

}

Members

Namesort descending Modifiers Type Description Overrides
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::config protected function Retrieves a configuration object.
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.
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.
WidgetForm::$searchApiSortsWidgetStorage protected property The search api sorts widget storage.
WidgetForm::buildForm public function Form constructor. Overrides FormInterface::buildForm
WidgetForm::create public static function Instantiates a new instance of this class. Overrides FormBase::create
WidgetForm::getFormId public function Returns a unique string identifying the form. Overrides FormInterface::getFormId
WidgetForm::submitForm public function Form submission handler. Overrides FormInterface::submitForm
WidgetForm::validateForm public function Form validation handler. Overrides FormBase::validateForm
WidgetForm::__construct public function Constructs the DisplaySortsForm object.