RewriteRule fails if called after line 112 of .htaccess I'm having an issue that is similar to this question.

In short, I'm trying to use some custom RewriteRules to point old (no longer functioning) urls to new working urls. To accomplish this, I'm trying something similar to:

RewriteRule ^oldsite/directory/ABCD(.*)\.html? /search/$1 [NC,R=301,L]

The issue is, this is completely ignored (as mentioned in the question linked to before.) However, I've noticed that if I move my RewriteRule from the bottom of the .htaccess file up a bit to line 112, which is:

# Pass all requests not referring directly to files in the filesystem to
  # index.php. Clean URLs are handled in drupal_environment_initialize().
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteCond %{REQUEST_URI} !=/favicon.ico
  RewriteRule ^ index.php [L]

The the rewrite rules work just perfectly fine. The answer to the previous question said that you couldn't use a clean url destination. So this would work:

RewriteRule ^home/code/([^/]+) ?q=home/software/node/&code=$1

but this won't:

RewriteRule ^home/code/([^/]+) home/software/node?code=$1

Problem is neither of them seem to work for me. I remember a few D7 updates ago there was an update to the .htaccess files. Could that be effecting this? Is there another way around this issue to get RewriteRules to work?

Just put it above line 112. The reason it doesn't work below that is line 117:

RewriteRule ^ index.php [L]

that [L] means that if the conditions above it match and that rule is applied no further rules will be checked. If you put it above that line clean or non-clean style url will work fine but probably don't want to include an L on the end of your rule so use:

RewriteRule ^home/code/([^/]+) home/software/node?code=$1 [R=301,NC]

on line 111 (well whatever actual content rule you need).


Date exposed filter default value I've got exposed date filter (with daily granularity) and I want to provide default value for it. I just want to show nodes that have today 'field_date' date by default. The field has both start and end date. I use start date for exposed filter.

How can I achieve it?

This can be done through contextual filters in views.

Navigate to edit the structure of your view, click advanced and add a contextual filter. Here you will select the date field and "Apply"

On the next page, under "WHEN THE FILTER VALUE IS NOT IN THE URL" you want to "Provide default value" of type "PHP Code". The code you want to use is fairly simple, but depends on your date/time setup. you should have something like this in the php code field:

return date("Y/m/d");

Good Luck!


Fetch data from database in cron_hook I made a custom module which runs during cron via de cron_hook.
On installation of the module a database table is installed:

  $schema['license_expire'] = array(
    'description' => 'The base table for license_expire.',
    'fields' => array(
      'uid' => array(
        'description' => 'The primary identifier for a user.',
        'type' => 'int',
        'unsigned' => TRUE,
        'not null' => TRUE,
        'default' => 0),
      'warned_user' => array(
        'description' => 'User warning',
        'type' => 'int',
        'unsigned' => TRUE,
        'not null' => TRUE,
        'default' => 0),
    ),
    'primary key' => array('uid'),
  );
  return $schema;

When the cron runs content is added to the database.
Say uid = 1 and warned_user = 1.

But when I try to fetch this warned_user data in de cron_hook it doesn't return any.

