Adding a “Filter by year” Facet for a Date Field in Apachesolr for Drupal 7

A Drupal 7 site I’m working on makes use of the Apache Solr Search module and FacetAPI. Some of the content has a date field named field_s_date. I was tasked with providing a sidebar “Filter by year” facet block to filter the content by the year value of this date field. I’m pretty sure I could have done this a few different ways, but I settled on adding the year value as a separate field to the solr index and adding an associated facet using hook_facetapi_facet_info() .

First, to add the field, I used hook_apachesolr_index_document_build() in a custom module as follows:

After saving that and clearing the Drupal caches, I re-queued all of the content for reindexing and executed Index all queued content (in the apachesolr module configuration pages).

After all of the content was reindexed I checked if the field was appearing in my solr index. It appeared in the Schema Browser (part of the solr admin) as expected.

Though it wasn’t required I decided to make this field available to theme_preprocess_search_result()  by implementing hook_apachesolr_query_alter()  as follows:

Again, I cleared the Drupal cache after running this.

Lastly, I implemented hook_facetapi_facet_info() as follows:

After saving that code, I cleared the Drupal caches one last time. The facet appeared in the Apachesolr Settings » Facets admin form. I enabled the facet, and then placed the block on the search page using context.

It worked well out-of-the box, but I changed a few of the options:

2016-02-28_17-48-07

Here’s what it looked like after some styling:

2016-02-28_17-45-29


Similar Example: Introducing a Fallback Value

Here’s another version that uses the nodes’ created date as a fallback. Notice how I changed the naming so that it doesn’t lead to the false expectation that all of the values are coming from field_pdate.

 

Tagged with: , , ,
Posted in Development

Leave a Reply

Your email address will not be published. Required fields are marked *

*