how to print output in drupal hook_block - drupal

How to Print the output, if i written in WHILE SNIPPET in the function ,
Below is my snippet, i want print retrieved result ,
i tried echo ,
but we should not use echo in drupal, and drupal set message function for debug purpose ,
So how to print my output in this example ,
function node_example_block($op='list',$delta=0){
switch($op){
case "list":
$block[0]['info'] = t('THIS IS EXAMPLE NODE EXAMPLE ');
return $block;
case "view":
$block['subject'] = "THIS MY FIRST SAMPLE BLOCK";
$block['content'] = drupal_get_form('display_node_title');
return $block;
}
}
function display_node_title(){
$result = db_query("SELECT * FROM node");
$output = '';
while ($obj = db_fetch_object ($result)){
$output .= $obj->title;
}
//drupal_set_message($output);
}

You're having display_node_title get passed through drupal_get_form, but display_node_title isn't a form function. If it were, it'd be constructing a $form array via the Form API and return $form; at the end.
Change:
$block['content'] = drupal_get_form('display_node_title');
to:
$block['content'] = display_node_title();
and add:
return $output;
to the end of your display_node_title() function.

Related

Cron Job In Custom Plugin Not Working In Wordpress

I have added this cronjob in my WordPress custom plugin but when I run the function manually it is working but through cronjob, it is not working. Here is my code! All the plugin files are loaded correctly not showing any error.
Can anybody help me to sort this out! I have tried a lot but still, it is not working.
<?php
if (!wp_next_scheduled('generateusedcarsfeed'))
{
wp_schedule_event(time() , '5mins', 'generateusedcarsfeed');
}
add_action('generateusedcarsfeed', 'generate_used_car_feed');
if (!wp_next_scheduled('generateusedcarsfeed'))
{
wp_schedule_event(time() , '5mins', 'generateusedcarsfeed');
}
add_action('generateusedcarsfeed', 'generate_used_car_feed');
// Getting all used cars with all data
function generate_used_car_feed(){
try{
// for opening the csv file
$file = fopen('all-cars-feed.csv', 'r');
fwrite($file, '');
$loop = new WP_Query($args);
chmod('all-cars-feed.csv', 0777);
// for creating array from csv file
$file="all-cars-feed.csv";
$csv= file_get_contents($file);
$array = array_map("str_getcsv", explode("\n", $csv));
$json_csv_arr = json_encode($array);
$my_array_csv = json_decode($json_csv_arr, true);
// for getting used car list from databse, only take publish used car
global $wpdb;
$query = "SELECT wp_postmeta.post_id, wp_postmeta.meta_value FROM wp_postmeta
INNER JOIN wp_posts ON wp_posts.id = wp_postmeta.post_id WHERE meta_key = 'car_registration_number'
AND post_status = 'publish'";
$result = $wpdb->get_results($query);
$json_reg_num = json_encode($result);
$my_array = json_decode($json_reg_num, true);
print_r($my_array);
foreach ($my_array as $value) {
$car_reg_array = $value['meta_value'];
$Post_id= $value['post_id'];
$isTrue=true;
$ch = fopen("all-cars-feed.csv", "r");
while($row = fgetcsv($ch)) {
if (in_array($car_reg_array, $row)) {
echo 'found</hr>';
$isTrue=false;
}
}
if($isTrue)
{
$wpdb->query(
'UPDATE '.$wpdb->prefix.'posts SET post_status = "trash"
WHERE ID = "'.$Post_id.'"');
}
}
//fclose($file);
}
catch(\Exception $e)
{
$txt = 'Message: ' . $e->getMessage();
$myfile = fopen("newfile.txt", "w") or die("Unable to open file!");
fwrite($fileLoger, $txt);
fclose($fileLoger);
}
}
I wonder if this 5mins interval really exists in your setup. Try adding this code to make sure this actually exists (if it does already, it won't break stuff):
function add_custom_cron_schedules($schedules){
if (!isset($schedules["5mins"])) {
$schedules["5min"] = array(
'interval' => 5*60,
'display' => __('Every 5 minutes'));
}
return $schedules;
}
add_filter('cron_schedules','add_custom_cron_schedules');
If you want to retrieve currently available schedules, you can also use wp_get_schedules() and check out if a certain key (like '5mins') exists.

Get gravity forms fields

I am using the gravity form on my site. I am working on create the custom report for this I have need gravity form fields name and id based on specific form id.Please let me know how I can do it.
I am using the following function but it is showing all forms info based on it. it is looking very hard to parse it. Please let me know any function so I can get fields name easily.
$forms = RGFormsModel::get_forms_by_id(13);
try this
function get_all_form_fields($form_id){
$form = RGFormsModel::get_form_meta($form_id);
$fields = array();
if(is_array($form["fields"])){
foreach($form["fields"] as $field){
if(isset($field["inputs"]) && is_array($field["inputs"])){
foreach($field["inputs"] as $input)
$fields[] = array($input["id"], GFCommon::get_label($field, $input["id"]));
}
else if(!rgar($field, 'displayOnly')){
$fields[] = array($field["id"], GFCommon::get_label($field));
}
}
}
//echo "<pre>";
//print_r($fields);
//echo "</pre>";
return $fields;
}
It's not that hard to parse:
$fields=array();
foreach ( $forms['fields'] as $field ) {
$fields[]=array($field['id'] => $field['inputName']);
}
P.S. I'm assuming you use Gravity Forms < 1.7 as RGFormsModel::get_forms_by_id is a deprecated function since 1.7
// Get the Form fields
$form = RGFormsModel::get_form_meta($form_id);
// Run through the fields to grab an object of the desired field
$field = RGFormsModel::get_field( $form, $field_id );
I use the above to get a specific field I want to filter the value of. The $field contains an object with all the properties you want.
echo $field->label // Gets the label
echo $field->inputName // Gets the name
echo $field->type // Gets the type
echo $field->cssClass // Gets the CSS Classes as a string
You are able to get the entered value/content of a field by using rgpost() and by referencing the id ($field->id).
// Check the entered value of every field
foreach( $form['fields'] as &$field ) {
// Get the content for the specific field
$fieldContent = rgpost( "input_".$field->id );
// Check the content
if ( $fieldContent == ... ){}
}

hook_alter uc_addresses submit function in Drupal/Ubercart

I am trying to hook into uc_addresses submit function, but it has become very confusing very fast. Just to note this is Ubercart running on Drupal 6. So I've isolated the code in uc_addresses.module that I'm interested in hooking in to:
function uc_addresses_get_address_form_submit($form, &$form_state) {
global $user;
$address_user = $form['stored_values']['#value']['user'];
$address = $form['stored_values']['#value']['address'];
$view = $form['stored_values']['#value']['view'];
if ($form_state['clicked_button']['#value'] == t('Delete address')) {
cache_clear_all();
$form_state['redirect'] =
array('user/'. $address_user->uid .'/addresses/' . $address->aid . '/delete');
}
else {
if (!$address) {
$address = new stdClass();
$address->uid = $address_user->uid;
}
$valid = TRUE;
foreach (element_children($form_state['values']['panes']) as $pane_id) {
$func = _address_pane_data($pane_id, 'callback');
$isvalid = $func('process', $address, $form_state['values']['panes'][$pane_id]);
if ($isvalid === FALSE) {
$_SESSION['expanded_panes'][] = $key;
$valid = FALSE;
}
}
if ($view == 'edit') { // Update database
_uc_addresses_db_update_address($address);
}
elseif ($view == 'new' || $view == 'add') { // Insert into datebase
_uc_addresses_db_add_address($address);
}
$form_state['redirect'] = array('user/'. $address_user->uid .'/addresses');
}
}
The goal is to copy a portion of the submitted form values in the database. Which in itself may be an issue because I need to make sure my hook occurs after the values have been written to the table. So my question is what should my hook function look like if I want it to occur after this form has been submitted?
Okay so foolish me didn't realize that there is a huge section in the uc_addresses documention about hooks. Link to the documentation. In this specific case where you want to hook into form submissions I would recommend using hook_uc_addresses_address_insert() and hook_uc_addresses_address_update().

Getting print_r from a Drupal variable

I have a Drupal variable, $view. I need to print out all of its values. I have tried:
dsm($view);
var_dump($view);
function hook_form_alter() {
$form['print'] = array('#value' => '<pre>'.print_r($view, 1).'</pre>');
}
All of these functions produce an output of Null, however. How can I get the value of the variable?
This is probably happening because the $view variable isn't within scope in the function hook_form_alter().
Use:
$view = views_get_current_view();
Then you can access, for example, the arguments of the view:
$arg0 = $view->args[0];
function MYMODULE_form_alter(&$form, &$form_state, &$form_id){
switch($form_id){
case 'MY_FORM':
$display_id = 'block_1';
$view = views_get_view('my_view_machine_name');
$view->set_display($display_id)
$view->set_items_per_page(0); // or other
$view->execute();
$result = $view->preview();
// Also you can use $view->result to get result as array
$form['print'] = $result;
break;
}
}

Search hook for filtering results?

I have been going through the docs and source code looking for something without luck.
Is there a Drupal 6 hook that gets called after hook_search(), but before the $results gets handed off to the template system?
I need to do a fairly custom pruning and reordering of results that get returned. I could just reimplement hook_search(), but this seems like overkill.
Thanks.
There isn't; search_view() (which displays the results) calls search_data(), which invokes hook_search() then immediately themes the results. Re-implementing hook_search() is probably the most straightforward route.
With that said, you could instead implement hook_menu_alter() and have the search page call your custom function instead of calling search_view() (and subsequently calling search_data()). Something like:
function test_menu_alter(&$items) {
$items['search']['page callback'] = 'test_search_view';
foreach (module_implements('search') as $name) {
$items['search/' . $name . '/%menu_tail']['page callback'] = 'test_search_view';
}
}
// Note: identical to search_view except for --- CHANGED ---
function test_search_view($type = 'node') {
// Search form submits with POST but redirects to GET. This way we can keep
// the search query URL clean as a whistle:
// search/type/keyword+keyword
if (!isset($_POST['form_id'])) {
if ($type == '') {
// Note: search/node can not be a default tab because it would take on the
// path of its parent (search). It would prevent remembering keywords when
// switching tabs. This is why we drupal_goto to it from the parent instead.
drupal_goto('search/node');
}
$keys = search_get_keys();
// Only perform search if there is non-whitespace search term:
$results = '';
if (trim($keys)) {
// Log the search keys:
watchdog('search', '%keys (#type).', array('%keys' => $keys, '#type' => module_invoke($type, 'search', 'name')), WATCHDOG_NOTICE, l(t('results'), 'search/'. $type .'/'. $keys));
// Collect the search results:
// --- CHANGED ---
// $results = search_data($keys, $type);
// Instead of using search_data, use our own function
$results = test_search_data($keys, $type);
// --- END CHANGED ---
if ($results) {
$results = theme('box', t('Search results'), $results);
}
else {
$results = theme('box', t('Your search yielded no results'), search_help('search#noresults', drupal_help_arg()));
}
}
// Construct the search form.
$output = drupal_get_form('search_form', NULL, $keys, $type);
$output .= $results;
return $output;
}
return drupal_get_form('search_form', NULL, empty($keys) ? '' : $keys, $type);
}
// Note: identical to search_data() except for --- CHANGED ---
function test_search_data($keys = NULL, $type = 'node') {
if (isset($keys)) {
if (module_hook($type, 'search')) {
$results = module_invoke($type, 'search', 'search', $keys);
if (isset($results) && is_array($results) && count($results)) {
// --- CHANGED ---
// This dsm() is called immediately after hook_search() but before
// the results get themed. Put your code here.
dsm($results);
// --- END CHANGED ---
if (module_hook($type, 'search_page')) {
return module_invoke($type, 'search_page', $results);
}
else {
return theme('search_results', $results, $type);
}
}
}
}
}
You can use hook_search_page() to reorder or format the search result.
Hook search_execute allows you to modify the query in the way you needed. You can even fire new queries with custom sql, for example:
function mymodule_search_execute($keys = NULL, $conditions = NULL) {
// Do some query here.
$result = my_fancy_query();
// Results in a Drupal themed way for search.
$results[] = array(
'link' => (string) $result->U,
'title' => $title,
'snippet' => $snippet,
'keys' => check_plain($keys),
'extra' => array($extra),
'date' => NULL,
);

Resources