how to alter drupal-6 view-2 query - drupal

I'm trying to update view query using drupal hook_views_pre_execute().
It's updating the query properly but even my query returning only couple of record, in view page it's showing pagination at the bottom but i've set the page limit 10. Can any one advise me how to resolve this issue.
function mymodule_views_pre_execute(&$view)
{
switch($view->name)
{
case 'test_merchandise':
$view->build_info['query'] = "MY QUERY";
drupal_set_message($view->build_info['query']);
break;
}
}

if you want to alter views query then use this method
function modulename_views_query_alter(&$view, &$query){
if ( $view->name == 'test_merchandise' ) {
//here you will get the whole $query object and alter only the place you want change
$query->orderby[0] = "substring(node_data_field_date_field_date_value,1,4) DESC";
echo "<pre>";print_r($query);echo "</pre>";
}
}

Related

is it possible to set a field in drupal to some value by using nodeapi

So I have this field named field_movie_cast_count this is a field of a content named movie so what I want is that whenever the movie is updated (like I add another cast member) the field_movie_cast_count field would be updated too. I have successfully done it using this code:
function count_cast_nodeapi(&$node, $op) {
$id = $node->nid;
if($op == 'update' && $node->type == 'movie') {
$count=count($node->field_movie_cast);
$q = db_query("update content_type_movie set field_movie_cast_count_value = '$count' WHERE nid = '$id'");
}
}
Now, my boss told me that I should not use query. So, how do I achieve this by not using a database query?
is it not possible to just set field_movie_cast_count[]['value']=$count? i tried this code it doesnt work. lol
OR SHOULD I REPHRASE THE QUESTION is there any other way of displaying the count cast? aside from my way? cause maybe i did not understand my boss right.
hook_nodeapi() has a presave operation which is invoked just before the node (and field data) is committed to the database. The definition of the operation is:
The node passed validation and is about to be saved. Modules may use this to make changes to the node before it is saved to the database.
You can use it to update a field value, without resorting to hitting the database manually (which will be overwritten anyway) like so:
function MYMODULE_nodeapi(&$node, $op) {
if ($op == 'presave' && $node->type == 'movie') {
$node->field_movie_cast_count[0]['value'] = count($node->field_movie_cast);
}
}

How to use nodeapi in drupal?

