views_filters_combine_field-8.x-1.x-dev/src/Plugin/views/filter/CombineField.php

src/Plugin/views/filter/CombineField.php
<?php

namespace Drupal\views_filters_combine_field\Plugin\views\filter;

use Drupal\Core\Form\FormStateInterface;
use Drupal\views\Plugin\views\filter\StringFilter;

/**
 * Filter handler which allows to search on multiple fields.
 *
 * @ingroup views_field_handlers
 *
 * @ViewsFilter("views_filters_combine_field")
 */
class CombineField extends StringFilter {

  /**
   * Query Variable.
   *
   * @var \Drupal\views\Plugin\views\query\QueryPluginBase
   */

  public $query;

  /**
   * {@inheritdoc}
   */
  protected function defineOptions() {
    $options = parent::defineOptions();
    $options['fields'] = ['default' => []];
    $options['select_field'] = ['default' => []];
    return $options;
  }

  /**
   * {@inheritdoc}
   */
  public function buildOptionsForm(&$form, FormStateInterface $form_state) {
    parent::buildOptionsForm($form, $form_state);

    $this->view->initStyle();

    if ($this->view->style_plugin->usesFields()) {
      $options = [];
      foreach ($this->view->display_handler->getHandlers('field') as $name => $field) {
        if ($field->clickSortable()) {
          $options[$name] = $field->adminLabel(TRUE);
        }
      }
      if ($options) {
        $form['fields'] = [
          '#type' => 'select',
          '#title' => $this->t('Choose fields to combine   for filtering'),
          '#multiple' => TRUE,
          '#options' => $options,
          '#default_value' => $this->options['fields'],
        ];
      }
      else {
        $form_state->setErrorByName('', $this->t('You have to add some fields to be able to use this filter.'));
      }
    }
  }

  /**
   * {@inheritdoc}
   */
  public function query() {

    $this->view->_build('field');
    $fields = [];
    if (!isset($this->view->field[$this->options['select_field']])) {
      $this->view->build_info['fail'] = TRUE;
    }
    $field = $this->view->field[$this->options['select_field']];
    $field->ensureMyTable();
    if (!empty($field->field_alias) && !empty($field->field_alias)) {
      if (!in_array("$field->tableAlias.$field->realField", $fields)) {
        $field_type = $field->configuration['id'];
        if (strpos($field_type, 'composite_field')) {
          $fields[] = "$field->tableAlias.value";
        }
        else {
          $fields[] = "$field->tableAlias.$field->realField";
        }
      }
    }
    if ($fields) {
      if (count($fields) == 1) {
        $expression = reset($fields);
      }
      else {
        $expression = implode(", ' ', ", $fields);
        $expression = "CONCAT_WS(' ', $expression)";
      }
      $info = $this->operators();
      if (!empty($info[$this->operator]['method'])) {
        $this->{$info[$this->operator]['method']}($expression);
      }
    }
  }

  /**
   * {@inheritdoc}
   */
  protected function opSimple($field) {
    $this->query->addWhere($this->options['group'], $field, $this->value['value'], $this->operator);
  }

  /**
   * {@inheritdoc}
   */
  public function getoperators() {
    return [
      'select' => [
        '=' => $this->t('Is equal to'),
        '!=' => $this->t('Is not equal to'),
      ],
      'number' => [
        '<' => $this->t('Is less than'),
        '<=' => $this->t('Is less than or equal to'),
        '=' => $this->t('Is equal to'),
        '!=' => $this->t('Is not equal to'),
        '>=' => $this->t('Is greater than or equal to'),
        '>' => $this->t('Is greater than'),
        'regular_expression' => $this->t('Regular expression'),
      ],
      'textfield' => [
        '=' => $this->t('Is equal to'),
        '!=' => $this->t('Is not equal to'),
        'contains' => $this->t('Contains'),
        'word' => $this->t('Contains any word'),
        'allwords' => $this->t('Contains all words'),
        'starts' => $this->t('Starts with'),
        'not_starts' => $this->t('Does not start with'),
        'ends' => $this->t('Ends with'),
        'not_ends' => $this->t('Does not end with'),
        'not' => $this->t('Does not contain'),
        'regular_expression' => $this->t('Regular expression'),
      ],
    ];
  }

