How to implement custom access to node revisions? I want to implement a custom access check in Drupal 8, where users assigned to the node field node-owner have view/edit and revisions view/edit permissions for this specific node.

I have implemented it for node view/edit using the node access system with hook_node_access_records() and hook_node_grants(). But I cannot find how to implement it for the node revisions, since the access check performed in NodeRevisionAccessCheck takes into account only the 'view revisions' and 'revert revisions' role permissions and I cannot see a relevant hook.

Should I do custom access checking on routes as described here?
https://www.drupal.org/docs/8/api/routing-system/access-checking-on-routes

And if yes, how do I implement the route check and fetch the current node?

As you said, node revision does not have hook implement for check access. So you need other way to resolved your problem. My way is alter existing services. Just following document, there is file my_module/src/MyModuleServiceProvider.php

<?php

namespace Drupal\my_module;

use Drupal\Core\DependencyInjection\ContainerBuilder;
use Drupal\Core\DependencyInjection\ServiceProviderBase;
use Symfony\Component\DependencyInjection\Reference;

/**
 * Class MyModuleServiceProvider.
 *
 * @package Drupal\mymodule
 */
class MyModuleServiceProvider extends ServiceProviderBase {

  /**
   * {@inheritdoc}
   */
  public function alter(ContainerBuilder $container) {
    $definition = $container->getDefinition('access_check.node.revision');
    $definition->setClass('Drupal\my_module\Access\MyModuleNodeRevisionAccessCheck');
    $definition->setArguments(
      [
        new Reference('entity.manager'),
      ]
    );
  }

}

After alter access_check.node.revision service. I'll define new class check access view node revision with extend class NodeRevisionAccessCheck and override method access like this. File src/Access/MyModuleNodeRevisionAccessCheck

<?php

namespace Drupal\my_module\Access;

use Drupal\Core\Access\AccessResult;
use Drupal\node\Access\NodeRevisionAccessCheck;
use Drupal\Core\Session\AccountInterface;
use Drupal\node\NodeInterface;
use Symfony\Component\Routing\Route;

/**
 * Provides an access checker for node revisions.
 *
 * @ingroup node_access
 */
class MyModuleNodeRevisionAccessCheck extends NodeRevisionAccessCheck {

  public function access(Route $route, AccountInterface $account, $node_revision = NULL, NodeInterface $node = NULL) {
    if ($node_revision) {
      $node = $this->nodeStorage->loadRevision($node_revision);
    }
    $operation = $route->getRequirement('_access_node_revision');
    // You can override logic check access here or provide a new hook.
  }

}


Cannot redeclare drupal_get_hash_salt() I had a site and it was running fine on the live server but when I moved it to my local server it gave me this error.

Fatal error: Cannot redeclare drupal_get_hash_salt() (previously declared in
D:\wamp\www\htdocs\projects\mysite\includes\bootstrap.inc:2248) in
D:\wamp\www\htdocs\projects\mysite\includes\common.inc on line 5045

I guess the problem occurred because of editing the variable

$drupal_hash_salt = 'zU4q79TqFe0thQO-xGQbfbrFfKloUk9OYXfQ70J1nw0';

manually in setting.php file.

Does anybody have any idea how can I solve this problem?

You've got definitely a Drupal upgrade problem, drupal_get_hash_salt used to be in common.inc and was moved to bootstrap.inc in Drupal 7.23 version as you can see in https://www.drupal.org/node/1739986.

Something went wrong with your core update, I'd suggest you to backup your data and upgrade your files to the latest version, then run update.php and check everything is OK.


Anonymous users can't use personal contact forms I'm using the core Contact module, with personal contact forms on profile pages. I set both the permissions "Visit user profile" and "Use users' personal contact pages" for anonymous users, but I still just get a 403 when trying to view a user's contact page when logged out.

I am using Pathauto (and Subpathauto) for user profiles; I don't think that's the issue but it's worth mentioning.

Also, this is occurring on Drupal 7.

Assuming that the anonymous users are not trying to access user/0/contact (which would not be an ordinary case), the reasons why they cannot access the contact for a an authenticated user A are essentially 3:

User A didn't enable the contact form
The setting for enabling the contact form for user A has not been yet saved
The anonymous user sent too much messages

In the first two cases, it's the access callback for the user's contact form that block the access, using the following code. (See the comment before the code.)

// If the requested user has disabled their contact form, or this preference
// has not yet been saved, do not allow users to contact them.
if (empty($account->data['contact'])) {
  return FALSE;
}

In the third case, it's the form builder that returns an access denied page.

// Check if flood control has been activated for sending e-mails.
  $limit = variable_get('contact_threshold_limit', 5);
  $window = variable_get('contact_threshold_window', 3600);
  if (!flood_is_allowed('contact', $limit, $window) && !user_access('administer contact forms') && !user_access('administer users')) {
    drupal_set_message(t("You cannot send more than %limit messages in @interval. Try again later.", array('%limit' => $limit, '@interval' => format_interval($window))), 'error');
    drupal_access_denied();
    drupal_exit();
  }

Notice that in last case, the default limit is 5 messages in a hour, and that limit is cumulatively valid for any user sharing the same IP, as flood_is_allowed('contact', $limit, $window) executes the following code.

if (!isset($identifier)) {
  $identifier = ip_address();
}

If you are not seeing any error message from Drupal ("You cannot send more than […]") and the enabled theme or any module is not hiding the error messages, I would assume the users didn't enable their contact form, or the setting to enable the contact form was not yet saved.


"Deprecated function: implode()" on GMap Drupal module I have containerised a legacy Drupal 7 website with Docker. This is the docker-compose file:
version: '2.0'
services:
    drupal:
        build: .
        ports:
         - "8080:80"
        links:
         - mysql:mysql
    mysql:
        build: ./db
        ports:
         - "6603:3306"

The drupal container uses the official drupal:7.72 image, whereas mysql stems from mysql:5. The database container is responsive and reachable from the Drupal container. The main page of the website loads correctly, but it shows this error message:

Deprecated function: implode(): Passing glue string after array is
deprecated. Swap the parameters in
Drupal\gmap\GmapDefaults->__construct() (line 107 of
/var/www/html/sites/all/modules/gmap/lib/Drupal/gmap/GmapDefaults.php).

There is a similar error reported for a different function in Drupal 7.70. But apparently it was resolved with 7.71.
How can this particular error be solved? Would editing the GmapDefaults.php file be an option?

This answer draws upon the comments above by leymannx. The essential problem is an incompatibility between the GMap module and PHP 7.4, for which a patch is available. In this answer the patch is applied to the code repository itself, prior to any Docker builds, this is possibly the cleanest method.
The first step is to download the patch into the right folder in the repository:
cd sites/all/modules/gmap
wget https://www.drupal.org/files/issues/2020-03-06/gmap-php7.4.patch

The patch file is encoded for MSDOS, therefore it must be converted before the patch can be applied. Here all the target files are converted too, as a precaution:
dos2unix ./gmap-php7.4.patch
dos2unix gmap_test/gmap_test.features.inc
dos2unix lib/Drupal/gmap/GmapDefaults.php
dos2unix tests/inc/gmap_defaults.inc

The patch can now be applied. Since this is a git repository, the git command itself can not be used.
patch -p1 -i ./gmap-php7.4.patch

Finally remove all the extra files the process may have created. They are not needed in the container.
rm *.patch gmap_test/gmap_test.features.inc.orig lib/Drupal/gmap/GmapDefaults.php.orig tests/inc/gmap_defaults.inc.orig


Display a menu on all pages except a specific page type In my site, I have a menu that should be displayed on all pages, except on pages of a certain type.

In "admin -> structure -> blocks" I can set the visibility parameters of this menu to "pages of a certain type", and check all page types except the one I dont want. This has 2 problems :

1) whenever I add a new page type, I need to update this menu visibility (minor problem)

2) the menu will not be visible except on pages. For example, on the contact page, there is no menu.

What should be the right way to do that ?

I suggest using the context module for better and more advanced handling of blocks.

Alternatively, you could use pathauto to create a unique url for that content type (like mysite.com/type/content ) and set the block to show up everywhere, excluding 'type/*'. If you do this, make sure to rebuild your urls.


How to reference a Current Node URL Prior/After a User submits a Rules Link trigger Maybe I'm way off mark here.
I have an Node 'application' page and require that the current view page be referenced within a following page after a logged in user has clicked the 'Apply' link (a Rules Link). The above node allows a user to apply for an advertised role say a musician for a bands project guitarist vacancy, but basically its like any other Jobsboard type process.

I can get my Nodes related with the Relation model, but that's not the issue. The issue is that I need to get the relation of the current viewed page so that once the User applies, the said Node will be referenced for later recall in any applicant or Advertiser's dashboard. At the moment, all that happens is that the Rules link takes an Applicant user to a custom vacancy complete form page (which I have made using Panel Pages) and it fires off fine, but there is no link to either parties involved for me to then manage back-end and build further functionality on.

I want to grab the Job Node URL so that after a user hits an 'Apply' Rules Link button (shown on the Job node page bottom) it then makes a note of the said Node (URL) so that a number of Rules Actions such as create a new Node number; create a relationship to the Applicant; saved a new entity as an Application Node. I can manage to get the 'Submit' to trigger to the application page, and 'send it' but I'm not sure at what stage or where temporarily the said Node url path needs to be set prior to Rules then taking it and working through it's Rules actions (ie, post application, send email to application, send message to Advertiser you have a 'new' applicant whereas after they can do further tasks (outside of this question posted here).

Or, maybe my approach is completely off goal. Maybe the only important point is to get the Rules Link to relate to the currently viewed Node (job position in question offered) which when triggered will then relate the user to any other uses. I'm not sure, but even looking at first loading any Node, is it possible that the Rules Link has to already pull in the Node ID once the user clicks to view the Node on screen, then the Rules Link will have already built a relationship?

Hope the above is not too confusing! but I've tried to express my mental ideas. I would like to do this in Rules. (I'm using Rules, Rules Link, Views).

Failing all of that, how do I link in a User application to relation to the original post so that the advertiser can see who has applied to the said vacancy advertised?

Please, where am I going wrong in my approach and what am I missing?
Much appreciated. Thanks.

Revised question: 21/05/14.

A custom way to do it... Sorry not using Rules but it might help.

So you have two main node types ? And advert and an application ?
And the link to the application needs to contain the node ID of the advert.
I would use a custom link and hook_form_alter. For example;

If the apply link is only seen on the advert node page then you can use:

