change the number of results per page in drupal views - drupal

I need to have an option on my search page which will allow the users to select the number of results that they want to display in the view i.e 25 results, 50 , 100 results per page. My theme_pager code is
function theme_pager($tags = array(), $limit = 10, $element = 0, $parameters = array(), $quantity = 9) {
global $pager_page_array, $pager_total;
$tags = array("", "< prev", "", "next >", "");
// Calculate various markers within this pager piece:
// Middle is used to "center" pages around the current page.
$ pager_middle = ceil($quantity / 2);
// current is the page we are currently paged to
$pager_current = $pager_page_array[$element] + 1;
// first is the first page listed by this pager piece (re quantity)
$pager_first = $pager_current - $pager_middle + 1;
// last is the last page listed by this pager piece (re quantity)
$pager_last = $pager_current + $quantity - $pager_middle;
// max is the maximum page number
$pager_max = $pager_total[$element];
// End of marker calculations.
// Prepare for generation loop.
$i = $pager_first;
if ($pager_last > $pager_max) {
// Adjust "center" if at end of query.
$i = $i + ($pager_max - $pager_last);
$pager_last = $pager_max;
}
if ($i <= 0) {
// Adjust "center" if at start of query.
$pager_last = $pager_last + (1 - $i);
$i = 1;
}
// End of generation loop preparation.
$view = views_get_current_view();
// ensure view exists
if (!$view) return;
// set object property to return total rows
$view->get_total_rows = true;
// set display_id
$view->set_display($display_id);
// execute view
$view->execute();
// acquire data from views object and $_REQUEST
$itemsPerPage = $view->pager['items_per_page'];
$currentPage = $_REQUEST['page']+1;
$total = $view->total_rows;
// start calculation
$start = ($itemsPerPage * $currentPage) - ($itemsPerPage-1);
$end = $itemsPerPage * $currentPage;
if ($end>$total) $end = $total;
// return html
$x = "<b>Displaying $start - $end of $total</b>";
$li_previous = theme('pager_previous', (isset($tags[1]) ? $tags[1] : t('‹ previous')), $limit, $element, 1, $parameters);
$li_next = theme('pager_next', (isset($tags[3]) ? $tags[3] : t('next ›')), $limit, $element, 1, $parameters);
if ($pager_total[$element] > 1) {
$items[] = array(
'class' => 'pager',
'data' => $x,
);
if ($li_previous) {
$items[] = array(
'class' => 'pager-previous',
'data' => $li_previous,
);
}
// When there is more than one page, create the pager list.
if ($i != $pager_max) {
// Now generate the actual pager piece.
for (; $i <= $pager_last && $i <= $pager_max; $i++) {
if ($i < $pager_current) {
if ($pager_first > 1 && $i == $pager_first) {
$output = '...'.$i;
$stopPreEllipsis = true;
} else {
$output = $i;
}
$items[] = array(
'class' => 'pager-item',
'data' => theme('pager_previous', $output, $limit, $element, ($pager_current - $i), $parameters),
);
}
if ($i == $pager_current) {
$items[] = array(
'class' => 'pager-current',
'data' => $i,
);
}
if ($i > $pager_current) {
if ($pager_last < $pager_max && $i == $pager_last) {
$output = $i.'...';
} else {
$output = $i;
}
$items[] = array(
'class' => 'pager-item',
'data' => theme('pager_next', $output, $limit, $element, ($i - $pager_current), $parameters),
);
}
}
}
// End generation.
if ($li_next) {
$items[] = array(
'class' => 'pager-next',
'data' => $li_next,
);
}
return theme('item_list', $items, NULL, 'ul', array('class' => 'pager'));
}
}