  /**
   * {@inheritdoc}
   */
  protected function valueForm(&$form, FormStateInterface $form_state) {
    parent::valueForm($form, $form_state);

    $options = [];
    foreach ($this->view->display_handler->getHandlers('field') as $name => $field) {
      if ($field->clickSortable()) {
        $options[$name] = $field->adminLabel(TRUE);
      }
    }
    if (isset($this->view->getExposedInput()['combinefield'])) {
      $this->value = $this->view->getExposedInput()['combinefield'];
      $this->options['value'] = $this->view->getExposedInput()['combinefield'];
    }
    if (isset($this->view->getExposedInput()['combinefield_op'])) {
      $this->options['combinefield_op'] = $this->view->getExposedInput()['combinefield_op'];
    }
    else {
      $this->options['combinefield_op'] = '';
    }
    if ($this->view->storage->get('base_table') == "webform_submission") {
      $entity = "webform";
      $webform_id = reset($this->view->filter)->configuration['webform_id'];
      $webform = \Drupal::entityTypeManager()->getStorage($entity)->load($webform_id);
      if ($webform) {
        $elements = $webform->getElementsDecodedAndFlattened();
      }
    }
    else {
      if ($this->view->storage->get('base_table') == "node_field_data") {
        $entity_type = 'node';
        $node_type = '';
        if (!empty($this->view->filter['type']->value)) {
          $node_type = reset($this->view->filter['type']->value);
        }
        if (empty($node_type)) {
          \Drupal::messenger()->addError('Unable to show fields please the type in filter criteria.');
        }
        $elements = $this->getelements($entity_type, $node_type);
      }
    }
    $options = [];
    $this->view->initStyle();
    $this->view->style_plugin->usesFields();
    $entity = $this->view->storage->get('base_table');
    foreach ($this->view->display_handler->getHandlers('field') as $name => $field) {
      if ($field->clickSortable()) {
        if (in_array($name, $this->options['fields'])) {
          $options[$name] = $string = $field->adminLabel(TRUE);
          $options[$name] = $string = str_replace("_", " ", ucfirst($field->options['id']));
        }
      }
    }

    if ($exposed = $form_state->get('exposed')) {
      $identifier = $this->options['expose']['identifier'];
    }
    $select_field_class = ['vfc-enabled', 'multiple_search_select'];
    $form_exposed_id = 'multiple_search_form';
    $select_search_field = ['multiple_search_field'];
    $operator_field = ['multiple_operator_field'];
    $form['select_field'] = [
      '#type' => 'select',
      '#options' => $options,
      '#attributes' => ['class' => $select_field_class],
      '#title' => $this->t('Select The Field'),
      '#default_value' => (!empty($this->options['select_field']) || isset($this->options['select_field'])) ? $this->options['select_field'] : reset($options),
    ];
    if (!isset($form['select_field']['#attached'])) {
      $form['select_field']['#attached'] = [];
    }
    $form['select_field']['#attached'] = array_merge($form['select_field']['#attached'], [
      'library' => ['views_filters_combine_field/global_style'],
    ]);
    $form['select_field']['#attached'] = array_merge($form['select_field']['#attached'], [
      'drupalSettings' => [
        'views_filters_combine_field' => [
          'elements' => $elements,
          'select_field_id' => $select_field_class,
          'form_exposed_id' => $form_exposed_id,
          'operator_field' => $operator_field,
          'search_field_id' => $select_search_field,
          'operator' => $this->getoperators(),
          'current_value' => $this->value,
          'current_operator' => $this->options['combinefield_op'],
        ],
      ],
    ]);
    if (isset($form['combinefield_wrapper'])) {
      $form['combinefield_wrapper']['combinefield_op']['#attributes'] = ['class' => $operator_field];
    };
    $form['combinefield_op']['#attributes'] = ['class' => $operator_field];
    $form['value'] = [
      '#type' => 'textfield',
      '#title' => $this->t('Value'),
      '#attributes' => ['class' => $select_search_field],
      '#size' => 30,
      '#default_value' => $this->value,
    ];

    if (!empty($this->options['expose']['placeholder'])) {
      $form['value']['#attributes']['placeholder'] = $this->options['expose']['placeholder'];
      $form['select_field']['#attributes']['placeholder'] = $this->options['expose']['placeholder'];
    }

    $user_input = $form_state->getUserInput();

    if ($exposed && !isset($user_input[$identifier])) {
      $user_input[$identifier] = $this->value;
      $form_state->setUserInput($user_input);

    }
    $form['#attributes']['class'][] = $form_exposed_id;
    if (!isset($form['value'])) {
      $form['value'] = [
        '#type' => 'value',
        '#value' => NULL,
      ];
      $form['select_field'] = [
        '#type' => 'select',
        '#title' => $this->t('Select The Field To Search'),
        '#attributes' => ['class' => [$select_field_class]],
      ];

    }
    if (isset($this->view->getExposedInput()['select_field'])) {
      $this->options['select_field'] = $this->view->getExposedInput()['select_field'];
      $this->options['select_field'] = $this->view->getExposedInput()['select_field'];
    }
  }

