orchardcmsorchardcms-1.9

How to make filters in queries optional


How to make a query filter bound to a request parameter inactive if the parameter is not present?

For example: I have a query MyQuery that can be accessed through the projection MyProjection. I add a filter to that query where I say that MyDate field should be equal to {Request.QueryString:MyDate}. I want URLs like ~/MyProjection?MyDate=2016-03-08 to filter content items by the given value, but the url ~/MyProjection to just not filter by that field. But this is not what happens: a condition gets added to the query anyway and it's of the form '[minimum DateTime value] < MyDate < [maximum DateTime value]'. This is not good because it will filter out fields with NULL values. If I try to do the same with a numeric field, it's even worse because it throws exceptions when the parameter is not present.

I know I can create a new query and projection to get different options, but that seems like an overkill - also, what if I wanted to create an advanced search form, it would have to target a single projection.

Is there an "official" way to do this? Or a workaround? Or is this simply not supported in Orchard?


Solution

  • I'm not aware of a way to do this out of the box. However, you could pretty easily create your own filter with the behavior you want by implementing IFilterProvider.

    Take a look at the Orchard.Projections module. That's where you'll find many of the default query filters (including the date field filter you referenced). Your's will likely be even simpler if you only need to handle a specific case.

    For a very simple example, checkout the Orchard.Tags module (look in the projections folder). The contents of this folder will give you pretty much all the boilerplate you'll need to get started creating your own. Just plug in your own logic.