Sunday, October 4, 2020

Exposed Filter content by year with Views on Drupal 8

 

Step 1 : Create a content type and add the date field. and My content type name is Article.

Step 2: Create a View page and add any Expose filter like.
           goto + FILTER CRITERIA

 NOTE:- Filter identifier name is most important it show on your URL

Step 3 : Goto Advance + CONTEXTUAL FILTERS 
       click + add button 
       add the field date and you want for setting the url

And we will look for our Date field (field_date) of our article content type in an aggregated form per year (Date in the form YYYY).

After validating our choice, we get the control panel of our contextual filter.


VIEW Setting is Done Now.

Step 1: Custom Static expose filter 
Module_name.module



Setp 2: Though content type filter.



full Code:-

/**
 * Implements hook_form_FORM_ID_alter().
 */
function themable_forms_form_views_exposed_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  if (isset($form['#id']) && $form['#id'] == 'views-exposed-form-news-media-page-1') {
    if (empty($view->total_rows)) {
      $form['studymyhub']['#access'] = FALSE;
    }
     $options = &drupal_static(__FUNCTION__);
        if (is_null($options)) {
        $cid = 'themable_forms:article:year';
        $data = \Drupal::cache()->get($cid);
       if (!$data) {
        $options = [];
        $options['all'] = new TranslatableMarkup('- All -');
        $query = \Drupal::entityQuery('node');
        $query->condition('type', 'article')
          ->condition('status', 1)
          ->sort('field_date', 'ASC');
        $result = $query->execute();
        if ($result) {
          $nodes = \Drupal\node\Entity\Node::loadMultiple($result);
          foreach ($nodes as $node) {
            $date = $node->field_date->value;
            if ($date) {
              $date = new DrupalDateTime($date , 'UTC' );
              $year = $date->format('Y');
              $month = $date->format('F');
              if (!isset($options[$year])) {
                $options[$year] = $year;
                $options2[$month] = $month;
              }
            }
          }
        }
      }
      else {
        $options = $data->data;
      }
    }
    $form['year'] = [
      // '#title' => new TranslatableMarkup('By year'),
      '#prefix' => '<div class="select-style">',
      '#type' => 'select',
      '#options' => $options,
      '#size' => NULL,
      '#default_value' => 'Year',
      '#cache'=> [
                'max-age' => 0,
              ],
      '#suffix' => '</div>',
      ];
       $months = [
        'all' => t('- All -'),
        'January' => 'January',
        'February' => 'February',
        'March' => 'March',
        'April' => 'April',
        'May' => 'May',
        'June' => 'June',
        'July ' => 'July',
        'August' => 'August',
        'September ' => 'September',
        'October' => 'October',
        'November' => 'November',
        'December ' => 'December',
      ];

       $form['month'] = [
      // '#title' => new TranslatableMarkup('By year'),
      '#prefix' => '<div class="select-style">',
      '#type' => 'select',
      '#options' => $months,
      '#size' => NULL,
      '#default_value' => 'Year',
      '#cache'=> [
                'max-age' => 1,
              ],
      '#suffix' => '</div>',
      ];
  }

}

Output :-


Alter the expose filter text filed to dropdown field and change the placeholder..

Step 1:- We have created the content type and also created some fields.

Step 2:- Now we create a view


       Click "Add new view" or go to the path "admin/structure/views/add".
Step 3:- View have added the new view and also added the expose filter for taxonomy filed.




Step 4:- Now I am going to add the expose filter in title filed auto completed and convert to dropdown.


1. We have added the Autocompleted field in drupal expose filter.

Install the view autocompleted module 


OutPUT:-

1. We have converted the Autocompleted text field to dropdown.

Code:-
if ($form['#id'] == 'views-exposed-form-id-block-1') {
  if (isset($form['field_supplier_value'])) {
    $options = [];
    $options = ["" => new TranslatableMarkup('Supplier')];
    $current_language = \Drupal::languageManager()->getCurrentLanguage();
    $langcode = $current_language->getId();
    $type = 'supplier_trade';
    $query = \Drupal::entityQuery('node');
    $results = $query->condition('type', $type)
      ->condition('status', 1)
      ->condition('langcode', $langcode)
      ->execute();
    if ($results) {
      $node_storage = Drupal::service('entity_type.manager')
        ->getStorage('node');
      $entity_repository = Drupal::service('entity.repository');
      foreach ($results as $result) {
        $node = $node_storage->load($result); 
        $node_translation = $entity_repository->getTranslationFromContext($node, $langcode);
        $title = $node_translation->get('field_subtitle')->getValue();
        if ($title) {
          $title_value = $title[0]['value'];
          if (!isset($options[$title_value])) {
            $options[$title_value] = new TranslatableMarkup($title_value);
          }
        }
      }
    }
    $form['field_supplier_value'] = [
      '#type' => 'select',
      '#options' => $options,
      '#size' => NULL,
      '#default_value' => '',
    ];
  }
}
OUTPUT:- 


How to Hide the id of expose autocompleted filed for example..
Before

After code:-

Simple jQuery:-

jQuery(document).ready(function(){
    jQuery("body").find('.form-autocomplete').on('autocompleteclose', function(event, node) {
        var val = jQuery(this).val();
        var match = val.match(/\((.*?)\)$/);
        if (match) {
          jQuery(this).data('real-value', val);
          jQuery(this).val(val.replace(' ' + match[0], ''));
        }
      });
});

Same but  using Drupal behaviors:-



'use strict';
(function($, Drupal) {
    Drupal.behaviors.my_module = {
        attach: function(context, settings) {
            // Remove TID's onload call to function.
            Drupal.my_module.remove_tid();
        }
    }
})(jQuery, Drupal);

Drupal.my_module = {
    remove_tid: function () {
      let field_autocomplete = $('body').find('.form-autocomplete');
      field_autocomplete.on('autocompleteclose', function(event, node) {
        var val = $(this).val();
        var match = val.match(/\((.*?)\)$/);
        if (match) {
          $(this).data('real-value', val);
          $(this).val(val.replace(' ' + match[0], ''));
        }
      });
    },
};

No comments:

Post a Comment

If you have any problem please let me know.