  /**
   * {@inheritdoc}
   */
  public function getelements($entity, $bundle) {
    $field_of_node = \Drupal::service('entity_field.manager')->getFieldDefinitions('node', $bundle);
    $fields_node = array_keys($field_of_node);
    $field_definitions = \Drupal::service('entity_field.manager')->getFieldDefinitions('node', $bundle);
    foreach ($fields_node as $field) {
      if (isset($field_definitions[$field])) {
        $allowed_options = [];
        if ($field_definitions[$field]->getType() == "entity_reference") {
          $fieldConfig = \Drupal::entityTypeManager()->getStorage('field_config')->load($entity . '.' . $bundle . '.' . $field);
          if (!empty($fieldConfig)) {
            $target = $fieldConfig->getSettings()['target_type'];
            $target_id = @reset($fieldConfig->getSettings()['handler_settings']['target_bundles']);
            if ($target == "taxonomy_term") {
              $result = \Drupal::entityTypeManager()->getStorage($target)->loadByProperties(['vid' => $target_id]);
              $field_options = [];
              foreach ($result as $key => $value) {
                $field_options[$key] = $value->get('name')->value;
              }
            }
            else {
              $getid = \Drupal::entityQuery($target)->execute();
              $result = \Drupal::entityTypeManager()->getStorage($target);
              $result = $result->loadMultiple($getid);
              $field_options = [];
              foreach ($result as $key => $value) {
                if (!empty($value->get('title'))) {
                  $field_options[$key] = $value->get('title')->value;
                }
                else {
                  $field_options[$key] = $value->get('name')->value;
                }
              }
              if ($target == "user") {
                unset($field_options[0]);
              }
            }
          }
        }
        else {
          $allowed_options = options_allowed_values($field_definitions[$field]->getFieldStorageDefinition());
        }
        if (!empty($allowed_options) || !empty($field_options)) {
          $elements[$field]['#type'] = 'select';
          if (empty($allowed_options)) {
            $elements[$field]['#options'] = $field_options;
          }
          else {
            $elements[$field]['#options'] = $allowed_options;
          }
        }
        else {
          $elements[$field]['#type'] = 'textfield';
        }
      }
    }
    return $elements;
  }

}

Главная | Обратная связь

drupal hosting | друпал хостинг | it patrol .inc