Drupal - Views. Setting a filter programmatically - drupal

I hope this is not a stupid question I have been searching for most of the day!
I have a Content Type (Documents) which simply contains a title, file and a category. The category value is required and is 'powered' by Taxonomy.
I now wish to create a view which will display these documents grouped and titled by the taxonomy term.
Using my limited Drupal knowledge I intent to iterate through the relevant terms IDs (using taxonomy_get_tree($vid)) and then render each view accordingly.
To do this I have been hoping to use this snippet.
view = views_get_view('documents');
$view->set_display($display_id);
$filter = $view->get_item($display_id, 'filter', 'field_dl_category');
$filter['value']['value'] = $filter_value;
$view->set_item($display_id, 'filter', 'field_dl_category', $filter);
$viewsoutput = $view->render();
But this is not working; when I query the value of the $filter ($view->get_item($display_id, 'filter', 'field_dl_category')) I get null returned.
Might this be that my filter name is not the same as the CCK field name?
I am using Drupal 7.
Any help much appreciated, I am running out of ideas (and time).

I finally managed to get this working but I took a slightly different approach.
I changed my view and added the relevant contextual filter and then used this function views_embed_view to get at my required results.
If this helps! this is my solution:
$display_id = 'default';
$vid = 7;
$terms = taxonomy_get_tree($vid);
foreach($terms As $term){
$content = views_embed_view('documents', $display_id, $term->tid);
//now we see if any content has been provided
if(trim($content) != ''){
print "<h3>" . $term->name . "</h3>";
print $content;
}
}
In my case the trim($content) returns '' with no data as the view template has been edited, this might not be the case for all.
I am a very new Drupal developer so I'm sure there are much better ways of doing this, if so please do post.

I am going to go ahead and assume that you want to show, using Views, a list of document nodes grouped by the category that they have been tagged with.
There are two (of maybe more) ways by which you can do this in Views 3:
(a) Choose a display style that allows you to select a Grouping field. (You could try the table style that ships with Views by default). Suppose you have properly related the node table to the taxonomy_term_data table through a Views relationship, you could choose taxonomy_term_data.name as the grouping field.
Note that this grouping is done before the view is just rendered. So, your query would just have to select a flat list of (content, tag) pairs.
(b) You could also make use of the Attachment display type to achieve something similar. Show the used categories first in a list view clicking on which will show a page (attachment) with all documents tagged in that chosen category.
To understand how to do (a) or (b), turn on the advanced_help module (which is not a Views requisite but is recommended) first.
For (a), read the section on Grouping in styles i.e. views/help/style-grouping.html and
For (b), read the section on Attachment display i.e. views/help/display-attachment.html
A couple of things about your approach:
(a) It will show all terms from that vocabulary irrespective of whether or not they were used to tag at least one document.
(b) views_embed_view() will return NULL even if the currently viewing user does not have access to the view. So, ensure that you catch that case.

Here's an alternative:
$view = views_get_view('view_machine_name');
$view->init_display('default');
$view->display_handler->display->display_options['filters']['your_filter_name']['default_value'] = 'your_value';
$view->is_cacheable = FALSE;
$view->execute();
print $view->render();
I know you can probably set this using some convoluted method and obviously that would be better. But if you just want a quick and dirty straight access without messing around this will get you there.

Related

Drupal Views Entity Reference Context

I'm running Drupal 7 with Entity Reference and Organic Groups. I have two content types, one of which is a group and the other is group content. I have an Entity Reference field (Select List) that references group content associated with the group.
I want to create a View that ONLY shows the value of the field that is selected from this Entity Reference field in the group content type.
For instance:
Team: Red Sox
Location: Fenway
Location is a content type (group content) and Team is the group. There are many teams and many locations but when I'm looking at the group page I want a View that ONLY shows a single location (the one SELECTED in the group content type).
After much research I realized that Views and context can't handle this on their own. I ended up using View PHP to construct a filter that effectively filtered out all OTHER results than the one that I wanted:
$node = menu_get_object();
$item = field_get_items('node', $node, 'field_name');
$loc = $item[0]['target_id'];
$refnode = node_load($loc);
$primary = $refnode->title;
if ($primary != $row->title) {
return TRUE;
}
You're welcome for this one :) If anybody has any better suggestions on how to code this feel free to comment or post alternate solutions.

how to change a drupal views output

