I found out that it is impossible to add a custom query tag to a view. I needed that functionality in a project (filtering on the 'currently selected' website-wide filter). I found the solution below, which basically checks for the description of the view (searches for '(addTag:TAG_NAME)') and adds tags using hook_views_query_substitutions.
It would be nice if there is an option in the View UI interface in which you can add some tags without having to code. It doesn't necessarily have to be advanced: a simple textfield in which you can put comma-separated tags would be great.
It would make views more flexible in it's interaction with 3rd party modules and custom code.
A possibility?
/**
* Implements hook_views_query_substitutions().
* @param $view
*/
function filter_post_views_query_substitutions(&$view) {
if ($view instanceof view && property_exists($view, 'human_name')) {
//Parse the view for an addTag expression and adds the defined tags as tags
$human_name = $view->human_name;
$matches = array();
if (preg_match("/\(addTag:(.+)\)$/", $human_name, $matches)) {
$tags = explode(',', $matches[1]);
foreach($tags as $tag) {
$view->build_info['query']->addTag($tag);
}
}
}
}
Comment | File | Size | Author |
---|---|---|---|
#6 | views_query_tags.patch | 2.74 KB | fubhy |
#5 | views_query_tags.patch | 2.75 KB | fubhy |
#2 | views_query_tags.patch | 3.57 KB | fubhy |
Comments
Comment #1
dawehnerYou know this seems to be a feature for me, which will probably be misunderstood by most people
Why not using the $view->query->add_tag function.
Comment #2
fubhy CreditAttribution: fubhy commentedComment #3
fubhy CreditAttribution: fubhy commentedComment #4
dawehnerI think this might be a leftover from another approach
Can't you use the options_validate in the query plugin?
Comment #5
fubhy CreditAttribution: fubhy commentedYes, sorry... That one was a leftover from my first approach (before I placed it in "Query Settings").
Regarding #2: I always prefer element_validate because that is exactly what it is good for (for me, the form validate function is good if multiple form elements need to be checked against each other and compared with each other, element_validate is nice for single form elements). So I would leave it like it is, but if you prefer the other approach I can of course use the form validator too.
Comment #6
fubhy CreditAttribution: fubhy commentedRenamed the element validator to
views_element_validate_tags()
Comment #7
dawehnerOh actually this is already committed
Comment #9
bvanmeurs CreditAttribution: bvanmeurs commentedGreat work guys. Thanks!