As you might have noticed, theme_pager does not call the database, it merely presents the items from the database. It does not even render the items in the list that is paged.
You will therefore need to override the amount before it gets passed into pager_query(). With views, I have no idea. In a custom module it would be really simple: read out an url parameter or POSTed variable and pass that along as second parameter into pager_query(). I suspect views has some hook to override the amount-per-page in runtime, just before it gets passed to the query-builder. But due to the poor documentation of views, it is not easily found.

Related

Count wordpress post hits

I want to count and show WordPress posts in admin panel.I don't want to show it on the website but I want to be able to sort posts in admin panel according to their hits.
I used this link to do so. Every thing is good but it only doesn't sort the posts. In the source website it has told to put some code in template.js. But I don't know where is this file.
functions.php
/*
Function: getPostViews (custom)
Gets the Post Views count
Returns:
$count.' Views'
*/
function getPostViews($postID){
$count_key = 'post_views_count';
$count = get_post_meta($postID, $count_key, true);
if($count==''){
delete_post_meta($postID, $count_key);
add_post_meta($postID, $count_key, '0');
return "0 View";
}
return $count.' Views';
}
/*
Function: setPostViews (custom)
Sets the Post Views count
*/
function setPostViews($postID) {
$count_key = 'post_views_count';
$count = get_post_meta($postID, $count_key, true);
if($count==''){
$count = 0;
delete_post_meta($postID, $count_key);
add_post_meta($postID, $count_key, '0');
}else{
$count++;
update_post_meta($postID, $count_key, $count);
}
}
template.js
// get querystring as an array split on "&"
var querystring = location.search.replace( '?', '' ).split( '&' );
// declare object
var queryObj = {};
// loop through each name-value pair and populate object
for ( var i=0; i<querystring.length; i++ ) {
// get name and value
var name = querystring[i].split('=')[0];
var value = querystring[i].split('=')[1];
// populate object
queryObj[name] = value;
}
// Check query string for sort filter method
if(queryObj[ "filter" ] === "popular"){
$('#newest').removeClass('active');
$('#popular').addClass('active');
} else if(queryObj[ "filter" ] === "newest"){
$('#popular').removeClass('active');
$('#newest').addClass('active');
}
Wordpress Post Sorting
<?
// Place this code into your archive.php template file
$filter = $_GET['filter'];
// Preserve existing query parameters
global $wp_query;
// Check query string parameter "filter" (options: 'popular' and 'newest')
if((isset($filter)) && $filter == 'popular'){
$args = array_merge( $wp_query->query, array('order' => 'desc', 'orderby' => 'meta_value_num', 'meta_key' => 'post_views_count') );
query_posts( $args );
}else if((isset($filter)) && $filter == 'newest'){
$args = array_merge( $wp_query->query, array('order' => 'desc') );
query_posts( $args );
}
?>

wp_insert_post called via cron duplicates posts instead of updating them