I need to create a block with eg the latest comments on the site.
when using views, concegui select the data I wanted, but the problem is that I need to edit the output of view (specify the html). I tried to make a tpl, but the fields when they get to this, are already formatted ([#markup]). also tried to make a block programmatically by accessing the fields of view, via $comments = views_get_view('last_opinions');, but so the fields do not bring content, but for example, ids (for referrals), or integers (in the case of dates), ....
basically, how to change views output?
views->your view->advance(third panel)-> Theme: Information -> click Information ->choose tpl as per your requirement and find $row which actually prints your output

Drupal 7 - Using Views Relationships With Filters

In Views, I have an exposed filter that looks at the UID (User ID / Author), but is there a way to limit this to "ONLY" the users who have posted in this content type?
I tried adding a "Content: Author" relationship and hit Apply. I'm not exactly sure why, but it wasn't until this point that I could go back into the relationships and see MORE options, like: "User: Content authored" (which must then be dependent on the first relationship?) so I selected that one too and set it up like so:
Now I was able to go to the exposed filter and select the relationship:
But this didn't work-- the exposed filter continues to show all the registered users.
I also tried putting in a User Reference field (to this content type) and attaching that to a relationship, but it didn't allow anything to show and gave this SQL warning:
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'field_data_field_hidden_name.uid' in 'on clause'
How can I limit this author exposed filter to "ONLY" the users who have posted in this content type?
There are a few drupal modules that may help you out. Such as Corresponding node references
However, if you are good with php code, you can create the logic to query the database and return the desired results (which would be the columns of the table). Create a contextual filter, then select a field (any field should work, but best select something in either content type). Then edit it, WHEN THE FILTER VALUE IS NOT AVAILABLE -> Provide default value -> PHP Code
$nid = arg(1);// current node id
$query = "SELECT <desired_field_column_name> FROM {<field_data_table_name>} c
WHERE c.<column_that_is_same_as_nid> = :nid";
$result = db_query($query, array(':nid' =>$nid));
$id = array();
while ($row = $result->fetch())
{
array_push($id, $row->field_curator_target_id);//put each node id that's referenced in array
}
$separated = implode("+", $id); // separate them by + for AND , for OR
return $separated; //eg.32 + 30 would represent nodes that you want.
In Linked theme there is answer about Views Selective Filters (aka "Views Selective Exposed Filters", aka views_filters_selective, aka views_selective_filters).
This module adds filters that have suffix "(selective)" in their names – add one you need instead of filter w/o the suffix.

Apachesolr query - filter by text in fields

I'm constructing an apachesolr query in my Drupal module programmatically and have had success with some aspects, but am still struggling with others.
So far, I have been able to construct a query that can search for specific text and limit the results based on terms to be filtered by with the following code:
$subquery_region->addFilter('tid', $term->tid);
$query->addFilterSubQuery($subquery_region, 'OR', 'AND');
What I'd like to achieve next is to be able to narrow the search further by adding a filter for finding certain text within a specific field in the node. Has anyone been able to do this.
I've been researching online and have tried lots of different ways such as adding the filter directly to the main search query
$query->addParam('fl', 'ss_my_field');
$query->addFilter("ss_my_field", "field_substring_to_search_for");
As well as breaking that out into a subquery to add to the main search query
$subquery_test = apachesolr_drupal_query("Test");
$subquery_test->addParam('fl', 'ss_my_field');
$subquery_test->addFilter("ss_my_field", "field_substring_to_search_for");
$query->addFilterSubQuery($subquery_test, 'OR', 'AND');
But none of these are working. They are returning an empty set, even though I know the substring exists in the field I'm adding as a filter and it has been indexed. I have verified through the apachesorl views module that the search index has been populated with that field and can see the substring exists.
Is there anything wrong with my syntax or the way I'm building the query?
If you know how to add filters for searching for text within certain fields, please share! It may not even be done with the addFilter function, but that's all I have been trying so far.
Thanks!
First you have to create an index for that specific field.
function hook_apachesolr_update_index(&$document, $node) {
$document->ss_your_field_name = $node->your_field_name;
}
where ss_* is the pattern.
ss_* -> String
is_* -> Integer
im_* -> Integer, Multivalued
After that you have to
1. delete the index - admin/settings/apachesolr/index
2. re-index the content
3. run the cron
4. check the filter that you created - admin/reports/apachesolr/index
Then, you can add filters
$query->addFilter("ss_your_field_name", "value");
Hope this helps you.
function hook_apachesolr_modify_query(&$query, &$params, $caller){
$subquery = apachesolr_drupal_query();
$subquery->add_filter("ss_my_field", "field_substring_to_search_for");
$query->add_subquery($subquery, "AND");
}

How to display the total amount of posts?

What's the best way to display in a block the total amount of posts and comments of my entire drupal website?
thanks
The quick and dirty way:
Ensure that you have PHP filter installed and available to you. Create a block with the php code
<?php
$ncount = db_query("SELECT COUNT(nid) FROM {node} WHERE status=%d", 1);
$ccount = db_query("SELECT COUNT(cid) FROM {comments} WHERE status=%d", 1);
print "Nodes: ".$ncount;
print "Comments: ".$ccount;
?>
One option is to use a View with the block display type. Views Calc can do the summing for you (http://drupal.org/project/views_calc).
Honestly, I think you will find it easier and possibly more performant to create a Statistics content type with CCK integer fields to store the initial values for the amount of each piece of information you need. Then configure the Rules module to increment/decrement the fields when you add or remove content/comments.
A third option I have not personally explored is the Statistics Pro module (http://drupal.org/project/statspro), which says it is Views-compatible.
Use Views GroupBy module ( http://drupal.org/project/views_groupby ). You can specify the filters (e.g. you want to count nodes of particular type only) and so on. It will count the nodes for you.
If your view type is comment then in a similar count can be done on comments.

Resources