Hello All,

I want to add my custom field in the search query and based on that field it should filter the results. But I don't have much idea about how do I add my custom field in the query string.
I tried with couple of hooks like hook_search_preprocess , hook_query_alter, hook_search_execute but nothing worked.
Any other hooks to implement the search query?

Any help would be much appreciated!!
Thanks!

Comments

NishaMetri created an issue. See original summary.

kiwad’s picture

From code in tests in core module search, here is an exemple that could help you for this

use Drupal\Core\Database\Query\AlterableInterface;

/**
 * Implements hook_query_TAG_alter().
 *
 * Tags search_$type with $type node_search.
 */
function search_query_alter_query_search_node_search_alter(AlterableInterface $query) {
  // For testing purposes, restrict the query to node type 'article' only.
  $query->condition('n.type', 'article');
}

sumit-k’s picture

I think need to index first custom field. For indexing can use Search api module.

function mymodule_search_api_query_alter(\Drupal\search_api\Query\QueryInterface &$query) {
  // Ensure field_myfield is being indexed
  $fields = $query->getIndex()->getFields();
  if (isset($fields['field_myfield'])) {
    $query->addCondition('field_myfield', 'myvalue', '<>');
  }
}

Reference - https://drupal.stackexchange.com/questions/78464/how-to-alter-search-que...
https://stackoverflow.com/questions/41855229/drupal-8-altering-search-ap...

Version: 8.9.x-dev » 9.2.x-dev

Drupal 8 is end-of-life as of November 17, 2021. There will not be further changes made to Drupal 8. Bugfixes are now made to the 9.3.x and higher branches only. For more information see the Drupal core minor version schedule and the Allowed changes during the Drupal core release cycle.

Version: 9.2.x-dev » 9.3.x-dev
cilefen’s picture

Status: Active » Closed (outdated)