Module for content publication workflow I am looking for a Drupal 7 module to manage a content publication workflow for different roles. When a user with a certain role creates a content node, it needs to be validated by another user within another role, before it is marked as published. In Drupal 6, I have used the Workflow module, but it is not available for Drupal 7.

There is now the Workbench module, for Drupal 7.

  Workbench provides overall improvements for managing content that Drupal does not provide out of the box. Workbench gives us three important solutions:

  a unified and simplified user interface for users who ONLY have to work with content. This decreases training and support time
  the ability to control who has access to edit any content based on an organization's structure not the web site structure
  a customizable editorial workflow that integrates with the access control feature described above or works independently on its own


Give unique class to last item in view UPDATE: I now see that drupal has a built in setting you can check to add even/odd,first, and last classes to the items in the view. Is there a way I can append another class to the last item using this?

For responsive purposes I was planning on adding the bootstrap .hidden-lg class to the last item in a view. This is in order to display more items when I go from a 3 column to a 2 column view. I did see that there was a style output template for views that iterates through each of the rows (as you can see below) but I wasn't sure how to take advantage of that.

<?php

/**
 * @file
 * Default simple view template to display a list of rows.
 *
 * @ingroup views_templates
 */
?>
<?php if (!empty($title)): ?>

<?php print $title; ?>

<?php endif; ?>
<?php foreach ($rows as $id => $row): ?>
  <div<?php if ($classes_array[$id]) { print ' class="' . $classes_array[$id] .'"';  } ?>>
    <?php print $row; ?>

<?php endforeach; ?>

Unless the only option is to perform some regex on the last item of the foreach statement.

As a heads up, I'm already outputting the content and applying custom classes using a view field output template.

You may try next code snippet

/**
 * @file
 * Default simple view template to display a list of rows.
 *
 * @ingroup views_templates
*/
end($rows);
$last = key($rows);
?>
<?php if (!empty($title)): ?>

<?php print $title; ?>

<?php endif; ?>
<?php foreach ($rows as $id => $row): ?>
<?php if ($id == $last): ?>
    <?php $classes_array[$id] .= ' last-element'; ?>
<?php endif; ?>
  <div<?php if ($classes_array[$id]) { print ' class="' . $classes_array[$id] .'"';  } ?>>
    <?php print $row; ?>

<?php endforeach; ?>


Help with URL argument token I'm trying to use tokens in the Linked Field module to link a field in one content type to another content type. I'm also using Pathauto.
So I want to link a field in URL /type/subtype/pagetitle to destination URL /type/subtype.
I've tried [current-page:url:args:first]/[current-page:url:args:second] but the second token doesn't work and the resulting URL is just /type.
I've tried using the [node:field_nameofsubtype] token but that results in /type/Sub Type instead of the /type/subtype generated by my Pathauto.
Surely it isn't that hard to use tokens to just move one step up the URL tree but I can't find it. What am I doing wrong?

Done it!!  This works anyway:
[current-page:url:args:first]/[current-page:url:args:value:1]


“Show as expanded” selected but children menu items not displaying I've main menu navigation and some links checked "Show as expanded" and have child items under it. In the main site page, only parent items are appearing and child items not appearing. I've created a twig template "menu--main.html.twig" and kint the item and found that "is_expanded" is FALSE and there are no child items.

I've solved it. I've figured that I should have to configure the block and extend the menu levels


Why can't I output the style tag in my twig template? I'm desperately trying to render a style attribute, inside a paragraph's template. But all of these variations:

{%
  set backgroundUrl = content.field_slider_background|render|naked|replace({' ': '', "\\n": '', "\\r": ''})
%}

,

{%
  set backgroundAttributes = create_attribute()
%}

and even:

and

just return
. Other tags are fine.

Does twig generally strip style tags?! Using the latest D8 version...

Edit: outputting backgroundUrl actually gives me the correct string, so writing a tag like data-test="{{ backgroundUrl }}" works nicely

I've done it to print a background color like this in a paragraph template

<div class="container color-{{ content.field_text_color[0] }}" style="background: #{{ content.field_card_color[0] }};">

And it just worked fine. Can you give us the full template maybe we can figure out why it doesn't work.


Create a table with courses of a certain curriculum I'm a newbie when it comes to Drupal. I already tried to do it with content types and views but can't seem to accomplish what I need.

I need to create a table with a list of curriculum. Each curriculum name should be a link. So, when you click on a certain curriculum, it'll take you to a page with a table that lists the courses for that curriculum.

Something like the following:

Curriculum List
| Name      | Total Credit Hours |
----------------------------------
| Drupal 7  |                 15 |
| WordPress |                 15 |
| Joomla!   |                 15 |
----------------------------------

Then, when user clicks on Drupal 7:

Drupal 7 Courses
| Name                                         | Credit Hours |
---------------------------------------------------------------
| Drupal 7 Essentials                          |           3  |
| Drupal 7 Advanced Training                   |           4  |
| Drupal 7: Reporting and Visualizing Data     |           4  |
| Drupal 7: Creating and Editing Custom Themes |           4  |
---------------------------------------------------------------

If possible, I don't want to create this by writing a template file since I'm new to Drupal. If someone can at least point me in the right direction I will really appreciate it.

Thanks in advance.

Add a vocabulary for Curriculum List ,then  add Drupal 7, wordpress etc as terms in your vocabulary.

Create a content type for 'Courses'. Link your Curriculum List taxonomy to courses content type.

Then create view to list your taxonomy term and Total Credit Hours  with format as table.

Create another view to list all courses, with a 'contextual filters' as taxonomy term id.

Link your first Curriculum view's taxonomy term to the courses view , eg: courses/2 where

courses is your course views display path and 2 is the term id.


Convert a node from one content type to another, using a rule set I want to convert a node from one content type ("Project") to another one ("Project follow up"), basing on the comparison between the current date (using PHP) and the value of a field date ("Project signup date," which is a CCK date field). Currently, I am using a rule set that will be scheduled based on a check that a rule does when the project is created. The rule set than checks (upon a successful cron run) if the date is higher than the field date (using the date timestamp); the rule set will then convert the node from "Project" to "Project followup."

As I keep getting errors when testing the rule/rule set, I must ask if I'm doing it right. What are the proper PHP evaluation and token replacement pattern? The following are the replacement tokens, and my default PHP code.

Replacement tokens

[node:field_pdate-value]     The raw date value.
[node:field_pdate-view]      The formatted date.
[node:field_pdate-timestamp] The raw date timestamp.
[node:field_pdate-yyyy]      Date year (four digit)
[node:field_pdate-yy]        Date year (two digit)
[node:field_pdate-month]     Date month (full word)
[node:field_pdate-mon]       Date month (abbreviated)
[node:field_pdate-mm]        Date month (two digit, zero padded)
[node:field_pdate-m]         Date month (one or two digit)
[node:field_pdate-ww]        Date week (two digit)
[node:field_pdate-date]      Date date (YYYY-MM-DD)
[node:field_pdate-datetime]  Date datetime (YYYY-MM-DDTHH:MM:SS)
[node:field_pdate-day]       Date day (full word)
[node:field_pdate-ddd]       Date day (abbreviation)
[node:field_pdate-dd]        Date day (two digit, zero-padded)
[node:field_pdate-d]         Date day (one or two digit)
[node:field_pdate-dS]        Date day (one or two digit) with ordinal suffix (st, nd, rd or th)
[node:field_pdate-time]      Time H:i

PHP code

php echo time();

Node Convert might help you with the node conversion from one type to another. http://drupal.org/project/node_convert

I'm not sure if you can use this module to do it programmatically, but it might help to look at this structure and run something similar on a cron job.


How do I remove outer/container divs from a view? I have a view which uses "unformatted list" as it's output format.

...

Now I want these divs to be stripped.

I tried the solution in this answer, but I just want to change the format. I do not want to use Semantic views as that does not help at all in my case.

I manually created a views theme (copying unformatted list) and changing its code as:

<?php if (!empty($title)): ?>

<?php print $title; ?>

<?php endif; ?>
<?php foreach ($rows as $id => $row): ?>
  <div<?php if ($classes_array[$id]) { print ' class="' . $classes_array[$id] .'"';  } ?>>
    <?php print $row; ?>

<?php endforeach; ?>

to:

<?php if (!empty($title)): ?>

<?php print $title; ?>

<?php endif; ?>
<?php foreach ($rows as $id => $row): ?>

<?php print $row; ?>

<?php endforeach; ?>

but that deeply craps out my overall design.

What is the most appropriate and simplest way to do this?

You should override the views-view.tpl.php, not the views-view-unformatted.tpl.php.

The two divs you mention are originating from sites/all/modules/views/theme/views-view.tpl.php, check out lines 30 and 55.

If you copy this over to your theme's templates folder, and rename to be specific to your page/block display, you can remove that part of the template's code and you should get what you need.

  cp sites/all/modules/views/theme/views-view.tpl.php
  sites/all/themes/your_theme/templates/views/views-view--your-ul-page.tpl.php

N.B.: This is exactly what the other post's accepted answer is doing in the first part, before going into Semantic Views configuration, you can ignore that part. Here is a modified/simpler version of the code snippet from that answer, for quick reference:

<div class="<?php print $classes; ?>">     // 30: delete this line
  <?php print render($title_prefix); ?>
  <?php if ($title): ?>
[...]
<?php if ($rows): ?>

  // 55: delete this line,
      <?php print $rows; ?>

                      // 57: delete this line
  <?php elseif ($empty): ?>
[...]

<?php /* class view */ ?> // 90: delete the div from this line

Good luck!


How to update some field of all article nodes programatically and set it equal to its title? I have a field name 'field_new' in a content type 'article'. I want to insert the value of node title on this field (all the nodes) programatically.

What I have done to achieve, I am using hook_node_update for this, but it is not updating the field values.

function modulename_node_update($node) {
  $new_value = $node->title;
  $node->field_new[LANGUAGE_NONE][0]['value'] = $new_value;
  field_attach_update('node', $node);
}

It would be great if there are another alternatives to do this.

hook_node_update - Respond to updates to a node. This is useful when you wants to update a field during node save. This will not helpful in this case because you wants to update all your exiting nodes.

1.Hope this code will helps you.
You will get an idea but this is not the exact code for copy and paste.

<?php
    // Get all nodes of 'article' type, populate the field with a value of '1'.
    $articles = db_query("SELECT nid, vid FROM {node} WHERE type = 'article'")->fetchAllAssoc('nid');
    foreach ($articles as $nid => $values) {
      $fields = array(
        'entity_type' => 'node',
        'bundle' => 'article',
        'deleted' => 0,
        'entity_id' => $values->nid,
        'revision_id' => $values->vid,
        'language' => LANGUAGE_NONE,
        'delta' => 0,
        'field_data_field_new' => 'title need to fetch',
      );
      db_insert('field_data_field_new') //data table name
        ->fields($fields)
        ->execute();
      db_insert('field_revision_field_data_field_new') //revision table name
        ->fields($fields)
        ->execute();
    }
    ?>