I'm currently stuck on a problem I can't figure out on a wordpress side project. Here's the thing :
I made a plugin that queries an API, and processes its data to insert posts.
The problem I face is that, when the main function is triggered manually (i.e. via a route or cron manually launched) posts are correctly created or updated, but when the cron executed automatically, posts are always duplicated. I may have narrowed the problem down to capabilities (I check if posts exists by querying the cpt for a unique meta-field), and when the cron executes on its own, it find no ids.
Here are code samples :
public function insertPosts() {
set_current_user(1); // <- here I tried setting the user as admin for the script, but it didn't work
// First, get all prestations from the api
$prestations = $this->api->getPrestations();
/*
* Then :
* we remove sessions of formations initiales, which are useless (gamme id 10 = formations initiales)
* I could have "only" taken the ids I need, but unsetting useless array entries allows for a lighter dataset
*/
$prestations_info = [];
foreach ($prestations as $key => $prestation) {
if ($prestation['gamme']['id'] == 10) {
// Removes the useless $prestation and breaks out of the loop so its ID's not stored
unset($prestations[$key]);
continue;
}
$prestations_info[] = [
'fid' => $prestation['id'],
'cat_name' => $prestation['gamme']['name'],
'cat_id' => $prestation['gamme']['id']
];
}
/*
* Then :
* Parse the array to process every id individually and query the api for core informations for the singles
*/
foreach ($prestations_info as $presta) {
// Meta query to check if a post with the formation's id already exists
$args = [
'post_type' => 'formations',
'posts_per_page' => -1,
'meta_query' => [
[
'key' => 'api_fid',
'value' => $presta['fid'],
'compare' => '='
]
]
];
$posts = new WP_Query($args);
if ($posts->have_posts()) {
while ($posts->have_posts()) {
// If a post with that formation id already exists, we retrieve its ID:
// this way, we can update existing post and avoid duplicates
$posts->the_post();
$post_id = get_the_ID();
}
}
$body = $this->api->getSessionsByPrestationsId($presta['fid']);
$post_array = [];
$locations = [];
$nb_places = [];
foreach ($body as $key => $item) {
if (!empty($item['seances'])) {
$duration = BOUtilities::getFormationDuration($item['seances']);
$dates = BOUtilities::getDatesPerSessions($item['seances']);
}
if ($dates) {
$session_date = [];
if (is_array($dates)) {
foreach ($dates as $i => $date) {
$session_date[$i] = [
'dates' => $date['start'] .' - ' . $date['end'],
];
}
} else {
$session_date[] = [
'dates' => $dates,
];
}
}
if (!empty($item['location'])) {
$locations[] = strtolower($item['location']);
$session[] = [
'sessions_location' => $item['location'],
'sessions_dates' => $session_date,
];
}
if (!empty($item['nbplace']) && $item['nbplace'] != 0) {
if (!in_array($item['nbplace'], $nb_places)) {
$nb_places[] = $item['nbplace'];
}
}
if ($item['price'] != 0) {
$prices[] = $item['price'];
}
}
$formatted_cost = BOUtilities::setPrices($prices);
$effectifs = BOUtilities::setEffectifs($nb_places);
if ($post_id) {
$post_array = [
'ID' => $post_id,
'post_type' => 'formations',
'post_title' => $item['prestation']['name'],
'meta_input' => [
'api_fid' => $presta['fid'],
'aside_cost' => $formatted_cost,
'aside_duration' => ($duration > 1 ? $duration . ' jours' : $duration . ' jour'),
'aside_effectifs' => $effectifs,
]
];
$inserted_post = wp_update_post($post_array);
}
else {
$post_array = [
'post_type' => 'formations',
'post_title' => $item['prestation']['name'],
'meta_input' => [
'api_fid' => $presta['fid'],
'aside_cost' => $formatted_cost,
'aside_duration' => ($duration > 1 ? $duration . ' jours' : $duration . ' jour'),
'aside_effectifs' => $effectifs,
]
];
$inserted_post = wp_insert_post($post_array);
}
// The cron does not have the capability of adding taxonomy terms, they need to be be added separately
$inserted_terms = wp_set_object_terms($inserted_post, $presta['cat_name'], 'categories_formations');
$inserted_terms = wp_set_object_terms($inserted_post, $locations, 'ville');
update_field('aside_sessions', $session, $inserted_post);
unset($dates);
unset($session);
unset($formatted_cost);
unset($nb_places);
unset($prices);
}
}
This is very much work in progress, but, for now, I am stumped.

Drupal 7 Batch Page Example

