What is the relationship between hook_cron() and hook_cron_queue_info()? Some modules (e.g. Feeds, Rules Scheduler, Revision Scheduler) implement both hook_cron() and hook_cron_queue_info(). When used with Ultimate Cron and the Enable cron queue processing setting enabled, this causes two jobs to appear in the jobs list. Are both jobs necessary?

Taking the Revision Scheduler module as an example, its hook_cron() seems to add items to the queue:

function revision_scheduler_cron() {
  $ids = db_query("SELECT * FROM {revision_scheduler} WHERE time_scheduled <= :now AND time_queued = 0 AND time_executed = 0 ORDER BY id ASC", array(':now' => REQUEST_TIME))->fetchCol();
  if ($operations = revision_scheduler_operation_load_multiple($ids)) {
    $queue = DrupalQueue::get('revision_scheduler');
    foreach ($operations as $operation) {
      if ($queue->createItem($operation)) {
        db_update('revision_scheduler')
          ->fields(array('time_queued' => REQUEST_TIME))
          ->condition('id', $operation->id)
          ->execute();
      }
    }
  }
}

whereas its hook_cron_queue_info() function calls a function that processes single revision operations:

function revision_scheduler_cron_queue_info() {
  $info['revision_scheduler'] = array(
    'worker callback' => 'revision_scheduler_operation_process',
    'time' => variable_get('revision_scheduler_cron_time', 30),
  );
  return $info;
}

Is it the case that hook_cron() adds the items to the queue and hook_cron_queue_info() processes them?

The documentation for hook_cron_info() says this:

  While there can be only one hook_cron() process running at the same
  time, there can be any number of processes defined here running.
  Because of this, long running tasks are much better suited for this
  API. Items queued in hook_cron() might be processed in the same cron
  run if there are not many items in the queue, otherwise it might take
  several requests, which can be run in parallel.

I'm not sure how to interpret that, but it seems to suggest tasks should be processed with one or the other.

The relationship is they are 2 independent hooks that can be used in conjunction with one another depending on what the task is.