Another suggestion is Views Bulk Operations (VBO). You need investigate on it.
Bulk field update?
Updating a single field value for a particular content type:

 $article_nodes = node_load_multiple(array(), array('type' => 'article'));
    foreach ($article_nodes as $article_node) {
          $article_node->field_new[LANGUAGE_NONE][0]['value'] = 'title value';
          field_attach_update('node', $article_node);
        }


Are CCK shared fields loaded on node_load()? field_metatitle is a CCK field that is used amongst 5 different content types, meaning that it is a "shared field". When I do $node = node_load('123');, I see that $node->field_metatitle is not present.

They definitely should be attached to the node object via content_nodeapi() and content_load().


How to drop all MySQL tables using drush? Normally I could drop and create database from scratch, but what if user doesn't have permission to do that?

Also I wouldn't like to specify my credentials in the command-line (1. it's hard to type, especially complex passwords, 2. it's not safe as it get stored in shell history files and on the process list).

Therefore how I can drop all tables using drush?

Related:

How to drop all MySQL tables from the command-line?
MySQL DROP all tables, ignoring foreign keys

It seems there is a single drush command to Drop all tables in a given database. Just run:

$ drush sql-drop


Add a link in management menu for specific role I can't find the way to display a link in the management menu for specific roles. The link shows up only for administrator, despite all the access callbacks I tried.

In the view displayed by the page callback I declared same path, menu  and access callbacks. As I don't know who is called last between module code and the view (?), I also tried with no menu nor access settings in the view.

If you could have a look at my implementation to check where I'm wrong ? Thanks a lot

function vts_dashboard_menu() {

  $items['admin/backoffice/production'] = array(
    'title' => 'Production',
    'description' => 'Edit catalogue',
    'page callback' => 'vts_dashboard_backoff_circuits',
    'access callback' => 'vts_dashboard_user_has_role',
    'access arguments' =>  array('éditeur voyages', 'éditeur taxonomie', 'administrator'),
    'type' => MENU_NORMAL_ITEM,
    'menu_name' => 'management',

    //2 alternative tests below. EVEN WITH TRUE, doesn't show up for non admin
    //'access callback' => TRUE,
    //OR ...
    //'access callback' => 'node_access',
    //'access arguments' => array('view', 1),
  );

  $items['admin/backoffice/production/circuits'] = array(
    'title' => 'Circuits',
    'type' => MENU_DEFAULT_LOCAL_TASK,
    'weight' => -10,
    'access callback' => 'vts_dashboard_user_has_role',
    'access arguments' =>  array('éditeur voyages', 'administrator'),
  );
  // ... more items...
);
//page callback function
function vts_dashboard_backoff_circuits(){
  $viewname = 'circuits_vts';
  $viewdisplay = 'backoffice_products_list';
  return views_embed_view($viewname, $viewdisplay);
}
//access callback function
function vts_dashboard_user_has_role() {
  global $user;
  $roles = func_get_args();
  foreach ($roles as $role) {
    if (in_array($role, $user->roles)) {
      return TRUE;
    }
  }
  return FALSE;
}

Precision : these roles can see the pages/tabs called if they access directly to the path.

Shame on me ! The solution relied of course in a single line of my code, shared below in case it could help somebody.

I aimed to block many admin pages access, from which the admin path, in  a radical manner :

function vts_dashboard_menu_alter(&$items) {
   $items['admin']['access callback'] = 'vts_dashboard_admin_access_only';
  //more items ...
}
function vts_dashboard_admin_access_only() {
  global $user;
  if( !in_array('administrator', $user->roles)){
    return false;
  }
  return true;
}

But $items['admin']['access callback'] blocks also descendant menus items... commented out and all's fine again !

Be what it is, if any enlightened Drupal guru can tell me how to restrict access to foo path but no foo/bar, he'll receive all my consideration !


convert 2 select in db_select I have this query in SQL

select *
from node n, node_collection_data nc
where n.nid = nc.nc_child_nid
and
nc.nc_parent_nid = (select nc_parent_nid
from node_collection_data
where nc_child_nid=17)

This is what I got so far:

 $query -> join('node_collection_data', 'nc', 'n.nid =
 nc.nc_child_nid'); $query->condition('type', $node->type)
       ->condition('status', 1)
       ->condition('n.nid', $node->nid, '!=')
       ->condition(db_or()
       ->condition('n.language', array($language->language, LANGUAGE_NONE), 'IN')
         ->condition('n.language', $node->language, '=')
       )
       // get nc_child_id
       //->join('node_collection_' . $sort, $sort, 'n.nid = ' . $sort . '.nc_child_id')
       ->fields('n', array('nid', 'title'))
       ->fields('nc',array('nc_parent_nid')) // select nc_parent_id

I am trying to convert the last part.

nc.nc_parent_nid = (select nc_parent_nid from node_collection_data where nc_child_nid = 17)

How can I convert it to db_select()?

You need to search for db_select using subquery.

Look the below links to get some idea.

Using db_select with subqueries

db_select condition with subquery


Changing date format in node template I have a content type called news which I created a template for, node--news.tpl.php. In my template, I call the date field as follows:

<?php print render($content['field_news_date']);  ?>

It displays like so:

  05/01/2015 - 15:25

I would like it to look like this:

  1 May 2015

I need to be able to do so solely through the node template, as making changes directly in Drupal will affect other sites and that is not an option. Is there a way to do that?

Assuming you need a specific template, you could also use template.php. This is the preferred method to keep logic out of the template.

Using template.php, you can do a template_preprocess_field()

This overview does a nice job walking you through altering the date. Also, using php date() function you can alter the field to display as 1 May 2015 using l M Y


Can I change an upload URL to match the original upload? I uploaded a PDF in Dupal and used the URL created. Somehow, that document wasn’t saved or was deleted, so now that URL (which is being promoted widely) leads to a page not found. I uploaded a new document, but Drupal renames the URL just slightly.

Can I somehow change this URL to match the original upload or redirect somehow?
I am not sure which version I use (or where to find this).

There are many ways you can approach this to solve it, but maybe the simplest is to just upload the file with the correct (old) name into the location where Drupal expects it. I don't mean upload through Drupal but through your hosting account into the correct folder.

Another way is to add a Redirect from the old URI to the new one, through Drupal Redirect module or on the server configuration (.htaccess usually).


How do convert mysql query with sub queries to a db_select version? Below is a mysql query that returns a proper result set. How can I convert this into a db_select() version?

SELECT p.id, u.name, pa.field_address_2_value, pa2.display, pa3.field_company_value
FROM ms_order_products p
LEFT JOIN ms_orders o ON p.oid = o.oid
LEFT JOIN users u ON o.uid = u.uid
LEFT JOIN
(
    select *
    from field_data_field_address_2

) pa
ON u.uid = pa.entity_id
LEFT JOIN
(
    select *
    from ms_order_adjustments

) pa2
ON o.oid = pa2.oid
LEFT JOIN
(
    select *
    from field_data_field_company

) pa3
ON u.uid = pa3.entity_id
WHERE p.id = 'RM11'

I found the answer, see below. (I added a few more fields as well)

  $sub_query_1 = db_select('field_data_field_address_2', 'addr2');
  $sub_query_1->fields('addr2', array('field_address_2_value', 'entity_id'));

  $sub_query_2 = db_select('ms_order_adjustments', 'a');
  $sub_query_2->fields('a', array('display', 'oid'));

  $sub_query_3 = db_select('field_data_field_company', 'comp');
  $sub_query_3->fields('comp', array('field_company_value', 'entity_id'));

  $query = db_select('ms_order_products', 'p');

  $query->fields('p', array('id', 'oid', 'type', 'amount'));
  $query->fields('o', array('oid', 'uid', 'status', 'order_type', 'created'));
  $query->fields('u', array('uid', 'mail', 'name'));
  $query->fields('fn', array('field_first_name_value'));
  $query->fields('ln', array('field_last_name_value'));
  $query->fields('adr1', array('field_address_1_value'));
  $query->fields('city', array('field_city_value'));
  $query->fields('state', array('field_state_value'));
  $query->fields('zip', array('field_zip_code_value'));
  $query->fields('pa', array('field_address_2_value'));
  $query->fields('pa2', array('display'));
  $query->fields('pa3', array('field_company_value'));

  $query->leftjoin('ms_orders', 'o', 'o.oid = p.oid');
  $query->leftjoin('users', 'u', 'o.uid = u.uid');
  $query->leftjoin('field_data_field_first_name', 'fn', 'u.uid = fn.entity_id');
  $query->leftjoin('field_data_field_last_name', 'ln', 'u.uid = ln.entity_id');
  $query->leftjoin('field_data_field_address_1', 'adr1', 'u.uid = adr1.entity_id');
  $query->leftjoin('field_data_field_city', 'city', 'u.uid = city.entity_id');
  $query->leftjoin('field_data_field_state', 'state', 'u.uid = state.entity_id');
  $query->leftjoin('field_data_field_zip_code', 'zip', 'u.uid = zip.entity_id');

  $query->addJoin('LEFT', $sub_query_1, 'pa', 'u.uid = pa.entity_id');
  $query->addJoin('LEFT', $sub_query_2, 'pa2', 'o.oid = pa2.oid');
  $query->addJoin('LEFT', $sub_query_3, 'pa3', 'u.uid = pa3.entity_id');

  $query->condition('p.id', 'RM11', '=');

  $result = $query->execute();


Adding user roles without access to permissions I want an administrator to add roles to a user without having access to admin/user/permissions where he can alter user permissions.
Currently, on the user permissions form there is only one checkbox that allowes neither one of them or both.
What is the correct way to achieve this?


How do I use a field summary in a view? I'd like to make a Drupal 7 view which displays nodes using the following behavior:

1) Show the body summary if it is populated.
2) Never show a trimmed version of anything.
3) If the body summary is empty, show the actual body.
4) If the body summary is not empty, display a "read more" link.
5) If the full body was displayed, don't display a "read more" link.

I've got this entirely working using a separate field for the summary (which may be what I end up with) but I'd hoped to use the body summary instead.  As far as I can tell the only way to access the body summary in a view is to use the "summary or trimmed" formatter in the field display, which violates #2.

I looked for modules, and all I found was "Smart Trim" which appears to do the opposite of what I want.

Suggestions?

I think this is a good example for using custom formatters.

