Views Exposed Filter: Terms for current language only

I’ve been working on a multilingual site that has a product finder. We have 3 exposed filters that allow a user to select an Activity, IP Category, or Industry. All of these filters are Taxonomy Term filters. Some of the terms throughout those vocabularies have a specific language set, and should only show when that language is active.

The first step is to make sure the output (Views results) only shows products where the node language matches the current language. This is easy using the built in Node translation: Language = Current user’s language filter.

The next step is to make sure the select lists (exposed filters) don’t show terms that belong to other languages. Note that we do want to show terms that do not have a language specified. So, how do we do this? Using a simple hook_form_alter() we can modify the exposed filter fields. All we need to do is gather a list of all terms that either don’t have a specific language set, or that have a language that matches the current language. By ​”current​ I mean the language in which the page is being viewed.

Here’s the function I wrote to get all term ids for the current language.

Next, all we need to do is compare the options in each of our exposed filters and reject any that aren’t in the valid “terms for this language” that we just got. We simply unset the values to remove them from the available options. Note that our hook_form_alter() switch() usually looks at $form_id, but for exposed filters, that isn’t specific enough.

That’s it! Now when viewing the product finder in Japanese, users will only see Japanese products and will only be allowed to filter using Japanese or language-neutral terms.

One last thing, in order to translate the actual terms in the display and in the exposed filters, I used the dev branch of i18nviews. It worked great.

Tagged with: , , , , ,
Posted in Development

Leave a Reply

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