hook_cron(): Provides a means to supply a custom function to respond to a cron event.
hook_cron_queue_info(): Provide a means to supply queue metadata for a cron event that will need a queue (i.e. any task that can't be fully processed in the limited time during a cron event).

In your example above:

Yes revision_scheduler_cron is adding to the queue.
But no, revision_scheduler_cron_queue_info is not processing the queue, it's providing the function (revision_scheduler_operation_process) to call for processing and how long (revision_scheduler_cron_time) it should be allowed to execute for processing.


How do I enable comments for user profiles? With users being entities in D7 I assumed the user type would would have built in "comment" option. That doesn't seem to be the case.
I just want to allow users to leave comments on the user profile page. Is there a simple way to doing that?

You can use Profile2, that attach node to user profile, so it can be commented and will look as commenting to user.


How can I customize the way my taxonomy terms are displaying? I have been searching all over the place for some help on this.

I currently have my tags displaying for each node like such: tag,tag,tag

Now I would like them to display a little cleaner and more appealing to my visitors. So what I would like to do is have them display like such: tag \ tag \ tag

Now from what I have read, I need to target the field API? and use a preprocess function to alter what the array is spiting out? Please correct me if I am wrong.

This seems like an easy task to complete but I just can't seem to find a solution.

Thanks in advance

Indeed a preprocess function is what you're looking for, I suspect in D7 this will help:

function MYTHEME_preprocess_html(&$variables) {
if(arg(0)=='node' && is_numeric(arg(1))) {
    $node = node_load(arg(1));
    $results = taxonomy_node_get_terms($node);
    if(is_array($results)) {
        foreach ($results as $item) {

In terms of D6, node-taxonomy.tpl.php and page-taxonomy-term.tpl.php should put you on the right path.


Is there a function or a way to invoke the comment object? I want to use the $comment object in page.tpl.php.
Is there a function or a way to use it?

The page.tpl.php template file is used for any page output from Drupal; it is not said the page is being output for a node. It would be rather better to use node.tpl.php, which is always used for a node, except when a different template is being suggested and that file exists.

The code I am reporting is valid for page.tpl.php, but with few changes it can be used also for node.tpl.php.
I am taking the assumption you are interested in the comments for the node being shown.

if (!empty($node)) {
  $result = db_query('SELECT * FROM {comments} WHERE nid = %d', $node->nid);
  while ($comment_obj = db_fetch_object($result)) {
    // $comment_obj contains the comment object.
    // ...
  }
}

In the case the code is used in node.tpl.php, it is not necessary to verify if $node is not empty, as the template is surely used to visualize a node.
I called the variable $comment_obj because in node.tpl.php there is already a variable named $comment, but that variable doesn't contain any comment object; it contains the comment settings for the node.

As pointed out from Jeremy French, such code should never go inside a template file, which should just contain presentation code (i.e. code that prints out the content of variables). That code could be the body of a function (contained in template.php of a theme) that builds up the output shown from the template file; alternatively, similar code should be used in a preprocess function.

In this case, the code is similar to the following one.

function mymodule_preprocess_node(&$variables) {
  $variables['comment_output'] = '';

  if (!empty($variables[node])) {
    $result = db_query('SELECT * FROM {comments} WHERE nid = %d', $variables[node]->nid);
    while ($comment_obj = db_fetch_object($result)) {
      // $comment_obj contains the comment object.
      // ...
      $variables['comment_output'] .= // ...
    }
  }
}

page.tpl.php should then print the content of $variables['comment_output'].

print $comment_output;

To notice also that Drupal uses comment.tpl.php, to which is passed a comment object. Depending on what you are trying to do, that could be the template file you are really interested in.


Programmatically loaded taxonomy form ajax errors I load a taxonomy term in the edit form via the following code:

module_load_include ( 'inc', 'taxonomy', 'taxonomy.admin' );
$vocabulary = taxonomy_term_load ( $tid );
$form = drupal_get_form ( 'taxonomy_form_term', $vocabulary );

The vocabulary has a custom text field with unlimited values, so this appears on the form, but when I click the "add another item" button, I get:

  Call to undefined function, taxonomy_form_term_validate() in [truncated path].../form.inc" on line 1513.

I appreciate any guidance I can get in solving this.

This function worked for me:
Please try to use form_load_include() and drupal_build_form() instead of drupal_get_form() to generate form

  $form_id = 'taxonomy_form_term';
  $vocabulary = taxonomy_vocabulary_load($tid);

  $form_state = array();
  $form_state['build_info']['args'] = array($vocabulary);

  // use form_load_include() and drupal_build_form() instead of drupal_get_form()
  form_load_include($form_state, 'inc', 'taxonomy', 'taxonomy.admin');

  $form = drupal_build_form($form_id, $form_state);


Content encoding error after enabling cache, aggregation and compression Yesterday I turned on caching, aggregation of css and js files and turned on compress cached pages. Then I logged out and closed my browser (FF). After a couple of minutes I openend my browser again, typed in the url of my website and got this error in FF: Content encoding error.

I tried opening my site in FF, Chrome and IE. None of them work.

I read some similar threads here and tried:
- setting display_errors=Off in php.ini
- disabling gzip of files in .htaccess
- Changing "Header append" to "Header set" in .htaccess

Nothing seems to work.

What I would like to do now is manually disable caching, aggregation and compression in the database, but I don't know which tables these settings reside in.

Add this lines to your settings.php file.

$conf = array(
'cache' => '0',
'preprocess_css' => '0',
'preprocess_js' => '0',
'block_cache' => '0',
'page_compression' => '0',
);

or with Drush

// To turn on JS Aggregation

drush vset preprocess_js 1 --yes

// To disable JS Aggregation

drush vset preprocess_js 0 --yes

// To clear cache of JS and CSS only

drush cc css+js

// To enable CSS Aggregation

drush vset preprocess_css 1 --yes

// To disable CSS Aggregation

drush vset preprocess_css 0 --yes


Varnish Cookies with Authcache Problem

I'm setting up Authcache to work with Varnish as a backend.

It comes with an excellent default.vcl which is very well documented. It has the following section on cookies. Varnish skips the cache if cookies are enabled, so the following example would appear to remove all cookies so it can cache.

However I've found if I un-comment this section Authcache stops caching. If I leave it commented out then it continues to cache and cookie functionality seems to work. (e.g. I have cookies which remember the state of facets across page refreshes and they continue to work).

Isn't this the wrong way around?

(I'm using Authcache debug to test for caching).

// * Example 2: Remove all but
  // * - the session cookie (SESSxxx, SSESSxxx)
  // * - the cache invalidation cookie for authcache p13n (aucp13n)
  // * - the NO_CACHE cookie from the Bypass Advanced module
  // * - the nocache cookie from authcache
  // *
  // * Note: Please also add the has_js cookie to the list if Authcache Ajax
  // * is also enabled in the backend. Also if you have Authcache Debug enabled,
  // * you should let through the aucdbg cookie.
  // *
  // * More information on:
  // * https://www.varnish-cache.org/docs/3.0/tutorial/cookies.html
  // */
  //if (req.http.Cookie) {
  // set req.http.Cookie = ";" + req.http.Cookie;
  // set req.http.Cookie = regsuball(req.http.Cookie, "; +", ";");
  // set req.http.Cookie = regsuball(req.http.Cookie, ";(S?SESS[a-z0-9]+|aucp13n|NO_CACHE|nocache|aucdbg)=", "; \1=");
  // set req.http.Cookie = regsuball(req.http.Cookie, ";[^ ][^;]*", "");
  // set req.http.Cookie = regsuball(req.http.Cookie, "^[; ]+|[; ]+$", "");
  //  if (req.http.Cookie == "") {
  //   unset req.http.Cookie;
  //  }
 //}

Copy pasta of Znerol's excellent answer to the incorrect bug I raised:

  The VCL shipping with Authcache Varnish needs to be adapted for
  Authcache Debug. The widget uses a cookie (aucdbg) with a unique value
  for each request in order to distinguish between cache hits and
  misses.

  By default the standard cache policy kicks in for anonymous users.
  I.e. requests having a cookie will be passed to the backend by
  Varnish. When you use ab for testing, no cookies will be sent along
  with the request and therefore the cache actually kicks in. When
  testing with the browser, the aucdbg and js cookies are added by
  JavaScripts and therefore the requests are bypassing the cache.

  Look for Example 4: Trigger key-retrieval for all users, including
  anonymous. in vcl_recv and enforce key-retrieval for all users. When
  this fragment is enabled, requests for anonymous users will be handled
  exactly like those for authenticated users and the default varnish
  cache policy will be disabled.

Un-commenting section 4 in the Authcache default.vcl solved this problem.


Surround specific webform elements with a div As the title describes, I am to style a webform and for that i need to surround specific fields in divs in order to give them their CSS properties and I have no idea how I should go about doing that. Also I'd like to do the same to the Submit button.

I've caught the form with hook_form_alter but no idea what to do after.

Why do you need a div?

Just use a field set and hide label and turn off the collapsible feature.

If anything this is more semantic than using a div in splitting up fields in a form. Visually will look excately the same and you can also use CSS class generated from the field set name in your styling.


Commerce message notify sending duplicate emails I have created a custom commerce order status called 'Sent'.

When an existing order is updated from 'Invoiced' to 'Sent' I have a custom message type ('Order sent') and, using Rules, a custom rule which creates a message entity and sends the 'Order sent' message.

The rule is as follows:

{ "commerce_message_commerce_order_message_order_sent_e_mail" : {
    "LABEL" : "Commerce order message: order sent e-mail",
    "PLUGIN" : "reaction rule",
    "WEIGHT" : "3",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "message_notify", "entity" ],
    "ON" : { "commerce_order_update" : [] },
    "IF" : [
      { "data_is" : { "data" : [ "commerce-order:status" ], "value" : "sent" } }
    ],
    "DO" : [
      { "entity_create" : {
          "USING" : {
            "type" : "message",
            "param_type" : "commerce_order_order_sent",
            "param_user" : [ "commerce-order:owner" ]
          },
          "PROVIDE" : { "entity_created" : { "entity_created" : "Created entity" } }
        }
      },
      { "data_set" : {
          "data" : [ "entity-created:field-ds-message-commerce-order" ],
          "value" : [ "commerce-order" ]
        }
      },
      { "entity_save" : { "data" : [ "entity-created" ], "immediate" : "1" } },
      { "message_notify_process" : {
          "message" : [ "entity-created" ],
          "save_on_fail" : "0",
          "save_on_success" : "0"
        }
      }
    ]
  }
}

At the moment, I am receiving 3 duplicate emails and can't work out why?

It's obvious that the update event you're using in your custom rule gets triggered twice, which explains why you get those duplicate mails. I've seen similar issues in the past with other entities being updated (using similar events), for entities such as users or nodes.

If you cannot find the root cause for the duplicate trigger, and cannot use any other Rules Event as an alternative, then the typical solution is to use the Flag module like so:

Define a non-global flag to flag orders.
Add a Rules Action to your custom rule to also flag the order (for which you want to send such eMails).
Add an extra Rules Condition to check that the order is NOT (repeat: NOT!) yet flagged.

With the above tuning of your existing rule in place, the first time your rule is triggered the Rules Actions do get performed (= send the eMail and flag the order) and the second time the extra Rules Condition will prevent the Rules Actions to be performed (= no more duplicate eMail).

Easy, no? ... And it works for any entity ...


Hide post information programmaticaly i would like to hide the post information for my content type,  but programmatically.

I don't find where the author and date information
 is stocked in the database, and I would like to hide it.

How can I achieve this?

i find....

variable_set('node_submitted_'.$my_content_type, false);


Form API + AJAX - Form doubles itself on submit I've been looking for an answer to this for hours now.

A) No matter what I do, the form will always be visible again after submit. How can I stop the from from displaying after a successful submit?

B) If there are validation errors, the form will attach to the existing form, resulting in 2,3,4,5,.. forms on the page. How to stop that?

This is the code:

function agals_support_form($form, &$form_state) {
$form['wrapper'] = array("#markup" => "

");

$form['name'] = array(
  '#type' => 'textfield',
  '#title' => t('Name'),
  '#default_value' => '',
  '#maxlength' => '128',
  '#required' => TRUE,
);

$form['submit'] = array(
  '#type' => 'submit',
  '#value' => t('submit'),
  '#ajax' => array(
    'callback' => 'agals_support_form_ajax_handler',
    'effect' => 'fade',
    'wrapper' => 'status',
  ),
);

if(isset($form_state['values']['name'])) { //output
  $form['form_output'] = array(
    '#prefix' => '
',
    '#suffix' => '
',
    '#markup' => t('You entered @value', array('@value' => $form_state['values']['name'])),
  );
} } return $form; }

function agals_support_form_submit(&$form, &$form_state) {
  watchdog('agals_support', 'submitted');
  drupal_set_message('Form submitted');
  $form_state['rebuild'] = TRUE;
}

function agals_support_form_validate(&$form, &$form_state) {
  watchdog('agals_support', 'validation');
  if (empty($form_state['values']['name'])) {
    watchdog('agals_support', 'name missing');
    form_set_error('name', t('Please enter your name.'));
  }
}

function agals_support_form_ajax_handler(&$form, &$form_state) {
  watchdog('agals_support', 'ajax_handler');
  return $form;
}

The issue you are facing is that you are not wrapping your form with the wrapper div, you're prepending a div to your form. When the ajax form is loaded, it is inserted into this wrapper div, rather than replacing the contents of the form.

Change this:

$form['wrapper'] = array("#markup" => "

");

To this:

$form["#prefix"] = "
";
$form["#suffix"] => "
";

This will wrap your form in the #status div.


Which type of entity should I use for editable homepage content? I have a set of social media links that I want to display in both the header and the footer, but I don't know where to put this content so that it is easily editable by users.

Right now I am using Panels and Views, but the links would be in the page.tpl.php, which has the header and footer areas.

I am thinking I could make a block, but it looks like you need to know the ID of a block to render it.

Is there a way to add a node, block, content pane, or mini panel and render it inside page.tpl.php?

Sure, there are modules that let you setup "blocks" of service badge/icon widgets for like Twitter, FB, YT, etc.

Look at Widgets, Social Media and Service Links modules.

I've used Social Media (which relies on Widgets) to put a block of badges on most pages via Context. And also to create other badge collection tokens that i've used within Footer blocks and embedded into WYSIWYG entries to show a FB link on the homepage for instance, or a mini-block of service links on a newsletter.


How to list all url of contents? I have so many content type like article, contribution, event, c_program etc.

For all content url alias is,

[site_name]/[content type name]/title

But we have some url alias that are like this,

[site name]/title

So, I want to list all url of,

[site name]/title format

How I can I list them out?

Use Drupal Pathauto

After enabling it go to admin/config/search/path/patterns and under Default path pattern (applies to all content types with blank patterns below) fieldset you'll get what you want.

Add your desired format there:

[site:name]/[node:title]

Once the configuration is done, click on admin/config/search/path/update_bulk and select Content paths from the given options.


Similar entries 7.x-2.0 known error When I try the view for out-of-the-box use that comes with Similar entries 7.x-2.0 i get this error:

Strict warning: Declaration of similar_handler_argument_nid::query() should be compatible with that of views_handler_argument_numeric::query() in require_once() (line 11 of C:\xampp\htdocs\drupal\sites\all\modules\similar\views\similar_handler_argument_nid.inc).

I searched drupal.org and found someone with the same problem: http://drupal.org/node/1270404
with no answer since September so I decided to try here.

I have tried the beta1 and dev version, run cron, tried to find some tutorial on how to use the module, read the readme for the module and had no luck. Am I missing something obvious?

I also get the error:

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'score' in 'order clause'

This is not you, it is a bug in the module. I'm sorry to say that the fact that the bug goes back to September does not bode well for a fix.  Neither does the fact that there is only one active maintainer who has not made any changes since the releases in August.  If you are a coder, you might try fixing the code.  If not, you may want to look for other options.


Reset boost cache in a busy site without crash We are having a high traffic Drupal 6.x site (25,000) uniques per day, mostly landing pages.

Everythings works OK, with great performance, until we try to reset the boost cache.

Once we reset it, Drupal tries to regenerate HTML from PHP and MYSQL, and we reach a performance crisis where the site crawls and becomes unusable due to slow performance.

Is there a better solution? I imagine there could be a script which clears cache slowly, resets files one by one, wait(10 seconds), wget the url, and then go to the next url.

More info added (edits):

The site has about 20,000 nodes.
We have two Linode 4096 machines: 4 GB RAM, 8 CPU (4x priority), 192 GB Storage, 8 TB Transfer each. Only one of them stores MySQL.
The reason we do manual purge is because when Boost purges pages by itself, we can get to a point where a lot of pages are not in the cache. This can cause a big performance hit.
When the server is too busy, PHP returns WSOD and then Boost caches it! So we get a page, in cache that is actually WSOD!!! Since this is a critical problem, we decided to affectively disable Boost from purging cache on it own and do it On Demand.
Why clear the boost cache? The CSS and JS files are global. If we change the CSS, or add some JS, then we "drush cc css-js" to load the new changes. Doing that, the CSS/JS files are deleted and we are left with cached HTML pointing to non-existing CSS/JS files. So we get "broken" pages. The solution is to refresh the Boost cache.

Will the advagg module help?

Any other solutions?

Pleae advise.

Here is the script that does the job:

<?php

/* function to list all relevant HTML files in a given directory */
function ListIn($dir, $prefix = '') {
  $dir = rtrim($dir, '\\/');
  $result = array();

    foreach (scandir($dir) as $f) {
      if ($f !== '.' and $f !== '..') {
        if (is_dir("$dir/$f")) {
          $result = array_merge($result, ListIn("$dir/$f", "$prefix$f/"));
        } else {
          if (stripos($f,".gz") === FALSE) {
            $result[] = $prefix.$f;
          }
        }
      }
    }

  return $result;
}

/* main function */
function go() {
  $isToNotify = false;
  // get all relevant HTML files, recursively
  $files = ListIn('/var/www/drupal_site/cache/normal/my.domain.com','');
  foreach($files as $file) {
    // save filename for later
    $filename = str_replace("_.html","",$file);
    // normalize path to file
    $file = "/var/www/drupal_site/cache/normal/my.domain.com/" . $file;
    echo "\n************************************\n\nChecking $file" . "...\n\n";
    // get HTML from file into string variable
    $html = file_get_contents($file);
    // create DOM object for easy parsing
    $dom = new DOMDocument;
    $dom->loadHTML($html);
    // get all <link> tags
    $links = $dom->getElementsByTagName("link");
    foreach($links as $link) {
      $css = $link->getAttribute('href');
      $css = str_replace("http://my.domain.com","",$css);
      // find only the relevant tags with the CSS file
      if (stripos($css,"css_") !== FALSE) {
        // normalize path to CSS file
        $path = "/var/www/drupal_site" .$css;
        // check if CSS exists
        if (file_exists($path)) {
          echo "The file $path exists\n";
          // no need to do anything else
        }
        else {
          echo "The file $path does not exist\n";
          // set notification ON
          $isToNotify = true;
          // delete HTML with links to not existing CSS file
          unlink("/var/www/drupal_site/cache/normal/my.domain.com/$filename"."_.html");
          unlink("/var/www/drupal_site/cache/normal/my.domain.com/$filename"."_.html.gz");
          // GET the HTML from scratch so Boost will re-cache it
          echo file_get_contents("http://my.domain.com/$filename");
          echo "Adding log entry...\n";
          // log activity
          $content = "\n\n".(date("Y-m-d H:i:s"))."\n    Refreshed HTML: my.domain.com/".$filename."\n    CSS file which was not found: ".$css;
          file_put_contents("/root/scripts/logs/monitorCSS.log",$content,FILE_APPEND);
          echo "Going to sleep for a while ZzZzZz...\n";
          // sleep for a while to avoid bombardment of the server by this script
          sleep(20); // in seconds
          // go to next file - no need to refresh same file more than once (if more than one CSS file was not-found in HTML)
          break;
        }
      }
    }
  }
  if ($isToNotify) {
    // send email notification if needed (we found some missing CSS files)
    mail('my@email.address', 'Monitor CSS Notification', wordwrap("Some missing CSS files discovered - see log file for more info...", 70));
  }
}

// call main function
go();
?>


a function to return the quiz nid There is a template file in the quiz/template/quiz-report-form.tpl.php of Quiz module.
this is the code:

<?php

/**
 * @file
 * Themes the question report
 *
 * Available variables:
 * $form - FAPI array
 *
 * All questions are in form[x] where x is an integer.
 * Useful values:
 * $form[x]['question'] - the question as a FAPI array(usually a form field of type "markup")
 * $form[x]['score'] - the users score on the current question.(FAPI array usually of type "markup" or "textfield")
 * $form[x]['max_score'] - the max score for the current question.(FAPI array of type "value")
 * $form[x]['response'] - the users response, usually a FAPI array of type markup.
 * $form[x]['#is_correct'] - If the users response is correct(boolean)
 * $form[x]['#is_evaluated'] - If the users response has been evaluated(boolean)
 */
// $td_classes = array('quiz-report-odd-td', 'quiz-report-even-td');
// $td_class_i = 0;
$p = drupal_get_path('module', 'quiz') .'/theme/';
$q_image = $p. 'question_bg.png';
?>

<?php print t('Question Results');?>

<?php
foreach ($form as $key => $sub_form):
  if (!is_numeric($key) || isset($sub_form['#no_report'])) continue;
  unset($form[$key]);
  $c_class = ($sub_form['#is_evaluated']) ? ($sub_form['#is_correct']) ? 'q-correct' : 'q-wrong' : 'q-waiting';
  $skipped = $sub_form['#is_skipped'] ? ''. t('(skipped)') .'' : ''?>

      <div class="quiz-report-score-container <?php print $c_class?>">

          <?php print t('Score')?>
        <?php print drupal_render($sub_form['score'])?>
        <?php print t('of') .' '. $sub_form['max_score']['#value']?>
        <?php print '
'. $skipped .''?>

<?php print t('Question')?>:

      <?php print drupal_render($sub_form['question']);?>

<?php print t('Response')?>:

    <?php print drupal_render($sub_form['response']); ?>

    <?php print drupal_render($sub_form['answer_feedback']); ?>

<?php endforeach; ?>

<?php print drupal_render_children($form);?>

Now I want to change this codes and I need a function to return the nid(number of id) of quiz that the user is seeing.
please help me.

Here is a very simple way to get the nid of the node currently being viewed:

$path = current_path();
list($entity_type, $entity_id) = explode('/', $path);

After this, you will have the entity id (the nid in the case of nodes) in the variable $entity_id.


Extending a year range of a popup calendar Good day

Is there a way I can extend a year range of a popup calendar in drupal 7?

Provided you have a Date field, the widget you use is the "Pop-up calendar" and there is no data in the field yet, you can edit the field and it holds the settings as shown below. Increment the ending year in the field settings


Display a Views slideshow only if more than one image I have a content type with an image field that allows multiple values. I have a View that displays the images using Views Slideshow.

If there is only one image added to a node, I just want to display it as a static image. If multiple images have been added, I want to display the slideshow View.

I'm using a Panels Page override for this content type, so I can use a visibility rule for the Views slideshow pane (i.e. only display if number of images > 1). But I'm not sure how to check the image field to see if there is more than one image for the current node?

Am using Drupal 7.

I think you'd have to do some custom coding to get that result. To simplify, you'd have to make a separate field for the single image option.


Pasting into CKEditor creates divs instead of paragraphs I'm working with content owners who think it's a good idea to compose their content in Microsoft Word.  Although I've created a detailed guide for them on how to make this less painful (describing how to format things in meaningful ways in Word, like using header styles instead of just bolding your text to make it look like a header--things that are obvious to anyone who cares about semantic HTML, and that should be obvious to a user of Word who actually cares about quality and precision instead of just spewing words all over the page), they pretty much ignore it and create poorly formatted content, which of course means it just gets worse when copied and pasted into a rich text editor in Drupal.

Since they don't know HTML, and so can't easily fix this horrible formatting in the rich text editor, I've suggested copying it into a text editor (probably Notepad for them) and then pasting it in, and adding the formatting again in the rich text editor.

The problem I'm running into here is that the WYSIWYG module, or else CKEditor itself, creates  elements for each paragraph instead of  elements.  I'm not sure why this is, but it is of course a very bad thing from the points of view of semantic HTML, CSS styling, and any other point of view I can think of.

How can I fix this?  How can I set things up so that plain text which is pasted into the WYSIWYG editor will give me  elements for each paragraph instead of  elements?

I believe this problem is unique to the Chrome browser, i.e. when pasting text directly into the WYSIWYG you get divs instead of paragraphs. In Firefox, for instance, you get paragraphs instead.

One workaround is to use the "Paste as plain text" or "Paste from Word" buttons. This should give you paragraphs instead of div tags.

You could also click the "Source" button and paste the text, then when clicking "Source" again the text should be converted into HTML with paragraphs.


Create configuration storage programmattically for list_string On a paragraph type, I have a field I want to migrate to a new field of type "list_string". To do that in the deployment and like our automatic deployment begin by an update of the database follow by importation of configurations, I want to create the new field programmatically before to do the migration in another hook_update.

I'm using the example of this article https://www.metaltoad.com/blog/programmatically-importing-drupal-8-field-configurations which is perfect except I have a problem because my new field is of type list_string. My configuration for field.storage is:

langcode: fr
status: true
dependencies:
  module:
    - options
    - paragraphs
id: paragraph.field_types_link
field_name: field_types_link
entity_type: paragraph
type: list_string
settings:
  allowed_values:
    -
      value: anchor
      label: Ancre
    -
      value: internal
      label: Interne
    -
      value: external
      label: Externe
  allowed_values_function: ''
module: options
locked: false
cardinality: 1
translatable: true
indexes: {  }
persist_with_no_fields: false
custom_storage: false

When I create my new field based on my configuration file like that:

$field_storage_link = \Drupal::service('config.storage.sync')->read('field.storage.paragraph.field_types_link');

\Drupal::entityTypeManager()->getStorage('field_storage_config')
  ->create($field_storage_link)
  ->save();

I have this error.

  [error]  The configuration property settings.allowed_values.0.label.0 doesn't exist.

If I remove the list of allowed_values, it works and I can add my field to paragraphes bundles but in this case, I'm not able to do my migration properly because the allowed_values of my field are empty and I don't know how to update it programmatically. Someone can explain what's is the problem in my code and how to fix it?

I finish by find what was the problem. When I read the config file, my allowed value are of format:

[
  [
    'value' => 'anchor',
    'label' => 'Anchor'
  ],
  [
    'value' => 'internal',
    'label' => 'Internal'
  ],
  [
    'value' => 'external',
    'label' => 'External'
  ]
]

But the FieldStorageConfig wait a format:

[
  'anchor' => 'Anchor',
  'internal' => 'Internal',
  'external' => 'External'
]

So I add a transformation before to save my new field:

$field_storage_link = \Drupal::service('config.storage.sync')->read('field.storage.paragraph.field_types_link');

$allowed_values_link = [];

foreach($field_storage_link['settings']['allowed_values'] as $value) {
  $allowed_values_link[$value['value']] = $value['label'];
}

$field_storage_link['settings']['allowed_values'] = $allowed_values_link;

\Drupal::entityTypeManager()->getStorage('field_storage_config')
      ->create($field_storage_link)
      ->save();

$field_type_link = \Drupal::service('config.storage.sync')->read('field.field.paragraph.link_tdm.field_types_link');

\Drupal::entityTypeManager()->getStorage('field_config')->create($field_type_link)->save();

It works properly.


Location proximity search using API I have a small number of location nodes with geofields, and need to programmatically get the distance between a location and a zip code.  It would be ideal if I could get a query, or a sort, of my location nodes by proximity to the zip code.  I couldn't easily tell how to do this in the geoPHP module.

In short : Use the Location Distance field in Views.

In detail : Check out the video http://www.youtube.com/watch?v=AxeskzN8BAc


Ajax not working inside hook_field_widget_form() How to make ajax work inside hook_field_widget_form()

    /**
      * Implements hook_field_widget_form().
     */
        function test_field_widget_form($form, &$form_state, $field, $instance, $langcode, $items, $delta, $element) {
      $form_field['autocomplete'] = array(
        '#type' => 'textfield',
        '#title' => 'Tags',
        '#autocomplete_path' => 'taxonomy/autocomplete' . '/' . $field['field_name'],
        '#size' => $instance['widget']['settings']['size'],
        '#maxlength' => 1024,
        '#element_validate' => array('taxonomy_autocomplete_validate'),
        '#prefix' => '
',
        '#suffix' => '
',
      );
      if (isset($form_state['values']['autocomplete'])) {
        $form_field['autocomplete']['#value'] = 'new value';
      }

      $form_field['search_tags'] = array(
        '#type' => 'button',
        '#value' => 'Recommend Tags',
        '#ajax' => array(
          'callback' => 'call_ajax_replace_value',
          'wrapper' => 'subscribers-name',
          'method' => 'replace',
        ),
      );
      $element += $form_field;
      return $element;
    }

    function call_ajax_replace_value($form, &$form_state) {
       return $form['field_tags'][LANGUAGE_NONE][0]['autocomplete'];
    }

How do i update autocomplete textfield value on AJAX callback?

Just assign the value in callback function.

/**
 * Implements hook_field_widget_form().
 */
function test_field_widget_form($form, &$form_state, $field, $instance, $langcode, $items, $delta, $element) {
  $form_field['autocomplete'] = array(
    '#type' => 'textfield',
    '#title' => 'Tags',
    '#autocomplete_path' => 'taxonomy/autocomplete' . '/' . $field['field_name'],
    '#size' => $instance['widget']['settings']['size'],
    '#maxlength' => 1024,
    '#element_validate' => array('taxonomy_autocomplete_validate'),
    '#prefix' => '
',
    '#suffix' => '
',
  );

  $form_field['search_tags'] = array(
    '#type' => 'button',
    '#value' => 'Recommend Tags',
    '#ajax' => array(
      'callback' => 'call_ajax_replace_value',
      'wrapper' => 'subscribers-name',
      'method' => 'replace',
    ),
  );
  $element += $form_field;
  return $element;
}

function call_ajax_replace_value($form, &$form_state) {
  if (isset($form_state['values']['autocomplete'])) {
    $form_field['autocomplete']['#value'] = 'new value';
  }
  return $form['field_tags'][LANGUAGE_NONE][0]['autocomplete'];
}


Make canonical URL in document HEAD absolute I have a requirement to use absolute URLs for the canonical URL element generated by Drupal 8.

hook_page_attachments_alter doesn't seem to have access the HTML element. Is there any other way I can access it?

True, for nodes you can't use hook_page_attachments_alter. You have to use hook_ENTITY_TYPE_view_alter!

And very likely you also find all of them in the end in hook_preprocess_html.

Here's how I got it working:

/**
 * Implements hook_ENTITY_TYPE_view_alter().
 */
function MYMODULE_node_view_alter(array &$build, Drupal\Core\Entity\EntityInterface $entity, \Drupal\Core\Entity\Display\EntityViewDisplayInterface $display) {
  if (isset($build['#attached']['html_head_link'])) {
    foreach ($build['#attached']['html_head_link'] as $key => $head) {
      if ((isset($head[0]['rel']) ? $head[0]['rel'] : FALSE) == 'canonical') {

        $url = \Drupal\Core\Url::fromRoute('<current>', [], ['absolute' => 'true'])
          ->toString();

        $build['#attached']['html_head_link'][$key][0]['href'] = $url;
      }
    }
  };
}

Source: How to remove specific meta-tag from header section of page?

Alternatively you can use Metatag. All you have to do is to set the [node:url:absolute] token into the Canonical URL form field in the Advanced section of the Metatag configuration for all Content.

And only then, all of sudden, they become available to be preprocessed in hook_page_attachments_alter. There I removed their trailing slash which gets added by default.

/**
 * Implements hook_page_attachments_alter().
 */
function MYTHEME/MYMODULE_page_attachments_alter(array &$attachments) {

  // Remove trailing slash from canonicals.
  foreach ($attachments['#attached']['html_head'] as $key => $head) {

    if ((isset($head[1]) ? $head[1] : FALSE) == 'canonical_url') {

      $href = isset($head[0]['#attributes']['href']) ? $head[0]['#attributes']['href'] : FALSE;

      if ($href) {
        $attachments['#attached']['html_head'][$key][0]['#attributes']['href'] = rtrim($href, '/');
      }
    }
  }
}


How to have two view panes in one Panel, so that selecting a node title in View A displays the content for that node in View B? Do I HAVE to use AJAX? I have been playing around with view panes, panels and context, and am struggling to find the best approach for the below:

I have a Panel which, say, is my Home Page and contains various elements.
Inside that panel, in a certain area, I wish to have Two View Panes
View Pane A - Contains, say, a list of node titles
View Pane B - Upon selecting a node title in View Pane A, I want View Pane B to display the content for that node

(My implementation uses Video Titles in Pane A which should display the relevant Videos in Pane B)

Current Approach:

Panel is set with URL: homePage/%currentVideo
In Page Manager, %currentVideo argument is configured to be assigned to the context Node:ID
View Pane B has a contextual filter of Node:ID
View Pane B has the Content ID from the Node assigned as the context for Argument Input
When adding View Pane B to the Panel, I set the contextual filter to get it's input from %currentVideo
View Pane A lists all the titles, and Rewrites the titles to a link that points to homePage/[nid] -- where [nid] is the input for the currentVideo

This works but I would ideally like to do this without using Arguments in the URL, since I want there to be several such Pane A/Pane B combinations on a home page, where selecting something in Pane A outputs content in Pane B. Therefore, the URL would just be /homePage, and wouldn't be used to pass arguments in/out in order to facilitate such a process.

Questions:

Do I need to use Ajax? If so, - could someone suggest how the above process is best implemented?
Or is there another approach using views, view panes, context and panels, that allows selection in one View Pane to trigger output in another View Pane within the same Page/Panel? (I'm not averse to re-loading the page, I just don't want to have to stuff multiple arguments in the URL as I feel it will get unmanageable over time.)

I have found an tried this Excellent tutorial on writing a module to implement an Ajax Callback, but am sure-ish that it could be all done within Views/Panels...

"Creating a Simple AJAX Interface with Views" : http://mrkadin.com/blog/node/70

Many Thanks in advance

There is sort of a hackish way to implement such behavior, described on this answer: https://stackoverflow.com/a/1596756/1421920

In short, the answer suggests two displays of the same view, one with the titles on the left with exposed filters (hidden by CSS) and the other one with the acutal content of the nodes. Add JS to the titles to fill the other view's exposed filter (also hidden by CSS) and submit. The relevant node loads on the second view with AJAX.


How to show main menu links based on user roles? I am showing menu items and I want to show some links to Anonymous user only and some links to Authenticate user.

It it possible to accomplish this in Drupal 7? If so how?

Meet Menu Per Role Module

  This module allows you to restrict access to menu items1 based on user
  roles. It depends on the Drupal core menu.module—just activate both
  modules and edit a menu item as usual.


How can I allow users to add a reason for a flag? I have the Flag module installed on my Drupal 7.8 site, but I can't figure out how to allow users to submit a reason for a flag along with the flag. I've tried looking this up, but the only thing I could find was the Flag Note module, which is only compatible with earlier versions of Drupal. What I want to have happen is:

User goes to a node, and notices it's not accurate
User clicks the "Report inaccuracy" button, and some sort of text field pops down below it
User fills out reason it's inaccurate, and submits it
Then I can have it be displayed in some stylized div at the top of the page when anybody visits it, similar to the Wikipedia sort of tagging wiki pages thing.

Does anyone know how I could do this? If there's a module that will let me implement the Wikipedia page tagging style of thing without needing a "flag note", that would work perfectly too.

Thanks!

There is a really good discussion about something like this at http://drupal.org/node/871064.  It will take some patching and such but there seems to be a semi-working version available.

Other than that, it doesn't look like there is anything else readily available for Drupal 7 at the moment.


How to know user submitted first content of a specific type? I used Rules module to know when a user has logged in and notify the user about his/her login event.

Now I just want to check when the user has submitted a content of one specific type for the first time, so I just can understand when the user has submitted his/her first content of a speccific content type!

How can I modify my rule in Rules to implement this?

While given answer works great, there are usually a variety of different methods to achieve your goals, one solution could be usage of a combination of Views and Views Bulk Operations (VBO) modules to achieve that

Create a view containing nodes of your desired type
Add a contextual filter and limits results to nodes written by logged in user
add a VBO view mode
in rules you can load a VBO items (check how)
Now if array is empty, created node is the first node of that type which the user has submitted

You also might do all the job with Rules, if you don't want this feature for many content types you can add a Boolean field to the user's account with default value of 'False' indicating if user has written his/her first content of desired type, then on node submit event you can check this field to recognize if this post is his/her first post of that type or not. Remember to set this field to True after submission of first content of desired type.

  The above approach saves some processing cause needs no query as it
  calculated once and used many times

You also can write a custom rules event (API), containing a query on nodes table with condition node.uid == user->uid and node.type == "TYPE_MACHINE_NAME", then if query is not empty, that means user has already submitted a content of that type. so return False.


Theme Upgrade for an existing D7 site - block and config management Working on developing a new Bootstrap theme for an existing D7 site.
How can I make sure that the blocks are assigned to specific regions when the new theme is installed.

Because I would be working in Dev where the theme config would be stored.(cannot update the prod db from dev).

Would really appreciate your inputs.

Thanks!

You need to ensure that your new theme has the same regions defined in the info file as the current theme, otherwise the blocks will lose their assignment when the new theme is installed. The blocks are assigned in the database and they will stay assigned to those regions, as long as those regions are available.


drupal 7 Ubercart recurring fee settings tab is blank I get an error
on my screen There are no payment methods configured for orders with recurring fees, enable one from recurring fee admin settings.

I then go to the link
cart/checkout#overlay=admin/store/settings/products/edit/features

Next i try and choose the Reccuring fee settings tab but it is completely blank.

Version of UC Recurring Payments and Subscriptions module is 7.x-2.0-alpha3

I am wondering if down grade will that fix the problem.

You may have to enable the module "Recurring - Hosted Gateways". This should be available under section "UBERCART - RECURRING" in the path admin/modules. In my case this is Paypal WPS.

Once the module is enabled you can see the option at admin/store/settings/recurring. You may also need to enable the required payment methods at admin/store/settings/payment.


How do I get the administrator to automatically flag? I created a module for flagging entities automatically when created or updated.
There are some errors in my code because only nodes work.
If a user "user1" creates a node, the flag will be in his name. I want the flag to be done automatically on behalf of the site administrator.
How do I get the administrator to automatically flag?
use Drupal\flag\FlaggingInterface;
use Drupal\Core\Entity\ContentEntityBase;
use Drupal\user\Entity\User;
use Drupal\commerce_store\Entity\Store;
use Drupal\commerce_product\Entity\Product;
use Drupal\group\Entity\Group;
use Drupal\node\Entity\Node;
use Drupal\comment\Entity\Comment;

/**
 * Flag node.
 */
function admin_task_notify_node_update(Node $node) {
    $flag_id = 'moderate_node';
    $flag_service = \Drupal::service('flag');
    $flag = $flag_service->getFlagById($flag_id);
    $flag_service->flag($flag, $node);
}

FlagServiceInterface::flag takes an $account argument:

The account of the user flagging the entity. If not given, the current user is used.

So for example:
$flag_id = 'moderate_node';
$flag_service = \Drupal::service('flag');
$flag = $flag_service->getFlagById($flag_id);
$account = \Drupal\user\Entity\User::load(1);
$flag_service->flag($flag, $node, $account);


Render a menu differently based on region I use Drupal 7 and I’d like to have two menus rendered different: one in the nav bar showing dropdowns links for child pages, and another that simply lays out all links in the sidebar. While I can get this sidebar functionality by targeting a specific menu name, I’d like to apply these rules more generally by targeting any menu that gets placed into the region. Is it possible to select regions in theme_menu_link?
Also open to the idea that I’m totally off on my approach for this.

You can add template suggestions. Because menus don't know their region, you first have to add a helper variable in block preprocessing:

function YOURTHEME_preprocess_block(array &$variables) {
  if (!empty($variables['elements']['#id'])) {
    $variables['content']['#attributes']['data-block-id'] = $variables['elements']['#id'];
  }
}

After that you can alter the menu template suggestions

function YOURTHEME_theme_suggestions_menu_alter(array &$suggestions, array $variables) {
  if (isset($variables['attributes']['data-block-id'])) {
    $block = \Drupal\block\Entity\Block::load($variables['attributes']['data-block-id']);
    if ($block) {
      array_unshift($suggestions, 'menu__' . str_replace('-', '_', $block->getRegion()));
    }
  }
}

Now you can use twig templates like menu__REGIONNAME.html.twig for all menus in a given region.


Media library duplicating results view in ckeditor After numerous problems on a certain website I tried a bare bones fresh install of drupal 7.5 on a subdomain with nothing but the medial library and its dependencies as well as all modules required to put the media library in the CKeditor and what I got was a brand new media library failure not yet seen...

Anyone know why the modal popup repeats the results view multiple times? 3 to be exact but you can only see 2 in this image. I followed the instructions on all components to get this far but the never ending failure of drupal continues to plague me.

update

I hadn't noticed before because of the baffling behavior, but it turns out I can't even select media from any of these repeating views. If I click one and hit submit it just returns me to the node, not updated. Right inside the modal box.

Another note, the views for media library include 3 different views - "media browser" "my files" and "media library" and if I disable any of them they do indeed disappear from the popup, which I could live with if any of the remaining views actually did anything. I applaud the champions who wrote this.

Final Update

With Kevin's help we figured it out. Basically we had to run with wysiwyg module, and use the manual install of ckeditor v 3.5.3 - between those 2 and all the configurations standard to drupal the wysiwyg media library finally works. I guess this makes sense since drupal 8 came out some people may have just not cared to keep the 7x modules stable. Or maybe I'm an idiot and following the step by step instructions on the latest media library module for 7x was just too complicated... but for all of us stuck in the nightmare of drupal, here's one option.

This is a shot in the dark, but are you running jQuery Update module? If not, you should give it a try and set the admin area to use jQuery 1.7. Drupal 7 core shipped with jQuery 1.4, and some modules evolved to needing a newer version of jQuery. jQuery Update will solve that for you.

https://www.drupal.org/project/jquery_update


subfolder installation user block login and destination issue I have installed drupal 6.22(fresh installation) on my localhost in which i have set user block on header. Now my problem is when i looked to action of user login form, here i can see my folder name is there.

Say My url : http://localhost/drupal6/

So i can find my form action : /drupal6/node/85?destination=node%2F85

Now after login my url becomes http://localhost/drupal6//drupal6/node/85?destination=node%2F85 and I got page not found error.

And that actually creates issue on redirection.

I want to mention that i have installed 6.22 cause we need to make changes to older version. TIA. What could be the actual reason? Do I need to create a custom user login block for the same? or any issue in url function though i have not changed core files or not added any custom login module. My active theme is garland.

Edit:

Without login go to "http://localhost/drupal6/admin/settings/site-information", It shows access denied message then login using your account and you will face page not found error.

Cause in browser its showing me "http://localhost/drupal6//drupal6/admin/settings/site-information?destination=admin%2Fsettings%2Fsite-information".

Just try out in your any setup on localhost or on subdomain installation. Its not working as expected.

After login url should be "http://localhost/drupal6/admin/settings/site-information?destination=admin%2Fsettings%2Fsite-information" instead page not found. TIA

EDIT : MOD-Rewrite

Finally i found the issue of redirection. I have checked form.inc file from where i have found that drupal_goto function from common.inc file is called.

Now by debugging that form.inc i found that drupal_redirect_form calls drupal_goto with different options. In subfolder case (i.e. my case) drupal_goto function i have found that $path has value like '/drupal6/' default. So what i have hacked is

$folder_name = '/drupal6/';
$length = strlen($folder_name);
$path_check = substr($path,0,$length);
$path_len = strlen($path);
$remaining_path = '';

if($path_check == $folder_name) {
    $remaining_path = substr($path,$length,$path_len);
    echo $path = $remaining_path;
}

So now my problem of adding two folder name like 'http://localhost/drupal6//drupal6/admin/settings/site-information?destination=admin%2Fsettings%2Fsite-information/' have been solved but as you know that this is core hack and i dont like it. Any better solution???

I know that if i transfer this site from my localhost to internet than that would not create any problem without making this kind of small hacks.


Converting MySQL to db_select with subquery count I have an SQL query, with subquery, that returns as set of nodes ordered by referenced nodes... It works fine in a db_query, but I need it to be dynamic, and it feels like a better idea to use Drupal's abstraction layer.

I have got so far, but I am having issues with the subquery. It doesn't appear to having any effect...

I should say I used the Query Coder module to help do the conversion.

SQL:

SELECT n.nid , dest.field_flight_hero_destination_tid  hero_desintation_tid , (
SELECT COUNT( * )
FROM {field_data_field_field_route_matrix} routes
LEFT JOIN  {field_data_field_flight_destination} destination ON routes.field_field_route_matrix_target_id = destination.entity_id
WHERE routes.entity_id = n.nid
AND  field_flight_destination_tid
IN (:stopovers_tids)
)total
FROM node n
LEFT JOIN  field_data_field_flight_hero_destination dest ON n.nid = dest.entity_id
LEFT JOIN field_data_field_flight_price_matrix prices ON n.nid = prices.entity_id
LEFT JOIN field_data_field_flight_cabin_class class ON n.nid = class.entity_id
WHERE dest.field_flight_hero_destination_tid = :destination_tid AND class.field_flight_cabin_class_tid IN (:class_tid)
ORDER BY total DESC

db_select:

// Subquery.
  $subquery  = db_select('{field_data_field_field_route_matrix}', 'routes');
  $subquery->addExpression('COUNT(*)', 'count');
  $subquery->leftJoin('{field_data_field_flight_destination}', 'destination', 'routes.field_field_route_matrix_target_id = destination.entity_id');
  $subquery->condition('routes.entity_id', 'n.nid');
  $subquery->condition('field_flight_destination_tid', $stopovers);

  // Main query sorted by subquery.
  $query = db_select('node', 'n');
  $query->fields('n', array('nid'));
  $query->fields('dest', array('field_flight_hero_destination_tid'));
  $query->addJoin('', $subquery, 'total');
  $query->leftJoin('field_data_field_flight_hero_destination', 'dest', 'n.nid = dest.entity_id');
  $query->leftJoin('field_data_field_flight_price_matrix', 'prices', 'n.nid = prices.entity_id');
  $query->leftJoin('field_data_field_flight_cabin_class', 'class', 'n.nid = class.entity_id');
  $query->condition('dest.field_flight_hero_destination_tid', $destination);
  if (!empty($cabin_class)) {
    $query->condition('class.field_flight_cabin_class_tid', array($cabin_class), 'IN');
  }
$query->orderBy('total.count', 'DESC');
$result = $query->execute();

Generated output:

[queryString] => SELECT n.nid AS nid, dest.field_flight_hero_destination_tid AS field_flight_hero_destination_tid
FROM
node n
 JOIN (SELECT COUNT(*) AS count
FROM
field_data_field_field_route_matrix routes
LEFT OUTER JOIN field_data_field_flight_destination destination ON routes.field_field_route_matrix_target_id = destination.entity_id
WHERE  (routes.entity_id = :db_condition_placeholder_1) AND (field_flight_destination_tid IN  (:db_condition_placeholder_2)) ) total
LEFT OUTER JOIN field_data_field_flight_hero_destination dest ON n.nid = dest.entity_id
LEFT OUTER JOIN field_data_field_flight_price_matrix prices ON n.nid = prices.entity_id
WHERE  (dest.field_flight_hero_destination_tid = :db_condition_placeholder_0)
ORDER BY total.count DESC
)

Devel dpq:

SELECT n.nid AS nid, dest.field_flight_hero_destination_tid AS field_flight_hero_destination_tid
FROM
{node} n
 JOIN (SELECT COUNT(*) AS count
FROM
{field_data_field_field_route_matrix} routes
LEFT OUTER JOIN {field_data_field_flight_destination} destination ON routes.field_field_route_matrix_target_id = destination.entity_id
WHERE  (routes.entity_id = 'n.nid') AND (field_flight_destination_tid IN  ('31', '366')) ) total
LEFT OUTER JOIN {field_data_field_flight_hero_destination} dest ON n.nid = dest.entity_id
LEFT OUTER JOIN {field_data_field_flight_price_matrix} prices ON n.nid = prices.entity_id
WHERE  (dest.field_flight_hero_destination_tid = '86')
ORDER BY total.count DESC

Your adding the subquery via a join. you want the subquery to be run as piece of the outermost Select statement, which Drupal 7 SelectQuery cannot do see:

https://stackoverflow.com/questions/20214014/how-do-i-place-a-sub-query-in-a-select-statement-in-drupal7

The easiest way to do this to use db_query (a string) or maybe hook_query_alter after adding a tag to the db_select query and adding in the subquery via a string  later. If you need additional info passed in and out the hook_query_alter then use the metadata options.


modify submit on user login so that only admins can log in through this route I have written a hook form alter which adds a submit action but I get this error

  Recoverable fatal error: Argument 2 passed to xxx_form_submit() must be an instance of FormStateInterface, instance of Drupal\Core\Form\FormState given in xxx_form_submit()

the code is like this

function xxx_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {

 if ($form_id=='user_login_form') {

    $form['actions']['submit']['#submit'][] = 'xxx_form_submit';
  }
}

function xxx_form_submit ($form, FormStateInterface  $form_state) {
  $username=$form_state->getValue('name'));
}

You are getting this because you did not include the use statement at the top of your file:

use Drupal\Core\Form\FormStateInterface;

function xxx_form_alter(&$form, FormStateInterface $form_state, $form_id) {

 if ($form_id=='user_login_form') {

    $form['actions']['submit']['#submit'][] = 'xxx_form_submit';
  }
}

You can use the full path, but it is preferred for developers to do use statements.


Creating Related Content views I have watched and read quite a few guides/tutorials on this subject and they each leave me with a blank block.

I am trying to create a related content module.  My content is tagged with multiple terms.

I go and create a block view and go to contextual filters.  I add the content: has taxonomy term ID.  Then I add the "Taxonomy term ID from URL", slect the correct vocabulary, filter to items that share any term, click reduce duplicates and click apply.

Then I create the content:nid contestual filter and the block wont appear.

I have pathauto installed and I have a feeling it might be an issue with that.  I cannot use the term id in my content paths.

I have been at this for a while.  Any help on what I am doing wrong is greatly appreciated.

Pathauto module doesn't have to do anything with this view. I think you are not supplying any default value to contextual filters used in your block type of view.

For creating the related content view, please try following steps

Create a Block type of display.

Add Contextual filter for the taxonomy term -> goto settings of this filter -> select "default value" -> select "taxonomy term id from url" -> select limit by vocabulary -> select "vocabulary" -> select appropriate option from "Multiple-value handling" -> expand "more" fieldset and set allow multiple values.
Enable Aggregation settings, and add the same taxonomy field in sort criteria and from aggregation settings select "COUNT DISTINCT"
Add "Nid" as contextual filter -> go to settings -> select "default value" -> select "Content Id from URL" -> From "more" fieldset -> select "Exclude" - now results will not show the current node.

Place this block now on your node page, and this block will list all the related content.


Where do you edit the css of a basic bootstrap theme in Drupal 7? I've download the latest release of the original Bootstrap theme for Drupal 7, and Installed it, and yet it is unclear to me where could I change it's css?

I need to RTLize the template, i.e make it RTL instead of the default LTR, and for this I need to flip some properties in the template's Style.css file (or whatever main css file) of this template as I did in the past with almost any other template...

I tired to search a bit in the theme's folder and just couldn't find such file... The following image display my navigation (at least the most logical part of it):

Bootstrap for Drupal 7 requires a lot more setting up than ordinary themes.  Make sure you read and follow the instructions about installing and sub-theming Bootstrap.

If you intend to change the CSS, it is strongly recommended that you create a sub-theme with all the Bootstrap 3 source files. This method is the most dynamic and will grant you the ability to change the variables and utilize the mixins provided by Bootstrap. It entails downloading and extracting the latest Bootstrap source into your sub-theme and place it in a folder named boostrap. Note that you will need to uncomment the lines under "METHOD 1: Bootstrap Source" in your sub-theme's .info-file if you want to use this method for sub-theming.

If you've done all this correctly, the folder structure of your sub-theme (here called my_bootstrap) should look like this:

Bootstrap CSS is generated by means of the CSS preprocessor less, so you do not edit the CSS directly.  Instead look up the file my_bootstrap/less/overrides.less.  You add your CSS overrides to this file.  Then, to make your overrides effective, you can compile the file less/style.less (which includes overrides.less) to CSS with this CLI command (provided you're in the my_bootstrap root directory).

lessc less/style.less > css/style.css

If you want a simpler, but less flexible method, you may use a Bootstrap CDN.  It utilizes CDN Bootstrap via the base theme, but will still allow you to override the existing CSS styling in the sub-theme.

If you choose the CDN method, to override the default Bootstrap base theme settings, you copy the settings you want to change from the base theme into the sub-theme's .info-file. To override CSS, you edit the provided css/style.css with your own overrides.

As always, after changing the CSS, remember to clear the cache to make your changes effective.


How to access a field of a referenced entity in a computed field? I would like to access a field of a referenced entity in a computed field.

For example: The content type A contains an entity reference field referencing the content type B; B has a "price" field. A has a computed field as well. In this field I would like to load the value of the "price" field from the referenced node.

How can I achieve this?

Only, you have to add a Condition (in 'Elements') to the rule of the class "Entity has field", and then a whole bunch of the referenced fields of the entity will appear and will be available.

You'll have to create another Component to call it and add it another Condition of "Entity has field" of the same bundle you want to access.


How can I remove "Show row weights" as well as the weight column in D7? This answer shows how to remove the "Show row weights" text from a form. However, as the comment to this answer suggests, it doesn't remove the weight column as well.

How can I update the following code to also remove the weight column from my form?

<?php
/**
 * Implements hook_js_alter().
 */
function MODULENAME_js_alter(&$javascript) {
  unset($javascript['misc/tabledrag.js']);
}
?>

Or, is there a better way to do this? This seems like a hacked way of removing the row weights.

If you do not want to display those elements because it confuses users, you could simply hide them with CSS. Use Firebug or something alike to determine the correct classes in order to adapt the code underneath.

#YOUR-FORM-ID .tabledrag-toggle-weight-wrapper,
#YOUR-FORM-ID .field-multiple-drag {
  display: none;
}


Do I need to run Captcha and Mollom simultaneously? Just wondering if I have Mollom installed and running successfully on a D7 site, if I still need to keep Captcha enabled?

I'm getting double captcha forms with both enabled.

If you're satisfied with the Mollom module, then I don't think it makes sense to also leave the Captcha module enabled/installed.

However, if you're looking for some kind of extra protection/layer but without those double captcha forms, then you may want to consider replacing Captcha with the Honeypot module. Because of the technique used by Honeypot, you don't risk to have double captcha forms in that case.

Some more details about the Honeypot module (from its project page):

  ... uses both the honeypot and timestamp methods of deterring spam bots from completing forms on your Drupal site (read more here). These methods are effective against many spam bots, and are not as intrusive as CAPTCHAs or other methods which Punish the user.

Note: even if you don't want to consider using the Honeypot module (for whatever reason), keep "the message" in mind about what that link quoted from its project page (Punish the user) is trying to explain whenever your researching similar modules.


In D7 how do I get JUST the value of a field in a view field template? This is at the top of the template file:

/**
 * @file
 * Default simple view template to all the fields as a row.
 *
 * - $view: The view in use.
 * - $fields: an array of $field objects. Each one contains:
 *   - $field->content: The output of the field.
 *   - $field->raw: The raw data for the field, if it exists. This is NOT output safe.
 *   - $field->class: The safe class id to use.
 *   - $field->handler: The Views field handler object controlling this field. Do not use
 *     var_export to dump this object, as it can't handle the recursion.
 *   - $field->inline: Whether or not the field should be inline.
 *   - $field->inline_html: either div or span based on the above flag.
 *   - $field->wrapper_prefix: A complete wrapper containing the inline_html to use.
 *   - $field->wrapper_suffix: The closing tag for the wrapper.
 *   - $field->separator: an optional separator that may appear before a field.
 *   - $field->label: The wrap label text to use.
 *   - $field->label_html: The full HTML of the label to use including
 *     configured element type.
 * - $row: The raw result object from the query, with all data it fetched.
 *
 * @ingroup views_templates
 */

I was hoping "raw" was just the value in the field, but I think it's the entity id. PLEASE tell me there is a straight-forward way to get just the value of the field from this template!

Thanks!

If you have devel installed then add dpm($field); to the template and see if the field array contains the value itself (if I remember right - it isn't). The second step (if the field array doesn't contain the value) will be to use dpm($view); ,and in the view array you have the value for sure (I think it is something like $view->$row['field_name'][0]['value'] )


is there any way to implement java into drupal? I am a programmer, I primarily program in java, but I am now working with drupal. drupal uses html and css for most of its design, from blocks to views. but I have discovered that it is much harder to create things that are dynamically designed. what I am used to is designing things in android programming where you use XML to design the layout, and java to control it. is there any way to do this in drupal (using a module or something of the sort that will allow me to create things like blocks using java or even javascript, or something similar). also, is there a way to develop my own modules using java, or can I only do it in PHP?

Drupal is a PHP web framework. The tools that is uses are those of the web. If you are trying to implement something with XML and Java you are not really using Drupal. There are skills that you have to learn in order to create web pages which are different from those on a phone.

Having said that. I believe that there are some Android front ends for Drupal. That may be a good starting point for you.


Why don't calls to drupal_set_message() show up after a drupal_goto()? My question is similar to How to  redirect the user to a  page and show a message on the admin overlay (using drupal_set_message and drupal_goto), but I'm not doing an overlay -- it's just a straight page.  This issue has been talked around a bit on this site, but I've never seen a real resolution of it.

My situation is:

The user submits a form, through the usual method.
The form has a _submit() handler, which runs: it does some stuff,
sets a drupal_set_message(), and then redirects somewhere via
drupal_goto().
The user properly ends up on the intended page, but the message is
nowhere to be seen.

Any clues on this?  I really can't figure out why this is happening.

I tried in my test site, and the message appears, even using drupal_goto(). I used the following code.

function code_testing_date_form($form, &$form_state) {
  $form['expire'] = array(
    '#type' => 'date_select',
    '#title' => t('Expire Date'),
    '#default_value' => date('Y-m-d H:i:s'),
    '#date_format' => 'Y-H:s',
    '#date_year_range' => '0:+20',
    '#required' => TRUE,
  );

  $form['weight'] = array(
    '#type' => 'weight',
    '#title' => t('Weight'),
    '#description' => t('Optional. In the menu, the heavier items will sink and the lighter items will be positioned nearer the top.'),
    '#default_value' => 5,
    '#delta' => 10,
    '#access' => FALSE,
  );

  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Submit'),
  );

  return $form;
}

function code_testing_date_form_submit($form, &$form_state) {
  drupal_set_message('You have been redirected.');
  drupal_goto('user');
}

What could cause the issue you are seeing could be:

There is code that clears the content of $_SESSION['messages'], used to contain the messages set with drupal_set_message().
There is code that invalidate the current session. In this case, the logged-in user should be logged out.
You are rendering the form in a template file.
The template file for the page to which the users are redirected doesn't have code to handle the $messages variable. The default node.tpl.php file contains the following code; if the template doesn't print $messages, the messages set with drupal_set_message() will be not seen.

<?php if ($breadcrumb): ?>

<?php print $breadcrumb; ?>

<?php endif; ?>
<?php print $messages; ?>


How to display a block to a specific user? I need to display a block just to a specific user.
I don't want to create a role just for a user. that does not make sense!

I would implement hook_block_view_alter() and remove the block's content when the uid is not the user you were aiming at. In this example we only show the block content for uid 2.

function hook_block_view_alter(&$data, $block) {

   if ($block->module == 'somemMdule' && $block->delta == 'someDelta') {
         global $user;

    if ($user->uid != 2) {
       $data['content'] = array();
    }
  }
}


How to hide all nodes of a particular content type? I have a site that used to run polls, but has stopped doing so.  I'd like to keep the poll nodes in the database, just in case things change in the future, but otherwise hide the nodes.  I guess this means returning a 403 or 404 if someone or a search bot requests the page, so that local users will be unable to see them and bots will eventually remove them from their indices.
I've disabled the poll module and disabled all the user permissions having to do with polls, so no new polls will get created.  However, if someone requests the page via its URL, they get a normally-themed page with the poll's title (but no other content).  I tried marking one of the polls as "not published", which comes pretty close to what I want: a normally-themed 403/access denied page.  This would require my hacking the "published" state of all the poll nodes to "false", which I guess is better than nothing, but I was hoping for a hook function that would produce the same result, but without messing around in the database.  Any advice out there?  Thanks!

Try the Rabbit Hole module:

Rabbit Hole is a module that adds the ability to control what should happen when an entity is being viewed at its own page.
Perhaps you have a content type that never should be displayed on its own page, like an image content type that's displayed in a carousel. Rabbit Hole can prevent this node from being accessible on its own page, through node/xxx.


How do I customize an entity's canonical page? I have an entity called SyncJob and it contains the following fields:

id
progress: integer
total: integer

I need to customize its view page (canonical, not the collections one) to show the following fields of one SyncJob entity:

id
status ('success' if progress == total, '' if progress < total)
percentage: progress / total * 100% as percentage

I have tried adding field plugins and altering views data but these seem only work on the collections view.
Is it possible to achieve these without writing HTML? If so, what kind of files do I need to create or modify?

There are modules you can find that help you do that. Search for "computed field" and similar.
You can then adjust your node form (Manage form display) not to show the computed fields, and on the Manage display page (default view mode is what you call canonical, you can create more of them though) adjust the fields so only the computed ones are shown.
One example: Computed Field


use two formatter for single field in view I want to use two formatter 'url,as plain text' and 'count the click happened on this link' for single field in view page

One way to use two formatter for single field in view is

Add same field two times in view.
Set different field formatter.
Exclude from display.
Add " Global: Custom text ".
Go to Rewrite results of " Global: Custom text ".
Use Replacement patterns to show that two fields.

How to add Global: Custom text?

For count the click you need to some js coding.


FAPI initial checked state for #type => radio Drupal FAPI reference doesn't have a working example for #type=>radio.  How can I indicate that I want the element to be rendered in a checked state?

$form['my_radio_button'] = array(
  '#type' => 'radio',
  '#default_value' => TRUE,
  '#title' => t('Checked by default.'),
);

I've tried #default_value TRUE, 1, and different combinations of #value, but nothing seems to work.  Thanks!

I may be totally remembering this wrong,  but I'm pretty sure you want to add "checked" as an attribute.
attributes => array("checked")


Is it safe to purge the /files/styles directory? I use Image Styles to automatically generate thumbnails (for teasers and views). I have a lot of images, so I end up with a lot of cached thumbnails in the /files/styles directory.

Is it safe to delete the contents of /files/styles without doing anything like clearing the cache in Drupal? My hope is that the thumbnails would be regenerated as needed without issue.

Yes, it's perfectly safe to delete the files/styles directory: Drupal will regenerate the images the next time someone attempts to access it.

The image module defines a menu router item, $directory_path . '/styles/%image_style', that maps to the callback image_style_deliver().

In turn, image_style_deliver() checks to see if the generated derivative image exists: if it does, it serves it. Otherwise, it calls image_style_create_derivative().


Create a print tpl for page views I'm working with print and I would to create a tpl for a specific view (for a "page" display).
Is it possible, using the naming convenction?

I think you can only style the view for print adding in your theme a print css hiding some field with css.

stylesheets[print][] = css/print.css


Add CSS class with hook I have a search box using custom_search module. I am trying to add multiple classes to the input field using a hook.

Here is the code I have tried:

<?php
function mytheme_form_search_block_form_alter(&$form, &$form_state) {
      $form['keys']['#attributes']['class'][] = 'custom_search-keys','form-search','form-control';
    }

But it does not add the classes to the search box input field?

Try this one, add class as array.

$form['keys']['#attributes'] = array('class' => array('custom_search-keys','form-search','form-control'));


LIKE clause not working in hook query alter I'm trying to replace the default search with a LIKE clause in Drupal 7. I tried to alter the query according to Adding an OR condition to an existing query:

function MYMODULE_query_node_access_alter(QueryAlterableInterface $query) {
  foreach ($query->getTables() as $table) {
    // LIKE for search results.
    if ($table['table'] == 'search_index') {
      // Get the query args and then the search term
      $args =& $query->getArguments();
      $search = $args[':db_condition_placeholder_1'];

      // Get a reference to the existing query conditions.
      $conditions =& $query->conditions();

      // Save the former conditions
      $former_conditions = $conditions;

      // Reset the condition array. It needs a default #conjunction for which AND is fine
      $conditions = array('#conjunction' => array_shift($former_conditions));

      // Replace the search condition in the query
      foreach ($former_conditions as $key => $condition) {
        if ($key != 1) {
          $query->condition($condition['field'], $condition['value'], $condition['operator']);
        }
        else {
          $query->condition('i.word', '%' . db_like($search) . '%', 'LIKE');
        }
      }
    }
  }
}

Searching with the word "declaration" displays the same results as the default drupal search, but searching with "decl" doesn't find any results.

Any ideas why my code isn't working?

Have you tried changing the hook you are using to MYMODULE_query_alter?

You are implementing hook_query_TAG_alter(), and I don't see where the Search query is tagged as such.

Per the Node API:

  This is the hook_query_alter() for queries tagged with 'node_access'.
  It adds node access checks for the user account given by the 'account'
  meta-data (or global $user if not provided), for an operation given by
  the 'op' meta-data (or 'view' if not provided; other possible values
  are 'update' and 'delete')


Turn /node off but keep aliases I want my node page turned off.  I don't want mysite/node/3 to work.  I want it to display 404.  I tried rabbit hole and it worked but the problem ws that it also stopped the aliases from working.

Is there a solution where I can turn off the node/whatever but keep my aliases?

I'm guessing you're on drupal 7?

Rather than trying to disable/show a 404 you could install this module:
https://www.drupal.org/project/globalredirect

That will make it so that if anyone tries to access one of the "node/*" urls they will be automatically be redirected to the proper alias of the page. Would that work for what you need?


Upgrading drupal 8 beta3 to beta4 table user__roles not exists When I upgrade my drupal site to beta4 release, it says that table user__roles is not exits.

It's look like that new beta version alter table name from users_roles to user__roles. how is possible to apply this change (How is possible to migrate schema of drupal to latest version).

Thanks.

There is no upgrade path yet.

You could try to alter the table manually, or copy it from a new install, but you will very likely run into other issues as well.


How to implement a store locator? Is it possible to create with something similar to this store locator using Drupal?

Another option is the recently released Google Store Locator module on drupal.org. Some cool features: you can customize the map marker pins to be your own custom icon, and you can make the map 'location aware' which allows the user to share their location with the browser, and the map will re-center and zoom based on their location.


How to debug EntityQuery? I have a query with a 'BETWEEN' operator and I should have some results. Is there any way to show the actual SQL query made ?

Here is my entity query :

    $query = $this->entity_query->get('node');
    $query->condition('type', 'store');
    $query->condition('status', 1);
    if ($lat_min && $lng_min && is_numeric($lat_min) && is_numeric($lng_min) && $lat_max && $lng_max && is_numeric($lat_max) && is_numeric($lng_max)) {
      $query->condition('field_store_geolocation.lat', [$lat_min, $lat_max], 'BETWEEN');
      $query->condition('field_store_geolocation.lng', [$lng_min, $lng_max], 'BETWEEN');
    }
    $nids = $query->execute();

Of course I made sure that my values were the one expected and I also tried with '<', '>' and with no vars but actual values to make sure nothing was wrong there.

I'm using the 'Geolocation Field' module here.

If you use devel module a simple approach for debugging entity query could be use the debug tag (simply add $query->addTag('debug') to your query).
Here an example

$query = $this->entity_query->get('node');
$query->condition('status', NODE_PUBLISHED);
$query->addTag('debug');
$query->execute();

And the result


Deletion of some watchdog messages with subquery What i want is to delete from watchdog the first 20 messages with type as 'blabla' what i did untill now is:

 $query = db_select('watchdog', 'w')
    ->fields('w')
    ->condition('type', 'blabla')
    ->range(0, 250);
  $subquery = $query->execute()->fetchCol('wid');

  if ($subquery != NULL) {

    db_delete('watchdog')
      ->condition('wid', $subquery, 'IN')
      ->execute();
  }

it works fine but i want to do it with subquery like:

$subquery = db_select('watchdog', 'w')
    ->fields('w', array('wid'))
    ->condition('type', 'blabla')
    ->range(0, 250);

  // Deletes the previous selected values.
  db_delete('watchdog')
    ->condition($subquery, 'wid')
    ->execute();

it gives me the error:

General error: 1093 You can't specify target table 'watchdog' for update in FROM clause

Any ideas how to solve this problem?

You were close; this should work for you:

$subquery = db_select('watchdog', 'w')
  ->fields('w', array('wid'))
  ->condition('type', 'blabla')
  ->range(0, 250)
  ->execute()
  ->fetchCol('wid');

// Deletes the previous selected values.
db_delete('watchdog')
  ->condition('wid', $subquery, 'IN')
  ->execute();

You weren't executing the subquery (meaning there were no results), and you mixed up the order of arguments passed to query condition.


How to convert PHP Logic to Views API I am writing a module to convert serialized value stored in database by the Composed Field Module. The serialized value is like:

a:3:{i:1;s:14:"First Subfield";i:2;s:15:"Second Subfield";i:3;s:14:"Third Subfield";}

The PHP Unserialize value of above serialized data returns the following array:

print_r(unserialize('a:3:{i:1;s:14:"First Subfield";i:2;s:15:"Second Subfield";i:3;s:14:"Third Subfield";}'));
Array
(
    [1] => First Subfield
    [2] => Second Subfield
    [3] => Third Subfield
)

I called the Module as composed_views

So far I have made few files like: composed_views.info, composed_views.module,

composed_views_handler_subfields.inc contains:

class composed_views_handler_subfields extends views_handler_field {
  /**
  * Render the unserialized value.
  */
  public function render($values, $index) {
    $uns = unserialize($values) // $values = serialized data from database
    return $this->get_value($uns[$index]); // $index = array index of serialized data
  }
}

In composed_views.views.inc

For eg: The table names are field_one, field_two
The data column are field_one-composed, field_two-composed respectively

I want to Query those tables
and send the serialized data to render function defined in composed_views_handler_subfields.inc file

So, far the structure is like this:

function composed_views_views_data() {
  $data['composed_views_table'] = array();
  // The actual code I am seeking help with
  return $data;
  }

Any help how to do with this with views would be appreciated.

There is some discussion in several places about this, including an issue in the Composed Field issues queue.

The module author writes;

  I haven't investigated the mechanics behind it but theoretically all that needs to be done is to somehow implements the process that those modules do on retrieving the field value from the database and then unserialize and concatenate the retrieved value.

The problem of course with storing serialised data is the inability to effectively query it using any type of relational db (No indexes.)

You can always build a query using a LIKE on the serialised data ...

WHERE field_one-composed LIKE '%query%';

But that's horrible. :(

My comment on the initial question stands; do you want to achieve this using the GUI or through code? I'll update this answer based on your response.

While I appreciate this is not the question, I'm curious about why you chose this module for your use case?


How to set default role in Drupal 6 I have created some user roles in my drupal 6 website.

Have can set one of them as default role when users register in the site?

The Auto Assign Role module will allow this.

It allows you to:

Provide an automatic assignment of roles when a new account is created.
Allow the end user to choose their own role or roles when they create their account.
Provide paths that will trigger a specific role when an account is created.


Edit one field across multiple nodes Is there a way to edit a single field (for example: publication date) across a few dozen nodes?

I added a field called "Publication date" to an existing content type, and now I need to add a date to a whole lot of them. I'd love to have a table display showing the node title, and the field in question next to it in an editable column.

The editable fields module (http://drupal.org/project/editablefields) works well with views.  So you could build a view with node title and this pub date field making the pub date editable.


print result of a node_load() I would like to print the result when calling the node_load() function. All I get is an error... How do I get something on my screen?

Here is the code I try:

$form = node_load(1473);
print render($form);

And the error:

Recoverable fatal error: Object of class stdClass could not be converted to string in include() (line 10 of ...

How can I display the content of $form properly?

You should use the node_view() function to prepare the correct output for your required view mode:

$view_mode = 'teaser'; // Or 'full' for example

$node = node_load(1473);

$view = node_view($node, $view_mode);

print render($view);


How to sort field_info_instances return value by field weight? I'm using field_info_instances() to retrieve the information for all the fields used by a content type, for example calling it as field_info_instances('node','bundle_name').
In the returned array, the fields aren't ordered as I expected. I need to get the fields ordered per weight.
For example, a field weight is 8, in the Manage fields list.

Despite this, it's shown on the top, in the output from field_info_instances().

Is there any possibility to get the fields ordered?

You probably want something like this

$info = field_info_instances('node','bundle_name');

uasort($info, function($a, $b) {
  $a_weight = (is_array($a) && isset($a['widget']['weight'])) ? $a['widget']['weight'] : 0;
  $b_weight = (is_array($b) && isset($b['widget']['weight'])) ? $b['widget']['weight'] : 0;

  if ($a_weight == $b_weight) {
    return 0;
  }

  return ($a_weight < $b_weight) ? -1 : 1;
});

// $info is now sorted by weight.


Can you restrict core search to the current language? I can't figure out how to restrict results to current language other than crude theme preprocess hacks to inspect the language of individual results. I haven't had luck getting contrib search modules that might allow filtering to work.

Can I override the results page with a view and filter there?

With a View you will need to do the following:

Make sure, you have also a second language and content translation is enabled (else you won't able to see the filter we need)
Add Filter Criteria: "Translation language"
And then check the following checkbox: "Interface text language selected for page"

Now this view is only going to list elements, which are available on the current language (and their translated version is going to be listed).


how to create a apply button in view table result ? I have created a view with display format as table
I want to create a button in the last column for every row
So that when user click on that button form then form open.
So how can I create that button for every row

1) On the left side of the Views admin screen, click the "Add" button next to Fields to add a new field

2) Search for "custom field" and select Custom Field

3) For Create a Label, enter: Apply for Job

4) For Text, enter:

Apply for Job

(class="button" is what makes the link look like a button)

5) Replace /link/to/destination above with the location of where they can apply for the job. If you need to use replacements in the URL like the node ID number, add the NID field to the view, and replace the URL with something like /node/[nid]/apply

View attached screenshot for what it should look like.


How to implement facets in Views I'm trying to implement a search function with location in Drupal.

At the moment I have a base setup with a custom Content Type (Discount), which has a Geofield parameter. This gets indexed in Solr with the proper fields, filters and facets.

Then, after this I see there are two options:

One is using directly Search API, which creates a search page with the facets. (Ok, deadly simple and works). Problem: I can't do really strange things like showing stuff on a map.
Use Views with Search API: it is also quite simple and I can show the output in a map (as well as I'm more used to them). However, I don't have any idea on how to implement facets there... I took as a reference this project.

I've tried with both this options and I can make them work properly.

So, my question is, how do I add a map to the Search Page in Search API, or how do I add facets into the Views page. I'd rather prefer views if possible, as I'm trying to setup a system which detects all the Discounts in a certain distance in your area, depending on your geolocated IP.

The only idea I have would be to create a Taxonomy, with which I could tag the Discounts with Country and category, and then use that somehow in the view, but not quite sure on how to do so.

Thanks a lot!

Ok, I answer myself as I realized what I was doing wrong. Just make sure that the facets you are selecting are the indexed facets, so this way they match with the indexed fields you want to filter by.

It works really nice now!


Disable Ajax Views scroll behavior? How can I disable the scroll to top behavior in an Ajax based View? Preferably, with Javascript.

The scroll behavior is triggered when running a search from an Exposed Form.

The solution above is for Drupal 7. In Drupal 8, hook_views_ajax_data_alter is deprecated and was replaced by hook_ajax_render_alter.

For those of you looking for it, here is how to do it in Drupal 8 (source here).

function YOURMODULE_ajax_render_alter(array &$data) {
  foreach ($data as $key => $command) {
    if ($command['command'] === 'viewsScrollTop') {
      unset($data[$key]);
      break;
    }
  }
}


Drupal Commerce Kickstart cloud zoom image not working? I am using Drupal commerce kickstart. I want to show the thumbnail images. I am using custom html theme in my project. How to show the thumbnail image in product page? Please anyone guide to me.I am new to Drupal commerce kickstart.

I would suggest using the following modules (since it basically creates this straight out of the box). Once you customize it you can define how you want hte widgets to appear and essentially create the view as you have outlined above.

Views Slideshow
Views


How to make a rule for limiting one product per cart Can anyone help me?
I want to know how to make a rule for limiting one product per cart. I found rule for limiting qty only but not order item.

I found this with code Drupal Commerce Shopping cart limit
But I want to do it with rule ...

Yes, to restrict to one product per order, add a rule:

Event: before add product to cart,
Action: remove all products from cart.

The effect is existing products are removed and only the latest selected product is added to the cart.


How to prevent the conversion of text URL to link on a single URL? I have a page that I am adding, and for my purposes I want to have a text-only URL without an automatic link, but only for that one link, one this specific page. I need to be able to add full html content to the page, and I would prefer if other URLs on the page automatically became links.

I have tried putting other tags around the URL and HTML-escaping certain characters in the URL, but it still gets converted to a link.

Is there a way to prevent a specific URL from becoming a link?

The only way I think it is possible to selectively disable the "Convert URLs into links" filter is to use CSS and add something like below to the body. Since CSS is applied client-side after Drupal has returned the page, the filter is effectively disabled for this one single link.

blah

Since you are using the 'Full HTML' format, you should be able to add CSS directly into the body field like shown.


Why doesn't my code to save an order work when invoked by AJAX? I am programmatically creating an order in Drupal Commerce. It works perfectly with a user who is logged in, but for anonymous users it redirect to a checkout page and shows a "page not found" message.

$product_id = 1;
$order = commerce_order_new($user->uid, 'checkout_checkout');
commerce_order_save($order);
$product = commerce_product_load($product_id);
$line_item = commerce_product_line_item_new($product, 1, $order->order_id);
commerce_line_item_save($line_item);
$order_wrapper = entity_metadata_wrapper('commerce_order', $order);
$order_wrapper->commerce_line_items[] = $line_item;
commerce_order_save($order);
drupal_goto('checkout/' . $order->order_id);

The reason you are getting page not found is might be because of security check. In other words why any user can not access checkout page for any other user.For authenticated user drupal manages the mapping of order id and user id, but when user is anonymous drupal checks if the accessed order id is in current session or not, so while creating the order progammatically we do not need to explicitly set the order into session.
A nice example:
commerce_cart_order_new()

Creates a new shopping cart order for the specified user.

When you are on the commerce_cart_order_new() api page, check the codes after comment

// If the user is not logged in, ensure the order ID is stored in the
session.

That is how drupal cart does while creating order for anonymous user.
Reason:
Before a user a able to move to checkout page drupal checks if the current user has access or not using commerce_checkout_acess().For authenticated user it simply checks if the current user id is same as the order owner user uid if so user can move to checkout page.For anonymous user drupal checks SESSION, if in current session acsessed order id exists user can move to checkout page or access is granted to user.
Solution:
Use of commerce_cart_order_session_save() to set the session like drupal cart does.So your code will look like
$product_id = 1;
global $user;
$order = commerce_order_new($user->uid, 'checkout_checkout');
commerce_order_save($order);
$product = commerce_product_load($product_id);
$line_item = commerce_product_line_item_new($product, 1, $order->order_id);
commerce_line_item_save($line_item);
$order_wrapper = entity_metadata_wrapper('commerce_order', $order);
$order_wrapper->commerce_line_items[] = $line_item;
  // If the user is not logged in, ensure the order ID is stored in the session.
  if (!$user->uid) {
    commerce_cart_order_session_save($order->order_id);
  }
commerce_order_save($order);
drupal_goto('checkout/' . $order->order_id);