function hook_cron() {
//EXPIRE VARIABLES
$expiresMonth = strtotime('+1 month');
$expiresWeek = strtotime('+1 week');
$expired = strtotime('today');

//ALL USERS EXPIRING WITHIN ONE MONTH
$query = new EntityFieldQuery();
$query
->entityCondition('entity_type', 'commerce_license')
->propertyCondition('status', COMMERCE_LICENSE_ACTIVE)
->propertyCondition('expires', 0, '<>')
->propertyCondition('expires', $expiresMonth, '<');
$results = $query->execute();

//SEND EMAIL TO USERS
if (!empty($results['commerce_license'])) {
    $license_ids = array_keys($results['commerce_license']);

    //all licenses
    foreach($license_ids as $license_id) {

       //get Uid
       $myUid = db_select('commerce_license','cl')
         ->fields('cl', array('uid'))
         ->condition('license_id', $license_id)
         ->execute()->fetchField();

       //for testing it only works for de admin account
       if($myUid == 1){
           //get user
           $to = user_load($myUid);

           //get expiring timestamp
           $myExpire = db_select('commerce_license','cl')
             ->fields('cl', array('expires'))
             ->condition('license_id', $license_id)
             ->execute()->fetchField();

           $myDate = date("d-m-Y", $myExpire);

           //get times user is noticed
            $myMessages = db_select('license_expire','le')
            ->fields('le', array('warned_user'))
            ->condition('uid', $myUid)
            ->execute()->fetchField();

           //for some reason the $myMessages value is nothing so watchdog is "myMails = = 1"
           watchdog('license expire', 'myMails = '.$myMessages.' = '.$myUid);

           if($myMessages){do something, but it never does because it can't pull $myMessages value from the db, and it sure is there}

The above code does work when I use it in a page.tpl.php file.

I found something about, cron being a Anonymous user and this could be the problem but the solution offered didn't work for me. What dit I forget/overlook/do wrong?

I found the problem, I was using the same variable names (for example $query) in different custom modules I build. Changing these variable names to unique names made it work perfectly.


What is wrong with this drush command in Drupal 7 Ubercart 3 to delete orders in bulk via command line? I am trying to delete my Ubercart 3 orders in bulk via the command line with just a one liner:

for XX in {1..12}; do drush ev 'uc_order_delete($XX)' -v; done;

It beats having to do it via the bulk operations in views. I'm not sure whats wrong with my command as it says I have an Undefined variable when i put $XX in quotes.

You've to use double quotes instead of single quotes, so variables retain their special meaning.

Read more:

https://stackoverflow.com/questions/6697753/difference-between-single-and-double-quotes-in-bash


How can I manage site translations in code? I have a site with multiple translations, including a heavily customized version of the default Drupal "English."  (The use case requires that a lot of the help text and labels throughout Drupal be changed.)

I am using the Features module to manage deployment.  However, I can't find a way to manage translations in code.

Currently, I visit the Languages page, click export, download the .po file for each type (built-in interface, node types, taxonomy) for each language, and then commit these downloaded files to code.  This seems extremely inefficient compared to working with Features.

I looked for a Drush command to help but the 5.0-rc3 version which I'm using doesn't have any i18n-related commands.

How can I manage site translations efficiently in code?

I had the same problem and had a look at the module Features Translation. However, there were some downsides to it. Don't know exactly what is was. From what I can remember is that when I import a feature, for example the menu link labels are imported in the built in interface. So it doesn't help to import the translations for Menu Items because the source labels are not available there but in the Built In interface. But maybe I am wrong, tried so many things I can really recall what I did.

But you can have a look at it, maybe it works for you.

Tell us when you have found a suitable solution. I am curious.


How to embed videos using the video module? I installed the video module and activated video and video ui modules using Drupal 7:
https://www.drupal.org/project/video

I created a content type with a video field. Now I can upload videos with this content type.

But I am not able to embed a youtube video. I can not find any settings or any embed widget as shown here.

I want to upload videos and I want to embed videos (youtube, vimeo..).
But I can not find any way to embed a video unsig this video module.

Do I have to install further modules?
On the module page you can read:

  Video module allows you to embedded videos from YouTube, Vimeo,
  Facebook, Vine etc (Drupal 8 only) and upload videos and play using
  HTML5 video player.

I can not find out how to embed a video using this module. Can you help?
I do not want to use another module, I want to find out how to embed videos using THIS module. Be in mind of this when you write your answer. Thank you.

If you install the WYSIWYG module, you can enable a button for embedding videos that have been uploaded using the Video module, and then you can use that button to embed videos into content.


Avoid duplicate hits in two separate Views I'm using Views to generate a number of lists, e.g. Newest articles and Popular articles.
Now, often newest articles will also be in the Popular articles list.

So when I'm using both views on frontage, I would like to prevent, that the same article is shown on both lists.

So basically skip articles in Popular list, if they also are available on Newest list.

This is not trivial to accomplish, and will in most cases require coding.

First of all, it's necessary to determine in which order the lists should be evaluated. One of them needs to take priority. The gist of the solution, is that in some way, you need to feed the hits from the first list, as arguments to the second list.

In Views, you can add a Contextual filter, or Argument, depending on your version. These arguments can be set to "exclude" their matches, and it's also possible to allow "multiple arguments per filter".

The high priority View can be left as it is, but the low priority View should be configured so that it takes several entity-id's as arguments, and excludes those from the result. The real difficulty for most is going to be in passing arguments between these two Views.

In code:

$first = views_get_view('most_important_view');
$second = views_get_view('less_important_view');

// Get results, but don't render them.
$first->preview('machine_name_of_display');

// Append together a list of node id's to a string.
$nodes_to_exclude = '';
foreach($view->result as $node) {
  $nodes_to_exclude .= $node->nid . '+';
}
// Remove the trailing +.
$nodes_to_exclude = rtrim($nodes_to_exclude, '+');

$second->execute_display('machine_name_of_display', array($nodes_to_exclude)););
return $second->render();

If you are not comfortable using the above code, there is a module called Viewfield that allows you to call a second View from a primary View. But unfortunately I'm not aware of a way to configure this to pass several arguments on, but just a single one, so I'm not sure if that's helpful.


Views exposed taxonomy filter - show only terms within results I have a block display with an exposed 'term' filter using BEF links filter.
I have the need to reduce the terms to display only the ones that show within the blocks results.

For example I have 'term1', 'term2', 'term3' - then if within the results there is only 'term1', 'term2' - I need to remove 'term3' from the list of filter links.

I realize that the filter is built before display so I am having difficulty grasping how the filter can be modified depending on what is in the display.

Any help is much appreciated.

Have a look at views_hacks. Specifically refer to Views Selective Exposed Filters (views_filters_selective)


How to change field values in a view programatically? I'm working in a custom module that displays date fields. I want to be able to change the date's timezone programmatically.

I've tried implementing hook_views_pre_render(), but that doesn't allow me to format the field value. I'd really like to do the theming inside my module code since that's where the logic is regarding my timezone.

As a total hack, I could use hook_views_post_render(), but then I'd be doing search/replace on the text and that seems like a poor solution.

What other hooks inside my module are available?

Okay, so after a little more googling I found my own answer on a thread on d.o that address this issue with sample code (which I'm condensing a bit):

<?php
/**
 * Implements HOOK_preprocess_views_view_fields().
 */
function MYTHEME_preprocess_views_view_fields(&$vars) {
  $view = $vars['view'];

  //Replace 'VIEW_NAME' with the machine_name of your view.
  if($view->name == 'VIEW_NAME') {

    //This for loop iterates over all fields in this view.
    foreach ($vars['fields'] as $id => $field) {

      //Custom formatting logic goes here....

      //Set the field value (not the surrounding tags) here.
      $vars['fields'][$id]->content = 'my new value';
    }
  }
}
?>

NOTE Make sure you replace "MYTHEME" with the name of your theme or module in order for this work.


Print array element syntax I am using devel and <?php dpm($items); ?> in my field template file so the node looks like the following.

I can print the #theme element (which is a string) with the following code.

<?php print $items[0]['#theme']; ?>

What is the syntax to print elements in an array such as URLs, labels, titles?

You'll have to follow the trail in the DPM structure. The url field is under the #element element. The #element element is under the 0 element. This means you can access the value of url with:

$items[0]['#element']['url'];

You can reach the title element in a similar way.

The value of #theme is directly under the 0 element, that is why you could access it with:

$items[0]['#theme']


Views isn't pulling custom field correctly I've been developing a custom module, which uses the node id, with the rate module, to output the results to a simple mathematical equation (which uses the rate module - i.e. voting api) to calculate the total number of votes.

The calculation is completed as part of hook_field_formatter_view for the field. It is then passed through to the node's display.

The issue arises when passing through this same value to a Views output. It seems the node id isn't passing through to the field, which renders this whole problem impossible. I have been using this to access the node id:

  $node = menu_get_object();
  $nid = $node->nid;

Which is then used to retrieve the necessary values from the database for the calculation. However, all fields are returning 0 (null) values in the views output.

Is this because the node id is not passing through, or could it be something else?

When using menu_get_object(), you'll get the node currently displayed from the menu. So for example, if you're on a page with a path like node/123, it will load the node with nid "123" (source). So that won't work inside a views for sure.

You should be able to retrieve the nid from the $entity element, which should be a parameter of your hook_field_formatter_view (as described here).


How to delete files when the node that displayed them is deleted? Is there a way to delete files/images from the server automatically when the main node is deleted?

How do I implement this?

It's a revisions thing. I guess it makes sense. If you have revisions enabled for that content type, it keeps all your old files on the server (associated with old revisions), so replacing a file definitely is harder. If you try to remove it and add it again to the node, the name/link is updated, as I mentioned in my question. Since a file with that name is kept on the server and there is a name duplication, it adds those "_0", "_1" etc suffixes to future uploaded versions of that file's name.

I understand why this is happening though, since the whole point of revisioning is being able to revert to any past version of the page.

The work-around is that you can actually delete the old revision from the 'Revision' or 'Moderate' tab (if using Workbench Moderation) that contained the file you're trying to replace. Then upload it again, and the name should then match without you having to go back and edit any links pointing to that file.

Hope that makes sense and that it helps somebody else too!


Is there any way to see the content of the theme registry? I was wondering if there is a way to see (print out) the content of the theme registry.

I've looked in the database; it seems to be stored in the cache table, if I understand things right, but the theme registry itself is stored as a blog.

When I looked at the blog, I couldn't seem to make any sense of what was there. It all seemed to look like hex values.

If you want to see the content of the theme registry, you can use _theme_load_registry(). The first argument could be the global $theme for the currently used theme, or one of the objects returned by list_themes().
As the function name is prefixed by an underscore, I would suggest to use it only for debugging purposes. (Theoretically, future Drupal versions could drop those private functions, and that would not probably be taken as API change.)

If you have installed Devel, you can use the following code:

global $theme;

$registry = _theme_load_registry($theme);
dsm($registry);

You can also simply visit the devel/theme/registry page which shows you the theme registry content.


How to create permission to allow access to an admin form? We have created a custom permissions that we want to use to prevent unauthorized access to an admin form. Only someone with "administer admin_form" should have access to the page. There is a menu link that was created to allow access to the page.

How can I create a controller that will check if the user has the permission and hide the menu link if the user does not have the permission? If somehow they got access to the menu link path, we would also like to display a message "you do not have access to this page" and hide the form.

We have tried the following:

mymodule.permissions.yml

administer admin_form:
  title: 'Administer admin form'
  description: 'Allows the ability to change settings'
  restrict access: true

mymodule.links.menu.yml

mymodule.settings:
  route_name: mymodule.settings
  title: 'My module'
  description: 'some message'
  weight: 99

mymodule.routing.yml

mymodule.settings:
  path: /admin/config/user-interface/admin-form
  defaults:
    _title: 'My module setting'
    _form: \Drupal\mymodule\form\AdminForm
  requirements:
    _permission: 'administer admin_form'

I think you can omit restrict access and remove the _ from your permission name.

Anyway, you have a typo in your permission key. It should be _permission instead of _permissions. See: https://www.drupal.org/docs/8/api/routing-system/introductory-drupal-8-routes-and-controllers-example

Make that change and clear the cache.


Cannot install modules I am very new to Drupal so please excuse me if this is an easily answered question.

Basically I wish to install CKEditor, however when I upload the module thorugh the online installer I am greeted with:

ckeditor_4.4.5_full.zip does not contain any .info files.

On trying to install from the URL another error:

The specified file temporary://files2sU5P could not be copied, because the destination directory is not properly configured. This may be caused by a problem with file or directory permissions. More information is available in the system log.
http://ftp.drupal.org/files/projects/ckeditor-7.x-1.15.zip could not be saved to temporary://update-cache-ac727b57/ckeditor-7.x-1.15.zip.
Unable to retrieve Drupal project from http://ftp.drupal.org/files/projects/ckeditor-7.x-1.15.zip.

When I attempt to install a different module (weather module) to test to see if it is the module itself, again an ulgy:

weather-7.x-2.6.zip does not contain any .info files.

Finally, on an attempt to place the extracted .zip file on the webserver in the /sites/all/modules directory, nothing shows up, I only see the 'Core' modules listed.

Any suggestion as to what I should do? Any help greatly appreciated,
- Dylan.

Try to check the settings of the "temporary directory" under File System (admin/config/media/file-system) admin page.

Usually should be folder: /tmp
Check if the folder has write access (specially for apache or the HTTP web server you are using).

You could find more info at Drupal documentation.


Defining a Complex Sort (by stripping out a pre-defined set of words) with Views I'd like to do a more complex sorting on my Drupal 7 View. Specifically, I'd like to sort by a particular field alphabetically (easy - that's the default). However, before the View sorts the field I want it to strip out (a predefined) set of words at the beginning of the field (if they exist) such as the word 'the' or 'a' and sort based on the words that follow.

Does anyone know if this is possible?

My workaround will be to just create a 'sort by' field in the content type.

Have you tried Views Natural Sort -module?

  Provides a views filter that sorts node titles by a more natural manner by ignoring articles like "The" and "A."

Not sure if it matches your needs because of "sorts node titles" and in your question you talk about particular field. But maybe you should try it?

At least you can get base for custom module if you need to build one.


How do I manually migrate a site? So far I copied all files to a new directory.

Put the site into Maintenance Mode

Then I downloaded the database and imported it into a new database I created.

Truncated the following tables in the database

cachetags
cache_*

Updated settings.php with new database name, database user and password.

Currently the problem I am having is that I where I moved it to has a different path. Before I had my Drupal site set up at /xyz/my_drupal_site and now I have it set to /abc/my_drupal_site. I believe at this point I just need to update the database with the new path and I am not sure what needs to be updated (a global replace did not seem like good idea) or if there is an admin page that I can go to to take care of it.

I found instructions for Drupal 7 and they mentioned /admin/settings/file-system but it does not appear to exist in Drupal 8.

Also I want to make sure I am not missing anything else.

You likely don't need to change anything at all. Just move the folder and clear caches. Maybe you need to change the path in settings.php but only if you hardcoded it there before.

The instructions you found are for Drupal 6 and changing the path is no longer necessary unless you manually changed it to something else than the default location before.


How to grant referenced user access to Profile page I use Node access user reference module in many projects. I have a very similar task: Grant access to a profile page for those user who is referenced in that profile. Unfortunately, Node access user reference doesn't work in this case, since it's not a node but a different kind of entity. Is there any solution for this task?

Here is ready to use code. For this to work you need to enable the Entity reference module, add entity reference field on admin/config/people/accounts/fields page targeting user entity and setting to unlimited, and finally giving access to View user profiles to all authenticated user role members.

Create my_module.info file and paste:

name = My Module
description = Does awesome things. Makes tea. Washes up. Favours of a personal nature.
dependencies[] = entityreference
core = 7.x

Create my_module.module file and paste:

/**
 * Implements hook_user_view_alter().
 */
function my_module_user_view_alter(&$build) {
  global $user;
  if ($build['#account']->uid == $user->uid || in_array('administrator', array_values($user->roles))) {
    // Return early if user is administrator or is at their own profile.
    return;
  } elseif (isset($build['field_users'])) {
    foreach ($build['field_users']['#object']->field_users[LANGUAGE_NONE] as $key => $referenced) {
      if ($user->uid == $referenced['target_id']) {
        return;
      }
    }
  }
  drupal_access_denied();
}

Go to a user profile, add some user references and try to view that user's profile as the referenced user to gain access and then as non-referenced user to get denied access.


Views 'Search terms' exposed filter not working as expected I have a view that displays a list of people. I want to allow the list to be filtered by its search terms, so I've added a 'Search terms' exposed filter. I'm using hook_form_alter() to override this exposed filter so the user can select from a list of countries, so they can "Search by country". This just passes a country name in as the exposed filter value. I've added a second 'Search terms' exposed filter so a user can further filter by keyword.

This doesn't seem to work as expected. When I choose 'Australia' from the first filter, I get 39 results, which is correct. When I then enter 'Astronomy' into the second filter, I get no results. I expected to get back 1 result, a user whose node contains both 'Australia' and 'Astronomy'. If I leave one filter blank and enter 'Australia Astronomy' into the other, I get the correct user result.

Is there a way to make this work the way I want to? The first exposed filter has to be filtering on a node's indexed content (find country mentioned anywhere in the node), so I can't filter on a single field here. Thanks in advance!

The mistake comes from the WHERE conditions :

AND(( (search_index.type = 'node') AND( (search_index.word = 'australia') ))AND( (search_index.type = 'node') AND( (search_index.word = 'astronomy') ))))

This will always return empty result ! Not convinced?  simply try

    SELECT * FROM `search_index` WHERE `word` = 'Australia' AND `word` = 'Astronomy'

So you'll need a subquery here : for the sake of example, let's say :

SELECT node.title AS node_title, node.nid AS nid
FROM node
LEFT JOIN search_index ON node.nid = search_index.sid
WHERE node.status = '1'
AND  search_index.word = 'Astronomy'
AND sid IN (
    SELECT sid FROM `search_index` WHERE `word` = 'Australia'
)
LIMIT 0 , 30

Now to get it I suggest that you implement hook_views_query_alter(&$view, &$query). First, call Views API :

/**
 * Implementation of hook_views_api().
 */
function YOUR_MODULE_views_api() {
  return array(
    'api' => 3, //Views 3
    'path' => drupal_get_path('module', 'YOUR_MODULE'),
  );
}

And then the tricky part

function YOUR_MODULE_views_query_alter(&$view, &$query) {
  if($view->name == 'YOUR_VIEW' && (count($view->YOUR_EXPOSED_FIELD) > 1 ) )  {
    dpm($view); //OR dpm($query);
    //alter your query here ; you'll have to debug and tune the following lines
    //short one
    $query->where ... = ...
    //alternative one
    foreach($query->where as &$condition_group) {
      foreach($condition_group['conditions'] as &$condition) {
        //not sure from here, use `dpm ()` on your own objects
        if($condition['field'] == 'search_index.word') {
          $condition = array(
            'field' => 'search_index.sid',
            'value' => db_query('SELECT sid FROM `search_index` WHERE `word` = '.$view->YOUR_EXPOSED_FIELD),
            'operator' => 'IN',
          );
        }
      }
    }
  }
}

  This hook should be placed in MODULENAME.views.inc and it will be
  auto-loaded. MODULENAME.views.inc must be in the directory specified
  by the 'path' key returned by MODULENAME_views_api(), or the same
  directory as the .module file, if 'path' is unspecified.

EDIT : as per Vincent, used add_where_expression for the subquery and unset the original part of the query related to that search

$query->add_where_expression('3', "sid IN (SELECT sid FROM search_index WHERE search_index.word = '{$search_value}')");
//sthing like
unset($query->where[1]['conditions'][0]);


Problem with HOOK_preprocess_breadcrump (Caching?) I run in a strange issue with breadcrumb modifying. In my template, I created a hook to show the current page in the breadcrumbs (for testing):

function business_preprocess_breadcrumb(&$variables){

if(($node = \Drupal::routeMatch()->getParameter('node')) && $variables['breadcrumb']){
    $variables['breadcrumb'][] = array(
                    'text' => $node->getTitle(),
                    'url' => $node->URL()
                   );
     }

}

The code above works after clearing the cache and loading the first node page. However, as soon as I load any other node page, it's always showing the title of the first loaded node (like it is cached). Even when I echo the Node id, I always see the same ID from the first node. How can I fix this?
I even tried to create a custom module which overrides the breadcumb generation - same result here.

Drupal 8.1.1.

Change the cache context from 'url.path' to 'url'

function xxx_preprocess_breadcrumb(&$variables) {
    ...
    $variables['breadcrumb'] = array(
      array(
        'text' => 'some text',
        'url' => "/someurl"
      )
    );
    ...
    $variables['#cache']['contexts'][] = 'url';
}

I ran into the same problem with Drupal 8.2.4


Can I clear front page cache only? How to clear only the front page cache? I want to clear the front page cache when a new node is added.

Drupal 6 and 7 use the URL of the page as the cache ID (the $cid, see drupal_page_set_cache()).  This should work.

$url = url('<front>',  array('absolute' => TRUE));
cache_clear_all($url, 'cache_page');

You will need to adjust the logic a bit if you can access the site through multiple URLs.


Chosen Module working on one  but not other selects I use drupal 8 and chosen module and I set "Minimum number of options for single select" and "Minimum number of options for multi select" and "Minimum number to show Search on Single Select" to "always apply" .
Now I create advanced searche with views and use 2 filter criteria whit entity refrenced exposed.
When I set one of them setting to dropdown and other to autocomplete , it worke correctly . But when I set all of them settings to dropdown chosen not work .

Set above code in theme.libraries.yml and it worked .

  dependencies:
    - core/jquery
    - core/drupal
    - core/jquery.once


What causes the errors in the rules that come with Commerce Coupon? I am trying to use Commerce Coupon module in my project. The problem is after download and enable this module, rules created by this module got error. And I can't find out what happened to this errors.

commerce coupon - 7.x-2.0-rc2+14-dev
commerce version - 7.x-1.11+39-dev
inline Conditions - 7.x-1.0-alpha7

Any suggestion is greatly appreciated.

A possible reason for running into this error is because the entity metainfo for "commerce_coupon_number_of_uses" is not provided, unless you have created a 'coupon type'.

In that case, try to create such coupon type and verify if it removes those errors.


How to get all linked nodes from all terms in a vocabulary I have a content type "News entry", which has a term reference "News category", which is of course a taxonomy vocabulary.

I’m not sure if I get this whole taxonomy thing right, but I’m able to render and theme each category correctly (/news/category-a).

Now I want to theme the overview or home page, which displays all news entries of all categories. Easiest way for me would be selecting the right rows out of the database, but I reckon that’s not very much the Drupal way.

So I figured out how to get all terms of a vocabulary. In the preprocessing function theme_preprocess_node_news_overview() I tried taxonomy_get_tree(). Now I've got an object for each term with the following contents:

http://i.stack.imgur.com/cbT8c.png
(can’t post images yet)

The news entries are preprocessed in theme_preprocess_node_news_post(), It’d be great if this function could be reused for the news overview.

And now I’m stuck. How do I get Drupal to behave like it’s displaying a category/tax. term, but instead of the nodes of one term get (and display) the nodes of all terms?

As "all linked nodes from all terms" are in my case the same as "all nodes of a content type", I solved my problem this way:

<?php
function themename_preprocess_node_news_overview(&$vars) {
  $results = db_query("SELECT nid, type FROM {node} WHERE type = 'news_post';");
  $tmp = array();
  foreach ($results as $result) {
    $tmp[] = $result->nid;
  }
  $vars['content'] = node_view_multiple(node_load_multiple($tmp), 'teaser');
}
?>


Make a directory and link it in a node at node creation I’m developing a site in Drupal 7 where users view a calendar of events as well as photos taken at those events.

I’ve already created an Event content type, generated several Event nodes, and put those nodes together in a Calendar view.

What I want to do now is add a ‘Photos’ link to Event nodes. Clicking on this link should open a gallery of photos for the given event. For example, imagine a user is viewing an Event node titled ‘Pool Party @ Jan’s House’. The user clicks on the node’s ‘Photos’ link and then sees a photo gallery also titled ‘Pool Party @ Jan’s House’ that displays all and only photos taken at that event.

How do I get the following two actions to happen (automatically) when an Event node is created?

Make a directory that will contain photos for the event. (These
photos will be uploaded later by users who attend the event.)
Include a ‘Photos’ link in the newly created Event node that opens a page display of the directory's files. (See the example I give above.)

I’ve been trying to figure this out using the Media, Rules, and Views modules, but I’m not making much progress.

Thanks in advance for your help.

Creating directories on the fly in the actual file system is uncharacteristic in Drupal.

The simplest way of attaching photos to nodes would be having an image field with unlimited number of uploadable images. That would show thumbnails of those related images right there when you go to the node page. This is all in core.

If allowing all users to edit event nodes is not an option, you could create an image node type and connect images to respective events with node references or taxonomy, and then create a view listing those images on the node page (views attachment) or on a separate, gallery page.


Check if logo, sitename, slogan, and secondary links exist How do you check if logo/sitename/slogan & secondary links are enabled from within a function? (outside of preprocess_page)

This seems to work for logo:

$logo = theme_get_setting('logo');
if (empty($logo)) {
...
}

but this doesn't for secondary links:

$secondary_links = theme_get_setting('toggle_secondary_links');
if (empty($secondary_link)) {
...
}

$secondary_links = theme_get_setting('toggle_secondary_links'); is working fine.

It doesn't work if secondary menu is disabled form admin/appearance/settings

It works when secondary menu is disabled form admin/appearance/settings/theme-name

OR

It works when secondary menu is disabled form admin/structure/menu/settings source of Source for the Secondary links is set to 'No Secondary links'


Drupal commerce: How to retrieve VAT number from order ID? I would like to print the VAT number (provided by module vat_number) on the invoice PDFs generated by module commerce_billy, but I can not figure out, how to retrieve VAT number when an order ID is given.

It took me a while to figure it out, but now I've found an answer myself:

$profile_id = $order->content['commerce_customer_eu_vat_rc']['#items'][0]['profile_id'];
$profile_wrapper = commerce_customer_profile_load($profile_id);
$vat_id = $profile_wrapper->commerce_vat_number['und'][0]['value'];


WYSIWYG + TinyMCE: Pressing Enter inserts break instead of paragraph Does anyone know, how I can manage TinyMCE to insert
 instead of
Paragraphs
 when pressing enter?

The best would be if you press enter once, it inserts a normal break. Pressing enter twice it starts a new paragraph.

And yes I know, that Shift+Enter would do it, but my client would like to have the behavior changed.

Thanks for any help

Give shift+enter a try.

That shortcut tends to be the default in a lot of different text editing apps for break type switching.


Override one line in core tabelselect jQuery behavior so custom checkboxes aren't affected I have created a custom table using a Form API tableselect element, and within my table, I have embedded a checkbox form element that is checked based on an entity field (see here for details). The checkbox functionality works fine. The problem I've discovered, though, is that the Select/Unselect All checkbox that is created as the first column in the table also affects my custom checkboxes, in that when I click on the select/unselect all checkbox, it also selects/unselects all the checkboxes in my column.

The offending code is in the tableselect jQuery behavior, and it's one line that makes the assumption that the only checkbox a tableselect element will ever have is the one that is part of the element:

if ($(event.target).is('input:checkbox')) {
  // Loop through all checkboxes and set their state to the select all checkbox' state.
  checkboxes.each(function () {
    this.checked = event.target.checked;
    // Either add or remove the selected class based on the state of the check all checkbox.
    $(this).closest('tr').toggleClass('selected', this.checked);
  });
  // Update the title and the state of the check all box.
  updateSelectAll(event.target.checked);
}

As the comment says, it does all checkboxes. Sigh.

From what I've been reading, my only option is to use hook_js_alter to replace the behavior with my own version. However, that seems like a bit of overkill just to change a couple lines. Is there another way to keep this behavior from affecting my checkbox field, or am I understanding correctly?

I ended up doing what I suggested, and overriding with my own custom version of tableselect.js

/**
 * Implements hook_js_alter().
 */
function language_dashboard_js_alter(&$javascript) {
  // Override core tableselect.js with custom version.
  $javascript['misc/tableselect.js']['data'] = drupal_get_path('module', 'language_dashboard') . '/js/language_dashboard_tableselect.js';
}

just to tweak this one line from this:

checkboxes = $('td input:checkbox:enabled', table).click(function (e)

to this:

checkboxes = $('td input:checkbox:enabled', table).not("input[id*='staging_only']").click(function (e)

by adding the .not() selector. It seems like a lot of code copying just for that one modification, but as of now, I don't see any other way.


Difference between $this->config and \Drupal::config in ConfigFormBase I want to override a custom module configuration in the settings.php file. So the configuration in database can be independent from the environment.

$config['my_module.settings']['prop'] = 'foo';

I my module configuration form, the config result is different given the method I use to get it :

class MyConfigurationForm extends ConfigFormBase {

    public function buildForm( array $form, FormStateInterface $form_state ){
        $config = $this->config( 'my_module.settings' );
        print_r( $config->get('prop') );
        // prints database value, or nothing if there is no value in database for 'prop'

        $config = \Drupal::config( 'my_module.settings' );
        print_r( $config->get('prop') );
        // prints 'foo'
    }

}

Why is that ?
What's the difference between these two methods ?

In a configuration form use $this->config() and not \Drupal::config().

The difference between both is that the configuration form uses immutable configuration.

When Drupal 8 was in beta, the immutable configuration was introduced to avoid bleeding of overridden values into configuration when saved to the database. See the change record:

Configuration objects by default are immutable

This is the code executed by $this->config() of a configuration form, in a static version:

\Drupal::configFactory()->getEditable('system.site')->set('name', 'My fantastic site')->save();

For Drupal 8.7 it is discussed to display a warning for overridden values:

  This form contains values that have been overridden. Changes to these
  values can still be saved, but the overridden values will take
  precedence. Overrides are as follows ...

See the issue:

There is no indication on configuration forms if there are overridden values


CURDATE() return wrong result I have write sql query in drupal looks like this.

Let's assume today's date is 2013-07-24 and total of node is 4.

    $query = "SELECT COUNT(*) amount FROM {node} n
              LEFT JOIN {flagging} f ON n.nid = f.entity_id AND f.fid = '1'
              LEFT JOIN {field_data_field_tarikh_tamat_passport} ttp ON n.nid = ttp.entity_id AND (ttp.entity_type = 'node' AND ttp.deleted = '0')
              WHERE (( (n.status = '1') AND (n.type IN  ('data_pekerja')) AND (ttp.field_tarikh_tamat_passport_value > CURDATE()) AND (f.uid IS NULL ) ))";
$result = db_query($query)->fetch();
print $result->amount;

The output of code above is 3 but with this code below is 1

 $query = "SELECT COUNT(*) amount FROM {node} n
                  LEFT JOIN {flagging} f ON n.nid = f.entity_id AND f.fid = '1'
                  LEFT JOIN {field_data_field_tarikh_tamat_passport} ttp ON n.nid = ttp.entity_id AND (ttp.entity_type = 'node' AND ttp.deleted = '0')
                  WHERE (( (n.status = '1') AND (n.type IN  ('data_pekerja')) AND (ttp.field_tarikh_tamat_passport_value > '2013-07-24') AND (f.uid IS NULL ) ))";
    $result = db_query($query)->fetch();
    print $result->amount;

The different of this sql query is only the value of CURDATE() and '2013-07-24'

Can you please explain why the output is different? I need the query to displaying total of node that has date field value greater than today.

Drupal usually stores dates as Unix timestamps, not regular date strings. Have a look at your field_data_field_tarikh_tamat_passport table to confirm which data format you're working with. If it's a timestamp, update your query to use UNIX_TIMESTAMP() instead of CURDATE().


Migrate d2d picture migration destination path incorrect I'm in the process of building a migration module for a d6 to d7 migration using the d2d module.

I'm almost there, but one thing that's holding me back is the DrupalPicture6Migration. After trial and error, this is what I have (using the d2d documentation):

/* Register the picture migration */

$picture_arguments = $common_arguments + array(
  'machine_name' => 'abcdPicture',
  'description' => t('Import Drupal 6 picture files'),
  'default_uid' => 1,
  'source_dir' => '/',
  'destination_dir' => 'public://pictures',
);
Migration::registerMigration('DrupalPicture6Migration', $picture_arguments['machine_name'], $picture_arguments);
}

source_dir points to the correct location: /sites/default/files/userPictures.

I'd expect the migration to go like this:

'sites/default/files/userPictures/picture-1589309970.jpg  -> public://pictures/picture-1589309970.jpg.

But when I perform the migration, the path gets migrated over instead of the pictures. So I end up recieving this error:

'The specified file sites/default/files/userPictures/picture-1589309970.jpg could not be copied to public://pictures/sites/default/files/userPictures/picture-1589309970.jpg.

The entire path sites/default/files/userPictures/picture-xx.jpg is copied into the public://pictures directory.

I am reading up on using destination_file but am failing to make the connection on how I'd code this.

Thanks!

You may try to specify the destination_dir in the __construct() instead of passing the arguments e.g.

class FooUserPictureMigration extends DrupalPicture6Migration {

  public function __construct(array $args) {
    parent::__construct($args);

    // Add simple field mappings
    $this->addFieldMapping('source_dir', FALSE)
         ->defaultValue(MIGRATE_D6_USERPIC_SRC_DIR);
     $this->addFieldMapping('destination_dir', FALSE)
         ->defaultValue(MIGRATE_D6_USERPIC_DST_DIR);

Where MIGRATE_D6_USERPIC_SRC_DIR is your source dir and MIGRATE_D6_USERPIC_DST_DIR is your destination dir (e.g. public://pictures).

Alternatively you can fix the user avatars by the following one-time query:

UPDATE users u
SET picture = (SELECT fid FROM file_managed fm WHERE filename = (SELECT SUBSTRING_INDEX(picture, '/', -1) as filename FROM DRUPAL6_DB.users as d6u WHERE name = u.name AND picture <> '' AND fm.filename = SUBSTRING_INDEX(picture, '/', -1)))
  WHERE u.name <> ''
    AND u.name IN (SELECT name FROM DRUPAL6_DB.users WHERE picture <> '')

WHERE DRUPAL6_DB is your database name for Drupal 6.


variable in HREF not working correctly I am trying to create a link in a Drupal views-view-fields.tpl that links to the original content but for some reason it's not working.  The code I have tried:

<a href="<?php $fields['path']->content; ?>">Read more

and

<?php $link = $fields['path']->content;?>
 <a href="<?php $link ?>"> Read more

as well as adding single quotes.  The above points the rendered link to the current page/ view.  When I echo $link_path i get /?q=node/1544 , which is correct.

I have also tried to create the URL by using

$link = $GLOBALS['base_url'] . '/node/' . $node->nid;
<a href="<?php $link ?>"> more

The above shows the correct link when I echo it but, again in the rendered link it points to the current page/ drupal view.

What am I missing? I have to add that I only have about 3 months Drupal/PHP experience so still lots to learn.

Thanks :)

The secure alternative would be to use l() to generate the link.
In your current code, it's very likely that you've created a security problem.

l('More', $fields['path']->content) would be better.

But in answer to your original question. you are missing echo statement here

<a href="<?php echo $link ?>"> more </a>


What is :source in the Token module? I look at the List of tokens and I see a lot of tokens with the same name and description, but some node have :source appended to it. Some of these, such as [node:title], I can understand, since title is a field of the node. But what is [node:source:title], or [node:source:source:title]? There's even an [node:source:source:source:source], which has the description 'The source node for this current node's translation set.'

What is :source in the Token module?

:source you can understand as parent of that node when you get in touch with drupal translation you can easily understand what hierarchy this :source is referring to.

as per above link:

Translations are managed in sets of posts, which represent the same information in different languages. Only content types for which the administrator has explicitly enabled translations could have translations associated. Translations are managed in sets with exactly one source post per set. The source post is used to translate to different languages, so if the source post is significantly updated, the editor can decide to mark all translations outdated.

so :source here is referring to the parent node from which it gets translated (if there are translation enabled if not then you need not to worry about :source)


What is wrong with my hook_schema code? I am pulling my hair for the past half of the day trying to figure out what is wrong. Here is my hook_schema function:

<?php

function image_gallery_schema() {
  $schema = array();

  $schema['gallery'] = array(
    'description' => 'The main store for gallery entity',
    'fields' => array(
      'id' => array(
        'description' => 'Primary key for our table of gallery',
        'type' => 'serial',
        'unsigned' => TRUE,
        'not null' => TRUE,
      ),
      'uid' => array(
        'description' => 'User id',
        'type' => 'int',
        'not null' => TRUE
      ),
      'title' => array(
        'description' => 'Title of the gallery',
        'type' => 'text',
        'not null' =>TRUE,
       ),
      'created' => array(
        'description' => 'Creation time',
        'type' => 'int',
        'default' => 0,
        'not null' => TRUE
      ),
      'changed' => array(
        'description' => 'Changed time',
        'type' => 'int',
        'default' => 0,
        'not null' => TRUE
      ),
      'gall_description' => array(
        'description' => 'Description of gallery',
        'type' => 'text',
        'not null' =>TRUE,
       ),
    ),
    'primary key' => array('id'),
  );

  $schema['photos'] = array(
    'description' => 'For storing photos',
    'fields' => array(
      'id' => array(
        'description' => 'Primary key for photo',
        'type' => 'serial',
        'unsigned' => TRUE,
        'not null' => TRUE,
      ),
      'g_id' => array(
        'description' => 'Gallery id',
        'type' => 'int',
        'unsigned' => TRUE,
        'not null' => TRUE,
      ),
      'full_path' => array(
        'description' => 'full photo path',
        'type' => 'text',
        'unsigned' => TRUE,
        'not null' => TRUE,
      ),
      'short_path' => array(
        'description' => 'short photo path',
        'type' => 'text',
        'unsigned' => TRUE,
        'not null' => TRUE,
      ),
      'img_description' => array(
        'description' => 'Image description',
        'type' => 'text',
        'unsigned' => TRUE,
        'not null' => TRUE,
      ),
    ),
    'primary key' => array('id'),
    'indexes' => array(
      'g_id' => array('g_id'),
    ),
    'foreign keys' => array(
      'gid' => array(
        'table' => 'gallery',
        'columns' => array('g_id' => 'id'),
      ),
    ),
  );

  return $schema;
}

I checked all the brackets and everything seems to be in place. It does create gallery table, but fails to create photo table. Error I get:

  Syntax error or access violation: 1064 You have an error in your SQL syntax;

I was trying to see how gallery schema is different from photos but I can't find anything. Maybe something is wrong with indexes and foreign keys? I checked multiple examples and everything seems to be the same. If someone could help me out, I would be more thank thankful.

It must be because you are adding the unsigned attribute to text fields.


Is there a function to output the tag and vocabulary? $terms = db_query('SELECT vid, name FROM {taxonomy_term_data} WHERE vid=:vid', array(":vid" => 2));

foreach ($terms as $term) {
    echo l($term->name, 'taxonomy/term/'.$term->vid);
}

I want to get all the term under the vocabulary. and the default tag.
If I use the above code to get that, I must know the value of vid, and read the database twice. It's too bad. If someone changes the vocabulary, this will change vid, and my code will not work. Is there a better way to get all the terms in a vocabulary?

There is taxonomy_get_tree() which can return all terms in a hierarchical array, you will however still have to display it and hardcode the vid (or use variable_get() to make it overridable).

Depending on how and where you are displaying this, one of the following alternatives could maybe work better for you:

If you are displaying this information in a block, consider using http://drupal.org/project/taxonomy_menu instead. It can create menus based on vocabularies, which you can then be displayed as a block. They will be properly cached and faster than querying them on every page.
You can also use Views to build a list, tag cloud or similar thing for all terms of a vocabulary.


Why the system enter two times in an hook_node_presave? I've write a simple module for my sites, where I populate a node reference by code.

I use hook_node_presave, but I notice that drupal enters TWO times in this hook, so if my node reference field is multiple, it populates it two times.

Is there something wrong on my code or is normal?
In the presave hook I've to load another node and then save it

I have something like this:

   function alterator_node_presave($node) {
      if ($node->type == 'partner_progetto') {
        // here I load a node "progetto"
        // that is referenced on my partner_progetto node
        $progetto = node_load($node->field_progetto_rif['und'][0]['nid']);

        // here I load another node "soggetto"
        // that is referenced on my partner_progetto node
        $soggetto = node_load($node->field_soggetto['und'][0]['nid']);

        // then I've to fill a node_reference in the node $progetto,
        // using the nid of $soggetto
        $progetto->field_soggetto_ref['und'][]['nid'] = $soggetto->nid;

        node_save($progetto);
      }
   }

In this hook the system enter 2 times, so when I save a "partner progetto" node that has a reference to the node soggetto with nid '150' I've that the "progetto" node has this structure:

$progetto->field_soggetto_ref
  ['und']
    [0]['nid'] = 150,
    [1]['nid'] = 150;

The value of this field is filled two times.

Remove node_save($progetto); from alterator_node_presave and try. Because hook_node_presave is called just before the node_save. It can be reason of saving the field twice.


How can I add a simple node creation form to a page? I'm trying to add a formspring-like page to my website. This looks like an easy task for Drupal 7: create a new content type, create a new view to list the questions and answers, add another view to the backend to view the unanswered questions, and you're ready to go.

But I have one remaining problem: how can I add a simple form to ask a new question? I want to have a simple form on top of the list-page, with just 1 input box where a visitor can ask his question and a submit button.

I've already found the "form block"-module, but I can't trim the output of the form to just 1 input box. Is there an off-the-shelf solution, or do I have to create a custom module/block that programmatically creates a new node?

the only way I can see this being possible, would be creating a custom node/add page for your content (see How can I theme the template for edit or add a node for a specific content type?) and then using Panels to create a custom page with your node on top and then your view directly below.

I would be interested to know if anyone else has any better/easier suggestions of course. +1 for question :)


Change catalog taxonomy URLs How do I change the Ubercart catalog taxonomy URLs in Drupal 8? When I view my catalog, I have URLs like catalog/1 and catalog/2. How do I change them into catalog/taxonomy-term-name?

(I can't find in view settings something like Convert term name to ID.)

The source for the header of (Catalog views)  is from a second view
(catalog terms view)      you can make changes there

make term id hidden and term name visible


Product variations are causing duplicates to show up in filter results I'm using Drupal Commerce and have created a different product for every variant combination of color and size. For example, if I'm selling a skirt with multiple colors and sizes I'd have a product for "color:blue size:small", "color:blue size:medium", "color:red size:small", "color:red, size:Large", etc.

I created a view for my products and have added exposed filters for color and size to this view. The problem I'm having is that I'm getting duplicates because of the sizes. I don't mind if the filter results show the same skirt twice in different colors, but I don't want results showing duplicates for different sizes. i.e: "color:blue size:small", "color:blue size:medium".

I've tried adding the filter "Content: Product:delta (= 0)", which eliminates size based duplicates. The problem with this is that it also gets rid of color based duplicates, which cause my color filter to stop displaying different colors for the same skirt. For example, if Content: Product:delta (= 0) is added and I set my color filter to red skirts nothing will show in the results.

Is there a way to add a delta (= 0) filter to only the "size" attribute? I'm guessing this would fix my problem if it's possible to do.

This issue has been killing me and I really need it resolved. Any help would be greatly appreciated.

No, that's not possible, the delta=0 will remove duplicates by restricting to the first product in the product reference field. It won't apply selectively to different attributes on that referenced product.

A better option may be to use the colour filter only, then on the product display node itself, add the value to select the size in the add to cart form.

That way, customers can filter by colour, then select the size they want when viewing the product detail.


Drupal 8 live preview question I'm a designer who is doing a design review on a Drupal 8 website. I'm having trouble doing the design review because 'admin objects' are getting in the way of the full page design:

Admin bar at top of screen

View, Edit, Up-Publish etc buttons below the header

Sticky provide feedback bar

(Sorry can't show the full page due to NDA)

Usually I would just log out and preview live site, but the staging server for this project is hidden behind multiple logins and trying to access the website when not being logged in just redirects to the currently live (old) Drupal 7 website.

Any idea for how to remove these items and just preview the normal page?

Thanks

You could create a user without any special admin privileges.  Then you can either view it from another browser as the normal user or use the Masquerade module to swap in and out of that user from the same session.


Endpoint services with url alias name Is it possible the to view xml/json format data with url alias name instead of endpoint_path/node/1 or endpoint_path/node/2

Try the Services node resource extension module

Extends functionality for the node resource available through services module.
Additional Resources:
-lookup - provides a resource to request a node through the url alias.
-POST data = [ 'alias' => the url alias. ]


How to do System Tests / Functional Tests with an existing database the last few weeks and days I have been reading into Drupal 8 testing with phpunit.

For a project I want to use Unit testing to test out functionality and services and the cooperation between different components.

Run the tests against an existing database / installation and not against a fresh Drupal installation, since we have configured a lot already and I need to make sure the new code does work with the whole configuration and data.

I can Unit tests to test out simple functions or classes but what I cannot use is the BrowserTests or KernelTest bases since they all create a new, fresh installation.

Maybe I have misunderstood something or I am on the wrong path.

Can anybody help me out or has an example on how to do that?

I have once answered this exact same question for Drupal 7. Though some things have changed, the concept remains the same; extend the test class.

The normal setup of a BrowserTest would look something like this:

  /**
   * {@inheritdoc}
   */
  public function setUp() {
    parent::setUp();

    // Create an article content type that we will use for testing.
    $type = $this->container->get('entity_type.manager')->getStorage('node_type')
      ->create([
        'type' => 'article',
        'name' => 'Article',
      ]);
    $type->save();
    $this->container->get('router.builder')->rebuild();
  }

All you need to is to remove the database definitions from parent::setUp();

So copy setUp() from core/tests/Drupal/Tests/BrowserTestBase.php and remove the database definitions. That should make the test run on the current database.

Though this is very simplistic and you might run into more problems along the way. All is in the BrowserTestBase class. Make sure to read my other answer, make sure to implement the teardown properly. And most of all, make proper backups!


“admin/people” filters not available anymore I have Drupal 8.7.3 so at admin side on people listing page I can't see the filter to find a particular user.

I would check:

Is the views module still enabled?
Is this specific view enabled?
Did the configuration get changed for the view that exists at admin/people?

For #1, go to the modules page and scroll down to views and confirm it is enabled.

For #2, I noticed that I was able to "Disable" the user_admin_people view and then I get a screen at admin/people that looks exactly like yours. The resolution to that problem is to go to /admin/structure/views/ and "Enable" the user_admin_people view.

For #3, you could install a fresh version of Drupal 8.7.3 and compare the configurations of the view to find if it's wrong.


Override the theme for the login page How can I override theme for the user login page in Drupal 7? By default, that page takes the default theme style.

You can separate template file for overriding the user-login page.

Just create a template file called page--user--login.tpl.php file for theming the login page.


How to rebuild the theme registry on every page? I returned to Drupal 7 after a short absence, and couldn't find the option to "Rebuild the theme registry on every page", which is useful while editing templates on a development site. I thought it was in the Performance options but I can't find it there, and searching for it gives unclear or out of date results, mostly around the Zen theme which I haven't used for years. I've definitely used this setting without using Zen.

Where's the Drupal option to rebuid the theme registry on every page?

This isn't included in stock Drupal 7.

If you're not using Zen, the most common way to access this feature is via the module Devel.

Then it's accessible from /admin/config/development/devel, right down the bottom of the page.


Prevent node from being saved in hook_node_presave When saving / updating node, i need to validate if certain fields combination is unique. Unique field module is supposed to allow this, but that feature is not working (validating only single field). So i created my own hook:

function mymodule_node_presave(\Drupal\Core\Entity\EntityInterface $node) {

  if ($node->bundle() == 'mycontent') {

    $term = \Drupal\taxonomy\Entity\Term::load($node->get('field_mytaxonomy')->target_id);

    $query = \Drupal::entityQuery('node');
    $query->condition('type', 'mycontent');
    $query->condition('field_mydate', $node->get('field_mydate')->value, '=');
    $query->condition('field_mytaxonomy', $term->id(), '=');

    $nids = $query->execute();

    if ($nids) {
      drupal_set_message('Fields are not unique!', 'error');
      // I need to prevent saving of node here
    }
  }
}

Detection of node with duplicite values being created works. How do i prevent saving that node?

How do i prevent saving that node?

If you want to prevent that the node is saved in a presave method or hook you have to throw an exception:

throw new \Exception(t('Fields are not unique!'));

More user friendly would be to check this in the form first and give the user a chance to correct the input before you throw an exception.

Double checking this in presave is still a good idea to make sure, that no incorrect node content gets saved, no matter which form, Rest API or code is used. If someone gets past the first level of checks in the form you have no other option than to throw an exception.

Edit:

In case an exception is raised, you can replace the default 500 response with a custom error handling in an exception subscriber, see Handle database connection exception via custom handler


Notice: Trying to get property 'nid' of non-object In Drupal\rsvplist\Form\RSVPForm->buildForm(), I wrote this to get the current nid:

$node = \Drupal::routeMatch()->getParameter('node');
$nid = $node->nid->value;

I get this error:

  Notice: Trying to get property 'nid' of non-object in
  Drupal\rsvplist\Form\RSVPForm->buildForm() (line 30 of
  modules\custom\rsvplist\src\Form\RSVPForm.php).

I am a new module developer. How to get the current nid in drupal 8?

You will need to check if the $node variable is actually an instance of node object.

if ($node instanceof \Drupal\node\NodeInterface) {
  // You can get nid and anything else you need from the node object.
  $nid = $node->id();
}

See

How do I get the current node ID?


How do I move a group of nodes to another Drupal instance? What:
I'm breaking a part a huge D7 site into a D7 multi-site instance.

Why:
Marketing demands have changed. They different units still want to use the same theme but have different main menus and slight CSS tweaks here and there. They also want separate authors and very different approval processes. This site is crippled under it's own weight.

So far: I've already copied over Content Types via Bundle Copy and most everything that will remain standard via source controlled features.

How/Question: How can I move a piece of content (node/XXX) to another Drupal 7 instance?  A drush solution would be preferred so that I have the ability to script this across Stage and Production servers once we figure it out on Dev.

Errata:
I've seen interesting methods to scrape content via feeds, sharing content, and seen great dev to prod workflows. However, I haven't seen something that addresses a one-time move of a node between instances.

What would suit you is the Deploy module: https://www.drupal.org/project/deploy

The README.txt states:

The Deploy module is used to deploy Drupal content to other Drupal sites or arbitrary systems. Two concrete use cases are:

using it as a content staging solution
using it to push content downstream from a main site to several sub sites.

Here's a demo:
https://www.youtube.com/watch?v=7PjwT0HWHxw


restrict shipping of particluar item for paticular shipping zone Is there a module available to restrict the shipping of the particular product for particular shipping zone(country)?
so that the message would appear and cancel the checkout.

I'm fairly certain there isn't a module that does this. You can build this with rules, but the effect will be very rudimentary.

Create a rule reacting to order updates:

Checks for a particular product included in the order.
Checks to see if a shipping address condition is met.
For your action, display a system message.
Set the status of the order to cart or perhaps checkout:shipping.

That way you wouldn't be able to advance past the shipping status without having it fulfilled.

Not knowing your situation, cancelling an order is a bit extreme, but you could forward the user to a webform, change the status of the order to some new, internal value for review, or even just remove the product from the cart so that the customer can continue.


The administrator menu disappeared I added the following code in my .htaccess file :

<IfModule mod_headers.c>
  Header set Set-Cookie HttpOnly;Secure
  Header always set X-XSS-Protection "1; mode=block"
  Header always set X-Content-Type-Options "nosniff"
  Header always set X-Frame-Options "DENY"
  Header set Content-Security-Policy "script-src 'self' https://apis.google.com"
  Header always set Strict-Transport-Security "max-age=15768000; includeSubDomains; preload"
</IfModule>

and the Administrator menu drupal no longer appear on my site. When I delete this line, the menu reappears. How to solve this problem ?

Header set Content-Security-Policy "script-src 'self' https://apis.google.com"

Check with the styles/css hiding the administrator menu.
style-src is script-src’s counterpart for stylesheets.


Editing a node deletes body content reproducibly if Locale module enabled I am experiencing a pretty serious problem leading to data-loss in D7. Editing any existing node leads to empty body content and newly created nodes have no body content whatsoever.
Update: The error is reproducibly linked to the Locale module (v 7.78), disabling Locale leads to normal behavior, enabling it leads to data-loss when editing.
However, Locale has been enabled for a long time, so I am suspecting one of the updates since May 2020 (last time new content was added without problems) introduced a bug or a failed database update. So, there might be a bug in Locale that only shows under certain circumstances, e.g. PostgreSQL, a site migrated from D6 or Locale activated after content was already created, ...
The following observations are with Locale enabled:
Tracking an existing node in Postgres shows the node body content in field_data_body before an edit.
After an edit, field_data_body has no entry with the entity_id. I can put back the data using SQL and then the body content is displayed. Newly created nodes never get an entry in field_data_body.
Therefore, I am suspecting something might be odd with HTML filtering (Filtered HTML, Plain text, ...) or the content edit form or language settings.
This is the original data of an existing node:
select * from field_data_body where entity_id = 745959;
 entity_type | bundle | deleted | entity_id | revision_id | language | delta |

    body_value               | body_summary | body_format
-------------+--------+---------+-----------+-------------+----------+-------+----------------------------------------+--------------+-------------
 node        | blog   |       0 |    745959 |      745959 | und      |     0 | The genome browser is not working TEST |              | 1

After editing:
select * from field_data_body where entity_id = 745959;
 entity_type | bundle | deleted | entity_id | revision_id | language | delta | body_value | body_summary | body_format
-------------+--------+---------+-----------+-------------+----------+-------+------------+--------------+-------------
(0 rows)

Also, the node.language and field language are different:
select nid, n.language as "node-language", b.language as "field-language" from node as n left join field_data_body as b on n.nid=b.entity_id  where nid = 745959;
  nid   | node-language | field-language
--------+---------------+----------------
 745959 | en            | und
(1 row)

Looks like it could indeed be a language setting conflict. When looking at the $form data, the values entered into body are found as such and only there.
So it indeed appears to be a language setting problem:

create a new Page node: node.language is initially set to "en", the site default, no body data entry is created or saved upon edit (in form_data_body)
In postgres, change node.language to "und"
The body content is now saved upon edit and displayed properly

Implement hook_form_submit() and either set a breakpoint there, output to the messages or log the form_state values to see what's actually being submitted. Implement hook_node_presave() and do the same to see what's actually going to be saved to the database.
There is a chance the client-side JS or some validation hook changes the value for the field, so you will have to either dig or debug through all your modules. It's hard to tell something specifically, because any module, either contrib or custom one, can put its own hook and empty the content for some reason.


How to insert Google Tag Manager code into pages with variable account value I need to insert the Google Tag Manager snippet code into each page just after the opening <body> tag. This is fine, except I would also like the user to specify the account number in an admin form, so what is put in this form will be output in the snippet.

In the snippet, the account number is required twice:

<noscript><iframe src="//www.googletagmanager.com/ns.html?id=<ACCOUNT NO HERE>"
...
(window,document,'script','dataLayer','<ACCOUNT NO HERE>');</script>

Setting up the admin form and storing and retrieving it by variable_set() and variable_get() is no problem, but what's the best way to insert it into the template?

My thought is to use hook_preprocess_page(), but I'm not sure if this is the right hook to use, and if it is - what part of the array I would need to change to get this to appear? Or would a better way would be to make a variable available to the tpl.php file and insert it there? In which case, how would this be achieved? Thanks!

you should use these two modules:

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

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

First one installs GTM on your page, second one enables passing many variables and taxonomies to be passed to dataLayer. It also has an alter function, if you'd like to add some extra data (since the module is written in a general way and i.e. extracting taxonomies from json arrays on the GTM side can be complicated).

User Id is part of default data added to dataLayer by data layermodule on each page, so you'll have it there.

Regarding your noscript part, you'd have to alter the module i think.


A better way to insert preformatted snippets into content/wysiwyg? Is there a way to insert pre-formatted objects (like a standardized sign-up form) in line in content via wysiwyg (a'la the fantastic wysiwyg-templates module), but encapsulated and protected...

I actually love that w-t can insert snippets, and will continue to use it, marketing likes to insert the same search form they always use and then change 2 words to test if that drives conversions.  For what it does, w-t is perfect.

HOWEVER...

Having done that, I now want to pop in content in exactly the same method, except LOCKED so it can't be edited, but so I can still SEE it, and potentially move it around the page as though it were an image.

I'm not expecting too much for response, but if I end up really needing it I'd rather hear what other ideas are out there than build something myself that has already been done.

(background to be posted in a comment below for context)

The perfect solution hasn't presented itself, but I settled on using specialized content types inside a parent content type, (via Entity & Entity Reference fields) and then using Better Formats, Wysiwyg with CKE, Fieldgroup, Conditional Fields to make a user interface that presents all the myriad options in a nice clean manner.

I'm kinda proud of the result, I expect I'll eventually reuse the system somewhere more public so I can show it off.


Colorbox not working for anonymous users, but works fine for logged in I am having an issue getting my colorboxed images to load while viewing the page as an anonymous user. As an anonymous user, there is no reference to anything related to colorbox at all. However, when logged in as admin, everything works fine.

This feels like a permissions issue, but I don't see any settings in permissions. also, the configuration in the 'manage display' settings leave a bit to the imagination.

What am I doing wrong? Is this indeed a permissions issue? 7.x 1.3 and drupal 7.14

I had a javascript conflict in my theme. Works great now that that has been cleared up. Thanks!


Adding a class to the  tag of a menu I need to put a class/ID on the actual li element as each link in the menu has a color-coded background when active meaning, I can't just style ".active-trail" as that will be the same color for every link.

Creating a menu and using the CSS ID or class puts the ID/class on the a element, not on the
 tag.

I could write something in jQuery, but I thought there might be a way in Drupal.

The output I want would be like the following.

Test links

first

second

You need to use theme_menu_item_link()

The following is an example that I pulled from an old site:

function THEME_menu_item_link($link)
{
    if (empty($link['localized_options']))
    {
        $link['localized_options'] = array();
    }

    //Give this menu item a unique id
    $link['localized_options']['attributes']['id'] = 'menu-item-' . $link['mlid'];

    //Not sure if this is the cleanest method, but it should allow us to follow
    //the active-trail across menu items, based on path.

    //Get the start of the current path (e.g. admin/build/modules would be admin)
    $base_path = preg_replace('/^([A-Za-z0-9_-]+)\/(.*)/', '${1}', drupal_get_path_alias($_GET['q']));

    //Get the current link we're looking at
    $this_link = drupal_get_path_alias($link['href']);

    //If the
   if($base_path == $this_link)
   {
       $link['localized_options']['attributes']['id'] = 'menu-active-trail-' . $link['mlid'];
   }

   return l($link['title'], $link['href'], $link['localized_options']);
}


How to publish unpublished nodes programmatically I have some unpublished nodes, for which I have their node IDs. How can I programmatically publish them?
Is it correct to achieve it in custom module using a query like the following?

db_query("UPDATE {node} SET status = 1 WHERE nid = %d", $nid)

Using db_query() is a Drupal 6 method, which is not used in Drupal 7.
To achieve your job I suggest this code (without any manual query).

// load the node object
$node = node_load($nid);
// set status property to 1
$node->status = 1;
// re-save the node
node_save($node);

If you have more node ID, and you want to publish all those nodes, you can use the following code.

$nids = array();
// Load all nodes in one go for better performance.
$nodes = node_load_multiple($nids);
foreach ($nodes as $node) {
  // set status property to 1
  $node->status = 1;
  // re-save the node
  node_save($node);
}


Change content of $page['content'] variable I have overwritten my login page with a file named page--user--login.tpl.php. Now I have this:

    <section<?php print $content_column_class; ?>>

Xmed.be Stocksolutions

"We help you Xchange your stock"

      <?php print render($title_suffix); ?>
      <?php print $messages; ?>
      <?php if (!empty($page['help'])): ?>
        <?php print render($page['help']); ?>
      <?php endif; ?>
      <?php if (!empty($action_links)): ?>

<?php print render($action_links); ?>

      <?php endif; ?>
      <?php print render($page['content']); ?>
      NO ACCOUNT? REGISTER
      FORGOT PASSWORD?

As you can see I added two links at the end (register and password). But I would like them to be inside $page['content'], so that they are in the section. How can I edit the $content variable, loop through it or something?

UPDATE:

Now I've added in my template.php:

function hook_form_user_login_alter(&$form, &$form_state, $form_id) {
    var_dump('test');
}

But I'm not getting test around my form (also looked in html).

I've also already tried:

function hook_form_alter(&$form, &$form_state, $form_id) {
    dpm($form);
}

But no result or something ...

You can use hook_page_alter to add them into the content array:

function YOUR_MODULE_page_alter(&$page) {

  // Check if this is the correct page.
  if(!isset($page['content']['system_main']['#form_id']) || $page['content']['system_main']['#form_id'] != 'user_login') return;

  // Add links.
  $page['content']['system_main']['register'] = array(
    '#markup' => '
NO ACCOUNT? REGISTER
',
    '#weight' => 20
  );
  $page['content']['system_main']['password'] = array(
    '#markup' => '
FORGOT PASSWORD?
',
    '#weight' => 21
  );

}

Another option here would be to use hook_form_alter instead. Although hook_form_FORM_ID_alter may well be the most efficient option as it will only run for this specific form removing any overhead from other pages.


redirecting legacy URLs to corresponding drupal path I'm planning to migrate the content from my existing legacy system to drupal. In process there are a lot of static pages, nodes and taxonomy terms which have hyperlink references to the legacy URLs that cannot be replaced with current URLs due to their sheer magnitude and for which redirects cannot be set manually (i'm using path_redirect module to handle redirects, atleast I intend to).

So my idea of implementing this by redirecting my legacy URLs in my .htaccess to handle them in a custom module where the drupal URL is deduced based on the URL and its params and redirect them. Also add an entry for them with HTTP 301 in path_redirect table so that next request I could check for the entry before proceeding to programmatically determine the node/page URL again. I skimmed the module code which seemed to use hook_init to work the redirections and it seemed feasible in theory, though i'm not sure of the results in practice.

Hence I wish to know if this idea is sensible or if it has some flaws as I'm not an expert in the areas of URL rewriting or SEO. Also I'd request anyone with practical experience on the same to know of any challenges involved in this.This served as a reference before I decided to post my query.

I've just done a transition like you mentioned and the domain names changed. I didn't want the old urls hitting my drupal server so I setup a 2nd site just for redirects. At first I had a simple php redirect script that would map old urls to Drupal urls. The mapping came off the "migrate_map" tables that the migrate module generated.

Then someone on the team was concerned about the immediate SEO impact and preferred to keep the old site content available at the old domain name. So I copied the new Drupal site to a 2nd hosting account.

I added a "custom404" module which uses hook_init() to read the URI, detect a pattern, find the unique key in the uri, then lookup the Drupal nid using the migrate_map table and then use drupal_goto() to do a 301 to Drupal URI.

On that Drupal site I show a "website has moved" message with a link to the same URI on the new domain. Pretty soon I'll change my script to just 301 redirect to the new domain directly.

I was initially toying with the idea of using a lower bootstrap level (to have faster redirects) but ran into issues with database connections. Got some great help here about that.


Need to use taxonomy term as url argument to filter a view but the term is attached to a node ref field Not sure if the title makes much sense so I'll try to explain what I'm trying to do a little more in detail.

I am building a scoreboard section of my site for high school football scores from around the state. My "score" node has two node reference fields, "home team" and "away team" that point to a "team" node. The "team" node has some taxonomy terms, namely "county" and "conference."

I am trying to build a view that lists all of the "score" nodes for the week. The main scoreboard is working, no problem. But I'd also like to be able to have links like "http://example.com/scoreboard/county-name" and "http://example.com/scoreboard/conference-name" that would just show the scores for the schools in the respective county or conference.

The following is a screenshot of how my relationships, arguments, and fields are set up.

The following is a screenshot of how the view displays on the "/scoreboard" page.

But, if I try to go to "http://example.com/scoreboard/hamilton" I get a blank page. Am I missing something simple here? It seems like it should be possible but I'm not getting it.

Configure the Taxonomy: Term argument to use one of the relationships that you have set up. I do not know why you have an additional Node: Nid argument. According to your description, it is not necessary. Remove it unless you have some other requirement that makes this argument necessary.

Setting up the view in a way that does not match the requirements should not result in a blank page. The usual techniques for debugging PHP applications can be applied to figure out what went wrong: Printing out variable values or (if you have Xdebug or the like installed) step-by-step execution.


Putting values in a template file In the past (Drupal 6), I used a function to put some values in a template file.

This function was something like function_name('templates/my_template.tpl.php', array('key1' => 'my value', 'key2' => 'my other value')); which returned HTML code.

Is there this function in Drupal 7?
How can I use it?

The function you are looking for is theme_render_template(), which gets the filename of the template file to render, and an array of variables to pass to the template file.

In Drupal 6, it is called as in the following code.

 $messages = drupal_set_message();
  if (isset($messages['warning'])) {
    $title = count($messages['warning']) > 1 ? 'The following update warnings should be carefully reviewed before continuing' : 'The following update warning should be carefully reviewed before continuing';
    $variables['messages'] .= '<h4>' . $title . ':</h4>';
    $variables['messages'] .= theme('status_messages', 'warning');
  }

  // This was called as a theme hook (not template), so we need to
  // fix path_to_theme() for the template, to point at the actual
  // theme rather than system module as owner of the hook.
  global $theme_path;
  $theme_path = 'themes/garland';

  return theme_render_template('themes/garland/maintenance-page.tpl.php', $variables);

theme_render_template() is still present in Drupal 7, and Drupal 8.

In Drupal 7, although, the function is only used from theme(). There isn't generally any reason to call the function directly; you can define a new theme function that uses a template file, and then call theme() as theme('theme_function', $array). (Replace 'theme_function' with the name of the theme function.)


d8 webform submission views how to exclude Action Apply to Selected Items The view created using the webform views integration module.. all the fields are shown as desired.  However the CBO box with choices to then apply changes is not wanted. Hoping it's a setting somewhere.

Just after posting I found the answer.  In fields section, the webform submissions bulk operation form entry can be deleted and that removes the pesky entry shown in the question.


Views: List of recent months containing nodes Using Drupal 7, views 7.x-3.0-beta3. I am trying to make a display containing a list of links which direct users to an archive page containing posts of that month (eg. all news messages posted in march 2011).

Tried to solve this with a contextual filter 'Created year + month',
which, when no parameter is given, gives a summary list of links like 'march 2011, december 2010' linking to the URL 'news/201103', 'news/201012'.

Is there a way to change the formatting of that URL to 'news/YYYY/MM' ?

You can create path alias to make the URL look how you want, but views need the year and month as a single argument.


Fieldsets in Content Types How do you add a fieldset to a content type in Drupal 7 to group fields? I don't see this option anymore. I just want to group related fields on a form together. Will that also trigger vertical tabs instead of let fields just float around in the open?

Now its a separate module called Field group. It comes with several display options including vertical tabs.


Is there any way to set line item status in an order? I want set line item status that if a line item is delivered. In an order, order status is for all the items but line item status is for each product.

Is there any module or something in UI?

I am using drupal commerce module.

You can try using Commerce Delivery module... It supports line items delivery status..

Project page says

  Provides basic functionalities and admin pages to handle deliveries.

  Each delivery need to be associated to an order. Each order can have
  zero, one or multiple deliveries.

  A delivery is automatically created on order save if it contains at
  least one shippable item. Further deliveries can be manually added
  from the deliveries tab under the orders menu. On the same page each
  order line item can be moved from one delivery to the other.


Module to manage submodules What I want to do is be able to tell what the parent of a submodule is on the admin/modules page. There is little to no indication of what it belongs to sometimes.

Example, under the Administration group, I have a module called "Actions permissions." I have no idea what this module is for, the purpose of the module, why I would want it, or what it belongs to. It's just out there. I know it's a child of something else, but there is no indication of that anywhere. I could go on the server and grep it but I think it might be helpful to people to have a way to determine the parent.

So is there a module that:

A) will group submodules in a hierarchy-type view under their parents? Or
B) a module that simply lists what the parent is on the module item itself like we do with Requires:

There's no such concept as parent and sub/child-modules in Drupal. You'd have to define what you consider to be the parent-child relationship, pick what physical properties of the module you're going to use to describe that relationship, and code a solution from there.

Drupal's own native mechanism for grouping modules is using the package key in the module .info file. In the case of Actions Permissions, for example, the package is defined as "Administration", so you can find it under the "Administration" fieldset, grouped with other modules that are considered to have (loosely) related functionality by their respective authors.

On a slightly un-related note, but you can improve the UI of the modules page using Module Filter if it's becoming unwieldy.


Create a general rewrite rule in .htaccess In an upgrade scenario I have to provide some alias URLs like www.server.com/reading_23.html that should actually deliver www.server.com/reading/23.

I spent lots of hours trying to make that work by adding a line in .htaccess:

RewriteRule reading_(.*).html reading/$1

I have put that line into the standard D8 .htaccess, right after RewriteBase /. Unfortunately none of my attempts worked. The /reading is a path that's provided by one of my modules.routing.yml.

EDIT, 18.1.
This seems to be very special for Drupal because it just doesn't work with the existing D8 redirects. I can only make a redirection ([L,R]) work but I don't want my end-users to see the reading/23 path in their browser.
So actually the question is how to make URLs like reading_23.html possible with Drupal, the routing parameters can only live as separate parts of the path (like reading/{number} is ok but reading_{number}.html is bad).

Anyone who knows how to do this?

I do not want to create aliases in my Drupal DB for all node-Ids.

[EDIT Nr 2. 18.Jan 2017]

The Solution is an inbound Path Processor like 4k4 wrote. Thanks a lot.

[END EDIT]

I think your rewrite collides with the other rewrites in drupal standard .htaccess. Try a redirect. The redirect will be executed right away and the rest of .htaccess will no longer be processed. And it will also tell search engines that the url has changed.

RewriteRule reading_(.*).html reading/$1 [L,R=301]


Nodes containing simple field collection not displaying properly I have a content type to which I added fields like description, image and a field collection containing two simple text fields. Editing and viewing in the backend (logged in as admin) works properly. But when I log off and go to the node it just shows the title and no more. Can anybody lead me to the right direction to find the error?

EDIT: If I leave the field collection fields empty, the other fields get displayed to other users, if I fill in something nothing shows up, just the title

I think I have found the answer, but not really the solution. I deleted the following code in my node.tpl which caused the malfunctioning of field collection:

<?php if (!empty($content['links'])): ?>
<nav class="links node-links clearfix"><?php print render($content['links']); ?></nav>
<?php endif; ?>

But I do not understand why.


Printing a form inside a block I have a specific block that has some form logic, intended for newly registered users. And I am a bit lost on what the logic would look like to render the contents for the form inside a hook_block_view. I've tried using a theme_form() call to get errors, mostly string offset and fatal errors from type comparison. I've tried using drupal_get_form, with the same results.

Here's the code below. Thoughts?

/**
 * Implements hook_block_info
 */
function example_module_block_info() {
  $block['item_select'] = array(
    'info' => t('Select Item'),
    'cache' => DRUPAL_CACHE_PER_ROLE,
  );

  return $block;
}

/**
 * Implements hook_block_view()
 */
function example_module_block_view($delta = '') {
  $block = array();

  switch ($delta) {
    case "item_select":
      $block['subject'] = t("Select a book");
      $block['content'] = theme_form('example_module_form_select_item_form');
      break;
  }

  return $block;
}

/**
 * Implements an example form
 */
function example_module_form_select_item_form($form, $form_state) {
  $form['item_type'] = array(
    "#type" => 'select',
    "#title" => t("Make a selection"),
    "options" => array(
      "1" => t("This"),
      "2" => t("That"),
      "3" => t("The Other"),
      "4" => t("Banana")
    ),
  );

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

  return $form;
}

Try making a function using hook_form() and calling it in your $block['content'] property?

$block['content'] = example_module_form($node);


How to theme checkout completion page in Drupal Commerce I'm having a problem with theming the checkout completion page. My designer gave me a layout that will show all of the order details in that page(nearly same as the checkout review pane). I already googled it and all of the links that I tried is not working. Please see the links below

theming checkout pages in Drupal commerce
http://theoleschool.com/blog/templating-commerce-order-completion-pane

Is there any tpl.php file that I need to include? or hooks to achieve my goal?

Thanks GUys

A quick google search yielded this result:

Templating the Commerce Order Completion Pane

  Turns out that's a fairly simple task thanks to
  hook_commerce_checkout_pane_info_alter. The function passes the
  variable $checkout_panes by reference which contains an array of
  checkout pane arrays. This function is going to allow us to redefine
  the function that the checkout completion pane is looking to for
  output.


Saving file upload destination as private I have a content type with a file field where I want the files to be private... I set the upload destination to private, but when the field instance is saved with features, this setting is not saved. How can I save this for use with an installation profile? (all other content types use public files)

The upload destination is not saved with the field instance, but with the field base. I was using an existing file field that was public. I needed to create a new field and define it as private and save that field base in my feature.


"Revert to last revision" action I made an update to a site for global search and replace of text across nodes and was too far-reaching. For a specific content type I need to revert my Node update of ~500 nodes.

I found this solution in the VBO issue queue:
https://www.drupal.org/node/1166630

But in evaluating this code a new revision is made by it is not set as the current revision of the node. If I visit the node revisions page and invoke node_revision_revert_confirm_submit a new current_revision is set for the node.

Code I'm trying:

/**
 * Implementation of hook_action_info().
 */
/**
 * Implements hook_action_info().
 */
function revert_last_revision_action_info() {
  $action = array(
    'REVERT_LAST_REVISION' => array(
      'label'        => t('Revert to Last Revision'),
      'type'         => 'node',
      'configurable' => FALSE,
      'triggers'     => array('any'),
    ),
  );
  return $action;
}

/**
 * Action function for REVERT_LAST_REVISION.
 */
function REVERT_LAST_REVISION(&$entity, $context = array()) {
  $node = $entity;
  $revision_list = node_revision_list($node);
  unset($revision_list[$node->vid]);
  if (count($revision_list) > 0) {
    $last_revision = max(array_keys($revision_list));
    $node_last_revision = node_load($node->nid, $last_revision);
    $node_last_revision->revision = TRUE;
    $node_last_revision->log = "Reverted via bulk operation action."; // Log message
    dpm($node_last_revision, __FUNCTION__);
    node_save($node_last_revision);
  }
}

Using devel the $node arrays look the same so I'm confused as to why my revert revision code snippet is not making the new revision the current_revision. The only thing node_revision_revert_confirm_submit is doing is setting $node->revision = TRUE and calling node_save().

Anyone have any ideas?

EDIT: 11/16/2015

As others have mentioned perhaps this has to do with how VBO is initiating the action.

I've also tried the below code but the Node isn't saved.

/**
 * Implements hook_action_info().
 */
function revert_last_revision_action_info() {
  $action = array(
    'REVERT_LAST_REVISION' => array(
      'label'        => t('Revert to Last Revision'),
      'type'         => 'node',
      'configurable' => FALSE,
      'triggers'     => array('any'),
      'behavior'     => array('changes_property'),
      'vbo_configurable' => FALSE,
      'pass rows'        => TRUE,
    ),
  );
  return $action;
}

/**
 * Action function for REVERT_LAST_REVISION.
 */
function REVERT_LAST_REVISION(&$entity, $context = array()) {
  $revision_list = node_revision_list($entity);
  unset($revision_list[$entity->vid]);
  if (count($revision_list) > 0) {
    $last_revision = max(array_keys($revision_list));
    $entity = node_load($entity->nid, $last_revision, TRUE);
    $entity->revision = TRUE;
    $entity->log = "Reverted via bulk operation action.";
  }
}

After much debugging this appears to work. This code appears to revert to the most recent revision properly and does not cause a 2nd node save to occur:

/**
 * Implements hook_action_info().
 */
function revert_last_revision_action_info() {
  $action = array(
    'REVERT_LAST_REVISION' => array(
      'label'        => t('Revert to Last Revision'),
      'type'         => 'node',
      'configurable' => FALSE,
      'triggers'     => array('any'),
      'behavior'     => array('view_property'),
    ),
  );
  return $action;
}

/**
 * Action function for REVERT_LAST_REVISION.
 */
function REVERT_LAST_REVISION(&$entity, $context = array()) {
  $revision_list = node_revision_list($entity);
  unset($revision_list[$entity->vid]);
  if (count($revision_list) > 0) {
    $last_revision = max(array_keys($revision_list));
    $entity = entity_revision_load('node', $last_revision);
    $entity->revision = TRUE;
    $entity->log = "Reverted via bulk operation action.";
    entity_save('node', $entity);
  }
}

Does anyone know what is causing the final node save in ViewsBulkOperationsAction::execute to not fire? I can't tell if it's because of the action info behaviors not set as: save, pre-save, or changes_property values. Or perhaps it's the usage of entity_save here  instead of a node_save ...

I've debugged this with a few nodes using Batch and single nodes.


How to include jquery.js before other javascript includes? I'm using a jquery carousel on my site and getting some errors on some pages. My jquery guru said the cause of the problem is that currently jquery.js gets included after other javascript includes.

Making the jquery.js the first include will fix the problem according to him. How do I change the order of the javascript includes?

Use hook_js_alter to change the order of js presentation.

For example, edit your theme's template.php:

function youtheme_js_alter(&$javascript) {

  $javascript['misc/jquery.js']['group'] = -500;

  $javascript['misc/jquery.js']['weight'] = -500;

}