I'm trying to setup a batch page for processing and I need an example. The example that's given in the Example module is within a form and I need a page that I can run independently of a form that will process batch requests.
For instance:
function mymodule_batch_2() {
$operations[] = array('mymodule_onefunction','mymodule_anotherfunction')
$batch = array(
'operations' => $operations,
'finished' => 'mymodule_finished',
// We can define custom messages instead of the default ones.
'title' => t('Processing batch 2'),
'init_message' => t('Batch 2 is starting.'),
'progress_message' => t('Processed #current out of #total.'),
'error_message' => t('Batch 2 has encountered an error.'),
);
batch_set($batch);
batch_process('');
}
Where the batch function would call other functions in the form of $operations.
You need to give batch process an id to work from. batch_process('mybatch')otherwise yourmexample is correct. are you having a particular problem with this strategy?
Here you can see my sample of batch relization with form that calls batch:
function my_module_menu() {
$items['admin/commerce/import'] = array(
'title' => t('Import'),
'page callback' => 'drupal_get_form',
'page arguments' => array('my_module_settings_form'),
'access arguments' => array('administer site settings'),
'type' => MENU_NORMAL_ITEM,
);
return $items;
}
/**
* Import form
*/
function my_module_settings_form() {
$form = array();
$form['import'] = array(
'#type' => 'fieldset',
'#title' => t('Import'),
'#collapsible' => TRUE,
'#collapsed' => FALSE,
);
$form['import']['submit'] = array(
'#type' => 'submit',
'#value' => t('Import'),
);
return $form;
}
function my_module_settings_form_submit($form, &$form_state) {
batch_my_module_import_start();
}
/**
* Batch start function
*/
function batch_my_module_import_start() {
$batch = array(
'title' => t('Import products'),
'operations' => array(
array('_batch_my_module_import', array()),
),
'progress_message' => t('Import. Operation #current out of #total.'),
'error_message' => t('Error!'),
'finished' => 'my_module_batch_finished',
);
batch_set($batch);
}
/**
* Import from 1C operation. Deletes Products
*/
function _batch_my_module_import(&$context) {
// Your iterms. In my case select all products
$pids = db_select('commerce_product', 'p')
->fields('p', array('sku', 'product_id', 'title'))
->condition('p.type', 'product')
->execute()
->fetchAll();
// Get Count of products
if (empty($context['sandbox']['progress'])) {
$context['sandbox']['progress'] = 0;
$context['sandbox']['max'] = count($pids);
watchdog('import', 'import products');
}
// Create Iteration variable
if (empty($context['sandbox']['iteration'])) {
$context['sandbox']['iteration'] = 0;
}
// Check for the end of cycle
if ($context['sandbox']['iteration'] < $context['sandbox']['max']) {
// Count of operation in one batch step
$limit = 10;
// Counts completed operations in one batch step
$counter = 0;
if ($context['sandbox']['progress'] != 0) {
$context['sandbox']['iteration'] = $context['sandbox']['iteration'] + $limit;
}
// Loop all Product items in xml
for ($i = $context['sandbox']['iteration']; $i < $context['sandbox']['max'] && $counter < $limit; $i++) {
/* Loop items here */
/* ... */
/* ... */
$context['results']['added']['products'][] = $product_item->title;
// Update Progress
$context['sandbox']['progress']++;
$counter++;
// Messages
$context['message'] = t('Now processing product %name. Product %progress of %count', array('%name' => $product_item->title, '%progress' => $context['sandbox']['progress'], '%count' => $context['sandbox']['max']));
$context['results']['processed'] = $context['sandbox']['progress'];
}
}
if ($context['sandbox']['progress'] != $context['sandbox']['max']) {
$context['finished'] = $context['sandbox']['progress'] / $context['sandbox']['max'];
}
}
/**
* Finish of batch. Messagess
*/
function my_module_batch_finished($success, $results, $operations) {
if ($success) {
drupal_set_message(t('#count products added.', array('#count' => isset($results['added']) ? count($results['added']) : 0)));
}
else {
$error_operation = reset($operations);
drupal_set_message(t('An error occurred while processing #operation with arguments : #args', array('#operation' => $error_operation[0], '#args' => print_r($error_operation[0], TRUE))));
}
watchdog('import', 'import finished');
}
function module_name_import_form_submit($form, $form_state) {
// Check to make sure that the file was uploaded to the server properly
$uri = db_query("SELECT uri FROM {file_managed} WHERE fid = :fid", array(
':fid' => $form_state['input']['import']['fid'],
))->fetchField();
if(!empty($uri)) {
if(file_exists(drupal_realpath($uri))) {
// Open the csv
$handle = fopen(drupal_realpath($uri), "r");
// Go through each row in the csv and run a function on it. In this case we are parsing by '|' (pipe) characters.
// If you want commas are any other character, replace the pipe with it.
while (($data = fgetcsv($handle, 0, '|', '"')) !== FALSE) {
$operations[] = array(
'module_name_import_batch_processing', // The function to run on each row
array($data), // The row in the csv
);
}
// Once everything is gathered and ready to be processed... well... process it!
$batch = array(
'title' => t('Importing CSV...'),
'operations' => $operations, // Runs all of the queued processes from the while loop above.
'finished' => 'module_name_import_finished', // Function to run when the import is successful
'error_message' => t('The installation has encountered an error.'),
'progress_message' => t('Imported #current of #total products.'),
);
batch_set($batch);
fclose($handle);
}
}
else {
drupal_set_message(t('There was an error uploading your file. Please contact a System administator.'), 'error');
}
}
/**
* This function runs the batch processing and creates nodes with then given information
* #see
* module_name_import_form_submit()
*/
function module_name_import_batch_processing($data) {
// Lets make the variables more readable.
$title = $data[0];
$body = $data[1];
$serial_num = $data[2];
// Find out if the node already exists by looking up its serial number. Each serial number should be unique. You can use whatever you want.
$nid = db_query("SELECT DISTINCT n.nid FROM {node} n " .
"INNER JOIN {field_data_field_serial_number} s ON s.revision_id = n.vid AND s.entity_id = n.nid " .
"WHERE field_serial_number_value = :serial", array(
':serial' => $serial_num,
))->fetchField();
if(!empty($nid)) {
// The node exists! Load it.
$node = node_load($nid);
// Change the values. No need to update the serial number though.
$node->title = $title;
$node->body['und'][0]['value'] = $body;
$node->body['und'][0]['safe_value'] = check_plain($body);
node_save($node);
}
else {
// The node does not exist! Create it.
global $user;
$node = new StdClass();
$node->type = 'page'; // Choose your type
$node->status = 1; // Sets to published automatically, 0 will be unpublished
$node->title = $title;
$node->uid = $user->uid;
$node->body['und'][0]['value'] = $body;
$node->body['und'][0]['safe_value'] = check_plain($body);
$node->language = 'und';
$node->field_serial_number['und'][0]['value'] = $serial_num;
$node->field_serial_number['und'][0]['safe_value'] = check_plain($serial_num);
node_save($node);
}
}
/**
* This function runs when the batch processing is complete
*
* #see
* module_name_import_form_submit()
*/
function module_name_import_finished() {
drupal_set_message(t('Import Completed Successfully'));
}

