You are here

class OrderForm in Frequently Asked Questions 8

Form for reordering the FAQ-s.

Hierarchy

Expanded class hierarchy of OrderForm

File

src/Form/OrderForm.php, line 19

Namespace

Drupal\faq\Form
View source
class OrderForm extends ConfigFormBase {
  protected $entityTypeManager;
  protected $languageManager;
  protected $database;

  /**
   * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entityTypeManager
   * @param \Drupal\Core\Language\LanguageManagerInterface $languageManager
   * @param \Drupal\Core\Database\Connection $database
   */
  public function __construct(EntityTypeManagerInterface $entityTypeManager, LanguageManagerInterface $languageManager, Connection $database) {
    $this->entityTypeManager = $entityTypeManager;
    $this->languageManager = $languageManager;
    $this->database = $database;
  }

  /**
   * @param \Symfony\Component\DependencyInjection\ContainerInterface $container
   * @return static
   */
  public static function create(ContainerInterface $container) {
    return new static($container
      ->get('entity_type.manager'), $container
      ->get('language_manager'), $container
      ->get('database'));
  }

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

  /**
   * {@inheritdoc}
   */
  protected function getEditableConfigNames() {
    return [];
  }

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

    // Get category id from route values.
    if ($id = FaqHelper::searchInArgs('faq-page')) {
      $next_id = $id + 1;

      // Check if we're on a categorized faq page.
      if (is_numeric(FaqHelper::arg($next_id))) {
        $category = FaqHelper::arg($next_id);
      }
    }
    $order = $date_order = '';
    $faq_settings = $this
      ->config('faq.settings');
    $use_categories = $faq_settings
      ->get('use_categories');
    if (!$use_categories) {
      $step = "order";
    }
    elseif ($form_state
      ->getValues() != NULL && empty($category)) {
      $step = "categories";
    }
    else {
      $step = "order";
    }
    $form['step'] = array(
      '#type' => 'value',
      '#value' => $step,
    );

    // Categorized q/a.
    if ($step == "categories") {

      // Get list of categories.
      $vocabularies = Vocabulary::loadMultiple();
      $options = array();
      foreach ($vocabularies as $vid => $vobj) {
        $tree = $this->entityTypeManager
          ->getStorage('taxonomy_term')
          ->loadTree($vid);
        foreach ($tree as $term) {
          if (!FaqHelper::taxonomyTermCountNodes($term->tid)) {
            continue;
          }
          $options[$term->tid] = $this
            ->t($term->name);
          $form['choose_cat']['faq_category'] = array(
            '#type' => 'select',
            '#title' => t('Choose a category'),
            '#description' => t('Choose a category that you wish to order the questions for.'),
            '#options' => $options,
            '#multiple' => FALSE,
          );
          $form['choose_cat']['search'] = array(
            '#type' => 'submit',
            '#value' => t('Search'),
            '#submit' => array(
              'faq_order_settings_choose_cat_form_submit',
            ),
          );
        }
      }
    }
    else {
      $default_sorting = $faq_settings
        ->get('default_sorting');
      $default_weight = 0;
      if ($default_sorting != 'DESC') {
        $default_weight = 1000000;
      }
      $options = array();
      if (!empty($form_state
        ->getValue('faq_category'))) {
        $category = $form_state
          ->getValue('faq_category');
      }
      $langcode = $this->languageManager
        ->getCurrentLanguage()
        ->getId();

      // Uncategorized ordering.
      $query = $this->database
        ->select('node', 'n');
      $query
        ->join('node_field_data', 'd', 'n.nid = d.nid');
      $query
        ->fields('n', [
        'nid',
      ])
        ->fields('d', [
        'title',
      ])
        ->condition('n.type', 'faq')
        ->condition('d.langcode', $langcode)
        ->condition('d.status', 1)
        ->addTag('node_access');

      // Works, but involves variable concatenation - safe though, since
      // $default_weight is an integer.
      $query
        ->addExpression("COALESCE(w.weight, {$default_weight})", 'effective_weight');

      // Doesn't work in Postgres.
      // $query->addExpression('COALESCE(w.weight, CAST(:default_weight as SIGNED))', 'effective_weight', array(':default_weight' => $default_weight));.
      if (empty($category)) {
        $category = 0;
        $query
          ->leftJoin('faq_weights', 'w', 'n.nid = %alias.nid AND %alias.tid = :category', array(
          ':category' => $category,
        ));
        $query
          ->orderBy('effective_weight', 'ASC')
          ->orderBy('d.sticky', 'DESC')
          ->orderBy('d.created', $default_sorting == 'DESC' ? 'DESC' : 'ASC');
      }
      else {
        $query
          ->innerJoin('taxonomy_index', 'ti', '(n.nid = %alias.nid)');
        $query
          ->leftJoin('faq_weights', 'w', 'n.nid = %alias.nid AND %alias.tid = :category', array(
          ':category' => $category,
        ));
        $query
          ->condition('ti.tid', $category);
        $query
          ->orderBy('effective_weight', 'ASC')
          ->orderBy('d.sticky', 'DESC')
          ->orderBy('d.created', $default_sorting == 'DESC' ? 'DESC' : 'ASC');
      }
      $options = $query
        ->execute()
        ->fetchAll();
      $form['weight']['faq_category'] = array(
        '#type' => 'value',
        '#value' => $category,
      );

      // Show table ordering form.
      $form['order_no_cats']['#tree'] = TRUE;
      $form['order_no_cats']['#theme'] = 'faq_draggable_question_order_table';
      foreach ($options as $i => $record) {
        $form['order_no_cats'][$i]['nid'] = array(
          '#type' => 'hidden',
          '#value' => $record->nid,
        );
        $form['order_no_cats'][$i]['title'] = array(
          '#markup' => Html::escape($record->title),
        );
        $form['order_no_cats'][$i]['sort'] = array(
          '#type' => 'weight',
          '#delta' => count($options),
          '#default_value' => $i,
        );
      }
      $form['actions']['#type'] = 'actions';
      $form['actions']['submit'] = array(
        '#type' => 'submit',
        '#value' => $this
          ->t('Save order'),
        '#button_type' => 'primary',
      );
    }
    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    $order_no_cats = $form_state
      ->getValue('order_no_cats');
    if ($form_state
      ->getValue('op')
      ->__toString() == t('Save order') && !empty($order_no_cats)) {
      foreach ($order_no_cats as $i => $faq) {
        $nid = $faq['nid'];
        $index = $faq['sort'];
        Database::getConnection()
          ->merge('faq_weights')
          ->fields(array(
          'weight' => $index,
        ))
          ->keys(array(
          'tid' => $form_state
            ->getValue('faq_category'),
          'nid' => $nid,
        ))
          ->execute();
      }
      parent::submitForm($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.
FormBase::validateForm public function Form validation handler. Overrides FormInterface::validateForm 62
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.
OrderForm::$database protected property
OrderForm::$entityTypeManager protected property
OrderForm::$languageManager protected property
OrderForm::buildForm public function Form constructor. Overrides ConfigFormBase::buildForm
OrderForm::create public static function Overrides ConfigFormBase::create
OrderForm::getEditableConfigNames protected function Gets the configuration names that will be editable. Overrides ConfigFormBaseTrait::getEditableConfigNames
OrderForm::getFormId public function Returns a unique string identifying the form. Overrides FormInterface::getFormId
OrderForm::submitForm public function Form submission handler. Overrides ConfigFormBase::submitForm
OrderForm::__construct public function Overrides ConfigFormBase::__construct
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.