-
Notifications
You must be signed in to change notification settings - Fork 210
Reuters tutorial: step 5
- Reuters tutorial
- Step 1: Talk to Solr
- Step 2: Add a results widget
- Step 3: Add a pager widget
- Step 4: Add a tagcloud widget
- Step 5: Display the current filters
- Step 6: Add a free-text widget
- Step 7: Add an autocomplete widget
- Step 8: Add a map widget
- Step 9: Add a calendar widget
- Step 10: Extra credit
We’ve been through the steps for creating a new widget twice now, so without further ado:
Create a new widget CurrentSearchWidget.js:
(function ($) { AjaxSolr.CurrentSearchWidget = AjaxSolr.AbstractWidget.extend({ }); })(jQuery);
Add the JavaScript file:
<script type="text/javascript" src="widgets/CurrentSearchWidget.js"></script>
And add an instance of the widget to the Manager in reuters.js:
Manager.addWidget(new AjaxSolr.CurrentSearchWidget({ id: 'currentsearch', target: '#selection', }));
Now, let’s implement afterRequest to display the current filters:
start: 0, afterRequest: function () { var self = this; var links = []; var q = this.manager.store.get('q').val(); if (q != '*:*') { links.push($('<a href="#"/>').text('(x) ' + q).click(function () { self.manager.store.get('q').val('*:*'); self.doRequest(); return false; })); } var fq = this.manager.store.values('fq'); for (var i = 0, l = fq.length; i < l; i++) { links.push($('<a href="#"/>').text('(x) ' + fq[i]).click(self.removeFacet(fq[i]))); } if (links.length) { AjaxSolr.theme('list_items', this.target, links); } else { $(this.target).html('<div>Viewing all documents!</div>'); } }, removeFacet: function (facet) { var self = this; return function () { if (self.manager.store.removeByValue('fq', facet)) { self.doRequest(); } return false; }; }
The above afterRequest method collects all the fq parameter values using the ParameterStore values API method. For each parameter value, it creates a link displaying the parameter value which, when clicked, removes the parameter value (using the ParameterStore removeByValue API method) and sends a request to Solr. If any links were created, it displays the links. It performs a similar operation for the q parameter. If no links were created, it displays the text “Viewing all documents!”
(The removeFacet method is necessary to work around JavaScript closures.)
Lastly, let’s add a link to remove all current filters. Add the following snippet before if (links.length) { ...
:
if (links.length > 1) { links.unshift($('<a href="#"/>').text('remove all').click(function () { self.manager.store.get('q').val('*:*'); self.manager.store.remove('fq'); self.doRequest(); return false; })); }
If more than one link was created, it creates a link displaying the words “remove all,” which, when clicked, removes all fq parameters (using the ParameterStore remove API method) and sends a request to Solr.
Now that we have filters, let’s add a free-text widget to finish the basics.