Friday, November 15, 2019

Using Views with Search Results – Drupal 8


STEPS

  1. Create Search Page – /admin/config/search/pages
  2. Create View /admin/structure/views
    1. Add View
    2. Make a view name
    3. Check mark create a page
      1. set path to match the search page url – ie search/node
    4. Save and Edit View
    5. add search keywords to Filter Criteria
      1. Checkbox Expose the filter to visitors and click apply
    6. Under Advanced change expose form in block to yes
    7. Click Save
  3. Go to admin/structure/block click Place Block in a region
  4. Find the exposed form click Place Block
  5. Click Save Blocks


click to Search keywords




Here comes an example snippet on how to override the page title by URL query:
/**
 * Implements hook_preprocess_HOOK().
 */
function MYTHEME/MYMODULE_preprocess_page_title(&$variables) {

  $current_path = \Drupal::request()->getpathInfo();
  if ($current_path == '/search/node') {
    if (\Drupal::request()->query->has('keys')) {

      // Get the searched string.
      $keywords = \Drupal::request()->query->get('keys');

          // I have tested locally at /search?keys=hello and
         //  \Drupal::request()->query->get('keys'); 
        //  works, as well as
       // \Drupal::request()->get('keys');
      // need to ensure the cache gets busted.
      $variables['#cache']['contexts'][] = 'url.query_args:keys';

      // Set the new title.
      $new_title = new \Drupal\Core\StringTranslation\TranslatableMarkup('Search result for Article (@keywords)', ['@keywords' => $keywords]);
      $variables['title'] = $new_title;
    }
  }
}



No comments:

Post a Comment

If you have any problem please let me know.