I Recommend you to use the custom formatters module as you cant get a fast result, but if you think this is useful, you should check the Field Formatter API to make more complex sollutions.

Install the module, and import this example:

$formatter = new stdClass();
$formatter->disabled = FALSE; /* Edit this to true to make a default formatter disabled initially */
$formatter->api_version = 2;
$formatter->name = 'test_body';
$formatter->label = 'test body';
$formatter->description = '';
$formatter->mode = 'php';
$formatter->field_types = 'text_with_summary';
$formatter->code = '$output = "";
foreach ($variables[\'#items\'] as $item) {
  if ( $item[\'summary\']) {
    $output = $item[\'summary\'];
  }else{
     $output = $item[\'value\'];
  }
}
return $output;';
$formatter->fapi = '';

it doesn't do all the job, but i think it can be enough for you to complete it.

Then go to your view and select the formatter for the body field.


Change waiting time for new user The registration of my website works by user email verification.

How can I change a waiting time of new user activation? I have many spam users that register at my website; they register and never activate the account.

In addition to what @Gisle Hannemyr said, I would recommend the spamicide module (sets hidden field that if it is filled by a bot on registration, it will not create the account) and the re-captcha module on your registration forms.


How to set up custom Entity Storage per bundle? Is it possible to use custom entity storage per bundle? Let's say I have node (entity type) which is called article (bundle). I want to store articles in different storage engine than every other nodes (like recipes). So far I have found no way to store single bundle in different storage engine. I could create custom entity type with custom bundle (that works, yes) but I really would like to use nodes and specify custom storage engine for one of them.

I'd strongly recommend against doing that. That's what separate entity types are for, bundles are just variations with different settings/configurable fields.

The assumption in many places is that all entities of a type a stored in the same places, for loading, querying and so on.

You could probably make it work by replacing the storage and have every relevant method (save, delete, load, query, ...) branch of into two different methods. Very likely more work and more complicated than just doing this for a separate entity type. and some things are impossible to get right (e.g. doing queries against a field shared by multiple bundles. core expects that to work).


hook_block and rendering a form in content section Basically, I have tabs on my modules admin page, I need to show a different form per page.
The node type and forms have been created and the first form on block[0] shows correctly, while the first part of block[1] shows correctly, it also icludes some fields from block[0] and this shouldn't be so.

Here is my hook_block, maybe someone can spot my mistake and point it out to me.

function svm_mail_block($op = 'list', $delta = 0, $edit = array()) {

switch ($op) {
  case 'list':
    $blocks = array(
      0 => array(
        'info' => t('Add New Account'),
        'status' => 1,
        'region' => 'content',
        'visibility' => 1,
        'pages' => array('admin/settings/svm-mail/add-account'),
        ),
      1 => array(
        'info' => t('Update Mail Statistics'),
        'status' => 1,
        'region' => 'content',
        'visibility' => 1,
        'pages' => array('admin/settings/svm-mail/ymlp/update'),
        )
      );
    return $blocks;
    break;

  case 'view':
    if(user_access('create mail account')) {
    switch ($delta) {
      case 0:
        //render node form from http://api.drupal.org/api/drupal/includes!form.inc/function/drupal_get_form/6
        module_load_include('inc', 'node', 'node.pages');
        $node_type = 'svm_mail_account';
        $form_id = $node_type . '_node_form';
        global $user;
        $node = new stdClass();
        $node ->uid = $user->uid;
        $node ->name = (isset($user->name) ? $user ->name: '');
        $node ->type = $node_type;
        $block['subject'] = t('Add New Account');
        $block['content'] = drupal_get_form($form_id,$node);
        dvm($block);
        return $block;
        break;
      case 1:
        module_load_include('inc', 'node', 'node.pages');
        $node_type = 'svm_mail_groups';
        $form_id = $node_type . '_node_form';
        global $user;
        $node = new stdClass();
        $node ->uid = $user->uid;
        $node ->name = (isset($user->name) ? $user ->name: '');
        $node ->type = $node_type;
        $block['subject'] = t('Update Mail Statistics');
        $block['content'] = drupal_get_form($form_id,$node);
        dvm($block);
        return $block;
        break;
    }
    break;
}
 }
}

When using my case statements for my form entities, I forgot to add in a break;

It all works nicely now!!


styling webform into 2 columns I am looking to style a webform that I have with the drupal webform module, but i am having a little bit of an issue. I would like to style the form into 2 columns and I am assuming the best way to go about this would be to throw the content into 2 div separate div tags. I have looked around and came across How do I theme a webform?.

I am using the following line in my file.

<?php print drupal_render($form['submitted']['name']);`

Unfortunately, no matter what I try, I can't seem to get the new webform-form-nodeid.tpl.php to work. They say the file should be created as webform-form-36.tpl.php (where 36 is the node ID, in my case) and that I should put it in my custom theme directory. I have done this and had no luck. I have also tried placing it in the template directory for the webform module, but it didn't work.

Does anyone have any idea on how to help me?

I also found that Drupal 7 looks for two hyphens instead of one. I tried renaming the template file webform-form--36.tpl.php, but it didn't have any effect.

I was able to specify the specific node by changing the filename to node--36.tpl.php, but I still feel like there should be a way doing this with the webform name included. Does anyone have any idea?

Please note that I know I was using 36. I have since then changed to 102.

What I did for one of my client in order to get the webform in two columbns, was to create two "Fieldset", containing the fields for column 1 and column 2.

Then with css, I added to my webform this property :

.webform-component-fieldset {width:50%; float:left;}

Of course, there are other ways of doing it, like display:inline-block, and maybe you need to be more precise with the css so you don't mess up other webforms.

And if you don't want the title of the fieldsets, you can do a simple:

.webform-component-fieldset legend {display:none;}

I think that's the easiest way of doing it.


Dashboard doesn't contain the "Customize dashboard" link The dashboard page doesn't contain the Customize dashboard link.

A normal dashboard would appear as in the following screenshot.

How do I make the link appear is it should?

To see the Customize dashboard link, the logged in user needs the Admin blocks permission, as said in admin/people/permissions.

  Customizing the dashboard requires the Administer blocks permission.

This is how I see it when logged in as user #1, who has all the permissions.

This is how I see it with an account without that permission.

If then I give the Administer blocks permission to that account, this is how the dashboard appears.


Manage data: users able to sort the data fields to select course I need to find the right module or set of modules to help visitors to my site review various course offerings. The categories would be presenter name, course name, interest area. Also want to list the course description as a pop up. The user should be able to sort the data (like you would sort from different airline options - price, flight duration, time, stops, etc.)

What do I use? Views? Fields? Data?

Although your question is quite general, you should be able to achieve that with a combination of

Content type for the course with relevant fields added.
Comments enabled on the course nodes for the visitor reviews
Views to list courses ( exposed filters for user filtering, table display provides column click sort options )
You may also want something like fivestar or rate for user voting.


Is possible to update a project that has been installed from the archive file? I'm very new to composer, I've only used it to install the occasional necessary library for our D8 projects. At each Drupal update I normally run

drush up drupal

Which (among other things) replaces the vendor folder and composer.json, so on sites with library dependencies, I need to re-run

composer require [library]

Aware of the touted benefits of Composer as a dependency manager, I want to use composer to maintain our Drupal projects. However I've run into issues, namely that

composer update

or
    composer update drupal/core --with-dependencies
both give me "Nothing to install or update". After some reading, I found this resource https://github.com/drupal-composer/drupal-project. With this unzip, if I run

composer install

I get the correct latest version of Drupal installed in ./web. But when I use the yaml from the template composer.json file in my own composer.json file I still get "Nothing to install or update".

My folder structure is identical to the .zip distribution, so /core and /vendor and /sites etc are all in the same folder, so I have obviously adjusted the composer.json file according. But it doesn't matter what I do, I just get
"Nothing to install or update"
"Nothing to install or update"
"Nothing to install or update"

So, I'm beginning to think that composer update with or without dependencies REQUIRES YOU TO HAVE INSTALL THE DRUPAL 8 PROJECT WITH COMPOSER TO BEGIN WITH.

Is that right? If so, then I can move on.
If not then I need to know what I'm doing wrong. Right now it's not a big deal and I can manage the update process, but it seems each new project requires more and more non-core libraries, so I know composer will save me a lot of time in the future.

TL;DR - Can someone give me a kickstart to configuring my EXISTING, WORKING PRODUCTION SITES so I can use composer to update them, the usual ReadMe's don't seem to work properly with sites that weren't also installed with composer.

I got this working, I was very close but removing /vendor and composer.lock was what helped in the end.
Here are the steps from the top:

add the line
        "drupal/core": "~8.1"
to the 'require' statement (or update it to whatever version you require - in my case ^8.0 - latest Drupal 8 release).
Remove the drupal/core line from the 'replace' statement.
Add the following line somewhere (at the end? I believe this should replace the existing repositories statement, more information here.
):

"repositories": {
    "drupal": {
        "type": "composer",
        "url": "https://packages.drupal.org/8"
    }
}

Remove the /vendor folder
Remove the composer.lock file
Run your core update as follows

composer update drupal/core --with-dependencies


Limit comment length I'm trying to put a max number of characters that users can enter when they comment on an article, but what seems to be a simple task actually seems pretty hard to do. I found a module and several code snippets, but they are all for Drupal 7 and under. Ideally, they would also be a character countdown so that users know when they are about to reach the limit.

How shall I proceed?

In D8 the fields of a comment can be configured in a comment type where you can define a field with a maximal number of characters. For a character countdown you need some javascript code or use a field module like Maxlength.


How do I limit the node count of a content type to one per user? I have a custom content type. I would like to limit that each user can only create one node of this content type. How can I achieve this?

You can use the Node Limit module for that:

  The Node Limit module allows administrators to restrict the number of nodes of a specific type that roles or users may create. For example, if a site has an "Advertiser" role that can create "advertisement" nodes, then the node limit administrator can restrict all users in that role to a specific number of nodes. He may also restrict users on a per-user basis.


Is there a way to provide theme name suggestion for form elements? I'm trying to look for a way to modify the markup for a form element without touching the default theme/template. Upon checking the source code, Drupal does not seem to recommend any theme suggestions for editing form elements. I have multiple views using the same field on the exposed filter. If I try to edit the form-element-label.html.twig it will affect all of the elements with the same field.

<!-- THEME DEBUG -->
<!-- THEME HOOK: 'form_element_label' -->
<!-- BEGIN OUTPUT from 'themes/iom/templates/layout/form-element-label.html.twig' -->
<label for="edit-field-themes-target-id" class="label">Themes</label>
<!-- END OUTPUT from 'themes/iom/templates/layout/form-element-label.html.twig' -->

Seems you have to implement two hooks. One to add the suggestion, and one to define a template. hook_theme_suggestions_HOOK_alter and template_preprocess_form_element (aka hook_preprocess_HOOK).

/**
 * Implementation of hook_theme_suggestions_form_element_alter().
 */
function MYTHEME_theme_suggestions_form_element_alter(array &$suggestions, array $variables) {
  if (\Drupal::service('path.current')->getPath() == '/user/login') {
    $suggestions[] = $variables['theme_hook_original'] . '--user-login';
  }
}

/**
 * Implementation of hook_preprocess_form_element().
 */
function MYTHEME_preprocess_form_element(&$variables, $hook, &$info) {
  $info['template'] = 'form-element--user-login';
}

Source: Form element template suggestion has no effect.


How to debug a rule that doesn't want to fire? I have nodes that can be flagged with a global flag.
When a node is updated I want a rule to unflag that node.

Rules Event: After updating existing content

Rules Action: Unflag a node.
I then select the flag, "data selector" = node, "User on whose behalf to flag" = node:author (this field should be ignored because it's a global flag),
"permission check" is unchecked.

When I update a node which has a global flag set, it doesn't get removed.
Did I set it up wrong? How can I debug a rule that doesn't want to fire?

Flag Module

"User on whose behalf to flag" will not be ignored in this case.

When a flag is global, users don't necessarily have the required permission to toggle it.  Be sure that the user role is allowed to flag or unflag the flag in question.

A nodes 'published' status is a good example of a 'global flag' (though it has nothing to do with the flag module.)  When published is TRUE content is visible, when FALSE it's hidden.  Though the flag is global, only those with the 'publish content' permission can toggle it.  The Flag module works similarly.

Rules Module

Rules has a built-in debugger that is useful at times.  It can be found at admin/config/workflow/rules/settings

I generally end up falling back on dd() or dpm() though when debugging rules.  Rules is an incredible module for sure, but debugging at times can be a pain.


drupal database & code out of sync I've lost the PHP installation of a Drupal 7 site just before a lot of updates were about to be applied. I still have the Drupal database.

If I install a current version of Drupal, it may be out of sync with the database (missing columns that were added by some update etc).

So, how can a new Drupal installation be grafted onto an old database?

Treat this as an upgrade. You won't have a problem with missing columns, because those are in your database. You'll have a problem with missing plugins to access those columns.

First, of course, back everything up.
Then install Drupal. It makes
sense to follow @Schnippy's hint and look in the database for the
version number, and install that version of Drupal. Otherwise,
install the current version; it will tell you if it needs to update the database.
Look in your database (hopefully you have phpMyAdmin available) for tables created by plugins. Use that and your memory to reinstall any modules. You might also look at admin/reports/updates and see if it'll list your missing plugins.

Later, I recommend installing the Schema plugin, which will report any mismatches between your modules and database tables. This gets reported on the Status Report page and is wonderful when developing a custom module.

If you lost your images and file uploads from your theme or site/default/files directory, you may be out of luck for that content. Good luck!


Drupal 7 hook_theme() not loading template file I'm trying to get a very simple module to load a template file using drupal's hook_theme(). It's pretty much as simple as you can possibly imagine.

function sectionheader_theme ( $existing, $type, $theme, $path ) {
  return array(
    'sectionheader' => array(
      'variables' => array( 'foo' => NULL ),
      'template' => 'sectionheader',
    ),
  );
}

The template is named sectionheader.tpl.php. The rest of the module is working as expected. I've cleared the Drupal cache. I've inserted a die("Debug") statement in this function, and it is being executed, but my template is simply not being called, ever. The template merely has some debug text in it so I can see that it's working, but is not visible in any view of the module.

I've done everything in every example I can find, I've even copied and pasted code directly from other modules, and this template will still not load.

I've tried renaming the template and the 'template' array value. No luck.

Try implementing hook_theme_registry_alter() in your module

function sectionheader_theme_registry_alter(&$theme_registry) {

  //register a template
  $theme_registry['sectionheader'] = array(
    'template' => drupal_get_path('module', 'sectionheader').'/sectionheader',
    'type' => 'module',
  );
}

http://api.drupal.org/api/drupal/modules--system--system.api.php/function/hook_theme_registry_alter/7


How to hide default "N/A" option for checkboxes? I have a "gender" (checkbox) option that I want to show on the user profile page (but not on the registration page).
The options are "Male" (default) and "Female". Since I don't make the field required it is showing the "N/A" option. Drupal does this by design.

If I make the field required the "N/A" option will go away but then it will automatically show on the registration page which I don't want.

I was trying to hide it with CSS but I cannot see a way to just hide that checkbox and "N/A" text:

<input id="edit-field-gender-und-none" class="form-radio" type="radio" value="_none" name="field_gender[und]">
N/A

<input id="edit-field-gender-und-0" class="form-radio" type="radio" checked="checked" value="0" name="field_gender[und]">
Male

<input id="edit-field-gender-und-1" class="form-radio" type="radio" value="1" name="field_gender[und]">
Female

Help! ;-)

You can use jQuery to accomplish this

$("#edit-field-gender-und-none").remove();


Sass error with zen 5, 'it is not clear which file to import So, I'm getting what seems to be  a common error in working with SASS in a windows environment. "Error: It's not clear which file to import @import'print';" using zen 5.

I have tried changing the sass-globbing versions, and even tried different variations of the @import statements syntax (e.g. @import "print/", "print/", "print//" etc, nothing seems to affect the error.

The issue is that while there are plenty of people reporting this issue, there doesn't seem to be a clear picture of how to fix or address the issue, suggesting changing developing environment is not helpful.

At it's face, the issue is that the SASS parser can't seem to tell the difference between the partial _print.scss and the other empty print.scss files in the same folder.

Do I need the empty print.scss file, or can I rename it? Or can I rename the partial _print.scss to something else? Is there a non-hack way to fix this?

So, this ends up being more of a environment/sass issue I post this here because I encountered in working with Omega, and I figured someone else would bump into this. Depending on your set up, especially if you're using a task manager, SASS file globbing might not be functional.


Should I be using node_load() rather than building my own queries with db_select()? I'm fairly comfortable with using Drupal 7 functions like db_select(). While node_load() is obviously very easy to use, I often find that it returns fields I don't need and doesn't provide fields that I do need (field that would require some joins to obtain).

Therefore, will building my own queries provide better performance than using node_load() in conjunction with other queries? Or is there some kind of performance boost that results from using node_load(), perhaps from cacheing, etc.?

I'm far from an expert on MySQL performance issues, but it seems to me that constructing a single, specific query is better than using multiple queries that individually only retrieve part of what I ultimately need (and a lot of what I don't).

Technically, yes, writing your own db_query() statements will return the data faster and with less overhead. However, it is not really the "Drupal way" to do things.

node_load() provides a 'static' cache; in other words, if you load the same node twice in one page request, it will only hit the DB once.

What you are really missing out on by not using node_load() is all the API hooks and third-party module integration. If you need a CCK field, node_load() gets all that data for you, where as a manual query would require a lot of joins.

As you note, there is a lot of extra processing/loading going on that you may not need at the given moment. If you don't need the data, it won't technically hurt you not to have it. It is really up to you if you want to go this route.

The biggest reason IMO for using node_load() even though you might not need the extra data is just for the purpose of standardization. You won't have to worry about what pieces of data you have at a certain point. You will have a fully loaded node and will have more options for adjusting the data as necessary through hook_nodeapi(). Other developers looking at your code will have an easier time understanding what they are working with. Also, 6 months down the road when you go to add a new feature/display field you wont have to adjust your queries.

node_load is definitely a resource hog, but i have found it better to use in my experience.  Drupal 7 greatly improves the situation by providing node_load_multiple() which, as its name implies, reduces the number of queries when loading multiple nodes.


How can I add a class to a link output via a form? Based on this answer, I'm attempting to add a cancel link.  By default, however, the following code just displays a plain link with no ids and classes.

  if(arg(1) == 'add') {
    // If adding node link to node/add screen
    $link = l(t('Cancel'), 'node/add');
  }
  elseif(arg(2) == 'edit') {
    // If editing node, link to node view screen
    $link = l(t('Cancel'), 'node/'.arg(1));
  }
  $form['cancel'] = array(
    '#type' => 'markup',
    '#value' => $link,
    '#weight' => 0,
  );

How can I add arbitrary css classes and an id to the link that is output?

Take a look at the l() function:

l(t('link_text'), 'path', array('attributes' => array('class' => array('your_class'), 'id' => 'your_id')));


Feeds: update nodes using a second import Is there a way in which you can use a second feeds import, to update nodes created during a first import?

In my first import, I create nodes and save a custom ID (from old system), and I want to reuse that custom ID in the second import to update the existing nodes and add a taxonomy value.

First importer:

Second importer:

To update existing content using feeds importer, you will have to mark Customer ID field as a Unique Key.


Grouping content by taxonomy, multiple taxonomies by node Note: The solution should not change the main Views properties, mainly that it is a View of content nodes.

I have a content type (books) which are under a taxonomy (Category). I have created a View to show the titles. By using "Grouping field" with the category (see picture #1), I can get the title of the category and order by that.

However, when I have books which are classified under several Categories (in this example, the book about Chess is under Sports and Science), I get a mixture of taxonomies in the Grouping field displayed, and the book does not appear in the other categories. I would like it to appear under Sports and under Sciende, and get rid of this "third" combined taxonomy "Science, Sports". (see picture #2).

Image 1

Image 2

You have many solutions available.

Solution 1:

Enable "Use aggregation" option with the default settings, it should be enough.

Solution 2:

You can create a view of terms and add a "Relationships" with "Taxonomy term: Content using Category". As fields you have to add the content fields (with the new relation) and the term name (used for the grouping).

This is an example of the view assuming the content type is "article", the category field is called "field_category" and the vocabulary is "category":

$view = new view();
$view->name = 'nestedexample';
$view->description = '';
$view->tag = 'default';
$view->base_table = 'taxonomy_term_data';
$view->human_name = 'nestedexample';
$view->core = 7;
$view->api_version = '3.0';
$view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */

/* Display: Master */
$handler = $view->new_display('default', 'Master', 'default');
$handler->display->display_options['title'] = 'nestedexample';
$handler->display->display_options['use_more_always'] = FALSE;
$handler->display->display_options['access']['type'] = 'perm';
$handler->display->display_options['cache']['type'] = 'none';
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['exposed_form']['type'] = 'basic';
$handler->display->display_options['pager']['type'] = 'full';
$handler->display->display_options['pager']['options']['items_per_page'] = '10';
$handler->display->display_options['style_plugin'] = 'default';
$handler->display->display_options['style_options']['grouping'] = array(
  0 => array(
    'field' => 'name',
    'rendered' => 1,
    'rendered_strip' => 0,
  ),
);
$handler->display->display_options['row_plugin'] = 'fields';
/* Relationship: Taxonomy term: Content using Category */
$handler->display->display_options['relationships']['reverse_field_category_node']['id'] = 'reverse_field_category_node';
$handler->display->display_options['relationships']['reverse_field_category_node']['table'] = 'taxonomy_term_data';
$handler->display->display_options['relationships']['reverse_field_category_node']['field'] = 'reverse_field_category_node';
/* Field: Taxonomy term: Name */
$handler->display->display_options['fields']['name']['id'] = 'name';
$handler->display->display_options['fields']['name']['table'] = 'taxonomy_term_data';
$handler->display->display_options['fields']['name']['field'] = 'name';
$handler->display->display_options['fields']['name']['label'] = '';
$handler->display->display_options['fields']['name']['alter']['word_boundary'] = FALSE;
$handler->display->display_options['fields']['name']['alter']['ellipsis'] = FALSE;
$handler->display->display_options['fields']['name']['link_to_taxonomy'] = TRUE;
/* Field: Content: Title */
$handler->display->display_options['fields']['title']['id'] = 'title';
$handler->display->display_options['fields']['title']['table'] = 'node';
$handler->display->display_options['fields']['title']['field'] = 'title';
$handler->display->display_options['fields']['title']['relationship'] = 'reverse_field_category_node';
/* Field: Taxonomy term: Name */
$handler->display->display_options['fields']['name_1']['id'] = 'name_1';
$handler->display->display_options['fields']['name_1']['table'] = 'taxonomy_term_data';
$handler->display->display_options['fields']['name_1']['field'] = 'name';
/* Sort criterion: Content: Title */
$handler->display->display_options['sorts']['title']['id'] = 'title';
$handler->display->display_options['sorts']['title']['table'] = 'node';
$handler->display->display_options['sorts']['title']['field'] = 'title';
$handler->display->display_options['sorts']['title']['relationship'] = 'reverse_field_category_node';
/* Sort criterion: Taxonomy term: Name */
$handler->display->display_options['sorts']['name']['id'] = 'name';
$handler->display->display_options['sorts']['name']['table'] = 'taxonomy_term_data';
$handler->display->display_options['sorts']['name']['field'] = 'name';
/* Filter criterion: Taxonomy vocabulary: Machine name */
$handler->display->display_options['filters']['machine_name']['id'] = 'machine_name';
$handler->display->display_options['filters']['machine_name']['table'] = 'taxonomy_vocabulary';
$handler->display->display_options['filters']['machine_name']['field'] = 'machine_name';
$handler->display->display_options['filters']['machine_name']['value'] = array(
  'category' => 'category',
);

/* Display: Page */
$handler = $view->new_display('page', 'Page', 'page');
$handler->display->display_options['path'] = 'nestedexample';

Solution 3:
Another solution is adding a relationshipt with the taxonomy terms "Content: Taxonomy terms on node" and use the taxonomy term from the relationship as group by field.
I hope this will help you.


Create drupal node programatically and set custom select list field I have a Drupal 7 node with custom fields. I have no problem setting values to the single text fields but I'm not sure how to set my select list field to one of the allowed keys of the field.

This is the code I've tried to assign the select list to the 'pending' key.

$node->field_referee_status['und'][0]['tid'] = 'pending';

Node creation code:

// CREATE NODE
$node = new stdClass;
$node->type = 'referee';
$node->title = 'Referee report for xx';
$node->uid = $user->uid;
$node->status = FALSE;
$node->field_referee_status['und'][0]['tid'] = 'pending';
$node->field_referee_id['und'][0]['value'] = 'test';
$node->field_testff['und'][0]['value'] = "testworked";
node_object_prepare($node);
node_save($node);

Question: Does anyone know the correct way to assign the key value to a custom select list field when creating Drupal nodes programmatically?

With a select list, you need to store the key value of the custom field.

I just noticed that you're storing taxonomy term reference value, which means you should be storing the term ID and not the actual text value of pending.

Theres a handy function which allows you to grab the TID based on a term name:

$term = taxonomy_get_term_by_name('pending');
$node->field_referee_status[LANGUAGE_NONE][0]['tid'] = $term->tid;

See the docs here.

EDIT

To save into a normal textfield select list:

$node->field_referee_status[LANGUAGE_NONE][0]['value'] = 'pending';


How to add css class to a field from a select list before rendering? I have a select list which has the following values where the key values are the same name as the css class name.

List1:

prim-blue|Blue
prim-black|Black
prim-orange|Orange

We also have a text field which is surrounded by the following div tag below. Before the page renders, we want to take the value from list1 and assign it as a class to the div tag. We need assistance in figuring out how to get this to work using a preprocess hook.

/*css*/
prim-blue {
   //some attribute
}
prim-black {
   //some attribute
}
prim-orange {
   //some attribute
}

/*field div tag */

 Some text values

Desired results (when page renders):

**Assume list1 is set to Blue (key: prim-blue)

 Some text values

Note (to provide more context):

I am using the paragraph module which a bundle that has a background color for list1 and the text field. Then on the basic page content type, i added a paragraph field.

Paragraph bundle fields:

text (field_text)
background color (field_bkg_clr) <-- the drop down list1

Basic Page content type:

Header (field_pr_hdr, which is of type paragraph)

I have used the Field Formatter CSS class module for the same task. The client wanted to have predefined colors for heading elements in paragraph bundles. I have to admit this seems like an amendable approach, but it worked.

I had set up a vocabulary for the color names list and referenced this in the paragraph bundle as a select list (taxonomy term reference). In the display settings for the field is css-class selected. The format settings are set to target tag = entity.

This results basically in following markup:

This is a headline

CSS:

.h1-colorclass-red .field-name-field-heading {
    color: red;
}


Some tokens show as "missing name or description" in status report Looking at a Drupal 7.43 maintenance project, my status report lists the following issue for Token 7.x-1.6:

The following tokens or token types are missing required name and/or description information:

$info['types']['date']
$info['tokens']['node']['url']
$info['tokens']['file']['size']
$info['tokens']['user']['url']
$info['tokens']['date']['custom']
The following token types are not defined but have tokens:

$info['types']['node']
$info['types']['term']
$info['types']['vocabulary']
$info['types']['file']
$info['types']['user']
$info['types']['current-user']

I have cleared cache a few times, hit update.php, and ran cron a handful of times. This message never goes away.

It is causing RealName to no longer work, path aliases are not being made, and page title / meta tags are not appearing (all are driven by Token).

What is causing this and how can I fix it? I am unable to replicate the issue locally with the same database and same code.

In my case, the answer is related to the autoslave module: https://www.drupal.org/node/2898888

Also discussed here (not resolved), https://www.drupal.org/node/1265848#comment-12191146

Other mentions online about the PHP memory settings had no effect for me.

Hopefully this helps someone as the issue has been quite elusive.


get result count of a view in another I have 2 views. One view is displayed in the header of other view. Both views has its own block template. I need to get the sum of both views result count to display a no result message if sum is equal to zero. Is there any way to do it.

Add a NO RESULTS BEHAVIOR Global: Text area to the inner view (the one in the header) and leave it empty.

Add this code to your theme's template.php file:

function THEME_views_pre_render(&$view){
  if (($view->name == 'outer' && $view->current_display == "default") || ($view->name == 'inner' && $view->current_display == "default")) {
    static $count = 0;
    $count += $view->total_rows;
    if (count($view->parent_views) && $count == 0){
      $view->empty['area']->options['content'] = "custom no result text";
    }
  }
}

Change the view names (outer and inner in my example) and display_names (default in my example) to reflect your views.

Clear the cache.

Perhaps someone else can elaborate on how to add the global text for the no result in code instead of setting it to an empty value in the UI and then altering that value in code.

EDIT

If you intend to add any of these block multiple times on the same page then this answer will no longer be valid. Also, the no result text displays in the no result text for the inner view. You may want to consider altering the title of the block in that case. Unfortunately the outer view runs first, so it cannot be added to there as the result count of the second view is not yet available at that stage. count($view->parent_views) is the bit of logic that checks for the inner view.You can change that to check for the $view->name if you want to.


Which settings to use in hook_field_formatter_view? Looking at the page of hook_field_formatter_view, the explanation for $display is:

  The display settings to use, as found in the 'display' entry of instance definitions. The array notably contains the following keys and values;

But I just found out that the $display variable does not hold accurate information.

This is what's inside my $instance (correct settings)

This is what's inside my $display (default values for settings)

I could overwrite $display from the $instance settings, but I can't figure out in which variable the current view mode is stored, so that I can grab the settings for the correct view mode.

As a little background info, this is a custom field with a custom formatter. Has anyone had similar issues with a custom field/formatter?

This wasn't really a problem. This was because the page was a Panels page, and the field was added into the panel page with its own formatter settings.

Solved by setting the correct field formatter settings on the panel page.

It's one of d'ohs days.


Architechture/ Foundation help for a drupal project I am thinking to develop my drupal website for various products like camera, mobile and others.

For this i will have various content types like camera and mobile and others and have term references for feature of products so that it will be helpful in filtering the products.

Now my big problem is here.
1. Each product i.e camera, mobile should have its rating properties like camera will have its own set of rating properties and mobile will have its own rating properties. How do i attach these rating properties to a content type ?
2. When user goes to the product page, He should give ratings for properties and add comment against each property. How ill i do this ?
3. If he has already given ratings and commented on the product it should be default displayed.

Main problem is that how do i attach rating properties to the content type and make user comment on these properties.

If i create separate content types will it be a problem to create a search on all products

I'm not sure what you mean by "properties" in your question.  However, you can use the Fivestar module to add ratings to a content type. So your Camera content type could have a rating for each camera and your mobile content type could have a rating for each mobile.

Search will work across all content types. http://drupal.org/documentation/modules/search


How to send email depending upon hidden component value (which will get from url)? xxx.com/apply-job/node/1949?jobCode=IR/001&functionalArea=HR

I have a form in the above url, the form components are

Name

Email

Resume

And also I have jobcode, functionalarea as hidden field, those field default value is

%get[jobCode], %get[functionalArea]

My question: How to send email to different address depends upon the hidden component value (functional area component)?

Webform rules
If you'd use the Webform Rules module, you have the power of the Rules module available to produce such eMails. Some details about Webform Rules (from its project page):

This module adds rules integration on webforms.
Did you ever want to react on webform submission using rules but couldn't find the proper event?
Webform Rules makes it possible to catch webform submissions by rules and do whatever you'd like to do with it (meaning: do whatever rules let you do with it).

Rules URL argument
And to make the value of URL arguments available as a new variable to Rules, you can use the Rules URL Argument module. Here is a quote about it (from its project page):

... provides two rules conditions based on URL arguments:

check if a URL argument is present.
compare the value of an URL argument.

It also provides an action that makes the value of an URL argument available as new variable to Rules.

The newly provided Rules actions and conditions can be found under the "URL Argument" conditions and actions groups in the rule configuration interface.
For an example of how to use it, refer to Comment # 3 in issue # 1686360 which is about "Pass an amount to the url, ie; site/content/node-title?amount=10 or /node-title?=amount:10". Here is the relevant part of it:

add a "Check if URL argument exist" condition to your rule and set the "ARGUMENT" value to "amount".
add "Provide URL argument value" action to the rule and set "URL ARGUMENT NAME" value to "amount" and in the "Provided variables" section "ARGUMENT FROM URL - Variable name" to e.g. "amount_from_url".

You will now be able to use the amount value as a variable "amount-from-url" for other actions in this rule.


Programmatically get exposed filters from view A little bit of context:
I am running a headless Drupal 8 with React in the front-end. All the data gets exposed through various endpoints.
Now i am trying to render a view in react, there was no problem in obtaining the data. But when i tried to get the exposed filters i ran into a problem (the filters are based on taxonomy terms). I expected to get the filter values like this:
value: {5:"Value one", 6:"Value two", 49:"Value three", 50: "Value four"}

Except i got the filter values like this:
value: {5:5, 6:6, 49:49, 50:50}

So it feels like instead of get the key and value i only get the keys...
I am wondering if i am doing something wrong or there is another way of obtaining the exposed filter values.
The following code i am using to obtain the filters
$this->$view // ViewExecutable
$filters = [];
foreach ($this->view->filter as $filter) {
  if($filter->isExposed()) {
    $filters[] = $filter->options;
  }
}

I think everything is fine. You have to load the taxonomy term names manually like:

\Drupal\taxonomy\Entity\TaxonomyTerm::load($ids)

Or maybe you can do a custom query to load only the taxonomy term titles without any field data (because that is what you need).


How to format the display of webform_select_options_info to include an image? Looking for some guidance on how to approach the formatting of the results of webform_select_options_info. What I want to present to the users is a dynamically populated list of items they flagged along with a checkbox. What I'd like to do is show a thumbnail of the image, the node title and a checkbox in  my list.

The function as I have it now is as follows

 function webform_hook_user_flag_sample_requests() {
   $view = views_get_view('webform_flag_views', TRUE);
   $view->set_display('webform_options');
   $view->execute();
   $options = array();
   if ($view->result) {
     $row_class = $view->style_options['row_class'];
     $attributes = $row_class ? " class='$row_class'" : '';
     foreach($view->result as $item) {
    $options[$item->product_id]= $item->commerce_product_title;
      }
       }
   else {
     $options[0] = t("Nothing");
   }
return $options;
      }

I'm not sure how to change the foreach loop to include additional fields?

Well, I still didn't get a good answer on modifying the syntax here but here is working result. I have a check box, thumb, and title all showing as a list in webform. Still not completely functional as the function doesn't seem to work for anonymous users, although the Flag is anonymous and I'm using sessions.

 <?php
    /**
     * Implements hook_webform_select_options_info().
     */
     function webform_hook_webform_select_options_info() {
       $items = array();
       if (function_exists('webform_hook_user_flag_sample_requests')) {
         $items['webform_hook_user_flag_sample_requests'] = array(
          'title' => t("Sample Requests (User Flag list)"),
          'options callback' => 'webform_hook_user_flag_sample_requests',
         );
       }

       return $items;
     }

     function webform_hook_user_flag_sample_requests() {
       $view = views_get_view('webform_flag_views', TRUE);
       $view->set_display('webform_options');
       $view->execute();
    // dpm($view);
       $options = array();

       if ($view->result) {
     //    $row_class = $view->style_options['row_class'];
     //    $attributes = $row_class ? " class='$row_class'" : '';
         foreach($view->result as $item) {
        $options[$item->product_id]= $item->commerce_product_title . render($item->field_field_image[0]['rendered']);
          }
           }
       else {
         $options[0] = t("Nothing");
       }
    return $options;
          }


Ajax form submit - how to recognize if form contains errors in ajax callback? I have a simple form with ajax submit:

function activit_registration_form($form, $state) {

  $form["ajax-start"] = array("#markup" => "
");

  // ... some form elements are here

  $form["submit"] = array(
      "#type" => "submit",
      "#value" => t("Odoslať"),
      "#ajax" => array(
          "callback" => "activit_registration_form_ajax",
          "wrapper" => "registration-form-ajax",
          "effect" => "fade"));

  $form["ajax-end"] = array("#markup" => "
");

  return $form;

}

Ajax callback:

function activit_registration_form_ajax($form, $state) {

  return $form;
}

Validation:

function activit_registration_form_validate($form, $state) {

  if(!valid_email_address($state['input']['email'])) { form_set_error('email', 'email'); }
  if(strlen(strval($state['input']['name']))<3) { form_set_error('name', 'meno'); }
  if(strlen(strval($state['input']['tel']))<6) { form_set_error('tel', 'tel'); }

}

Ajax callback is now returning the same form, but I would like to achieve returning just a simple string instead of the form when form does not contain any errors.

What is the best way to recognize if a form contains errors or not in ajax callback?

You can define the form status in $form_state and check the status during rebuilding form.

Example code:

function activit_registration_form($form, $state) {

  if (isset($state['submit_success'])) {
    $form['ajax_form']['message'] = array("#markup" => t('Thanks for your submission.'));
  }
  else {

    $form["ajax_form"] = array(
      "#prefix" => "
",
      "#suffix" => "
",
    );

    // define form elements under 'ajax_form', such as
    // $form["ajax_form"]["element_1"] = array( ... );

    $form['ajax_form']["submit"] = array(
      "#type" => "submit",
      "#value" => t("Odoslať"),
      "#ajax" => array(
        "callback" => "activit_registration_form_ajax",
        "wrapper" => "registration-form-ajax",
        "effect" => "fade",
      ),
    );
  }

  return $form;
}

function activit_registration_form_ajax($form, $state) {
     return $form['ajax_form'];
}

function activit_registration_form_validate($form, &$state) {
  $has_error = FALSE;

  if (!valid_email_address($state['input']['email'])) {
    form_set_error('email', 'email');
    $has_error = TRUE;
  }
  if (strlen(strval($state['input']['name']))<3) {
    form_set_error('name', 'meno');
    $has_error = TRUE;
  }
  if (strlen(strval($state['input']['tel']))<6) {
    form_set_error('tel', 'tel');
    $has_error = TRUE;
  }

  $state['submit_success'] = !$has_error;

  $state['rebuild'] = TRUE;
}


How to to render a webform (or any configurable form) in a node edit form? I have a weird use case, where I was looking to perform the following:

In a node edit form, allow a user to entity reference a collection of webforms
When a user selects an appropriate webform from the entity reference autocomplete, render that form in the current node edit form
User fills out fields in these webforms then proceeds to save the node.
On node save, the webform submit data is stored in a particular field in the node (perhaps in json format).

Is this even possible with webforms, or do any other form modules exist that support this use case?

In this instance it sounds like the paragraphs module solves your problem. However to answer your original question...

I would use entityform, not webform to do this.

Once you added all of your field to your entity form then you can use Inline Entity Form to embed the child form.


How to install ckfinder outside the ckeditor module folder? I have installed both the ckeditor module and the ckfinder plugin. They work fine. So far so good.

The problem is that I have ckfinder plugin inside the ckeditor module folder (sites/all/modules/ckeditor/ckfinder). Then every time I update the ckeditor module I lost the ckfinder plugin.

I'm sure that there is a way to put ckfinder inside the libraries folder instead but I don't know to do it in the right way.

maybe this helps:

  This module allows you to use CKFinder with the WYSIWYG version of
  CKEditor. This module requires both the libraries and WYSIWYG modules.
  Please read the installation instructions carefully.

found here: https://github.com/jrsinclair/Drupal-WYSIWYG-CKEditor-CKFinder-bridge

Update 21 August 2012 This module has now been published on Drupal.org. You can find it at: http://drupal.org/project/WYSIWYG-CKFinder


User role permissions per language Drupal 8 supports Multilingual (i18n) in core. I was wondering, is it possible to restrict users to be able to add/edit content for only one specific language?

Yes, you can use hook_node_access to control access to add/edit for the node.

For example, you can check the value of:

$language = \Drupal::languageManager()->getCurrentLanguage()->getId();

and return the access result accordingly


How to capture bank payment info to store for payment processing using Drupal Commerce? I'm using Drupal Commerce. Is there any way to capture bank payment info to store for payment processing? So that a customer doesn't need to enter details on each transaction.

Commerce Card on File

Commerce Card on File provides an API and user interface for storing
and reusing credit card data on subsequent orders within Drupal
Commerce. The module does not retain full card numbers locally but
instead stores the remote ID of the full card data from the payment
gateway used to validate and process your credit card transactions.
This means card on file data will only be good for a single payment
gateway; if you change payment gateways or accounts, your stored card
data may no longer be usable.

How this module is PCI compliant
This module is safe as it does not retain the full card number. Only the last 3 numbers and expire date are stored in your DB. So if your DB gets hacked, you'll be fine.
Furthermore, when this module connects your payment processor, it uses a token to represent the persons card. Only you can use that token to deposit funds to your account. So even if somehow they intercept the token value, they can't do anything with it.
source: David Kitchen

You should also get Commerce Dunning to deal with expired card numbers.
Commerce Dunning

Dunning management (Delinquent User Notification) is the automated
process that's kicked off when a charge attempt of a recurring order
fails. This process involves periodic customer communication and
payment retries.

Dunning Video Tutorial


Taxonomy overview search term In this manager:

admin/structure/taxonomy

admin/structure/taxonomy/manage/[fruit]/overview

There is a way to add a search a term?

So, if you have 100 terms it will easier to find a term.

This one is not ported at all https://www.drupal.org/project/term_search

This module is not full ported to D8
https://www.drupal.org/project/taxonomy_manager

I also find this interested article to alter a task in a specific vocabulary. https://www.computerminds.co.uk/drupal-code/replacing-vocabulary-listing I created the view, but I still find out how to add a tab for that view in the overview taxonomy.

There other way to add an option to search a term in manager?

Views with exposed filters sound like a great way to add a Search page to Vocabulary configuration tabs.

You can add your Views page to Vocabulary pages through Views configuration. Since the List already exists as the default tab, simply configure your Views page Menu option as a normal Menu tab and set the page path to the [path-to-default-vocabulary-page]/search.

The tab will appear as one of the tabs you see when you visit the Vocabulary configuration page.


Does Google Analytics module tracks superuser 1 out of the box? Does Google Analytics module tracks superuser 1 out of the box?

UPDATE: Found this in the .install file of the module. What does it basically say about user 1? Can anybody explain them to me? Does it track uid 1? Thanks.

variable_set('googleanalytics_roles', $roles);

// Upgrade disabled tracking of "user 1" to new logic.
if (!$track_user1 = variable_get('googleanalytics_track__user1', 1)) {
  variable_set('googleanalytics_custom', 1);

  // Load user 1 object, set appropriate value and save new user settings back.
  $account = user_load(1);
  $account = user_save($account, array('data' => array('googleanalytics' => array('custom' => 0))), 'account');
  $messages[] = t('Disabled user specific page tracking for site administrator.');
}

// Delete outdated tracking settings.
db_delete('variable')
 ->condition('name', db_like('googleanalytics_track_') . '%', 'LIKE')
 ->execute();

// ...

Does Google Analytics module tracks superuser 1 out of the box?

Yes, it does. In fact, the default value for the Drupal variable googleanalytics_track__user1 is 1, which means the control statement is executed by default.

if (!$track_user1 = variable_get('googleanalytics_track__user1', 1)) {
  // ...
}

What the code does is to save in $user->data the module settings, and delete the old settings.


Combining 2 Queries to pull titles of 2 related content types from the node table Time to put our database hats on! We have a complex database call that responds to an AJAX request. We've omitted most of the code to just include the portion that is giving us trouble. We are working in Drupal 7.

  $products = "field_data_field_product_ref"; // table that contains the info about the product
  $productref = "field_product_ref_target_id"; //

  // The following query prints the Title of our Object and the ID of the product it references

  $query = db_query ("Select n.nid AS nid, n.title AS title, p.$productref AS productid
  FROM {node} n
  INNER JOIN {$products} p ON p.entity_id = n.nid");

foreach ($query as $row) {
  print 'Swatch Title: '.$row->title.'
';
  print 'Product ID: '.$row->productid.'

';

}

This outputs:
Swatch Title: Saddle Brown
Product ID: 19
Swatch Title: Sandalwood
Product ID: 20
Swatch Title: Saratoga
Product ID: 22

However, we want to also return the actual title of the product being referenced not its Product ID. A separate query can do this:

    $query = db_query ("Select n.nid AS pnid, n.title AS ptitle, p.entity_id AS productentityid
      FROM {node} n
      INNER JOIN {$products} p ON p.$productref = n.nid");

    foreach ($query as $row) {
      print 'Product Title: '.$row->ptitle.'
';
      print 'Swatch ID: '.$row->productentityid.'

';

    }

Our second query's output:
Product Title: Slab
Swatch ID: 265
Product Title: Stone
Swatch ID: 184
Product Title: Brick
Swatch ID: 185

We would like the results to be:

Swatch Title: Saddle Brown
Product Title: Slab
Swatch Title: Sandalwood
Product Title: Stone
Swatch Title: Saratoga
Product Title: Brick

Can anyone clear up how to combine the 2 queries to get the intended output?

I think you just want to join the node table in to your query again and grab the title that way:

$query = db_query("
  SELECT n.nid AS pnid, n.title AS ptitle, n2.title as swatch_title
    FROM {node} n
    INNER JOIN {$products} p ON p.$productref = n.nid
    INNER JOIN {node} n2 ON n2.nid = p.$productref"
);


Specify default sort header for a sortable table (tablesort) in D8? I am trying the table sort example module and noticed that I am unable to specify the default sort col once the page load. Meaning, when the page load for the first time it's always sorting by the first column in the table. In this case the number column (see screenshot). I tried 'sort'=> 'DESC' and 'sort'=> 'ASC' on the second and third col but it did not pick any as a default sort col.
  Here is the code generating the tablesort:

<?php

namespace Drupal\tablesort_example\Controller;

use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\Database\Connection;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * Controller routines for tablesort example routes.
 */
class TableSortExampleController extends ControllerBase {

  /**
   * The Database Connection.
   *
   * @var \Drupal\Core\Database\Connection
   */
  protected $database;

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static(
      $container->get('database')
    );
  }

  /**
   * TableSortExampleController constructor.
   *
   * @param \Drupal\Core\Database\Connection $database
   *   The database connection.
   */
  public function __construct(Connection $database) {
    $this->database = $database;
  }

  /**
   * A simple controller method to explain what the tablesort example is about.
   */
  public function description() {
    // We are going to output the results in a table with a nice header.
    $header = [
      // The header gives the table the information it needs in order to make
      // the query calls for ordering. TableSort uses the field information
      // to know what database column to sort by.
      ['data' => t('Numbers'), 'field' => 't.numbers'],
      ['data' => t('Letters'), 'field' => 't.alpha'],
      ['data' => t('Mixture'), 'field' => 't.random'],
    ];

    // Using the TableSort Extender is what tells  the query object that we
    // are sorting.
    $query = $this->database->select('tablesort_example', 't')
      ->extend('Drupal\Core\Database\Query\TableSortExtender');
    $query->fields('t');

    // Don't forget to tell the query object how to find the header information.
    $result = $query
      ->orderByHeader($header)
      ->execute();

    $rows = [];
    foreach ($result as $row) {
      // Normally we would add some nice formatting to our rows
      // but for our purpose we are simply going to add our row
      // to the array.
      $rows[] = ['data' => (array) $row];
    }

    // Build the table for the nice output.
    $build = [
      '#markup' => '<p>' . t('The layout here is a themed as a table
           that is sortable by clicking the header name.') . '</p>',
    ];
    $build['tablesort_table'] = [
      '#theme' => 'table',
      '#header' => $header,
      '#rows' => $rows,
    ];

    return $build;
  }

}

I was trying  $header= [ .... ['data' => .... 'sort'=> 'DESC' , and that was not working. After step debugging, I found out the sort value is case sensitive. In function tablesort_get_order we have

  if (empty($default) && isset($header['sort']) && ($header['sort'] == 'asc' || $header['sort'] == 'desc')) {
    $default = $header;
  }

So it must be lower case to work. So the follwoing code achieve the desired behavior:

$header = [
      // The header gives the table the information it needs in order to make
      // the query calls for ordering. TableSort uses the field information
      // to know what database column to sort by.
      ['data' => t('Numbers'), 'field' => 't.numbers'],
      ['data' => t('Letters'), 'field' => 't.alpha'],
      ['data' => t('Mixture'), 'field' => 't.random', 'sort' => 'desc'],
    ];

hope this helps others.


Drupal View of CiviMember troubleshooting I've created a Drupal View of our current members in CiviMember

SELECT civicrm_contact.organization_name AS civicrm_contact_organization_name,    civicrm_website.url AS civicrm_website_url
FROM
{civicrm_membership} civicrm_membership
LEFT JOIN {civicrm_contact} civicrm_contact ON civicrm_membership.contact_id =  civicrm_contact.id
LEFT JOIN {civicrm_website} civicrm_website ON civicrm_contact.id = civicrm_website.contact_id
WHERE (( (civicrm_membership.status_id IN  ('4', '5', '6')) AND   (civicrm_contact.contact_type NOT IN  ('Individual', 'Household')) ))
ORDER BY civicrm_contact_organization_name ASC
LIMIT 50 OFFSET 0

But it keeps on returning duplicate results, sometimes 3 or 4 in a row and yet they're all single contact records with one current membership? Can anyone see where I've gone wrong?

Is there nothing to give you a clue in the actual table of results? Eg are the duplicates ones that have multiple websites (since that field has not filtering in field for ' website type' afaik but you should be able to apply a Views Filter)
That seems the most likely reason.
If not, have you tried setting the Query Settings (under Advanced) to Disinct or Pure Distinct.
If none of that helps, can you attach the view?


How to add dynamic created css using drupal_add_css I am trying to add a file which is located in sites/default/files/color/theme-768/color.css using drupal_add_css().

I have tried drupal_add_css($filepath), but it doesn't work. I tried putting it in template.php and hook_init(), but still it isn't included in the style tags of head section or anywhere.

How I do include a CSS file like this using drupal_add_css()?

I found a alternate way to include css file which is in some other location other than modules and themes.In my case including a dynamically generated file.
Even though i can't find a way through drupal_add_css(),this helped me in adding css.

This is the way i included dynamically generated css file which is located at sites/default/files/color/theme-768/color.css

In the theme folder in the html.tpl.php  after <?php print $styles;?> include this

<?php
       print '<style>';
       print '@import url("' . $filepath . '")';
       print '</style>';
?>

This includes the css file.


How can a site programmatically detect if cron has not run in a long time? I'm developing a module intended to proactively warn the admin if there are problems with the site. The idea is to periodically check the system status report and sends an email notice if certain statuses have gone from REQUIREMENT_OK to REQUIREMENT_WARNING or REQUIREMENT_ERROR. I'm planning on firing this check in hook_cron().

But what if the problem with the site is that cron is broken? What is a safe and performant way for the site to periodically check if the 'cron_last' variable is too old, that doesn't rely on cron?

I would like to keep the module self-contained and avoid external dependencies or "phone home" solutions.

What is a safe and performant way for the site to periodically check
  if the 'cron_last' variable is too old, that doesn't rely on cron?

As said before by @Clive, you a script running periodically to do this check for you. Having said so, the simplest way is to create a basic module that checks the last time Drupal Cron ran succesfuly and acts based on that. You could include a drush command so you can call it via a server cronjob. E.g.

Check if cron hasn't run in X minutes and send e-mail if so, using  Drush

1) Create a file named cronwatch.drush.inc

2) Create the drush command that you will invoke via a crontab / automated task in your server. For instance, you would be running drush cronwatch every X minutes.

/**
 * Implements hook_drush_command().
 */
function cronwatch_drush_command() {
  $items = array();
  $items['cronwatch'] = array(
    'description' => dt('Check last time Drupal cron ran and send an email if necessary.'),
  );
  return $items;
}

3) Add a function to check if Drupal Cron hasn't run in longer than X minutes, send an alert email.

/**
 * Callback function for drush cronwatch command.
 */
function drush_cronwatch() {
  // Minutes since the last time cron run.
  $last_cron = variable_get('cron_last', 0);
  $minutes_ago = (time() - $last_cron) / 60;

  // How many minutes to allow without having run the cron.
  // This number should be larger than the frecuency of Drupal cron. E.g. If
  // Drupal cron is set to run every 60m, this number could be 70.
  $tolerance = 70;

  // If the cron last ran longer than tolerance minutes ago, it means that it
  // probably failed.
  if ($minutes_ago >= $tolerance) {
    $to = 'you@example.com';  // E-mail to get the alerts
    $message = t('Drupal cron could not run successfuly. Last succesful run was !minutes minutes ago.', array('!minutes' => floor($minutes_ago)));
    drush_mail_send_email($to, 'Drupal Cron failed', $message);
  }
}

4) Finally, this is the function to send an e-mail via drush:

/**
 * Send an e-mail to a specified e-mail address from within Drush.
 * @see http://drupal.org/files/mail.drush_.inc__0.txt
 */
function drush_mail_send_email($to, $subject = '', $body = '') {
  // Define $from and headers
  if (!$from = drush_get_option('from')) {
    // E-mail to send the alerts from. Replace here if desired.
    $from = ini_get('sendmail_from');
  }
  $headers = array();
  $headers['From'] = $headers['Sender'] = $headers['Return-Path'] = $headers['Errors-To'] = $from;

  // D7 implementation of drupal_mail
  if (function_exists('drupal_mail_system')) {
    // Prepare the message.
    $message = drupal_mail('drush', 'key', $to, NULL, array(), $from, FALSE);

    $message['subject'] = $subject;
    $message['body'] = array();
    $message['body'][] = $body;
    $message['headers'] = $headers;

    // Retrieve the responsible implementation for this message.
    $system = drupal_mail_system('drush', 'key');
    // Format the message body.
    $message = $system->format($message);
    // Send e-mail.
    $message['result'] = $system->mail($message);
    $result = $message['result'];

    // D6 implementation of drupal_mail_send
  }
  else {
    $message = array(
      'to' => $to,
      'subject' => $subject,
      'body' => $body,
      'headers' => $headers,
    );
    $result = drupal_mail_send($message);
  }

  // Return result.
  if ($result) {
    drush_log(dt('E-mail message sent to !to', array('!to' => $to)), 'ok');
  }
  else {
    drush_set_error('DRUSH_MAIL_ERROR', dt('An error occurred while sending the e-mail message.'));
    watchdog('cronwatch', 'An error occurred while sending the e-mail message with Drush.', array(), WATCHDOG_ERROR);
  }
}

And there you go. If Drupal Cron is set to run -let's say- every 60 min, and for some reason failed, the next time this script is executed, it will send you an alert e-mail and you can act based on that.

---- EDIT: Added code to check without depending on Drush / Server Cronjobs ----

Check if cron hasn't run in X minutes and send e-mail if so (no Drush / Server cronjobs)

You could also run the checks without Drush nor server cronjobs. For this, you will necessarily need to hook your checks to a certain event in your website (e.g. every page load).

In your cronwatch.module file:

1) In this case, we check on every page load, that is almost guaranteed to run periodically. However, you can use any other hook to trigger your checks.

Let's find out when the Drupal cron check was last executed.

/**
 * Implements hook_page_alter().
 *
 * Finds out when was the last time Drupal cron check was executed. If it's
 * been longer than the desired frequency, proceeds with a new check.
 *
 * We depend on page loads in order to emulate a 'periodically running' event,
 * as an alternative to a server cronjob / scheduled task.
 */
function cronwatch_page_alter() {
  // Defines how often we want to run the checks (in minutes).
  // We need this flag variable, since we don't want to make a check on
  // every single page load.
  $frequency = 60;

  // Only proceed if it's been longer than 60 minutes since the last check.
  $last_check = variable_get('cronwatch_last_check_timestamp', 0);
  $minutes_ago = (REQUEST_TIME - $last_check) / 60;

  if ($minutes_ago < $frequency) {
    return;
  }

  // More than 60 min have passed since the last check. So, let's proceed with
  // a new check.
  if (cronwatch_check()) {
    // Check was succesful. Now update the 'last check timestamp' variable so
    // the next check runs an hour from now.
    variable_set('cronwatch_last_check_timestamp', REQUEST_TIME);
  }
}

2) Make the actual check for the last time Drupal cron ran. If more than X minutes have passed, send an email.

/**
 * Checks the last time Drupal cron ran, and acts based on that.
 */
function cronwatch_check() {
  // Minutes since the last time cron run.
  $last_cron = variable_get('cron_last', 0);
  $minutes_ago = (time() - $last_cron) / 60;

  // How many minutes to allow without having run the cron.
  // This number should be larger than the frecuency of Drupal cron. E.g. If
  // Drupal cron is set to run every 60m, this number could be 70.
  $tolerance = 70;

  // If the cron last ran longer than tolerance minutes ago, it means that it
  // probably failed.
  if ($minutes_ago >= $tolerance) {
    $to = 'you@example.com';  // E-mail to get the alerts
    $message = t('Drupal cron could not run successfuly. Last succesful run was !minutes minutes ago.', array('!minutes' => floor($minutes_ago)));
    $mail_sent = cronwatch_mail_send_email($to, t('Drupal Cron failed'), $message);

    if ($mail_sent) {
      return TRUE;
    }
  }
  return FALSE;
}

3) Function to send an e-mail

/**
 * Sends an e-mail from the cronwatch module.
 */
function cronwatch_mail_send_email($to, $subject, $body) {
  // Let's get the mail ready to be sent.
  $module = 'cronwatch';
  $key = 'alert_mail';
  $from = variable_get('site_mail', ini_get('sendmail_from'));
  $language = language_default();

  // Build the mail, but don't send it yet.
  $message = drupal_mail($module, $key, $to, $language, array(), $from, FALSE);

  // Prepare the message.
  $message['subject'] = $subject;
  $message['body'][] = $body;

  // Retrieve the responsible implementation for this message.
  $system = drupal_mail_system($module, $key);

  // Format the message body.
  $message = $system->format($message);

  // Send e-mail (Drupal will log any error).
  $message['result'] = $system->mail($message);

  return $message['result'];
}

Only drawback is you depend on page loads, so accuracy would be affected by a website with very few or no visits (in that case, do you even need this?). And, of course, this code could be refactored, but this should do the trick.


How to apply image style to image field in view based on the sort position of that image field? my homepage is done with panels. Home panel contains a view that displays specifically 9 nodes that contain image field. Sort criteria is Random. These 9 nodes are in three rows each containing three. What I want to achieve is that image field of the first node in the first row would have image style: medium, second node in the row would have style: large, third would have medium again. Second row first node would have image style: large and so on.

I know there is a module to style specific nodes but this styling should be based not on the node itself but on the position it was given by the Random sort. Please see image attached.

I think it would be acceptable to shrink the images using CSS, but then each position should have it's own class, how could I go about this? Without JS li order targeting would be preferable.

Thanks a lot for your help.

You can add a field of the type "Global: View result counter"

This will add a number depending on the position of the result.

You can use this to add a class using token to the image.


Entity Query from comment not working I tried using entityquery for comment by nid but its not working here is my code :

$query = new EntityFieldQuery();
    $query->entityCondition('entity_type', 'comment')
    ->entityCondition('entity_id', 257, '=')
    ->addMetaData('account', user_load(1));

and also I tried changing to nid but still its showing all the comments instead of by specific nid:

$query = new EntityFieldQuery();
    $query->entityCondition('entity_type', 'comment')
    ->entityCondition('nid', 257, '=')
    ->addMetaData('account', user_load(1));

can someone tell me I am doing anything wrong?

thank you

nid is a property of the comment entity, so try:

$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'comment')
    ->propertyCondition('nid', 257)
    ->addMetaData('account', user_load(1));


Node value from form state I have a node which I want to update from a form states values. I can set each value individually like:

$node->set("foo", "bar");

Is there a way to mass assign the values instead of setting each individually?

You can always create an array of name/value pairs and then a simple foreach loop to set them all. Or you can pass it to Node::create() if it is a new node.

There is no setMultiple() or similar API.


How is the file data in the database table file_usage created and managed? I am deleting orphaned image files in Drupal 7, but I have to first cross reference them to other tables that might be using the images. Given that I don't upload any images via the IMCE editor interface and mainly do uploads via the image module, would it be safe to say i can cross reference the table file_managed and image_dimensions to file_usage and delete what's not there?

Right now I'm just wondering how file_usage is populated. Is it populated every time I upload any file type?

The code used by Drupal to delete temporary files is the following one. (It runs during cron tasks.)

  // Remove temporary files that are older than DRUPAL_MAXIMUM_TEMP_FILE_AGE.
  // Use separate placeholders for the status to avoid a bug in some versions
  // of PHP. See http://drupal.org/node/352956.
  $result = db_query('SELECT fid FROM {file_managed} WHERE status <> :permanent AND timestamp < :timestamp', array(
    ':permanent' => FILE_STATUS_PERMANENT,
    ':timestamp' => REQUEST_TIME - DRUPAL_MAXIMUM_TEMP_FILE_AGE,
  ));
  foreach ($result as $row) {
    if ($file = file_load($row->fid)) {
      $references = file_usage_list($file);
      if (empty($references)) {
        if (!file_delete($file)) {
          watchdog('file system', 'Could not delete temporary file "%path" during garbage collection', array('%path' => $file->uri), WATCHDOG_ERROR);
        }
      }
      else {
        watchdog('file system', 'Did not delete temporary file "%path" during garbage collection, because it is in use by the following modules: %modules.', array('%path' => $file->uri, '%modules' => implode(', ', array_keys($references))), WATCHDOG_INFO);
      }
    }
  }

file_usage_list() is the function that queries the "file_usage" table.
The function that adds a row in that table is file_usage_add(); looking at the functions/hooks that calls it, I conclude that the "file_usage" table is used for managed files. Since you are not deleting the files with a row in the "file_managed" table, I would say you can avoid checking the "file_usage" table.


How to change commerce order owner to someone else? I create a commerce order for a spesific user prograticaly by admin user, after completing checkout process by admin, I want to change owner of order to someone else to show created order in order history of spesific user
I changed the uid of order but does not work for me.

-> If you want to do programatically, then Load Order as
$order = commerce_order_load(1);
$order->uid = 4;
commerce_order_save($order);

-> By admin UI
   Edit order and in User Information, specofy username of user you want to assign and save.


How can I add relative path to a pdf file link in drupal menu I have created menu link for a pdf file. I can use a full path like "http://website/sites/all/myfiles/file.pdf", but if I try to put a relative link such as "sites/all/myfiles/file.pdf" it does not work. If anyone has idea please tell me.

The thing with the menu system is that what you are typing is not a relative path, but an internal Drupal URL.

Since what you are after is not a Drupal path, but instead a static file server outside of Drupal by your webserver your options are limited.

You can write the full url like you tried yourself
You can create a module/theme where you can make this possible, either by adding the extra link or creating a drupal path that redirects to the static file.

Of these, I personally think that a an absolute path is the lessor of evils, unless you need to do this a lot of times.