Create form dynamically in Symfony 2

A simple question:
I have one form, it returns one number and I need create this number of labels in Controller.
I try:
$form2 = $this->createFormBuilder();
for($i = 0; $i < $num; $i++) {
$name = 'column'.$i;
$form2->add($name,'number');
}
$form2->getForm();
I think it should very simple, but i can't..
Yes, you can do it with an array / hash map instead of a real object.
Here is an example :
// Create the array
$dataObj = array();
$dataObj['data1'] = '';
$dataObj['data2'] = 'default';
// ... do a loop here
$dataObj['data6'] = 'Hello';
// Create the form
$formBuilder = $this->createFormBuilder($dataObj);
foreach($dataObj as $key => $val)
{
$fieldType = 'text'; // Here, everything is a text, but you can change it based on $key, or something else
$formBuilder->add($key, $fieldType);
}
$form = $formBuilder->getForm();
// Process the form
$request = $this->get('request');
if($request->getMethod() == 'POST')
{
$form->bind($request); // For symfony 2.1.x
// $form->bind($this->get('request')->request->get('form')); // For symfony 2.0.x
if($form->isValid())
{
$dataObj = $form->getData();
foreach($dataObj as $key => $val)
{
echo $key . ' = ' . $val . '<br />';
}
exit('Done');
}
}
// Render
return $this->render('Aaa:Bbb:ccc.html.twig', array(
'requestForm' => $form->createView()));