guys i have this node type -> movie. this movie has casts in it. so now i was instructed to display the number of cast in a movie. how do i achieve this by using nodeapi? please someone guide mo through this. im very new to drupal coding here. here's what ive made so far:
function count_cast_nodeapi(&$node, $op) {
switch ($op) {
case 'update index':
if ($node->type == 'movie') {
$text = '';
$q = db_query('SELECT count(field_movie_cast_nid) FROM content_field_movie_cast ' .
'WHERE nid = %d', $node->nid);
if ($r = db_fetch_object($q)) {
$text = $r->count;
}
drupal_set_message($text);
}
}
}
but i have no idea where to put this code. where to save it. do i make a module of this? and is this code even correct?
also i have only copied this code. so i dont know what that 'update index' means. and who or what function will set that parameter $op
I can suggest you follow solution:
Create new integer CCK field for content type "movie" which will store the number of casts. Name it movie_cast_number.
This field will be updating in hook_nodeapi (similar to your example). For that you need to create custom module "count_cast". Place it to sites/all/modules directory.
In hook_nodeapi need to use $op "insert" and "update". $op generating by module node and means which operation is performed with node. Insert means new node has been created and update - existing node has been updated.
If you need custom output for this content type then you need to create node-movie.tpl.php in your theme directory.
Code which update the number of casts can looks follow way:
function count_cast_nodeapi(&$node, $op) {
switch ($op) {
case 'update':
case 'insert':
if ($node->type == 'movie') {
$result = db_result(db_query('
SELECT count(field_movie_cast_nid) cnt
FROM {content_field_movie_cast}
WHERE nid = %d
', $node->nid));
$node->field_movie_cast_number[0]['value'] = $result->cnt;
}
}
}

WordPress: Having trouble in pagination for plugin settings page

Developing a plugin in WordPress and getting well but stuck on pagination for the plugin page. Here is my code downloaded from internet ( got reference from here )
$items = $wpdb->get_var($wpdb->prepare("SELECT COUNT(*) FROM $wpdb->review_media GROUP BY post_id")); // number of total rows in the database
// tested and got results as commented
print_r($items); // say this is outputs value 2
echo $rm_options['list_per_page']; // this is my option set with value 1
if($items > 0) {
$p = new pagination;
$p->items($items);
$p->limit(empty($rm_options['list_per_page']) ? 20 : $rm_options['list_per_page']); // Limit entries per page
$p->target("admin.php?page=moderate.php");
$p->currentPage($_GET[$p->paging]); // Gets and validates the current page
$p->calculate(); // Calculates what to show
$p->parameterName('paging');
$p->adjacents(1); //No. of page away from the current page
if(!isset($_GET['paging'])) {
$p->page = 1;
} else {
$p->page = $_GET['paging'];
}
//Query for limit paging
$limit = "LIMIT " . ($p->page - 1) * $p->limit . ", " . $p->limit;
} else {
echo "No Record Found";
}
When I don't group my query by post_id it is working fine but as soon as I grouped its behaving weird. It is creating a pagination links and getting blank page. I think the reason is grouping the row. But don't know how to solve this.
Here is my table screenshot
Thanks a lot for your help...
If you use WordPress WP_List_Table class, it will take care of the pagination and provide a default table experience for the user.
This tutorial covers it all, the pagination part is:
function prepare_items() {
[...]
$per_page = 5;
$current_page = $this->get_pagenum();
$total_items = count($this->example_data);
// only necessary because we have sample data
$this->found_data = array_slice($this->example_data,(($current_page-1)*$per_page),$per_page);
$this->set_pagination_args( array(
'total_items' => $total_items, //WE have to calculate the total number of items
'per_page' => $per_page //WE have to determine how many items to show on a page
) );
$this->items = $this->found_data;
}
And here's the full plugin shown in the tutorial. And in this other plugin you can see WP_List_Table in action using database data.

How do I filter results in APYDataGridBundle in Symfony2?

I have been looking for hours for a way of setting a condition on the list of items that an APYDataGridBundle grid should return but could not find an answer.
Is there a way to set a DQL Query and pass it to the grid to display the exact query results I want to fetch?
This is the code:
public function filteredlistAction(){
// Create simple grid based on the entity
$source = new Entity('ACMEBundle:MyEntity');
// Get a grid instance
$grid = $this->get('grid');
// Attach the source to the grid
$grid->setSource($source);
...
...
**$grid->getColumns()->getColumnById('myentity_filter_column')->setData('the exact value I tried to match');**
// Manage the grid redirection, exports and the response of the controller
return $grid->getGridResponse('ACMEBundle:MyEntity:index_filteredlist.html.twig');
}
You can add a callback (closure or callable) to run before QueryBuilder execution - its done like this :
$source->manipulateQuery(
function ($query)
{
$query->resetDQLPart('orderBy');
}
);
$grid->setSource($source);
$query is an instance of QueryBuilder so you can change whatever you need to
Example taken from docs here
A more "complicated" query.
$estaActivo = 'ACTIVO';
$tableAlias = $source->getTableAlias();
$source->manipulateQuery(
function ($query) use ($tableAlias, $estaActivo)
{
$query->andWhere($tableAlias . '.estado = :estaActivo')
->andWhere($tableAlias . '.tipoUsuario IN (:rol)')
->setParameter('estaActivo', $estaActivo)
->setParameter('rol', array('VENDEDOR','SUPERVISOR'), \Doctrine\DBAL\Connection::PARAM_STR_ARRAY);
}
);
Cheers!

Custom logic for exposed filters in a Drupal view

I'm working on a Drupal site and would love some advice on this. Currently, a user enters his level for a number of different skills. This is stored in a CCK integer field and exposed to the user as a drop-down widget containing the key/value pairs 1|Beginner, 2|Intermediate, 3|Advanced.
In a view, I expose the allowed values for each skill, which are presented to the user as checkboxes (using the Better Exposed Filters module) and then listed in a sortable table. In practice, users generally search for people who have "at least knowledge level X in skill Y". Is there a module or straightforward way to display the allowed values as a drop-down and use a "greater than" operator in the query instead of a "one of"?
Any sample code or advice on how to dynamically change the filter logic or the WHERE clause of the query would be very appreciated.
You want to use hook_views_query_alter(), while I haven't specifically altered the WHERE clause, I have altered the SORTBY clause and the idea behind both should be relatively similar.
Here's a quick piece of code:
function my_module_views_query_alter(&$view, &$query) {
switch ($view->name) {
case 'view1':
$args = _my_module_get_querystring();
switch ($args['condition']) {
case 'condition1':
$query->where[0]['args'][0] = 1;
break;
case 'condition2':
$query->where[0]['args'][0] = 2;
break;
}
break;
}
}
/**
* Returns querystring as an array.
*/
function _my_module_get_querystring() {
$string = drupal_query_string_encode($_REQUEST, array_merge(array('q'), array_keys($_COOKIE)));
$args = explode('&', $string);
foreach ($args as $id => $string) {
unset($args[$id]);
$string = explode('=', $string);
$args[$string[0]] = str_replace(' ', '-', $string[1]);
}
return $args;
}
This particular piece would allow you to alter the WHERE clause using a querystring (?condition=condition1), but you could alter it to get the arguments however you wish.
Hope this helps.
Using Decipher's sample and spending a few hours reading up and playing around, I've gotten a basic module that works perfectly for my needs. Thanks again!
Here's my code if anyone else comes across a similar need:
<?php
// $Id$
/**
* #file
* Module for modifying the views query to change an EQUALS
* to a GREATER THAN for specific filters.
*/
function views_greater_than_views_query_alter(&$view, &$query) {
//only implement for views that have Search in their name
if(strstr($view->name, "search")) {
$whereclauses = $query->where[0]['clauses'];
foreach ($whereclauses as $i=>$currentrow) {
$currentrow = str_replace('= %d', '>= %d', $currentrow);
$query->where[0]['clauses'][$i] = $currentrow;
}
unset($whereclauses);
}
}

Resources