$nid = arg(1);
print l(t("Apply"), "node/add/application/$nid");

either in a node.tpl.php or in a preprocess function.

This will take the user to the node add form.
In a custom module you use hook_form_alter to get the $nid from the URL and add it to the form in the in the right field such as :

/**
 * Implements hook_form_alter().
 */
function custommod_form_alter(&$form, &$form_state, $form_id) {
  if ($form['#id'] == 'application-node-form') {
    if (isset(arg(3))) {
      $form['field_advert_relation'][LANGUAGE_NONE][0]['target_id']['#default_value'] = arg(3);
    }
  }
}

This is for a normal entity reference field.
And the field could be disabled or hidden also.


Can't login with varnish enabled I can't login from the front-end with varnish installed.
Here's what I think it is issue

sub vcl_recv {

 # Do not cache these paths.
 if (req.url ~ "^/status\.php$" ||
  req.url ~ "^/admin$" ||
  req.url ~ "^/admin/.*$" ||
  req.url ~ "^/admin/?" ||
  req.url ~ "^/user" ||
  req.url ~ "^/user/.*$" ||
  req.url ~ "^/users/.*$") {
  return (pass);
 }

and the session cookies

if (req.http.Cookie) {
    set req.http.Cookie = ";" + req.http.Cookie;
    set req.http.Cookie = regsuball(req.http.Cookie, "; +", ";");
    set req.http.Cookie = regsuball(req.http.Cookie, ";(SESS[a-z0-9]+|NO_CACHE)=", "; \1=");
    set req.http.Cookie = regsuball(req.http.Cookie, ";(SESS[a-z0-9]+|SSESS[a-z0-9]+|NO_CACHE)=", "; \1=");

If I try to login directly from apache port:8000 it works as expected.
Here's the whole default.vcl file: http://pastebin.com/qPRyFEjP

I don't get why it's not piping to the authenticated users. Why wouldn't it login in?
Thanks.

The offending parts in your VCL are (line 53):

# Drop any cookies sent to Drupal.

 if (!(req.url ~ "install\.php|update\.php|cron\.php|admin\.php")) {
 unset req.http.cookie;
 }

and (line 81):

# Drop any cookies Drupal tries to send back to the client. This will make it unpossible to login, unless you filter it a bit better that it is made below
sub vcl_fetch {
 if (!(req.url ~ "install\.php|update\.php|cron\.php|admin\.php")) {
  unset beresp.http.set-cookie;
 }
}

Remove both of them.


Which tokens can I use in a rule to email all suppliers mentioned in an entity reference field? In my website, I need to send a notification email to suppliers. I’ve created a content type supplier with email, warehouse 1 and warehouse 2 as fields.

In commerce product, I’ve created a supplier field (entity reference).
Now, I need to send an email on the rule event ‘completing the checkout process’ to those suppliers for them to start preparing the products for pickup and I can’t find any related tokens on the Rules Action ‘Send email’.

Any suggestions?

Assuming your question is about D7, you could try to create a view (using the Views module) of those suppliers that you want to send an eMail to.

After you succeeded in creating such view, you can process the results of a VBO enabled view via Rules, whereas your rule performs 2 Rules Actions (in the rule you already have in place related to your Rules Event about "completing the checkout process":

load the VBO list of those suppliers.
add a loop to perform a Rules Action "send an eMail", for each supplier contained in your Views results.

For more details, have a look at the tutorial "How to process the results of a VBO enabled view via Rules?".


Solr search with exact match I am using drupal 8, search api and solr on our site. In views, I am using full text search with direct query option. Search is working for multiple words. What I want is when I search with double quote, I want the result with exact match of query string. But putting double quote doesn't seem to have any effect on it. If I changed parse mode to multiple words, double quotes work but it doesn't return any result for query without double quotes. Can I even achieve it in single view display? Any workaround suggestion so that it works for query without double quotes but also respect double quotes to do exact match depending upon query.

Take a look at this issue:

keys of fulltext searches must be encoded as phrases for terms parse mode

A quick read indicates that you might be able to just escape the spaces, e.g foo\ bar.

Also see the view settings image in comment #10 of that issue.


How do I remove webforms from content types? Currently, our site is built so that anytime a specific type of new content is created, the page automatically includes a form required for the end user.  Due to tracking issues we're having with other software, we would like to remove these automatic forms from this specific resource type so that the resource is no longer gated.

Can anyone explain how I can make this change to my current content type so that we're not forced to create a whole new content type and replacing things systematically?

If you use the webform module (I'm not 100% sure from your question), and you want to disable the webform functionality for the content type, then you can do this on the settings page of the content type (Admin > Structure > Content types). There should be a a fieldset or vertical tab called "Webform", and when you click on that there should be a checkbox that you can disable.

But be aware that this removes the form from all previously created nodes too, not only for the new ones.

If you're not using webform then please specify what modules do you use so that we can understand how this functionality is build into your site.


Create custom variables for a template file inside a menu callback function here is a good one that has always stumped me.

I would love to see a solution in both D6 and D7.

I create custom modules and usually work with the menu api to create menu type -> MENU_CALLBACK.

Here is an example:

function example_menu() {
  $items['example/page1'] = array(
    'page callback'     => 'example_page1_callback',
    'access callback'   => TRUE,
    'type'              => MENU_CALLBACK,
  );
  return $items;
}

I would like to see the exact code solution to provide three different variables to be printed in a custom theme template based on the following code.  To add to that challenge, I would like the code to be written in the menu callback function only.  I know there are many possible ways to do it but could never figure out how to do it in a menu callback function which would be the most useful way.

//****************************************
// This code block goes in a custom module called example_menu_variables.module

// hook_menu example
function example_menu() {
  $items['example/page1'] = array(
    'page callback'     => 'example_page1_callback',
    'access callback'   => TRUE,
    'type'              => MENU_CALLBACK,
  );
  return $items;
}

// hook_meny callback function
function example_page1_callback() {
  // please provide code within this function to turn these next three
  // variables into separate output variables for the template.
  $variable_to_print1 = 'Foo';
  $variable_to_print2 = 'Bar';
  $variable_to_print3 = array('bing', 'bang', 'bong');
  return;
}
//****************************************

//****************************************
// This block of code represents the part of the custom theme template related to the menu location from the hook_menu call
// D6 template name would be page-example-page1.tpl.php
// D7 template name would be page--example--page1.tpl.php

<?php print  $variable_to_print1?>

<?php print  $variable_to_print2?>

<?php print  $variable_to_print3[0] . ' ' . $variable_to_print3[1] . ' ' . $variable_to_print3[2]?>

/*
output should look like:
Foo
Bar
bing bang bong
*/

//****************************************

Hope this is the kind of problem that someone wouldn't mind solving.  Thanks for your time.  :)

Ray James

I don't believe you can do this without using hook_theme, but this is exactly what it's for and it's quite simple. (This code is for Drupal 6.)

/**
 * Implements hook_menu().
 */
function example_menu() {
  $items['example/page1'] = array(
    'page callback'     => 'example_page1_callback',
    'access callback'   => TRUE,
    'type'              => MENU_CALLBACK,
  );
  return $items;
}

/**
 * Page callback function
 */
function example_page1_callback() {
  $variable_to_print1 = 'Foo';
  $variable_to_print2 = 'Bar';
  return theme('example_contents', $variable_to_print1, $variable_to_print2);
}

/**
 * Implements hook_theme().
 */
function example_theme() {
  return array(
    'example_contents' => array(
      'arguments' => array('variable_to_print1' => null, 'variable_to_print2' => null),
      'template' => 'example-contents',
    ),
  );
}

$variable_to_print1 and $variable_to_print2 are now available in example-contents.tpl.php.


How to soley wrap the -field in a custom -wrapper in Webform 4.x? I've a fairly simple question. Due to a given CSS I need to wrap the <input>-field (as well as <select> or <textarea>) of webform-component with a custom
-wrapper.

Change the follwoing ->

    Name
    <input type="text" id="edit-submitted-title" name="submitted[title]" value="" size="60" maxlength="128" class="form-text required">

to ->

    Name

         <input type="text" id="edit-submitted-title" name="submitted[title]" value="" size="60" maxlength="128" class="form-text required">

I tried this snippet (changing #prefix and #suffix with hook_form_alter()), but it wraps the whole webform-componoent in a custom div.

Result is like this:

        Name
        <input type="text" id="edit-submitted-title" name="submitted[title]" value="" size="60" maxlength="128" class="form-text required">

I also tried to modify #field_prefix and #field_suffix with, but it doesn't result in any output at all. It seems, that these doesn't allow to have any custom html in it.

Any suggestions? Thanks.

Use hook_form_alter and add "'#title_display'    => 'none'," and use label in prefix. e.g.

if($form_id == "content_type_node_form"){
   $form['field_name']['#prefix'] = 'name
';
   $form['field_name']['#suffix'] = '
';
}

I have not tested it but this can work.


Creating Content List I have an custom content type movie.By which users can create "movie" content.
The movie content type is simple containing a title, director's name and a poster.

Now,what i need is,  Each user should be able to create lists of movies.As example , one may create "10 most scariest movies" , "10 most comedy movies" etc.

I want the creation of list in the following way ,

1) User will give it a title to his list.

2) Then he will add movies to his list , which are already crated .(like the way one user can tag other user in facebook - user should be able to tag movies.)

3) After the list is created when a movie on a list is clicked, it should lead to the page of the corresponding movie.

How should i solve this problem??

I am using Drupal 7

Thanks in advance

I solved the problem using Entity Reference  Module.

I made a custom content type - "Movie List" , and add a field of "Entity Reference" type , then made a reference to "Movie" content.


How do I test a paragraph bundle entity reference with Behat? I am learning Behat with Drupal 8 and I'm stuck on trying to test a paragraph bundle (field_related_content) which has a title and description field, the title is an entity reference field to content type marine_notices. Currently I have the below, but the results are 'No link to Post Title', am I missing something?

  @api
  Scenario: Reference site pages from within a "marine_notices" node
  Given "marine_notices" content:
    | title      |
    | Post title  |
  When I am viewing a "marine_notices" content:
    | title                | Post title         |
    | field_related_content | Post title - <front> |
  Then I should see the link "Post title"

I needed something similar so I implemented a context for paragraph support.

Install using composer require miiimooo/behat-tools

The follow the installation and usage here: https://github.com/miiimooo/behat-tools

In your feature you can then write:

Feature: Content
  @api
  Scenario: Paragraph creation through Drupal 8 API

    Given a "my_paragraph_type" paragraph named "my_arbitrary_name":
      | title             | Lorem ipsum |

    Given I am viewing a "page" content:
      | title            | Dolor sed         |
      | field_paragraphs | my_arbitrary_name |


Access node only from manual URL Looking for a module or hint to allow a node only be accessed from the manually set URL.

Ex. having node 42 with  URL path setting = myStory can only be accesed with http://host/myStory, while http://host/node/42 will return a NOT FOUND.

With respect to all of the commentary given to the question, if you really want to do this, you can look at $_SERVER['REQUEST_URI'] in any number of places and based upon its content, do things differently.

For example, if you go to:

www.example.com/path/to/hidden/content

$_SERVER['REQUEST_URI'] will be /path/to/hidden/content

yet if you go to

www.example.com/node/###

$_SERVER['REQUEST_URI'] will be /node/###

but the same content will be displayed while the url in the browser will be different.

So, if you want to obfuscate your nodes based up that, you could delete their content in a preprocess hook, or cobble together something in hook_init to do a 404 but just also be very wary of the caching of pages for anonymous users as well, so hook_boot would be needed instead, and do you want to do this for logged in users and any of numerous other what ifs.........

Plus, if you have global redirect or another similar module installed, the above won't work as it will have already redirected you to the alias.


How do I get the token for a date field type to display as a custom format? When adding content I entered a date which is February 2013 within a Date field type but it is displayed as raw data such as 2013-02-01T00:00:00 for the token that is listed as [node:field_fact_sheet_date].

If I instead change the token to [node:field_fact_sheet_date:custom:F Y] or                                                     [node:field_fact_sheet_date:custom:F,Y] then nothing is listed.
However it is working when I use [current-date:custom:F Y] and displayed correctly as August 2013.  How do I get the token for a date field type to display as a custom format?

A date may be a range, therefore [node:field_date] cannot be considered as a date token. Install Entity API and enable the module "Entity tokens" to get access to the actual date value,
Beware that for an obscure reason Entity token replace the underscore ([node:field_date...) of the original tokens name by a dash ([field-date...), you will then have access to a properly formatted date (in my case "[node:field-date:value:custom:Ym]", in the original question I guess therefore "[node:field-fact-sheet-date:value:custom:F,Y]")


Make a copy of the live site for localhost testing I'd like to copy my live site so I can run it on localhost and test some modules before installing them on the livesite.

Is there a step-by-step way to do this? I have access to PHPyAdmin, so I can easily export the database. I know there's more to it than just exporting, thought.

You can easily do this with the backup and migrate module. If you have lots of dynamic content you should be using this module to schedule a backup on cron jobs too.

Before I learned how to use the MySQL command line, because phpmyadmin has an import file size limit, I would compress a whole website with the backups in a private file path and move it to a new server. Then I just remove the database settings and install a new installation of Drupal. After I will enable the backup and migrate module and restore that last database.


Term reference field - print as other format I'm using term reference field, which is displaying as entity.

I want to print this in the other place of node.tpl, not full entity but only names.

Is this possible?

I've tried

<?php print render($content['event_speakers']['und'][0]['value']); ?>

But it doesn't print anything

EDIT: I didn't completely get your question initially. To do this you will need to fetch the term names yourself, and make them available to your node template file. This means you'll have to use hook_preprocess_node() implementation.

Here's the code you'd use:

function YOUR_THEME_preprocess_node(&$variables) {
  if ($variables['node']->type == 'YOUR_CONTENT_TYPE' && isset($variables['node']->field_event_speakers[LANGUAGE_NONE][0]['tid'])) {
    $event_speakers = array();
    foreach ($variables['node']->field_event_speakers[LANGUAGE_NONE] as $event_speaker) {
      $term = taxonomy_term_load($event_speakers['tid']);
      // Just to display the name:
      $event_speakers[] = $term->name;
      // To display linked name instead, use this:
      // $event_speakers[] = l($term->name, 'taxonomy/term/' . $term->tid);
    }
    // This will separate names with a comma, and a space.
    $variables['event_speakers'] = implode(', ', $event_speakers);
  }
}

You can then use this as many times as you want in the template; example:

<?php print $event_speakers; ?>

<?php print $event_speakers; ?>


how to add taxonomy vocabulary and terms through code I have added some taxanomy vocabulary with terms in my local development server which I need in some modules. I want to get these vocabularies with terms auto inserted when ever I install these modules where I have used them. Is there a way I write some code in drupal module which inserts the taxonomy vocabularies and terms when ever I install the module.

Thanks for your suggestions.

Rather than writing code, I use the Taxonomy CSV module.  It allows you to export and import taxonomy as CSV files.  You can use the module's user interface or do it by command line with Drush to speed things up even more.

Initial configuration can be a little tricky, but it's able to preserve tree hierarchies and order, etc. so a bit of complexity is to be expected.


How can I programmatically reset a user's password I have a native mobile application communicate with my drupal 7 site via services module.  I'd like to give users the ability to reset their password from the app.  Is there a way to initiate this process programmatically, so a an email is generated with a one time use token that expires in 24 hours?

Thanks

You can use the _user_mail_notify() function, along with a user object, to invoke the password reset email:

// Load a user (admin in this case).
$account = user_load(1);

// Invoke the email. It will be queued along with other system mail to be sent during cron
_user_mail_notify('password_reset', $account);

A one time login URL with a 24 hour expiry is included by default with that particular email.


In Views, how to allow users to toggle between a grid and list? I have a view that returns a 4 column grid view.  The client wants to be able to toggle between grid results and teaser results by clicking on an icon.

Does Views handle this naturally?  Do I need to utilize AJAX?

If you want to do something like this,

then you can use QuickTabs Module

So, here user can switch from TAB-ONE to TAB-TWO .. so on ..

To implement this, first you have to create View-Blocks and then you have to create Quick Tabs by using QuickTabs Module

Here is one Video Tutorial to create QuickTabs.


Is it possible to add multiple fields within a single component? $form['value'] = array(
        '#type' => 'textfield',
        '#title' => t('Webservice URL'),
        '#default_value' => $component['value'],
        '#description' => t('The default value of the field.'),
        '#size' => 60,
        '#maxlength' => 1024,
        '#weight' => 0,
    );

I want to make a second textfield in my component where I can specify the second part of my Webservice URL and then concatenate them in my rendering. How can I add a second textfield to my webform_edit?

For one of my projects I spend almost whole week trying to find similar functionality it turns out that you cannot render the input of two fields as one entry from webform result due to the fact that webform creates separate database entry for every field. I solve my problem by just creating multiple fields value_1 value_2 and so on and when exporting result concatenate them in Excell (stupid I know :-) and does not work for your case) . There is module Webform Add More but it only use the same aproach but hides the extra fields and shows them when needed. If you are willing to switch from webform you can try EntityForms this way you can use regular Drupal fields to get entered values and embedding Entityforms on Nodes using Entity Reference


EntityMalformedException: Missing bundle property on entity of type node. in entity_extract_ids() I created a node called "Tutorial". When I preview the post before saving it, I received the following error:

  EntityMalformedException: Missing bundle property on entity of type node. in entity_extract_ids() (line 7693 of /var/www/clients/client1/web2/web/includes/common.inc).

However, the error when submitting a blog (a node created by drupal) is different. Here it is:

  PDOException: SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 1: SELECT nid FROM {node} WHERE uid = ; Array ( ) in eval() (line 10 of /var/www/clients/client1/web2/web/modules/php/php.module(80) : eval()'d code).

and

  Notice: Trying to get property of non-object in eval() (line 8 of /var/www/clients/client1/web2/web/modules/php/php.module(80) : eval()'d code).

Any help please...

I had similar issue. In my case I was using following line in node.tpl

$field = field_get_items('node', $node, 'field_foo');
$sponsored = field_view_value('node', $node, 'field_foo', $field[0]);

And field_foo was not in all content type.
In Drupal 6 or 5 approach was different to get field values. That's why it was not happening.

Solution was:

if($node->type=='story'){
 $field = field_get_items('node', $node, 'field_foo');
 $sponsored = field_view_value('node', $node, 'field_foo', $field[0]);
}


Is there any convention about the name to use for a file containing a class definition? I have a static class I want to call in my module.

Does the file containing the class definition need to have a special name convention, such as MyStaticClass.class.php? The file is in my module folder.

The only part of the Drupal coding standards that talks of filenames doesn't say how to name PHP files containing class definitions.

Files containing PHP code, which are not the main module file, or the installation file, usually use the extension .inc, in Drupal 7 and previous versions. As there isn't any possibility of conflict between files used from different modules, you can decide the rest of the filename.

Note that Drupal 7 uses a registry, which contains a list of files defining classes. If you have a file defying a class, you just add a line similar to the following one, on the .info file.

    files[] =

In this way, the file will be automatically loaded by Drupal when you reference the class, such as when you instance an object of that class, or you call a method defined in that class.

Drupal 8 uses .php as extension for PHP files containing a class, such as Node.php, Uuid.php, and Database.php.


How to make global math expresssion in views searchable? I did manipulation calculation on webform submission data in Views by using Global Math Expression. I need to use filter of this Math Expression field, but I could not find it in the filter field. I tried to define in relationship also not available.

How can I use the global math expression in view filter?

views doesn't allow to filter data based on computational field. In your case you are using global math function which is a calculated field.

I would suggest to use computed_field module and calculate your value in this field then you can easily filter your result based on this field.


Building a full featured gallery with voting system I'm looking for a way to build a simple gallery node type in Drupal, with vote (with Votingapi and Fivestar)per image enabled. (1 vote per image, per node, per user, and users are able to vote on any image in the node).
As simple as it looks, I'm unable to build a simple proof of concept of what I'm trying to achieve.

Here's a mockup of how I see the thing, and here's how I see the thing in Drupal.
A content type 'Gallery' these following fields:

Title
Body
Field Collection (multiple):

Image (single)
Fivestar rating

I succeeded to do it and now, to compute the results, I would like to get the results per node.
However, if you look into the votingapi_vote table, the only data for a vote are:

MariaDB [voting]> SELECT * FROM votingapi_vote;
+---------+-----------------------+-----------+-------+------------+------+-----+------------+-------------+
| vote_id | entity_type           | entity_id | value | value_type | tag  | uid | timestamp  | vote_source |
+---------+-----------------------+-----------+-------+------------+------+-----+------------+-------------+
|      10 | field_collection_item |         2 |    80 | percent    | vote |   1 | 1455270089 | 127.0.0.1   |
|      13 | field_collection_item |         3 |    60 | percent    | vote |   1 | 1455271926 | 127.0.0.1   |
|      15 | field_collection_item |         1 |    80 | percent    | vote |   1 | 1455272041 | 127.0.0.1   |
+---------+-----------------------+-----------+-------+------------+------+-----+------------+-------------+

It is impossible to retrieve data from the parent node because it simple doesn't exists in the DB.

It looks like we could change tags dynamically, so I hooked into fivestar to generate dynamic tags, but it gets blocked in _fivestar_cast_vote(), especially in fivestar_validate_target(), and I'm unable to generate tags dynamically.

I also tried to hook into Votingapi using hook_votingapi_preset_votes_alter() but if you're using Fivestar with the AJAX widget, it's impossible to get information on the current node using menu_get_object(). So I'm still stuck.

Now I'm trying to look for another solution, if you have ideas, please let me know.

1 vote per image, per node, per user, and users are able to vote on
  any image in the node

I don't fully understand the use case here; it might be easier to visualise the scenario with a fuller explanation?

At a guess, the issue might revolve around the use of field collection module here? I'm not a wizard at the internals of that, but personally in this situation I usually manage this with a container/item setup:

Gallery (node/entity)

Image (node/entity)
Image

Gallery

Image
Image

I then relate these either with entity_reference or I guess you could use inline entity form, depends. I don't know if there is anything that precludes you from doing it this way, but I think you're more likely to have better data from votingapi et al like this? Probably using two content types is going to give more joy than entities for that reason.

This is all from a site builder perspective, where using this kind of setup generally means I have to write as near to zero code as possible!


Form #states visible for numeric values The form has two radio buttons like follows.The "design" radio field should be visible only when user selects 'Ten' or 'hundred' from the "price" field.

If user choose 'other' it should not be visible.

I tried like follows, it's working but by default the 'design' field is come with visible state.

//$options array is dynamic.
$options =  array(10 => 'Ten', 100 => 'hundred', 'other' => 'Other');

  $form['price'] = array(
    '#type' => 'radios',
    '#title' => t('Price?'),
    '#options' => $options,
    );
  $form['design'] = array(
   '#type' => 'radios',
   '#title' => t('Designs'),
    '#options' => $designs,
   );
  $form['design']['#states'] = array(
    'visible' => array(
        array(':input[name="price"]' => array('!value' => 'other')),
    ),
  );

I've tried several ways like follows with no luck.

array(':input[name="price"]' => array('!value' => '')),
array(':input[name="price"]' => array('checked' => TRUE)),

Is there any option like to check the selected value is numeric or not? like

array(':input[name="price"]' => array('value' => isNumeric)),

or the other option would loop through the dynamic option values?

      array(':input[name="category"]' => array('value' => 10)),
      'or',
      array(':input[name="category"]' => array('value' => 100)),
      'or',
        .
        .
        etc

Any suggestions or input would be much appreciated.

Try this:

$form['design']['#states'] = array(
  'visible' => array(
    ':input[name="price"]' => array('!value' => 'other'),
  ),
);

though, to be honest I'm much more a fan of:

$form['design']['#states'] = array(
  'invisible' => array(
    ':input[name="price"]' => array('value' => 'other'),
  ),
);

Here are some good examples to follow. Not exactly your case, but close.


How do I create a role programmatically? How do I create a role programmatically?

What am I doing wrong here?

$role = \Drupal\user\Entity\Role::create(['id' => 'client', 'name' => 'Client']);
$role->save();

The problem is in the data array change name by label:

$role = \Drupal\user\Entity\Role::create(array('id' => 'client', 'label' => 'Client'));
$role->save();

Or you can use:

//your data array
$data = array('id' => 'client', 'label' => 'Client');
//creating your role
$role = \Drupal\user\Entity\Role::create($data);
//saving your role
$role->save();


Force image link download I have an image path like http://example.com/sites/default/files/image.jpg.

I have a download link like:

Download

So on clicking on the download it opens the image in the browser. Instead I want when I click on the Download link, it should download that image.

Is it possible?

You can use DownloadFile module. This module provides display formatter, for images, file etc, that uses downloadable links(of type: /download/file/fid/[fid]) and should be compatible with older browsers.

Note:

If you are doing custom coding, you can use file id (fid) to create your download link.
You must upload the image, so that it can be assigned a file id.


Does anyone know how to use the Ubercart UC VAT module? I have to implement different VAT for different products (regardless of the category). Some products can have 19%, some 4%, some 6%, and some they don't have a VAT rate at all.

So far I couldn't even specify a global 19% vat.

I don't understand how this is handled. I've searched for documentation but it's almost nonexistent.

VAT module adds 'VAT settings' tab to your Store administration > Configuration > Tax Rates and Settings (/admin/store/settings/taxes), where you can specify global VAT value.


Missing "view mode" permission in core Context

Drupal 8
Switching to Drupal for intranet site in large organization

Background

OtraganixLocker Corporation is switching to Drupal from a custom-made home-grown intranet site. They want to use D8.

The problem is, the old custom-made intranet had the following permissions for
(its equivalent of) D8 nodes:

add content
edit own content
edit any content
delete own content
delete any content
view own content
view any content

Moreover, the granularity of the permissions worked down to the "content-type" level on the old intranet.

Moreover, the granularity of the permissions on the old intranet permitted user-based-assignment as well as role-based-assignment.

Question

Drupal 8 seems to be missing the view own content and view any content permissions that the old intranet system had.

Moreover, there seem to be a lot of ways to handle this, at least in D7.

Is this missing functionality accounted for in D8 core and simply missing from the front-end interface, or is it also absent from D8 core?
If it is not absent from D8 core, which specific function or functions in the D8 API account for this functionality?

See also

Blog post detailing the lack of granularity issue
Blog post addressing lack of granularity issue in D8

The node access control methods between Drupal 7 and Drupal 8 are largely the same and described in Node access rights.  There are still the same hooks, just some of the plumbing is different.

So, if you want to implement the Drupal 6 fine grained access in Drupal 8, you can either do hook_node_access() or proper grants.  Remember, node usage can exist in case other than the node pages (eg, lists); the node access system takes care of this.  Work has begun on the ACL module and dependencies which provide some abstractions for these.

Drupal 8 also has a new concept for route access.  It uses classes that implement AccessInterface, and then use YAML configuration for providing the requirements for the route.  Looking at how routing is set up for the code node module (which defines the Node entity), may be the best starting point for delving into this, though it uses the same Access classes as the node acccess system.  I think explaining it here may be too much.


Infinite scroll pager in Drupal 7 I want to add infinite scroll page in search result pages. I am using Drupal 7.

To achieve it i followed this link.

When i do exactly as per the step given on this page, but i am not able to get it working.

Here is the HTML generated on my search result page.

Now to apply the pager in this page i made the following changes in the scripts given in the above link.

Remove .autopager class as i will have to add .pager class
Remove the imagesLoaded function as there are no images in the result

So after removal js will be like this. In his code i have added the .pager class. I am not able to get the pager and what should i write instead of viewsInfiniteScroll

   (function ($) {
  Drupal.behaviors.viewsInfiniteScroll = {
    attach: function (context, settings) {
      $(function(){
        var $container = $('div.pager');
      });
    }
  };
})(jQuery);

After lots of brainstorming and googling one user Marc from drupal.org suggested me the working solutions. Thanks to Marc for the solution.

Here is the solution:

To set it up, you will need a couple of steps:
REM: This method don't use the "Infinite Scroll Module", it's a rewrite of the stuff. In this method I choosed to integrate it in the theme, you could also create your own module (wish would be probably better .... )

1) download https://github.com/desandro/imagesloaded (jquery.imagesloaded.min.js) place it in your theme folder YOURTHEME/js
This will make sure all images are loaded before activate the infinite scroll

2) download https://github.com/paulirish/infinite-scroll (jquery.infinitescroll.min.js) place it in your theme folder YOURTHEME/js
In order to make it work with Drupal search modify it as follow: Search match(/^(.*?page=)2(\/.*|$)/ replace it by match(/^(.*?page=)2(&.*|$)

3) Create a new js (ex:infinitescroll.js) with the content of the below jquery & place it in your theme folder YOURTHEME/js
Rem: You will probably have to change the img path

4) modify YOUR_THEME.info and add

scripts[] = js/jquery.imagesloaded.min.js
scripts[] = js/jquery.infinitescroll.min.js
scripts[] = js/infinitescroll.js

5) flush the cache

6) cross finger & try .... it should work if not ... it's time to debug with firebug ...

Jquery code which you should place in infinitescroll.js

(function($){
    Drupal.behaviors.viewsInfiniteScroll = {
            attach: function (context, settings) {
              $(function(){
                if (this.processed) return;
                this.processed=true;
                if ($('.search-results').length==0) return;
                var $container = $('.search-results');
                $container.imagesLoaded( function(){
                  $container.infinitescroll({
                    navSelector  : 'ul.pager',    // selector for the paged navigation
                    nextSelector : '.pager-next a',  // selector for the NEXT link (to page 2)
                    itemSelector : '.search-results',     // selector for all items you'll retrieve
                    animate      : true,
                    msgText  : Drupal.t("Loading new results..."),
                    img: '/sites/default/themes/bartik/images/ajax-loader.gif',
                    donetext:Drupal.t('No more results to load.'),
                },function(arrayOfNewElems,state){
                    //YOUR CALLBACK STUFF .. To re-attach behaviour if needed

                    })
            })
          });
          }
        };
})(jQuery);


Can I move a webform to another drupal installation? I have created a few webforms on our development server and would like to move them over to a production installation. Can I do this with node export?

I'm not concerned with migrate any user responses (as we were only testing).

You didn't say what version you are using but if it is drupal 6, there is a module for that exact purpose.

http://drupal.org/project/webform_share

Edit: Since posting this, the module has been updated with a Drupal 7 branch as well.


Rewriting output of existing content block I've added a content block via the administration panel, and placed and themed it - but now I realise I need to add some extra logic to output different things depending on what user is logged in.

What hook would I use to do this, and does using a hook guarantee it will overwrite whatever content has been put in via the Block admin panel?

You can try hook_block_list_alter() hook.

Act on blocks prior to rendering.

This hook allows you to add, remove or modify blocks in the block list. The block list contains the block definitions, not the rendered blocks. The blocks are rendered after the modules have had a chance to manipulate the block list.

You can also set $block->content here, which will override the content of the block and prevent hook_block_view() from running.


Form API 'image_button' vs 'submit' breaks my AJAX form I have an AJAX form that works as expected with the following submit code:

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

I want to use an image for the button, but the type 'image_button' breaks the AJAX functionality (multiple repopulating select fields, won't appear, or update):

$form['submit'] = array(
  '#type' => 'image_button',
  '#src' => '/themes/moon/images/go.gif',
  '#value' => t('Go'),
);

Oddly, the 'image_button' works fine when clicking it (form works as expected) it's just the AJAX updating of the form that stops working? Drupal Form API Reference

You have to set an unique '#name' tag for EVERY button (submit, image_button, button) on the page. This worked for me.


Add form field with AJAX Here is the form:

function payment_form($form, &$form_state) {
  $form['#tree'] = TRUE;

  // since credit card is also an option, the gift card section is contained in this div.
  $form['payment']['giftcard'] = array(
    '#type' => 'container',
  );

  // there are additional fields above here, but trimmed them out since they are not relevant to the issue.
  $form['payment']['giftcard']['giftcards'] = array(
    '#type' => 'container',
    '#attributes' => array(
      'class' => array('giftcards'),
    ),
    '#prefix' => '
',
    '#suffix' => '
',
  );

  // initialize the gift card field counter
  if (!isset($form_state['gift_cards'])) {
    $form_state['gift_cards'] = 1;
  }
  // build the fields
  for ($i = 0; $i < $form_state['gift_cards']; $i++) {
    $form['payment']['giftcard']['giftcards']['gift_card_number'][$i] = array(
      '#type' => 'textfield',
      '#title' => t('Gift Card Number'),
      '#title_display' => 'invisible',
    );
  }
  // validate the current gift card and add another field.
  $form['payment']['giftcard']['giftcards']['validate'] = array(
    '#type' => 'submit',
    '#value' => t('Validate'),
    '#ajax' => array(
      'callback' => 'validate_giftcard_add_field',
      'wrapper' => 'giftcards-wrapper',
      'method' => 'replace',
    ),
  );

Here is the callback function for the AJAX call. There is no validation currently, just trying to get it to add another field. If I add print statements in this function they are being output in a javascript alert, so this function is being called. However it is not returning any new fields.

function validate_giftcard_add_field($form, $form_state) {
  $form_state['gift_cards']++;

  return $form['payment']['giftcard']['giftcards'];
}

What is the right way to add new fields via ajax?

Additionally, all instances of  '#required' => TRUE, have been removed during my testing. I have not done anything with the validate or submit callbacks either.

#ajax->wrapper refers to an ID. Where as you have class="giftcards-wrapper". Change it to ID and it should replace it.


How to handle tokens in Rules field? I have duplicated Drupal Commerce module "Cash on delivery", from which I am trying to make custom module, where if customer choose as payment method my new payment, it will simply print out text with tokens inside.
(This is because client needs to be able to pair orders with payments sent by credit card directly to his account, he will pair them with commerce order number)

I have successfully made a textarea in rules UI even with token field under this area, now I have to print them.

Working code for making textarea:

function bankovy_prevod_settings_form($settings = NULL) {

  $settings = (array) $settings + array(
    'information' => '',
    'var_symbol' => ''
  );

  $form = array();

  $form['information'] = array(
    '#type' => 'textarea',
    '#title' => t('Information'),
    '#description' => t('Informácie, ktoré chcete zobraziť zákazníkom, keď si navolia túto možnosť platby.'),
    '#default_value' => $settings['information']
  );

  $form['var_symbol'] = array(
    '#type' => 'textarea',
    '#title' => t('Variabilný symbol'),
    '#description' => t('Sem vložte token, na základe ktorého sa bude generovať variabilný symbol.'),
    '#default_value' => $settings['var_symbol']
  );

    if (module_exists('token')) {
      $form['token_help'] = array(
        '#theme' => 'token_tree',
        '#token_types' => array('commerce-order'),
      );
    }

  return $form;
}

Code for displaying the output on commerce order:

function bankovy_prevod_submit_form($payment_method, $pane_values, $checkout_pane, $order) {
  $form = array();

  $var_symbol = "";
  if (!empty($payment_method['settings']['var_symbol'])) {
      $var_symbol = token_replace($payment_method['settings']['var_symbol'], array('node' => $form['commerce_checkout_form']));
  }

  if (!empty($payment_method['settings']['information'])) {
    $form['grafeon_bankovy_prevod_description'] = array(
      '#markup' => $payment_method['settings']['information'] . "<br/>" . $var_symbol
    );
  }

  // Need to create a dummy value to solve http://drupal.org/node/1230666
  // Probably an issue in the main commerce module
  $form['dummy'] = array(
    '#type' => 'hidden',
    '#value' => 'dummy'
  );

  return $form;
}

Now I have to somehow replace tokens, trying to use function token_replace, but it does not seem to work with "node" as checkout is not node, so I tried various different "commerce_checkout_form" strings but neither of them worked. Can anyone please help me out to solve this?

Thats the part I have problem with:

$var_symbol = token_replace($payment_method['settings']['var_symbol'], array('node' => $form['commerce_checkout_form']));

Any advice would be greatly appreciated.

Just needed to replace this one field with this:

$var_symbol = token_replace($payment_method['settings']['var_symbol'], array('commerce-order' => $order));

Now it works perfectly.


Altering the "Status report" page The hosting provider I user for my site disabled the phpinfo() function and, as consequence, the link that would normally appear in the status report page is not anymore shown, replaced by a warning message.

I would like to create a custom module to remove that message, and show a link to a page that, similarly to the page shown by phpinfo(), reports information about PHP and the enabled extensions.
Is there a way to alter the information about PHP system_requirements() normally shows in that page?

You may not be able to alter the system_requirements array directly, but you can hack around it in the theme layer by implementing theme_status_report.

 theme('status_report', array('requirements' => $requirements));


How to display label and field output inline I want to display same line label and fields in drupal 8. But by default it's showing field down and label up.

I'm using suffix and prefix it works.
How can I display it without suffix and prefix?

 $form['doc_date'] = array(
'#type' => 'date',
'#required' => TRUE,
'#date_date_format' => 'd-m-Y',
'#default_value' => (isset($record['doc_date']) && $_GET['num']) ? $d_date:'',
  '#attributes' => array('type'=> 'date', 'min'=> '-180 days', 'max' => date('d-m-Y') ),
  '#prefix' => '

Document Date : *',
'#suffix' => '

',
);

According to default field.html.twig file template which is use to render fields, you have to set #label_display => 'inline'
and #title => 'Your label'
Most of themes render inline label and content when class field--label-inline exist, but it is possible that you remove this css style from your theme.


Alternatives to hook_init() I use hook_init() to check the users' last access time. If the last access time is yesterday, I increment a counter and set some variables.

The problem is that hook_init() is sometimes executed more that once (i can see this using dsm()) for the same page load, so my code is executed multiple times resulting in wrong variables.

Why is hook_init() executed more than once?
What would the best approach to my problem be? Should I use another hook?

I did some more digging on this:
I search for calls to the hook_init() (searched for string module_invoke_all('init');) but found only the core call). I dont know if this can be called differently.

This is my hook_init()

function episkeptis_achievements_init(){
    dsm('1st execution');
    dsm('REQUEST_TIME: '.format_date(REQUEST_TIME, 'custom', 'd/m/Y H:i:s').' ('.REQUEST_TIME.')');
}

and this is the output:

1st execution
REQUEST_TIME: 09/07/2012 11:20:32 (1341822032)

then, changed the dsm() message to dsm('2nd execution'); and executed again, this is the output:

1st execution
REQUEST_TIME: 09/07/2012 11:20:34 (1341822034)
2nd execution
REQUEST_TIME: 09/07/2012 11:22:28 (1341822148)

You can see that the code is executed twice. However, the first time executes an old copy of the code, and the second time the updated copy. There is also a 2 sec time difference.

This is a d7 version with php 5.3.10

hook_init() is invoked by Drupal only once for each requested page; it is the last step done in _drupal_bootstrap_full().

  // Drupal 6
  //
  // Let all modules take action before menu system handles the request
  // We do not want this while running update.php.
  if (!defined('MAINTENANCE_MODE') || MAINTENANCE_MODE != 'update') {
    module_invoke_all('init');
  }

  // Drupal 7
  //
  // Let all modules take action before the menu system handles the request.
  // We do not want this while running update.php.
  if (!defined('MAINTENANCE_MODE') || MAINTENANCE_MODE != 'update') {
    // Prior to invoking hook_init(), initialize the theme (potentially a custom
    // one for this page), so that:
    // - Modules with hook_init() implementations that call theme() or
//   theme_get_registry() don't initialize the incorrect theme.
    // - The theme can have hook_*_alter() implementations affect page building
//   (e.g., hook_form_alter(), hook_node_view_alter(), hook_page_alter()),
//   ahead of when rendering starts.
    menu_set_custom_theme();
    drupal_theme_initialize();
    module_invoke_all('init');
  }

If hook_init() is being executed more than once, you should discover why that happens. As far as I can see, none of the hook_init() implementations in Drupal checks it is being executed twice (see for example system_init(), or update_init()). If that is something that can normally happen with Drupal, then update_init() would first check if it has been already executed.

If the counter is the number of consecutive days a user logged in, I would rather implements hook_init() with code similar to the following one.

// Drupal 7
function mymodule_init() {
  global $user;

  $result = mymodule_increase_counter($user->uid);
  if ($result[0]) {
    // Increase the counter; set the other variables.
  }
  elseif ($result[1] > 86400) {
    // The user didn't log in yesterday.
  }
}

function mymodule_date($timestamp) {
  $date_time = date_create('@' . $timestamp);
  return date_format($date_time, 'Ymd');
}

function mymodule_increase_counter($uid) {
  $last_timestamp = variable_get("mymodule_last_timestamp_$uid", 0);
  if ($last_timestamp == REQUEST_TIME) {
    return array(FALSE, 0);
  }

  $result = array(
    mymodule_date($last_timestamp + 86400) == mymodule_date(REQUEST_TIME),
    REQUEST_TIME - $last_timestamp,
  );
  variable_set("mymodule_last_timestamp_$uid", REQUEST_TIME);

  return $result;
}

// Drupal 6
function mymodule_init() {
  global $user;

  $result = mymodule_increase_counter($user->uid);
  if ($result[0]) {
    // Increase the counter; set the other variables.
  }
  elseif ($result[1] > 86400) {
    // The user didn't log in yesterday.
  }
}

function mymodule_increase_counter($uid) {
  $last_timestamp = variable_get("mymodule_last_timestamp_$uid", 0);
  $result = array(FALSE, time() - $last_timestamp);

  if (time() - $last_timestamp < 20) {
    return $result;
  }

  $result[0] = (mymodule_date($last_timestamp + 86400) == mymodule_date(REQUEST_TIME));
  variable_set("mymodule_last_timestamp_$uid", time());

  return $result;
}

If hook_init() is invoked two times in row during the same page request, REQUEST_TIME contains the same value, and the function would return FALSE.

The code in mymodule_increase_counter() is not optimized; it is just to show an example. In a real module, I would rather use a database table where the counter, and the other variables are saved. The reason is that Drupal variables are all loaded in the global variable $conf when Drupal bootstraps (see _drupal_bootstrap_variables(), and variable_initialize()); if you use Drupal variables for that, Drupal would load in memory information about all the users  for which you saved information, when for each requested page there is only one user account saved in the global variable $user.

If you are counting the number of page visited from the users in consecutive days, then I would implement the following code.

// Drupal 7
function mymodule_init() {
  global $user;

  $result = mymodule_increase_counter($user->uid);
  if ($result[0]) {
    // Increase the counter; set the other variables.
  }
  elseif ($result[1] > 86400) {
    // The user didn't log in yesterday.
  }
}

function mymodule_date($timestamp) {
  $date_time = date_create('@' . $timestamp);
  return date_format($date_time, 'Ymd');
}

function mymodule_increase_counter($uid) {
  $last_timestamp = variable_get("mymodule_last_timestamp_$uid", 0);
  if ($last_timestamp == REQUEST_TIME) {
    return array(FALSE, 0);
  }

  $result = array(
    mymodule_date($last_timestamp + 86400) == mymodule_date(REQUEST_TIME),
    REQUEST_TIME - $last_timestamp,
  );
  variable_set("mymodule_last_timestamp_$uid", REQUEST_TIME);

  return $result;
}

// Drupal 6
function mymodule_init() {
  global $user;

  $result = mymodule_increase_counter($user->uid);
  if ($result[0]) {
    // Increase the counter; set the other variables.
  }
  elseif ($result[1] > 86400) {
    // The user didn't log in yesterday.
  }
}

function mymodule_increase_counter($uid) {
  $last_timestamp = variable_get("mymodule_last_timestamp_$uid", 0);
  $result = array(FALSE, time() - $last_timestamp);

  if (time() - $last_timestamp < 20) {
    return $result;
  }

  $result[0] = (mymodule_date($last_timestamp + 86400) == mymodule_date(REQUEST_TIME));
  variable_set("mymodule_last_timestamp_$uid", time());

  return $result;
}

You will notice that in my code I don't use $user->access. The reason is that $user->access could be updated during Drupal bootstrap, before hook_init() is invoked. The session write handler used from Drupal contains the following code. (See _drupal_session_write().)

// Likewise, do not update access time more than once per 180 seconds.
if ($user->uid && REQUEST_TIME - $user->access > variable_get('session_write_interval', 180)) {
  db_update('users')
    ->fields(array(
    'access' => REQUEST_TIME,
  ))
    ->condition('uid', $user->uid)
    ->execute();
}

As for another hook you can use, with Drupal 7 you can use hook_page_alter(); you just don't alter the content of $page, but increase your counter, and change your variables.
On Drupal 6, you could use hook_footer(), the hook called from template_preprocess_page(). You don't return anything, but increase your counter, and change your variables.

On Drupal 6, and Drupal 7, you could use hook_exit(). Bear in mind that the hook is also invoked when the bootstrap is not complete; the code could not have access to functions defined from modules, or other Drupal functions, and you should first check those functions are available. Some functions are always available from hook_exit(), such as the ones defined in bootstrap.inc, and cache.inc. The difference is that hook_exit() is invoked also for cached pages, while hook_init() is not invoked for cached pages.

Finally, as example of code used from a Drupal module, see statistics_exit(). The Statistics module logs access statistics for a site, and as you see, it uses hook_exit(), not hook_init(). To be able to call the necessary functions, it calls drupal_bootstrap() passing the correct parameter, such as in the following code.

  // When serving cached pages with the 'page_cache_without_database'
  // configuration, system variables need to be loaded. This is a major
  // performance decrease for non-database page caches, but with Statistics
  // module, it is likely to also have 'statistics_enable_access_log' enabled,
  // in which case we need to bootstrap to the session phase anyway.
  drupal_bootstrap(DRUPAL_BOOTSTRAP_VARIABLES);

  if (variable_get('statistics_enable_access_log', 0)) {
    drupal_bootstrap(DRUPAL_BOOTSTRAP_SESSION);

    // For anonymous users unicode.inc will not have been loaded.
    include_once DRUPAL_ROOT . '/includes/unicode.inc';
    // Log this page access.
    db_insert('accesslog')
      ->fields(array(
      'title' => truncate_utf8(strip_tags(drupal_get_title()), 255),
      'path' => truncate_utf8($_GET['q'], 255),
      'url' => isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : '',
      'hostname' => ip_address(),
      'uid' => $user->uid,
      'sid' => session_id(),
      'timer' => (int) timer_read('page'),
      'timestamp' => REQUEST_TIME,
    ))
      ->execute();
  }

Update

Maybe there is some confusion about when hook_init() is invoked.

hook_init() is invoked for each page request, if the page is not cached. It is not invoked once for each page request coming from the same user. If you visit, for example, http://example.com/admin/appearance/update, and then http://example.com/admin/reports/status, hook_init() will be invoked twice: one for each page.
"The hook is invoked twice" means there is a module that executes the following code, once Drupal has completed its bootstrap.

module_invoke_all('init');

If that is the case, then the following implementation of hook_init() would show the same value, twice.

function mymodule_init() {
  watchdog('mymodule', 'Request time: !timestamp', array('!timestamp' => REQUEST_TIME), WATCHDOG_DEBUG);
}

If your code shown for REQUEST_TIME two values for which the difference is 2 minutes, as in your case, then the hook is not invoked twice, but it is invoked once for each requested page, as it should happen.

REQUEST_TIME is defined in bootstrap.inc with the following line.

define('REQUEST_TIME', (int) $_SERVER['REQUEST_TIME']);

Until the currently requested page is not returned to the browser, the value of REQUEST_TIME doesn't change. If you see a different value, then you are watching the value assigned in a different request page.


Caching the Drupal bootstrap I'm curious if anyone has made attempts to "cache" the bootstrap process in Drupal.

Normally, Drupal will run the 7 bootstrap phases on each request, but perhaps on a deployed production system, one could "do away" with some or all of these?

Possible suggestions I have in mind could be

Serializing the bootstrapped state and sticking it into memcache
A script could generate a patch for bootstrap.inc that will hardcode certain information into the file.
I believe David Strauss has tried to keep a bootstrapped Drupal running on libevent.
Other craziness?

What attempts are there, and which are known to be (somewhat) reliable?

PHP is a shared nothing architecture. That has its advantages and disadvantages.

One disadvantage is that it's not easy to do something like this. There isn't much of a state that can be stored somewhere.

I did some quick tests and when logged in, then the boostrap seems to take about ~17% of the total time and more than 50% of that is actually loading all the .module and .inc files. That's not something that you can store in memcache. Also, it doesn't seem to matter much if I use memcache or the database cache.

I tried to get some results when having the page cache enabled, but Xhprof doesn't seem to return reliable results then; the whole thing simply seems to be too fast. But even then, the biggest part involves executing init/exit hooks and loading files it seems. I found an interesting issue there: It looks like the User module is seriously slowing down the cached page response because it triggers the registry due to the entity controller in the .module file.

That said, David Strauss showed some experimental work in Copenhagen where he created a memory snapshot after bootstrapping and then returning to that once the page was served. He did use Drupal 6 for that. After looking at the numbers above, I imagine that the performance gains of doing this in Drupal 7 would be quite a bit smaller. One reason for this is that the database connection is lazy loaded (And you can get quite far in the bootstrap when using e.g. Memcache before you need to execute the first query) and there's a lot that is cached.

What's really bad in Drupal 7 is the render layer with these huge arrays and endless recursions and loops. That one pretty much undoes all the performance work that went into Drupal 7. Let's see how it looks in Drupal 8, if Twig makes it into core.

Lastly, about the mentioned advantages. One large advantage is that memory leeks are rather irrelevant because everything is freed after each request. I've seen many Java applications where memory usage constantly increases and need regular restarts.


Users can't log in sometimes Drupal 7.5, PHP 5.6.27 Debian 8, remote host.

We are running into a problem where some people can't log in some of the time and sometimes it works if they try multiple times. Users have reported the issue with different browsers and only a small percentage of people seem to be affected. Please note that I can only reproduce the error on occasion, and very inconsistently.

Watchdog simply shows that a session is opened for the user, even if the front page shows that they are not logged in.

Edit: Users can usually log in if they enter the wrong password first!

Things I've tried:

changed cookie_domain from www. to .
made sure rewrite condition allows https
cleared Drupal cache
we have no external caching
added redirect from port 80 only to default-ssl.conf
Users can't always log in with a one-time log in link generated with drush uli "[username] (the site will ask them to log in)
creating a custom login module to set a new custom session suggested here
added some cookie configurations to the sites/default/settings.php file as suggested in this post
installed the website on a different environment with PHP 5.5 and different settings.php .htaccess and php and mysql configurations.

Known Workarounds:
May or may not provide clues.

Sometimes if we change a user's password, they can get in that way
If a user enters the wrong password first on purpose then logs in, they are able to log in
Sometimes we can provide a one-time log in link for users to get in, but that doesn't always work

Edit: I've managed to recreate the issue on a local development environment with different settings files. I removed all the settings files information from my original post since I know now that they are not relevant.

That can happen if the site is redirecting to a different domain or to a secure/non-secure protocol upon login. I.e. with/without www or to http/https. If so, you could set a base domain and cookie domain in settings.php, and/or enable www/non-www redirect in .htaccess.

It also seems there may be a problem with PHP 5.6.1.
https://www.drupal.org/node/2723927
https://www.drupal.org/node/2379019


Duplicate taxonomy terms from view So I haven't yet been able to find a solution to this without using a preprocess function to check for duplicates or just using the 'tagadelic' module.. it'd be nice to get some closure.

How do I configure a (block) view to only display a list of terms for a vocab, each term displayed once (maybe followed by a number indicating how many times it's used) - even though the term may be used by multiple nodes? 'Distinct' doesn't do the job.. Fields 'Taxonomy:All terms' and 'Taxonomy: Term' both yield similar duplicate item when the term is reused by another node.

It's a fairly basic request, I'm sure I'm missing something but can't find a solid answer for dealing with it in views

I think you're using a Node view instead of a Term (Taxonomy) view. So you're pulling in nodes and getting the tags associated with them. Since multiple nodes can have multiple tags, you're getting duplicates. I think the "Distinct" doesn't work because it's checking the Nodes to make sure they're distinct, not each field you add to the view.

So instead, try creating a view and choosing the Term type, instead of Node. I put together a very simple view without even using Distinct and I have no duplicated values, even though each term is definitely used on more than one node.

I don't know how you would do the count next to each term using Views, but I know the Advanced Taxonomy Blocks module does this.


Location and Gmap relationship - what is alternative to show Location items on a google map? Recently the Gmap module has described itself on the module page as now being a 'legacy' module.  If you have used this recipe in the past, you may be familiar with the long and unresolved issue of the project trying hard to migrate to Google Maps API v3.

Unfortunately, because of this issue, the Location and Gmap combination is no longer a viable solution to show Location based items on a google map.

What would be the current Drupal 7 equivalent recipe? I would prefer to keep the Location module in use as I need it for proximity searches, but I am open to suggestions.  Thanks for your ideas!

According to the book Mapping with Drupal, the alternate to Location/Gmap is Geofield/Geocoder/Addressfield.  However, proximity searches don't currently work with this solution.

I have been experimenting with a lot of modules in this space and unfortunately Drupal 7 is behind the times in this regard.


One exposed filter for many views/views blocks I want to have one exposed filter and 2 blocks displaying different content types. They both have 'date' field and I want to show same-day content with one date exposed filter.

Anyone knows how to achieve this? Do I have to create one or two different views? How to share exposed filter (ie. field_content_type_1_date) with another content type (which has field_content_type_2_date field)?

If the two content types are using the same date_field and the blocks are shown on the same url, you can use the exposed filter of one view display to filter both views blocks. You just have to configure the exposed filter on the same field in both views/displays


Disable admin menu for specific page Is there a way to disable the top admin menu (not default toolbar), for a particular page? I am not looking for a JS or CSS workaround, but a proper solution such that the rendering of the admin menu does not happen.

Thanks and help appreciated...

You can assign your admin menu to a block,  and have that block disabled on certain pages.


Add JavaScript files to the administrative pages How do I add JavaScript/CSS files in every administration pages, using a module?

Using a module, you can follow two methods:

Implementing hook_init()
Implementing hook_form_alter()

The first method would allow you to add the extra JavaScript (or CSS) files to any administration pages, while the second method would allow you to add those files only to pages containing forms.

function mymodule_init() {
  if (arg(0) == 'admin') {
    $path = drupal_get_path('module', 'mymodule');
    drupal_add_js($path . '/mymodule.js');
    drupal_add_css($path . '/mymodule.css');
  }
}

function mymodule_form_alter(&$form, &$form_state, $form_id) {
  if (arg(0) == 'admin') {
    $path = drupal_get_path('module', 'mymodule');
    $form['#attached']['css'][] = $path . '/mymodule.css';
    $form['#attached']['js'][] = $path . '/mymodule.js';
  }
}

Replace "mymodule" with the short name of your module; replace "mymodule.js" and "mymodule.css" with the actual names of the JavaScript and CSS files.

system_init() contains the following code, to add specific files to administrative pages.

  $path = drupal_get_path('module', 'system');
  // Add the CSS for this module. These aren't in system.info, because they
  // need to be in the CSS_SYSTEM group rather than the CSS_DEFAULT group.
  drupal_add_css($path . '/system.base.css', array('group' => CSS_SYSTEM, 'every_page' => TRUE));

  // Add the system.admin.css file to the administrative pages.
  if (path_is_admin(current_path())) {
    drupal_add_css($path . '/system.admin.css', array('group' => CSS_SYSTEM));
  }

  drupal_add_css($path . '/system.menus.css', array('group' => CSS_SYSTEM, 'every_page' => TRUE));
  drupal_add_css($path . '/system.messages.css', array('group' => CSS_SYSTEM, 'every_page' => TRUE));
  drupal_add_css($path . '/system.theme.css', array('group' => CSS_SYSTEM, 'every_page' => TRUE));

path_is_admin() is the function that in its documentation is described as:

  Determine whether a path is in the administrative section of the site.

Consider that some node-related paths, such as node/<nid>/edit, could be included in the administrative section, depending on the setting found on admin/appearance.

The list of the node paths that could be included in the administrative pages is returned from node_admin_paths().

  if (variable_get('node_admin_theme')) {
    $paths = array(
      'node/*/edit' => TRUE,
      'node/*/delete' => TRUE,
      'node/*/revisions' => TRUE,
      'node/*/revisions/*/revert' => TRUE,
      'node/*/revisions/*/delete' => TRUE,
      'node/add' => TRUE,
      'node/add/*' => TRUE,
    );
    return $paths;

If, for any reason, you need to avoid any page with a path like node/*, you need to add specific code to avoid those, if you are using path_is_admin(). Consider that any module could change the pages that are considered part of the administrative pages.

In both the cases, the alternative would be using a library, if the module implements hooks_library() with code similar to the following one.

function mymodule_library() {
  $path = drupal_get_path('module', 'mymodule');

  $libraries['mymodule.library'] = array(
    'title' => 'MyModule Library',
    'version' => '1.0',
    'js' => array(
      $path . '/mymodule.js' => array(),
    ),
    'css' => array(
      $path . '/mymodule.css' => array(
        'type' => 'file',
        'media' => 'screen',
      ),
    ),
  );

  return $libraries;
}

In this case, the previous implementation of hook_form_alter() would become the following.

function mymodule_form_alter(&$form, &$form_state, $form_id) {
  if (arg(0) == 'admin') {
    $form['#attached']['library'][] = array('mymodule', 'mymodule.library');
  }
}

Instead of calling drupal_add_js(), and drupal_add_css(), the code should call drupal_add_library('mymodule', 'mymodule.library').

The pro of using hook_library() is:

Dependencies between libraries are automatically handled. That is what happens in the case of system_library(), which defines two libraries using the following definitions.

  // Drupal's form library.
  $libraries['drupal.form'] = array(
    'title' => 'Drupal form library',
    'version' => VERSION,
    'js' => array(
      'misc/form.js' => array(
        'group' => JS_LIBRARY,
        'weight' => 1,
      ),
    ),
  );

  // Drupal's collapsible fieldset.
  $libraries['drupal.collapse'] = array(
    'title' => 'Drupal collapsible fieldset',
    'version' => VERSION,
    'js' => array(
      'misc/collapse.js' => array('group' => JS_DEFAULT),
    ),
    'dependencies' => array(
      // collapse.js relies on drupalGetSummary in form.js
      array('system', 'drupal.form'),
    ),
  );

Calling drupal_add_library('system', 'drupal.collapse'), misc/collapse.js and misc/form.js would both be included.
The CSS files associated with the library would be automatically loaded together the JavaScript files.
Whenever the library would use more JavaScript, or CSS files, the code to include the library would not change; it would still be using $form['#attached']['library'][] = array('mymodule', 'mymodule.library');, or drupal_add_library('mymodule', 'mymodule.library').

There is no need to use current_path() when you can use arg(). If the path for the current page is admin/structure/block, then

arg(0) will return "admin"
arg(1) will return "structure"
arg(2) will return "block"

Update

hook_init() is not used anymore from Drupal 8. The alternative for Drupal 8 is using hook_form_alter(), hook_page_attachments(), or hook_page_attachements_alter(). hook_page_build() and  hook_page_alter() are not anymore used in Drupal 8.
What I said about using a JavaScript library is still true, even if it is suggested to use #attached to attach a library (or a Javascript file, or a CSS file) to a page. Drupal 8 doesn't allow anymore to attach just JavaScript or CSS files to a page; you need to always attach a library, which a set of JavaScript and CSS files, eventually made of just JavaScript or CSS files.


Print translated links in custom page--front.tpl.php I have a custom template for my front page, where I have to manually set URLs. Some of them are Views paths (such as news), some - aliased node URLs (projects/project-1). How to get their path translation URL in raw PHP code?

If I say something like:

<a href="<?php print url('news', array('language'=> $langcode, 'alias' => TRUE)) ?>" ...>

the rendered link is invalid langauge-crossed, such as mysite.com/es/news.

I tried also with the l() function but I'm getting untranslated link pointing to the root mysite.com/news.

This might be an obvious answer to experts, but hopefully this will help some newbie someday. I painstakingly investigated the url stuff in Drupal and my findings surprised me - especially when I referred them to the docs.

In the tpl I placed the following nasty debug lines:

<?php dpm(drupal_get_normal_path('alias-en')) ?>
<?php dpm(drupal_get_normal_path('alias-en', 'es')) ?>
<?php dpm(drupal_get_normal_path('alias-en', 'en')) ?>
<?php dpm(drupal_get_normal_path('en/alias-en')) ?>
<?php dpm(drupal_get_normal_path('/en/alias-en')) ?>
<?php dpm(drupal_get_normal_path('es/alias-es')) ?>
<?php dpm(drupal_get_normal_path('/es/alias-es')) ?>

And the results were:

alias-en
alias-en
node/298
en/alias-en
/en/alias-en
es/alias-es
/es/alias-es

Only the third result (node/298) was returned as desired, good for passing to i18n_get_path_translations. Even though the drupal_get_normal_path() function docs say the language parameter is optional, and subsequently called drupal_lookup_path() is said to put current language if NULL is passed, it does not seem to work this way.

drupal_get_normal_path() seems to require that you pass two parameters: alias and the language the alias is set for. Only then you'll get the result that will work reliably with i18n_get_path_translations.

I'm close to thinking it is a bug in Drupal or docs, and if no one sheds light on me, I'm going to file an issue.


How to set a specific vocabulary in a taxonomy reference field during migration? I am doing a D7 > D8 migration (where the D7 site in question itself was migrated from D6 some years back) and most stuff just works fine. But I am stuck on the field (instance) settings for taxonomy reference fields.

When migrating the field instances, I am using a slightly changed version from the one provided by core (that's how I did it with most other stuff, too):

langcode: en
status: true
dependencies: {  }
id: my_fields
class: Drupal\migrate_drupal\Plugin\migrate\FieldMigration
field_plugin_method: processField
cck_plugin_method: null
migration_tags:
  - 'Drupal 7'
  - Configuration
migration_group: my
label: 'Field configuration'
source:
  plugin: d7_field
  constants:
    status: true
    langcode: und
process:
  entity_type: entity_type
  status: constants/status
  langcode: constants/langcode
  field_name:
    plugin: static_map
    source: field_name
    map:
      taxonomy_vocabulary_1: field_issues
      taxonomy_vocabulary_2: field_tags
    bypass: TRUE
  type:
    plugin: process_field
    source: type
    method: getFieldType
  cardinality: cardinality
  settings:
    plugin: d7_field_settings
destination:
  plugin: 'entity:field_storage_config'
migration_dependencies: null

When I run this via drush mim my_fields all field instances on all content types are created (wonderful!), the only thing missing is the restriction in taxonomy term reference fields regarding a specific vocabulary.

When I create such a field manually and export the configuration, there is a section in the yaml file describing that restriction:

settings:
  handler: 'default:taxonomy_term'
  handler_settings:
    target_bundles:
      issues: issues
    sort:
      field: name
      direction: asc
    auto_create: false
    auto_create_bundle: ''

I guess this needs to be in the process section of the migration configuration, but how do I set it correctly? If I read that right, the vocabulary name (issues) is both field name and value, which would probably pose a problem for multiple vocabularies. Also, how would I set this for taxonomy reference fields only?

Added note: In Drupal 7, the restriction was set within the field global settings (allowed_values[vocabulary], could be found in the DB table field_config) and not with the field instance.

In Drupal 8, it seems to be a field_instance setting as the same field can be restricted to different vocabularies in different content types. May that be the reason, why this setting is not migrated?

By the way: I did try a simple migration first by using the Migrate Drupal module and while it got most configuration right by just using defaults, here also the restrictions on taxonomy reference fields was missing.

The field settings are created in the process plugin, d7_field_settings, in this section of the process pipeline.

 settings:
    plugin: d7_field_settings

It seems that you will need to write a custom process plugin. You may want to preserve the settings created by d7_field_settings. I don't recall what d7_field_settings does. So you could put something like this after the settings property is set..

 'settings/handler_settings/target_bundles': my_custom_plugin

Edit:
Glad got it working. Found the core issue for this today, https://www.drupal.org/project/drupal/issues/2763637.


Unattended automatic security updates / upgrades What is the best way to get Drupal to automatically perform security updates? And are people commonly employing such a method?

For motivation, consider this: Drupal just released a PSA about a recent vulnerability saying:

  ...You should proceed under the assumption that every Drupal 7 website was compromised unless updated or patched before Oct 15th, 11pm UTC, that is 7 hours after the announcement.

Fortunately I caught this one and performed the update manually one hour after the announcement. But what if I hadn't? I'd like to have an automatic update process in place to give me some piece of mind.

And I'd like for this automatic upgrade system to only apply security updates. (It just doesn't seem worth the risk to bother with potentially breaking some functionality after an update, unless the update is critical.)

Please also keep in mind there are '0-day' vulnerabilities out there, which can be used to compromise your website even before Drupal publishes a security advisory and corresponding patch. And that even if you use an automated update for Drupal core, there still will be a time window in which your site was vulnerable.

The best way to deal with these kind of issues is therefore to have all your Drupal code in a version control system - Subversion or Git for example. This way you can easily:
- identify when there has been an intrusion with a status command (this will show you all modified files in your source files)
- reverting these changes, and therefore repair all harm done, by resetting the source tree to your latest commit

The only downside is that you have a little more work to do with each update, as you need to commit all changes back to your repository after each code change. But this is a very small price to pay for the added benefits and piece of mind this provides.


Simplenews condition results in double email I've got a simple rule sending a notification email to site admin on the event 'A user has been subscribed'.

I'm however getting 2 emails on a signup. Any idea why and how to fix so the admin only gets notified once on each signup?

SimpleNews Version: 7.x-1.1
Core Version: 7.39

@Kristoffer Rom, I've just tested and I've got the same duplication.
So, I suggest you create such notification rule based on:

"After saving new user account" event.
"Send mail" action from "System" actions group.


How to copy taxonomy terms of a node into a textfield using rules? So what are the steps for the Rules module to copy taxonomy terms of a node into a textfield?

How do you copy all the taxonomy terms of a node and populate a text field with them?

Note: I am testing search speed of views exposed filters. Instead of using relatioships I will create a field containing keywords of all other fields in a form of an "index" and I will search on that.

Well that was easy then.

Create a rule with this configuration.

Trigger the rule "After updating existing content" and "After saving new content".
IMPORTANT. Create a condition with "Entity is of bundle" and choose the desired Content Type. If you don't do this, not all the fields of the content type are exposed to rules for manipulation.
The Action is "Set Data Value" and as Data choose you text field (node:field-keywords in my case). For value choose your desired terms field ([node:field-business-categories] in my case).

Run a "Published" procedure on all desired nodes with VBO and you are done.

And here is the exported rule.

{ "rules_keyword_field_generation" : {
"LABEL" : "Keyword Field Generation",
"PLUGIN" : "reaction rule",
"OWNER" : "rules",
"REQUIRES" : [ "rules" ],
"ON" : { "node_update" : [], "node_insert" : [] },
"IF" : [
  { "entity_is_of_bundle" : {
      "entity" : [ "node" ],
      "type" : "node",
      "bundle" : { "value" : { "business" : "business" } }
    }
  }
],
"DO" : [
  { "data_set" : {
      "data" : [ "node:field-keywords" ],
      "value" : "[node:field-business-categories]"
    }
  }
]

}
}


How to get the managed_file progress bar working in a custom theme? I'm trying to get the managed_file progress bar working in a custom theme.  Right now, when I start an upload, the empty progress bar widget appears in the form, but it doesn't visually update while the file is being uploaded. If I switch my site from my own theme to Bartik, the bar works properly, so it's evidently a theming problem.  (This also confirms that I've got all the uploadprogress stuff properly installed.)

I've found theme_progress_bar, and tried adding it to my theme's template.php file, renaming it to MYTHEME_progress_bar, but it didn't work.  Any advice on how to get it to work?  Thanks!

Found, I think: My theme was based on Bootstrap 2, and I was getting bit by a problem of Drupal and Bootstrap disagreeing on what sort of thing the "Upload" button should be:

https://drupal.org/node/2155419

Since I'm still on Bootstrap 2 (I think) I wasn't having the problem with the input fields being out of order, but I did need to deal with the behavior assignments.  In addition to the fix outlined in the cited page, I also needed to run the assignments on page load / document ready to get things properly assigned.


Print Webform reference in custom view display On our D8 site we have a content type with a webform reference field field_reference_webform.
We then created a view with a custom views display style plugin for above content type that uses the webform reference field field_reference_webform.

What we want to achieve is to print the webform field in our custom view display style directly via views-view-our-display-plugin.html.twig.

The contents of our Webform reference field, however, wouldn't print. We tried to print it with below code:

{% if rows|length %}
{% for row in rows %}
{{ row._entity.field_reference_webform }}
{% endfor %}
{% endif %}

Instead we get the following error:

Object of type Drupal\webform\Plugin\Field\FieldType\WebformEntityReferenceFieldItemList cannot be printed

We cannot figure out what we got wrong.

We are on Drupal 8.6.2 using Webform 8.x-5.0-rc22

At first glance it would seem you need to render this webform yourself in a preprocess function and then pass it to twig. You are trying to access the entity object using row._entity.field_reference_webform which is protected from outside access. However views should already be rendering this webform. I think maybe your template file is just setup wrong. All you have done is create a view, and put a template file for it in your theme correct?

For row level output, if your display is setup as unformatted list, your views twig file should be named:

views-view-unformatted--our-display-plugin.html.twig

and the basic code inside it should be:

{% if title %}
  <h3>{{ title }}</h3>
{% endif %}
{% for row in rows %}
  {%
    set row_classes = [
      default_row_class ? 'views-row',
    ]
  %}
  <div{{ row.attributes.addClass(row_classes) }}>
    {{- row.content -}}
  </div>
{% endfor %}

Just use {{ row.content }} which should have the rendered webform in it already.

If that doesn't work perhaps we need more information on what exactly youre trying to create a template file for. The view container, the row level, or the field level.


Dynamic menu linking to the forum associated with the current Organic Group I've got two groups. I've got two forums belonging to each group.
I've got a panel set up to display a custom view of forum topics that are defaulted to the group id, so that when given the group id arg in the url it shows the forum topics that belong to that group.

The problem is, I now want a menu item on each group page which says 'forum' which points to  the forum view with a group id argument which causes the display of only related forum topics.

You do this with contextual filters. In the forum view, under the advanced settings, go to relationships and add OG membership: OG membership from Node. Then add a contextual filter OG membership: OG group gid. You will also need a default argument for "When the filter value is not in the url". You will use "Current OG group from context" for that. Rearrange your contextual filters if necessary so that is the first one.

Then in your page settings, set the path to group/%/forum (or whatever the correct path to your group page is). The % will be expanded to the group id, so that group/1/forum will show you the forum view for the group with gid=1.

You can then set the menu option just below the path option. That will put the menu on any page in the path you set.

Give that a try.


views exposed filter does not redirect to itself I came across to issue with exposed filter in my view. In a view's preview everything works fine. But on the page, after clicking apply button, the site redirects to front page, with get parameters in URL. What is wrong with this? I did everything in a UI and I didn't work with code. Thanks.

Look at the "Advanced" pane on the View config page: There is "Link display" where you can define custom URL for the view - it's something like a "base path" for the view and the exposed filter values will be added to it, e.g.: if you define my-view-path than the filtered view has the path my-view-path-?filter_1=true&filter_2=false&filter_3=&filter_4=0.

Hint: If you have created a panel pane you have to set "Link to view" to yes in "Pane settings" to make use of path/URL defined in "Link display".


How to hide "Log in or register to post comments" when I've already disabled displaying comments? I already disabled comments. How can I remove the "Log in or register to post comments" text at the bottom of articles or other content types?

You also have to disable the "links" section or you'll see this message.
Go to the Administration > Structure > Content types > Article page. Drag comments and links to the disabled section. Repeat for any other content types where you want to hide this message.


How to create node reference fields in Drupal 7? I am puzzled. This was a very valuable option in D6 CCK, but since it moved into core, I can't find the option to create a noderef field (found a term reference field, though). I know it must be out there, where is it?

The project that maintains the Drupal 7 versions of the "node reference" and "user reference" field types is References.

Part of the code of CCK has been ported in core code, but some code is still living in third-party modules. CCK itself has a version for Drupal 7, which contains the code to update from Drupal 6 to Drupal 7 (among other things).