Drupal 6 Pager Stying - theme_pager issue "Array"

I went onto the Drupal website and found the theme hook for theme_pager I have copied the code from the comments to do a devient art style pager as this is close to what I need although when I am implmenting it i am getting
"1 Array Array Array Array"
This is the code from http://api.drupal.org/api/drupal/includes--pager.inc/function/theme_pager/6:
function yourthemename_pager($tags = array(), $limit = 10, $element = 0, $parameters = array(), $quantity = 5) {
global $pager_page_array, $pager_total;
$tags = array("", "< prev", "", "next >", "");
// Calculate various markers within this pager piece:
// Middle is used to "center" pages around the current page.
$pager_middle = ceil($quantity / 2);
// current is the page we are currently paged to
$pager_current = $pager_page_array[$element] + 1;
// first is the first page listed by this pager piece (re quantity)
$pager_first = $pager_current - $pager_middle + 1;
// last is the last page listed by this pager piece (re quantity)
$pager_last = $pager_current + $quantity - $pager_middle;
// max is the maximum page number
$pager_max = $pager_total[$element];
// End of marker calculations.
// Prepare for generation loop.
$i = $pager_first;
if ($pager_last > $pager_max) {
// Adjust "center" if at end of query.
$i = $i + ($pager_max - $pager_last);
$pager_last = $pager_max;
}
if ($i <= 0) {
// Adjust "center" if at start of query.
$pager_last = $pager_last + (1 - $i);
$i = 1;
}
// End of generation loop preparation.
$li_previous = theme('pager_previous', (isset($tags[1]) ? $tags[1] : t('‹ previous')), $limit, $element, 1, $parameters);
$li_next = theme('pager_next', (isset($tags[3]) ? $tags[3] : t('next ›')), $limit, $element, 1, $parameters);
if ($pager_total[$element] > 1) {
if ($li_previous) {
$items[] = array(
'class' => 'pager-previous',
'data' => $li_previous,
);
}
// When there is more than one page, create the pager list.
if ($i != $pager_max) {
// Now generate the actual pager piece.
for (; $i <= $pager_last && $i <= $pager_max; $i++) {
if ($i < $pager_current) {
if ($pager_first > 1 && $i == $pager_first) {
$output = '...'.$i;
$stopPreEllipsis = true;
} else {
$output = $i;
}
$items[] = array(
'class' => 'pager-item',
'data' => theme('pager_previous', $output, $limit, $element, ($pager_current - $i), $parameters),
);
}
if ($i == $pager_current) {
$items[] = array(
'class' => 'pager-current',
'data' => $i,
);
}
if ($i > $pager_current) {
if ($pager_last < $pager_max && $i == $pager_last) {
$output = $i.'...';
} else {
$output = $i;
}
$items[] = array(
'class' => 'pager-item',
'data' => theme('pager_next', $output, $limit, $element, ($i - $pager_current), $parameters),
);
}
}
}
// End generation.
if ($li_next) {
$items[] = array(
'class' => 'pager-next',
'data' => $li_next,
);
}
return theme('item_list', $items, NULL, 'ul', array('class' => 'pager'));
}
}
Please help.
Idealy I would like a pager like this:
< 1 2 3 4 5 6 7 8 9 10 > (all the page numbers with next and previous) - But if I can get around this issue of Array then I should be able to modify the code.
Thanks
James
Install devel module, replace all the print statements in the code with, dpms. That way you will get to know what are contents of the array and then you can print whatever is required.

Resources