Drupal - How can I alter the value of a filter and have the output altered before the view renders?
It can be tough to figure out the exact part of the views object to modify. I usually export the view first and look at the generated code to get me started.
The snippet below is unmodified and working as expected on one of my production sites. Hopefully it's enough to get you headed in the right direction (obviously, this is in a custom module named offer_select
). If you can provide the code from the exported view, someone might be able to take a look.
//Alter the End date filter on the offer views
function offer_select_views_pre_view(&$view) {
if ($view->name == 'active_offers') {
$view->display['default']->handler->options['filters']['field_end_value']['value']['value'] = time();
}
}
--UPDATE--
For your specific view I installed the Location module and created a few nodes in NC and a few in Georgia and imported your view to test. In my custom module (named dev
) I started with this code (with devel installed):
function dev_views_pre_view(&$view) {
if ($view->name == 'north_carolina') {
dpm($view->display['default']->handler->options['filters']);
}
}
From there, I continued to add the obvious values displayed in krumo on to the array until I got here:
function dev_views_pre_view(&$view) {
if ($view->name == 'north_carolina') {
dpm($view->display['default']->handler->options['filters']['province']['value']);
}
}
Which simply printed North Carolina
in Krumo. At that point I changed from printing the value to setting it like this:
function dev_views_pre_view(&$view) {
if ($view->name == 'north_carolina') {
$view->display['default']->handler->options['filters']['province']['value'] = 'Georgia';
}
}
And voila. That did the trick.
In case someone has this thread popped up while searching for same solution on D8 (as I did):
New API allows to manipulate these parameters in a lot more clear way. See this section for references.
Small example
function dev_views_pre_view(ViewExecutable &$view, $display_id, array &$args) {
if ($display_id === 'my_unique_display_name') {
$args[0] = 'desired_value';
}
}