Is there a way to figure out the block machine name? In Drupal 8, is there a way to figure out what current block or view machine name you should use?

For example, with the following code, I noticed that 'machine_name_to_determine' could change depending on how many times you have used your block.

$block_id = 'machine_name_to_determine';
$block_config = \Drupal\block\Entity\Block::load($block_id);

I need a way to retrieve this at run-time. How can I retrieve it?

You can query the blocks by the plugin id. This is the id of a block plugin or for derivatives like a view block (which you probably are looking for as you've mentioned a view machine name) with additional parameters:

$plugin_id = 'views_block:' . $view_id . '-' . $display_id;

Where $view_id is the view machine name which you find in the Views UI and $display_id is the display machine name, usually block_1 for the first block of the view.

Then get all blocks placed for this plugin id and print the block machine names or use the loaded blocks in your code:

$blocks = \Drupal::entityTypeManager()->getStorage('block')
  ->loadByProperties(['plugin' => $plugin_id]);
foreach ($blocks as $block) {
  echo $block->id();
}

Add a theme or region to loadByProperties() if needed:

['theme' => 'bartik', 'region' => 'header']


Send email to specific users using webforms In a view, everytime a user clicks on a link "click to connect" field, an email has to be sent to the specific username based on its id. I am using webform to send the mail. But, it restricts me to send all mails to the same email address.
In order to hide the email to which mail has to be sent, I am fetching the id of the user(to whom mail has to be sent) in a hidden field in webform. But, i cant figure out a way to get the destination email dynamically.

Why not activate individual user contact forms, add a User: Link to contact page field to your view, and put your 'Click to connect' in the Text to display?

This will allow users to control whether or not they wish to receive such emails. They will be able to opt out in their account page and the link will not appear in the view.


I need to switch from database logging to syslog I'm running a drupal 6 website and I was thinking of speeding it up following these steps:

Completely stop database logging
Enable syslog

How do I configure Drupal to use syslog?
What if I enable just syslog and disable the database log? Do I have to further configure stuff?

This article explains the whole process into details.

The very bottom line is activating the Syslog module (a core module), and configure it on admin/settings/logging/syslog. It should already work out-of-the-box.

To make sure you can find the log file, you can set it in /etc/syslog.conf and /etc/rsyslog.d/50-default.conf.


What is the intended use of drupal_static? I understand Drupal static cache is used to store static values in the memory for the length of the request to faster access them. However throughout Drupal and contributed modules I tend to see two different versions:

Example from drupal_is_front_page:

function drupal_is_front_page() {
  // Use the advanced drupal_static() pattern, since this is called very often.
  static $drupal_static_fast;
  if (!isset($drupal_static_fast)) {
    $drupal_static_fast['is_front_page'] = &drupal_static(__FUNCTION__);
  }
  $is_front_page = &$drupal_static_fast['is_front_page'];

  if (!isset($is_front_page)) {
    // As drupal_path_initialize updates $_GET['q'] with the 'site_frontpage' path,
    // we can check it against the 'site_frontpage' variable.
    $is_front_page = ($_GET['q'] == variable_get('site_frontpage', 'node'));
  }

  return $is_front_page;
}

They way I read (and used) it from some tutorial I once found:

$static_cache = &drupal_static(__FUNCTION__);
if (!isset($static_cache[$key])) {
  // Obtain value
  $static_cache[$key] = $obtained_value;
}

return $static_cache[$key];

So I skipped the static declaration of the local variable, and to be honest I don't see why I should be adding it, it is in the first line of drupal_static:

function &drupal_static($name, $default_value = NULL, $reset = FALSE) {
  static $data = array(), $default = array();
  // First check if dealing with a previously defined static variable.
  if (isset($data[$name]) || array_key_exists($name, $data)) {
    // Non-NULL $name and both $data[$name] and $default[$name] statics exist.
    if ($reset) {
      // Reset pre-existing static variable to its default value.
      $data[$name] = $default[$name];
    }
    return $data[$name];
  }
  ...
}

Is is even faster if I declare another static variable in my module to hold a function that manages a static variable? (The name drupal_static_fast implies this.) Is this some old Drupal 6 convention where there was no drupal_static and it had to be declared locally? Or am I missing something else?

The code in drupal_is_front_page() makes the page rendering faster because it calls drupal_static() once for each page request; how much faster it makes it depends from how many times drupal_is_front_page() is called. The fact it is using that code means the core maintainers know the function is called enough times to need that code.
The drupal_static() documentation explains this with the following paragraph:

  In a few cases, a function needs a resettable static variable, but the function is called many times (100+) during a single page request, so every microsecond of execution time that can be removed from the function counts. These functions can use a more cumbersome, but faster variant of calling drupal_static(). It works by storing the reference returned by drupal_static() in the calling function's own static variable, thereby removing the need to call drupal_static() for each iteration of the function. Conceptually, it replaces:

$foo = &drupal_static(__FUNCTION__);

  with:

// Unfortunately, this does not work.
static $foo = &drupal_static(__FUNCTION__);

  However, the above line of code does not work, because PHP only allows static variables to be initialized by literal values, and does not allow static variables to be assigned to references.

  http://php.net/manual/language.variables.scope.php#language.variables.scope.static
  http://php.net/manual/language.variables.scope.php#language.variables.scope.references

  The example below shows the syntax needed to work around both limitations. For benchmarks and more information, see http://drupal.org/node/619666.

function user_access($string, $account = NULL) {
  // Use the advanced drupal_static() pattern, since this is called very often.
  static $drupal_static_fast;
  if (!isset($drupal_static_fast)) {
    $drupal_static_fast['perm'] = &drupal_static(__FUNCTION__);
  }
  $perm = &$drupal_static_fast['perm'];
  // ...
}

Your code calls drupal_static() every time, and essentially is the same code as the following one, which in Drupal documentation is not considered the fast version.

  $added = &drupal_static(__FUNCTION__);

  // User-uploaded files cannot set any response headers, so a custom header is
  // used to indicate to ajax.js that this response is safe. Note that most
  // Ajax requests bound using the Form API will be protected by having the URL
  // flagged as trusted in Drupal.settings, so this header is used only for
  // things like custom markup that gets Ajax behaviors attached.
  if (empty($added)) {
    drupal_add_http_header('X-Drupal-Ajax-Token', '1');
    // Avoid sending the header twice.
    $added = TRUE;
  }

@Clive explained the reason drupal_static() was added to Drupal: The idea behind its implementation was to use a static variable that at the same time could be reset (or changed) from other functions as well. In fact, the drupal_static() documentation says:

  All functions requiring a static variable to persist or cache data within a single page request are encouraged to use this function unless it is absolutely certain that the static variable will not need to be reset during the page request. By centralizing static variable storage through this function, other functions can rely on a consistent API for resetting any other function's static variables.


Possible to call a function after user sets their password for the first time after using their one-time login link? I have a Drupal 8 site and I need to dynamically redirect the user after they set their password for the first time after using their one-time login link.

I cannot figure out any way to hook into the workflow for this condition. Is it possible?

You could try using hook_user_login() in a custom module or theme.

function my_module_user_login($account) {

  // Get the end part of the URL.
  $request_uri = \Drupal::request()->getRequestUri();

  // Check if the URL is a reset / one time login link.
  if (strpos($request_uri, 'user/reset') !== false) {
    _my_module_custom_function();
  }
}

function _my_module_custom_function() {
  // Do stuff.
}


Drupal.behaviors get results from function I am struggling to understand how this works and I just can not get a grasp of if it. Basically what I am trying to do is get the results from my php function and pass it into ajax to make my page redirect to a certain area.

This is what I have for my php

function paydayform_submit($form, &$form_state){

    $entry = payday_parse($form, $form_state);

    /*if($entry['response'] == "sold"){
        print 'success';
    } else {
        print 'failed';
    }*/

    drupal_add_js(array('payday_form' => array('redirect'=>$entry)), 'settings');

}

And this is where I am completely lost and in the dark at.

(function($){
Drupal.behaviors.payday_form = {
 attach: function (context, settings) {
    $('#edit-submit', context).once('payday_form', function () {
        $(this).click(function(){

            //Response from payday_parse($form, &$form_state)
            final_redirect = Drupal.settings.payday_form.redirect;

                    //this comes back as undefined =/
            console.log(final_redirect);

            //if statement giving from the response above.
            if(final_redirect = 'success'){
                console.log('worked');
            }else{
                console.log('didnt work');
            }
        });
    });
    }
  };
})(jQuery);

Am I using this correctly? What am I doing wrong that it isnt picking up the function?

Use ajax_command_settings. Here is the answer Drupal.settings merging when using AJAX


How to format user profile content to be printed on a printer? I'm building a recruiting website using the eRecruiter profile distribution which uses Profile2 and was wondering if there is defined solution to creating a formatted page specifically for printing in D7 so the resumes can easily be printed in a nice format.

One of the easiest is to create your separate CSS for print. If you have a custom theme you can add the css file in the theme's info file. This way you can hide regions you don't need on paper to be printed.


Count the number of results of a free text field if they are similar I'm using Drupal 8.

I want to count the number of results of a text field if they are similar.

I added a simple text field to my "Article" content type.

Users can enter the text (short) they want: textA, textB, textC ... I do not know this text and can not make a selection list.

I wish I could count the number of times a user entered textA, textB etc.

I tried with Views and Aggragation function, but it does not work. Indeed it works only for the results corresponding to selection lists where a reference to a term etc.

Any idea ?

I'd use taxonomy terms and the tagging feature built into drupal. There's an example of it on the Article content type that comes with drupal's standard install

So a user can start typing a term and the autocomplete will appear if that term already exists. The user can select it if it exists already. Otherwise when the node is saved the term will be created. You can select multiple terms by comma separating them exactly as you mentioned

Then getting a count of terms will be much more straight forward and should be do-able in views as each time a term is associated to a field it's stored in the database


Private message prefill message body I'm using Drupal 7 Privatemsg module.
To prefill the message body, I use the following hook but don't get anything displayed.

function MyModule_privatemsg_message_view_alter(&$vars) {
  module_load_include('pages.inc','privatemsg');

  $vars['message']['body'] = "Dear Friend,\n you rock!";
}

Any help ?

One solution is to use the Prepopulate module and then customize the URL to send a privatemsg.  This works well if you are using Views to generate the links, for example.


Form redirection to registration for anonymous users while preserving data entered How is it possible to have CCK form on the front page for instance and once the user clicks on "Save", check if the user is already signed in and if not, redirect to the creation of an account, but by keeping the data entered in the CCK form to avoid them to reenter every field ?

I've checked on the net but nothing seems to do this so far...

Thanks for any help :-)

One option would be to do this in a custom module with hook_form_alter(). You could use it to alter the CCK form to add a custom validation/submit handler that redirects anonymous users to the registration page. The inserted form data could be stored in the session (before redirecting) from where you can retrieve it later to fill in the form with default values (using hook_form_alter() again). I'm assuming that you do not need to store the data for long periods of time since session is not suitable for that. You should also unset the used session variables after use.


How to initiate node_save() on module install? If I wanted to create a node programmatically when a module is installed what hook should I use to initiate node_save()? I found guides on how to make the node I just can't seem to figure out how to initiate it.

If it's your own module, use hook_install():

Perform setup tasks when the module is installed.

or hook_enable():

Perform necessary actions after module is enabled.

If it's not your own module, use hook_modules_enabled():

Perform necessary actions after modules are enabled.
This function differs from hook_enable() in that it gives all other modules a chance to perform actions when modules are enabled, whereas hook_enable() is only called on the module actually being enabled. See module_enable() for a detailed description of the order in which install and enable hooks are invoked.


How do I check whether the patch for SA-CORE-2018-002 is applied? How do I check whether the patch for SA-CORE-2018-002 is applied in a Drupal 7 website?

I have applied the patch. How does it secure my Drupal websites?

As you see in top of the patch, the patch changes the bootstrap.php file, so you can check that file has been changed, and it contains the correct code.

FAQ about SA-CORE-2018-002
 describes why the patch is a security patch.


How to list the most popular content for different periods of time with Radioactivity? I'd like to create a view with the most popular content of the last week, the last month and of all time. I've installed the Radioactivity module and created the three required profiles. While adding a radioactivity field 'Popularity' to my nodes, I had to select one of these three profiles, so I assume that I'll have to add another two radioactivity fields with the other profiles and that I'll end up with three fields

'Popularity (week)'
'Popularity (month)'
'Popularity (all time)'.

Is that correct? If yes, I'm wondering whether I now have to create the same rules for the three fields every time in order to change their value. Isn't it possible to add an action that adds an incident to the three fields at the same time, as the incident-values will be the same in the three cases?

This repetition is not a very big problem, but I'm not sure whether the set-up for what I want to achieve is completely correct, because doing the same work multiple times in Drupal is wrong most of the time.

You are right.  There is a one-to-one relationship between fields and profiles.  Since one field cannot represent multiple profiles, you will need 3 fields.

In answer to your Rules question, it should be possible to create a rule with 3 actions to update the 3 fields at the same time.


Why do my files get lost when migrating a CCK Filefield? I'm just getting stuck in to migrating D6 to D7 (please note: migrating, NOT upgrading). I'm using the Drupal-to-Drupal data migration module and its UI to define what I need to bring across.

One of the content types is "Issue": an issue of an online publication which just has a title, some body text (optional) and a file attachment for the PDF version of the publication.

To prepare the migration, I set up a corresponding content type in the D7 database, making sure that the field name was the same in D6 and in D7.

I have run a migration reasonably successfully (except for the major issue of Book structure which doesn't get handled), and all the "Issue" content has come across. However, none of the files in the "File Field" fields have been copied across. I'm trying to get my head round this: do I need to extend the Node Migration class, and if so how do I go about this?

Have a look at the Video about Upgrade Drupal6 to Drupal7 using the MIGRATE module. You're probably familiar already with many of the things shown in it, but it also provides some other interesting tips about things like:

Before starting the migration, make sure your current Drupal 6 site is in good shape (like update your contributed modules to the most recent D6 version first).
If you have a lot of files (attachments) to be upgraded also, it might be possible to do that part without using the migrate module.
If you have a possibility to create a (temporary) subdomain for your Drupal 7 version, that will speed up the migration execution quite a lot.

Especially bullet nr '2.' above may be worth experimenting with. In the video it is shown starting from about 12:05 (and the "Step 4: Files" screen provides some more details about what your options are here). Later on in the video, starting from about 15:45, you can see that the "image placeholders" (pointing to some files) are already OK. So afterwards you just need to copy those files to the right spot, using FTP or something.

So try running migrate with that option for Step 4 "unchecked" (turned off)!


Generate URL from hook_menu() pattern Does Drupal have any tool to generate URL from hook_menu() link pattern? Something like this:

some_function('node/%/edit/something/%', array(1, 19))

that will generate this URL: http://maindomain.com/node/1/edit/something/19.

I don't think Drupal has a function for that specific case - at least not one that I've come across.

Obviously lots of ways to accomplish it though. Without writing your own function, my thought was to make use of the format_string() and url() functions.

$args = array(
  '@arg_1' => 1,
  '@arg_4' => 19,
);
$path = format_string('node/@arg_1/edit/something/%arg_4', $args);
$url = url($path, array('absolute' => TRUE)); // I used absolute here because
                                              // your example has an absolute
                                              // path. It shouldn't be
                                              // necessary though.
print $url // Prints `http[s]:[domain.com]/[base_path]/node/1/edit/something/19`

Of course, you could take that a step further and use the l() function to create an actual link, but I'm not sure what your exact use case is.


Need to add meta tags in custom page created by custom module I have installed "Tagadelic" module.Then I created one custom module to display tag clouds in a page.
Now I need to add/modify meta description for this page only.
So what is the process for it?

A programmatical solution could be to use something like this. you could put it in a preprocess hook in your template.php

$path_alias = drupal_get_path_alias();

  if ($path_alias == 'thepathofmypage') {
    $meta_head_blog = array(
      '#type' => 'markup',
       '#markup' => '<meta name="title" content="My metatag title"><meta name="description" content="My metatag desc">',
);
drupal_add_html_head($meta_head_blog, 'metaHeadBlog');


Adding a variable to a menu twig template Im trying to use bootstrap for an accordion menu. My issue is that I need unique ID's for each accordion item. I found some similar topics here: Add Unique ID to Menu Item and here: How to add a custom variable that can be accessed on bootstrap's menu--account.html.twig?
Id like to know how I can get a unique ID for each item. Preferably an ID I can store within a variable which I can then pass to the data target attribute. As you can see in my code below, I'm trying to achieve something like that. The issue is that I cannot use the variable in a twig template that I declared within the preprocess function. Help me understand what I'm doing wrong.
Here is my code in my .theme file:
function my_theme_preprocess_menu__main(array &$variables) {
    $id = 0;
    foreach ($variables['items'] as $key => $item) {
      $variables['items'][$key]['accordionNav']=[];
      $key_hash = hash('crc32b', $key);
      $variables['items'][$key]['accordionNav'] = $key_hash ;
}
}

Here is my twig file menu--main.html.twig:
{% import _self as menus %}

{#
  We call a macro which calls itself to render the full tree.
  @see http://twig.sensiolabs.org/doc/tags/macro.html
#}
{{ menus.menu_links(items, attributes, 0) }}
{% macro menu_links(items, attributes, menu_level) %}
  {% import _self as menus %}
  {% if items %}

    {% if menu_level == 0 %}

    {% else %}

    {% endif %}

    {% for item in items %}

      {%
        set classes = [
          menu_level ? 'sub-item' : 'nav-item',
          item.in_active_trail ? 'active',
          item.below ? 'card',
        ]
      %}

        {%
          set link_classes = [
            not menu_level ? 'nav-link',
            item.in_active_trail ? 'active',
            item.url.getOption('attributes').class ? item.url.getOption('attributes').class | join(' '),
            'nav-link-' ~ item.url.toString() | clean_class,
          ]
        %}
        {% if item.below %}
        {% if item.in_active_trail %}

        <button class="btn btn-link" data-toggle="collapse" data-target="{{accordionNav}}" aria-expanded="true" aria-controls="collapse{{ip}}">

          {{ item.title }}
         </button>

          {{ menus.menu_links(item.below, attributes, menu_level + 1) }}
          {% else %}

        <button class="btn btn-link" data-toggle="collapse" data-target="{{accordionNav}}" aria-expanded="false" aria-controls="collapse{{ip}}">

          {{ item.title }}
         </button>

          {{ menus.menu_links(item.below, attributes, menu_level + 1) }}
         {% endif %}

        {% else %}
          {{ link(item.title, item.url, {'class': link_classes}) }}

        {% endif %}

    {% endfor %}

  {% endif %}
{% endmacro %}

You could use directly the derivative id (which will be unique) of the menu item in twig, with:
item.original_link.getDerivativeId()

otherwise you need to add a custom unique id in preprocess function to each item, like:
function yourtheme_menu_link_alter(&$item) {
  if($item['menu_name'] == 'custom-menu')
  {
    $item['uuid'] = \Drupal\Component\Utility\Html::getUniqueId($item['menu_name']);
  }
}

which you then access in twig with:
item.uuid


Create user login programmatically in Drupal 7 The questions is very simple and the task is difficult.
Which functions I need to create a new login form from scratch in Drupal 7?

The reason I need this is because I modified the default login form. It connects to a web service with two different methods and it has different validates, depends from a user roles and lots of customized stuff.

Right now to login as admin, I have to comment my custom module, so I can use the default login form.

I need to create a new login form on different page that will be dedicated to admin user.

It's not going to be possible to list all of the functions involved as your mileage will vary depending on what you need to do.

Basic steps:

Read up on and understand the Form API; try out a few examples so you're familiar with it.
Create a form function in your module, to be delivered in whatever method makes sense (a menu callback or embedding directly, for example). This will involve using drupal_get_form(), and viewing the user login form code will be useful here.
Create a validate handler for the form which does any validation you need. See user_login_default_validators() for the login form defaults.
Make use of user_login_finalize() in your form's submit handler to log the user in. You'd be best off copying the logic from user_login_submit() almost directly.


Getting the first field item in Twig Why does this work in Twig:

{{ content.field_image.0 }}

but this does not?

{% for item in content.field_gallery|slice(0, 1) %}
<div>{{ item }}</div>
{% endfor %}

At a guess...

field_gallery, and other fields, are render arrays; that means they have extra elements in them for the meta data (so called # properties). slice doesn't know the difference between a render array child element, and a # property, so it just chops the array up the same way it would any other. The first item in the array is probably a # property, hence nothing is being rendered.

The first example works because you're referencing a specific child of the render array by key, which is then rendered immediately.


How do I return an SQL query result as custom variable in a template? Is there any way to pass a SQL result with using hook in .theme file? My scenario is following: I have a paragraphs module's view in which I've need of all nodes from content type News to iterate and show by taxonomy term.

You can add variables using a hook_preprocess_THEME() function. For example, if you are trying to add a variable to the page.html.twig template, the theme hook is page. So you would use the following:

function hook_preprocess_page(&$vars)
{
  // Add your result to the $vars array:
  $vars['some_variable'] = db_query('SELECT something FROM {some_table} WHERE some_column = :some_value', [':some_value' => 'some value'])->fetchField();
}

Because you've added some_variable to the $vars array, some_variable will be available in your template.


Most effective way to create a landing page for content types? I have a "facility" content type which I am creating programmatically, through a module called "facility". I would like to have a landing page, such that when you go to http://www.mysite.com/facilities, you are taken to a heavily styled/scripted page that displays facility information in a specific format. To do this, in my facility module, I implemented hook_menu to point to a callback that will return the necessary markup. Here's my code:

facility.module

<?php

function facility_menu() {
    $items['facilities'] = array(
        'title' => 'Facilities',
        'page callback' => 'facility_landing',
        'access callback' => TRUE,
        'type' => MENU_CALLBACK
    );

    return $items;
}

function facility_landing() {
    return file_get_contents(drupal_get_path('module', 'facility') . "/facility_landing.php");
}

Due to the length and complexity of the markup, I would like to have it in a separate file. The issue is that this markup is not being evaluated in the Drupal context, since it is being read in with PHP's file_get_contents function. For instance, if my markup contained...

<?php echo $user->uid; ?>

...nothing would be displayed. Is there a function within Drupal that will parse a PHP file in the bootstrapped environment, and return the generated string? If not, what is the best/easiest way to handle this situation?

EDIT: This just occurred to me - I've already created an API within Drupal that would allow me to access the facility info I need via AJAX. I could just output the page without the facility data, then include a JS file which would get that. I'm still not convinced that's the best way, though. Thoughts?

If you want your code to live outside your module's .module file, hook_menu has a way to tell Drupal where to look for your page callback. A common name for include files containing page callbacks is MODULENAME.pages.inc. Place this file in the same folder as your .module file. Just add one line to your menu item definition:

function facility_menu() {
  $items['facilities'] = array(
    'title' => 'Facilities',
    'page callback' => 'facility_landing',
    'access callback' => TRUE,
    'type' => MENU_CALLBACK,
    'file' => 'facility.pages.inc',
  );
  return $items;
}

Now Drupal will load the facility.pages.inc file when example.com/facilities is requested. In facility.pages.inc you place the facility_landing() function. Inside facility_landing() you call other functions to generate the page and finally you return the markup (Drupal 6) or render array (Drupal 7) for your landing page.


How to disable Google fonts and other things like that? How do I configure my theme or Drupal itself from fetching data such as Google fonts or anything like that? Also some JS files that get transferred as well.

Ex: if the theme is called "cooltheme"

You need to go to drupal/sites/all/themes/cooltheme

and edit the cooltheme.info file

you should see something like this inside:

scripts[] = js/main.js  <-- so just delete this so it won't load it.

Then go to drupal/sites/all/themes/cooltheme/js and delete the .js file from here too.

For the fetching data from google fonts, they might be inside the .css file of the theme.


Listen to AJAX complete event from a behavior I have a form that has an AJAX button.  When I click it, it updates a bunch of stuff as expected which is fine.

I was wondering if there is a way to create a listener in behavior that gets called when the AJAX call is complete?

Thanks

Yes, there is :

Drupal.behaviors.YourBehaviour = {
attach: function(context, settings) {
  $('#yourform').ajaxComplete(function(event, xhr, settings) {
    if ($(event.target.id) == 'the-id-of-your-item') {
      // Your code here
    }
  });
 }
}


How can I have Devel generate nodes with different terms and not always the same term? I am using the Devel module to generate content (nodes) as a test. The content type has a field referencing a vocabulary that has terms already added to it. When 1000 nodes are generated, Devel assigns the same term to every node (the first term in the vocabulary). Is it possible to have Devel assign different terms at random to different nodes? How about setting one term as the default value for the field?

This happens when you have a default term chosen for the content type.

If you remove the default, it will then randomly choose terms that already exist (if they exist) or randomly generate terms if the vocabulary allows it.


I need a solution to in-depth scan into Drupal git repositories to find useful code snippets I'm looking to find out the best solutions to in-depth search into git repositories for code snippets: inside Drupal custom modules, revisions, contribs, themes, profiles.

As far as I know, Drupal no longer uses CVS/SVM but switched to git instead.

I am working on a Windows machine, but I commit/checkout to linux server using tortoiseSVN.

There is an old nice tutorial movie by Jonathan Lambert about how to search into SVN on GotDrupal.com on how to search into http://www.searchdrupal.org/ but searchdrupal.org no longer exists.

I need to know how you guys are building up modules using other people's snippets and how do you find it.
Any solution is precious to me

drupalcontrib.org is a nice place to find functions used within contributed modules as well as the core Drupal API.  It has helped me out in the past


I'm using Mobile Navigation but does not load the dropdown menu after installing jQuery Update After installing the module jQuery Update not shown the Menú Mobile. Why?

You have to set the correct Default jQuery Version in configuration. May be that causes this problem..


Add CSS class to a flagged node I want to add CSS classes to flagged nodes in order to theme them.

Found the documentation How to add CSS classes to nodes, based on flags set, but this solution is for D6.

Can someone help me to figure out how to make it work with D7?

Try this in your template.php of your theme. Change MYTHEME to the name of your theme and bookmark to the machine name of your flag. And change node-flag-bookmark to the css class you want to be added to your node.

/**
 * Implements template_preprocess_node().
 */
function MYTHEME_preprocess_node(&$variables) {
  $flag = flag_get_flag('bookmark'); // Machine name of your flag.
  if ($flag && $flag->is_flagged($variables['node']->nid)) {
    $variables['classes_array'][] = 'node-flag-bookmark';
  }
}


Multiple filenames in Entity form notification mail I have an Entity form with a file upload and need to include multiple filenames in the mail that is sent to the site admin upon form submission.

If I only allow one file to be uploaded through the form the replacement pattern [entity:field-uploadfield:file] works fine to make rules display the filename in the notification mail. But if I enable the users to upload multiple files the replacement pattern does not work anymore – how can I solve this?

Edit:
[entity:field-uppladdarfaltet:0:file] works, but then I'd have to cap the number of files at like 10 and also this doesn't really seem like a "clean" solution. Can I use the :0 :1 :2... format to support an unlimited amount of files?

[UPDATED] Your Rule will need to have some additional actions preceding the Send Mail action.

Add variable (Text). Let's call it - [file_list]
Add Loop that loops over your file field [entity:field-uppladdarfaltet] and produces a List Item. Lets call the list item variable [file_n]
Add action Add Variable (text). Call it [file_item]
Add action Set a Data Value. Data to change will be [file_item]. Value to set will be [file-n:file:name]
Add action Set a Data Value. Data to change will be [file_list]. Value to set will be [file-list:value][file-item:value]<br>. This will add each uploaded file's name to the list with a line break after the name.
Print variable [file_list:value] in the email body.

Here's screenshot:


Drupal 7 Fields Not Showing Up I have a Drupal 7 install that acts as a user network site. Users have 'member' permissions but are not administrators.

Some user fields are hidden via the field permissions module, but the rest should be viewable and editable by the user.

After updating the OG module, as well as the Webforms module, all custom fields added to the user node disappeared, both for registered members and new applicants (http://member.clevergirlscollective.com/drupal/?q=user/register , there should be several additional fields here).

I've adjusted permissions both at the field level and at the user node level, but for some reason this still happens.

Any ideas you have would be great!

There are several issues that could be plaguing you related to various configurations. However as a starting point, let's start with the basics:

Clear all caches. This will clear most issues caused by upgrades.
Rebuild permissions. Sometimes new access permissions or changes to old ones occur during upgrades. Since the fields still exist, but are not seen in the content view, it's possible that a permissions error is in your way.

http://www.example.com/admin/reports/status/rebuild
Check your PHP logs. Sometimes issues can occur with PHP where upgrades adding new features break things in a subtle way. Running out of memory, or breaching the 'max_input_vars' threshold are common issues I've seen.


How to add selected users to OG Group from field selection when creating group I have an OG and a field that lists users with checkboxes. Is there a way using Rules, to add the selected users as group members when group is saved/updated?

This is the rule I created to solved it:

After updating/adding existing content of type
Entity has field Parameter: Entity: [node], Field: FIELD WITH UNAMES
Crete a LOOP
(In Loop) Subscribe user to group -- Parameter: User: [list-item],
Group: [site:og-context--node]

Here is an export of my rule:

{ "rules_watch_list_group_add" : {
  "LABEL" : "Watch List Group Add",
  "PLUGIN" : "reaction rule",
  "OWNER" : "rules",
  "REQUIRES" : [ "rules", "og" ]
  "ON" : { "node_insert" : [], "node_update" : [] },
  "IF" : [
    { "entity_has_field" : { "entity" : [ "node" ], "field" : "field_watch_list" } }
  ],
  "DO" : [
    { "LOOP" : {
        "USING" : { "list" : [ "node:field-watch-list" ] },
        "ITEM" : { "list_item" : "Current list item" },
        "DO" : [
          { "og_subcribe_user" : { "user" : [ "list-item" ], "group" : [ "site:og-context--node" ] } }
          ]
        }
      }
    ]
  }
}


How to add image cache headers? When doing SEO tests, we consistently seeing a message for cache headers on images. We were thinking of implementing but cannot find the appropriate way to test this as the x-cache still gives a MISS.

Below is the htaccess file we have to accommodate for adding cache header for images.

How can I test to see the performance gain if I did this?

# One month
<filesMatch ".(css|jpg|jpeg|png|gif|js|ico)$">
  Header set Cache-Control "max-age=2628000, public"
</filesMatch>

Currenty working on that. The code

# One month
 <filesMatch ".(css|jpg|jpeg|png|gif|js|ico)$">
  Header set Cache-Control "max-age=2628000, public"
 </filesMatch>

helped me to remove images from the list below https://developers.google.com/speed/


how to connect to database in drupal in order to display the content in a table I am using drupal in order to create a website on my localhost machine.

I have a mysql database that i want to connect it  to the drupal website and display its data in a table.

and in the drupal I download the Views Database Connector (VDC) module in order to  connect to the external database.

but it did not work .

second method  I used views and created content types that are the fields table of the  external databases.

but I do not know how to continue to display the data.

third method  I created the tables in drupal database and want to display  its content .

I am new to drupal so I want  any of these method to  work for me

note  feeds module  also did not work because its not set up yet on the drupal 8.x

You need add the followings lines in settings.php for connecting 'external' database.

$databases['default']['default'] = array(
      'database' => 'drupal8',
      'username' => 'username',
      'password' => 'password',
      'prefix' => '',
      'host' => 'localhost',
      'port' => '3306',
      'namespace' => 'Drupal\\Core\\Database\\Driver\\mysql',
      'driver' => 'mysql',
    );

$databases['external']['default'] = array(
  'database' => 'external',
  'username' => 'username',
  'password' => 'password',
  'prefix' => '',
  'host' => 'localhost',
  'port' => '3306',
  'namespace' => 'Drupal\\Core\\Database\\Driver\\mysql',
  'driver' => 'mysql',
);

To activate external database

\Drupal\Core\Database\Database::setActiveConnection('external');

//code to fetch data and display

To activate drupal database

\Drupal\Core\Database\Database::setActiveConnection();

If you are looking some example refer How to connect to another database in your Drupal 8 site ?


Speeding up Views 2? How can I speed up my complex views? I don't want to remove functionality from my views to speed them up. Some of my views have 5 lefts joins. Is there anything I can do to optimize these queries?

Here's an example: http://i27.lulzimg.com/214ce7e242.png

Here's another one: http://i27.lulzimg.com/5c1d52ab2d.png

You can try installing DB Tuner and/or run mysqltuner.pl and experiment with the suggestions.

Edit to address the comments.

In addition to trying to optimize the database itself, you can also copy/paste the SQL that Views generates and run the query manually with an EXPLAIN.  This may shed some light on why the query is taking a while to run.  You can then edit the view as needed, and potentially add some indexes that the above tools may not have identified.


menus from modules: help me understand basic menu concept in drupal7 Here's some paths I'm using in my module

control (this isn't really a page, it just goes to the next item)
control/jobs (provides list of jobs)
control/jobs/% (path for editing a particular job)
control/download (separate page)
control/settings (separate page)

I would like a simple menu that shows jobs, download and settings. I would like it to add the 'active' class when visiting the page. And when visiting a particular subpage (e.g. a particular job), I would like the parent menu items to have an "active-trail" class or such.

Using hook_menu I've created these menu items, all as MENU_NORMAL_ITEMs and I've put them in a new menu called menu-control. I've added this menu's block to my page. I get the menu items listed. But when I visit a particular job, there is nothing to indicate I'm on a child page of 'jobs' (or indeed, 'control').

This seems like the simplest implementation of a menu and I've been hacking at it for weeks (on and off!). Can anyone help?

Take a look at the Views Module.  You can define your page view and attach it any menu.
Define it with a path such as control/%/jobs and set it to provide a list of all jobs using filters and format settings Set the menu type as menu tabs, and give it a name.
Add additional pages to the same view and with paths such as control/%/job and use a contextual filter to read the value in the URL in the % wildcard position. (You may have a bit of trouble if the wildcard is multiple words due to spaces vs. dashes in the path. If so ask another question here). Set the menu tab for this item as well.

Menu tabs are the menu that appears above the content (user Admin has View and edit tabs for content pages).  Note that you must have two menu tabs for them to show.

Your pages for download and settings sound like they require user input.  Those pages will require either an add-on module or custom coding to design a form.


Port of Ubercart "Dependant Atributes" or "Chained Attributes" modules Do you know of a Drupal 7 version of either of these modules?

Ubercart dependant atributes
Chained Attributes and Options

I've spent a couple of days trying to find an appropriate solution.

This answer may be slightly late judging by your ask date but I figured I would post it anyway.

This module performs similar to the above.

https://drupal.org/node/1192892


Caching a variable for a fixed amount of time So I'm at odds with Twitter API which only allows 15 requests per 15 minutes (of course this encourages and promotes good behaviour by not allowing repeated request for the same data).

My task is simply to get the latest tweets for a Drupal based homepage which is easy enough but my question is as follows: is there a native function within the Drupal API to store an array or variable (...my twitter JSON request) for a fixed amount of time?

I recently implemented Twitter caching for a Wordpress site and it was super simple using Wordpress Transients API, see the example here: http://www.codeforest.net/wordpress-transients-api-caching-benchmarks

Is there an alike function in Drupal?

yes there is a native function cache_set

<?php
cache_set('my_module_data', $my_data, 'cache', time() + 360);
?>

here is a great tutorial about caching in drupal


If Statment in Custom node template based in feild content existance I have a content type called specials

In that content type I have a field called discount code which has a machine name of field_discount_code

I have a custom node template called node--specials.tpl.php that I am using to fomate the display of this content type

If the discount code if filled in by the user I want drupal to show some text if it is left empty I want it show some other generic text

here is the code I am trying but not having any luck with

<?php if (!empty($content['field_discount_code'])): ?>

Call 1-800-661-2555 to contact our Guest Service specialists to reserve this package or book online by using discount code "<?php print render($content['field_discount_code']);?>".

<?php else: ?>

Call 1-800-661-2555 to contact our Guest Service specialists to reserve this package.

<?php endif; ?>

If I leave the discount code empty drupal is still showing the first text chunk but with nothing in the render($content['field_discount_code']); area.

so like this

Call 1-800-661-2555 to contact our Guest Service specialists to reserve this package or book online by using discount code "".

I have also tried

<?php if ($content['field_discount_code'] == "NONE"): ?>

text to display here

<?php else: ?>

text to display here

<?php endif; ?>

but no joy I am relatively new to drupal dev so perhaps I am doing this the wrong way any insight would be greatly appreciated!

That's weird, the first code works in my end. Are you sure the node--specials.tpl.php is being called in the first place? I am suspecting that maybe you're still using node.tpl.php though I'm not sure.

Try to print some text in your tpl file to check if it is being used by your content type.


Access custom block in page.html.twig template I've added a custom block (which is an image) in the HEADER section of a view. I want to show this image at the top of my page but currently it appears in content views-view.html.twig.

How can I access to this image in page.html.twig?

Take away the block from the view header and use twig_tweak module to be able to insert something like this in your twig template

{# No need to configure this block on "admin/structure/block" page. #}

Block:

{{ drupal_block('BLOCKID') }}

Or if you don't want to use an extra module add to your THEMENAME.theme

function THEMENAME_preprocess_page(&$variables) {
  $block = \Drupal\block\Entity\Block::load('BLOCKID');
  $content = \Drupal::entityTypeManager()->getViewBuilder('block')->view($block);
  $variables['my_block'] = $content;
}

and in your twig template just use

{{ my_block }}


Drupal Search API facet block not listing all indexed fields I have a content type that has a term reference field to a vocabulary called 'Categories'.

Categories

- Cat 1
- - Cat 1.1*
- - Cat 1.2
- - - Cat 1.2.1
- - - Cat 1.2.2*
- - Cat 1.3
- Cat 2
- Cat 3
- - Cat 3.1
- - - Cat 3.1.1
- - Cat 3.2

As you can see, the Category vocabulary has a terms in a Hierarchy.

Using Search API and Solr, im indexing the term reference field using 'Parents All'. I have set the index up to index the hierarchy.

Its all working perfectly, however, not all terms are listed in the facet box, despite the products being indexed correctly. There are a few terms that do not appear. (marked with a * above).

However, I know that the nodes are indexing correctly. I know this as I can filter by a facet that is working, then swap the argument in the URL arguments for the TID of a term that isnt working. When this happens, the products are displayed correctly in the view.

So my question is...what could cause Drupal/Search API to not display all items in a facet.

How can I start to debug this?

I have tried rewriting the facet using this function:

function HOOK_facet_items_alter(&$build, &$settings) {
                        if ($settings->facet == "YOUR_FACET_NAME") {
                          foreach($build as $key => $item) {
                            $build[$key]["#markup"] = drupal_strtoupper($item["#markup"]);
                          }
                        }
                      }

However, when I print out the list of terms inside $build the ones that arn't displaying are not listed in the array.

ANy help or any other hook suggestions are greatly appreciated.

Turns out that I had a limit on the number of items to display.

To fix it, I had to change the limit under Facet > Display.


How do I set the HTML5 date "min" attribute? I have a date field set up on a node in Drupal 8 using the default date time field formatter. I would like the date picker pop-up to start with a specific date I have defined in a config variable.

How can I do this? I have tried the code suggested on How to add select years and months select Drupal 8.1 date picker? but it doesn't do anything for me.

I have also looked for a way to pass datepicker options to the field element (looks like you could do that in Drupal 7 date module), but couldn't find a way to do that either.

In Drupal 8, the datetime fields are HTML5 inputs, so the popup is provided by the browser itself, or from a polyfill library for browsers that don't support these inputs (eg, Firefox).

If you want to provide a default value, you can do it from the settings for the field.  You can use the Current Date or a Relative Date as the default.  Despite the name and the docs on Relative Date, you can use this to set an actual date/time.

If you need to pull the default value from somewhere else (like config), you would hook_form_alter() the node form, and then check the field value.  If it is empty, you would set the value there.


Where to find all possible keys for BaseFieldDefinition -> setSettings() I am a noob to Drupal. I am trying to create a module and am currently in the process of creating a content entity and defining its base fields. Can anyone tell me where I can find a list of possible keys for the setSetting method? In other modules I have seen things like:

 BaseFieldDefinition::create('entity_reference')
  ...
  ...
  ...
  ->setSetting('target_type', 'commerce_store')
  ->setSetting('handler', 'default')

How is it that the module creator knew to use target_type and handler??
Any help is much appreciated. I am very confused.

The settings are specific to each field type, and each type can provide both storage and field settings (storage settings apply to the field as a whole, per type of entity it's used in, and field settings are the per-bundle settings).

For example, the entity_reference type, backed by the EntityReferenceItem class, provides a target_type storage setting, and several field settings (including handler).

You can use the API to get the default settings, which equate to the available settings that you're looking for, like this:

$field_type_manager = \Drupal::service('plugin.manager.field.field_type');
$storage_settings = $field_type_manager->getDefaultStorageSettings('entity_reference');
$field_settings = $field_type_manager->getDefaultFieldSettings('entity_reference');

That gets you something like this:

If you need to inspect the code to find out what's going on, you can find the class responsible for a particular field type with the same service:

$class = $field_type_manager->getDefinition('entity_reference')['class'];


How do I get rid of the node title on a specific view mode? I'm using Drupal 7 with Omega subtheme and Display Suite module.

I have a content type and the nodes are displayed as default (Full Content). But I have two or three nodes of this content type which must be displayed in slightly different way (just a few fields hidden, some others perhaps).

So using Display Suite I've created a new view mode for these specific nodes and on the content edit page I've selected new view mode rather than Default.

Now the problem with this new mode is that node's title is rendered twice, once as the page title and second as the node title. This is different from the Default/Full Content mode, which seems to just have a page title and no node title.

How to get a rid of the node title on the new view mode so it's the same as the way Default/Full Content displays are shown (without using Views)?

Maybe there's some way to clone the Full Content view mode and then just edit that clone. So the new view mode also only shows a page title not the node title?

Since already using Display Suite you can enable Extras module in orde to hide page title

DS config
admin/structure/ds/extras

Tab "Other"
Check "Page title options"

Node Manage Display
admin/structure/types/manage/article/display/full

Tab "Layout for article full"
select Hide "Page title"


How to remove duplicate view results from multiple blocks on same page in Drupal 8 I have multiple view blocks with different info on same page of same content type. I want to remove the duplicate results. I want one result to appear only once on whole page.

How can I achieve that in Drupal 8 ?

Thanks

Try Views Exclude Previous, check screenshots bellow


How to create a button that sets a node value I would like to create a set of buttons or text links on my site that set the value of a node field and/or create additional nodes.  Currently, I am using a combination of flags and rules to do this (when a flag is set, do the following...) This works fine, but it feels a bit cumbersome.  The flag has no other purpose other than triggering an action.  Is there a module specifically for doing this (including ajax) or is there another simpler way to perform this activity?

There is a Field Button module that creates and renders a button.  You can then write a rule that is triggered by button clicks.  This works great if you only need one or two buttons on a page.  However, this module has trouble figuring out which node the button belongs to (and therefor may not be a good option for lists of nodes & buttons rendered by views.)

Another option is the Rules Link module.  This module does roughly the same thing.  It  is not as pretty, but it has better rule integration.


Want to rename contact form fields name I am using drupal 7 contact form in my site and I want to rename  some field names, like  "Subject" to "Emne" etc..

Use hook_form_FORM_ID_alter() as shown below:

/**
 * Implements hook_form_FORM_ID_alter().
 */
function MODULENAME_form_contact_site_form_alter(&$form, &$form_state) {
    $form['subject']['#title'] = t('New Title');
}

Update #1

For Page Title use drupal_set_title() as shown below:

drupal_set_title('kontakt'); // Add this line in above function MODULENAME_form_contact_site_form_alter


Context aware plugins I am working on porting a module from Drupal 7 to Drupal 8.
In the process I have to port a ctools content type plugin to the new context aware plugin.
The legacy plugin had "node" as a required context because it had to appear only on the node pages. I am finding it hard to implement it in the new plugin system.
Here is how I define the new plugin

/**
 * Provides a 'Custom' block for the current node.
 *
 * @Block(
 *   id = "machine_name_of_block",
 *   admin_label = @Translation("Admin label for the block"),
 *   context = {
 *     "node" = @ContextDefinition("entity:node", required = FALSE)
 *   }
 * )
 */
class ModuleBlock extends BlockBase {
  /**
   * {@inheritdoc}
   */
  protected function blockAccess(AccountInterface $account) {
    /** @var $user \Drupal\user\UserInterface */
    // $user = $this->getContextValue('user');
    $node = $this->getContextValue("node");
    if (!is_null($node)) {
      return AccessResult::allowed();
    }
    else {
      return AccessResult::forbidden();
    }
  }

  /**
   * {@inheritdoc}
   */
  public function build() {
    // Sample output which will be changed later.
    return array('#markup' => '' . $this->t('Powered by Drupal', array('@poweredby' => 'https://www.drupal.org')) . '');
  }

}

I have a problem in accessing the context value in this plugin using $this->getContextValue('node');. It seems to return null even if I am on a node page.
Am I missing something?

Why don't you just use the existing node type condition plugin?

That won't solve your problem if you also need the node to actually display something, but core currently just doesn't really do this for blocks, there is no UI to configure the mapping, so it only works if the context has the exact same name.

You will likely have to fall back to getting the parameter yourself out of the route match service, for now.


How to create toggle effect using jQuery? I am using views to to display title,image,date,description of a specific content type. By default the first element in the views has to be shown, where else the remaining![enter image description here][1] would be hidden . When the user clicks the 2nd title the 2nd node's content has to be shown and the rest has to be hidden.
It would be great if some one can help me to achieve this.

If you prefer to handcraft you can create a template (look inside your Views template suggestions) and paste inside this code. Then using functions like views_get_view_result() you can fetch views field and use them inside it.

<?php
    drupal_add_library('system', 'ui.accordion');
    drupal_add_js('jQuery(document).ready(function(){jQuery("#accordion").accordion();});', 'inline');
    ?>

Section 1

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.

Section 2

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.

Section 3

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.


"languages" is not found in regional settings I installed drupal commons 7.3.4,

I want to ADD an additional language. I try to follow this manual:

https://docs.acquia.com/articles/adding-another-language-your-drupal-7-site#language

go to Configuration > Regional and language > Languages

But there's no "Languages" section under "Regional settings"

I tried to enter the URL manually, but it brings me to "regional settings".

I enabled

Locale
content translation
Entity Translation
Variable admin
Internationalization
...

i also flipped-flopped in the air, and prayed to budhha.

but there's no "Languages" in Regional settings.

What am I missing?

You're misreading the instructions (they're correct) and as a result, you're looking in the wrong place.  It is not in "Regional settings".

Start by clicking on "Configuration" on the admin toolbar. Then scroll down the page until you see a box with the heading "Regional and language".  Inside that box, below "Regional settings", you should see the link to "Languages"


Commerce: is there something in the basket? Is there a global variable of sorts that can be used as a bool to determine if something is in the basket?

This is what i use :)

function items_on_cart(){
  global $user;
  $cart = commerce_cart_order_load($user->uid);
  $line_items = count($cart->commerce_line_items) ? true : false;
  return $line_items;
}


How to name a template file for the following theme hook suggestions? I hardly managed it to create theme hook suggestions to work with different bean blocks, so I can use custom .tpl files like:

bean--{bundle_name}.tpl.php // currently only bunde is 'zielgruppe'

Here is the code so far:

/**
 * Override or insert variables into the block templates.
 */
function mymodule_preprocess_block(&$variables) {
  // For bean blocks.
  if ($variables['block']->module == 'bean') {
    // Get the bean elements.
    $beans = $variables['elements']['bean'];
    // There is only 1 bean per block.
    $bean = $beans[reset(element_children($beans))];
    // Add bean type classes to the parent block.
    $variables['classes_array'][] = drupal_html_class('bean-' . $bean['#bundle']);
    // Add template suggestions for bean types.
    $variables['theme_hook_suggestions'][] = 'bean__' . $bean['#bundle'] . '_tile';
    $variables['theme_hook_suggestions'][] = 'bean__' . $bean['#bundle'] . '_' . $bean['#entity']->delta;
  }
}

But for the last suggestion I just cant figure how to freakin name the file. delta prints "für-angehende-lehrkräfte". I've tried to following file names which dont get noticed:

bean--zielgruppe-für_angehende_lehrkräfte.tpl.php
bean--zielgruppe-für-angehende-lehrkräfte.tpl.php

(appearently stack messes up ü characters in code areas)

For instance, bean--zielgruppe-tile.tpl.php works.

You can also output the theme_hook_suggestion with DSM. You'll see all the suggestions and template candidates for your content. (https://drupal.org/project/devel_themer could help you too)


Views: Get nodes of last added Node Reference I'm working on a online magazine in drupal.
I have one content type called issue with one field, the title field.
And I have a content type called article the default drupal content type with a node reference field linking to issue.

I first make an issue called 'issue 01'. Then I start making some articles linked to 'issue 1' via the node reference field.

Then I make a second issue called 'issue 02'. And make some articles to go with this issue.

Now I want to make a view to show on the homepage showing all articles of the last added issue so for 'issue 02'. And when I would add a new issue called 'issue 03' the home page should automatically show the articles from this issue.

I'm trying to make this work via the relationship option and the contextual filter option in Views, the relationship is made. And the view is showing all articles. Now I want it to be filtered to showing articles of the last issue only so I thought about using the contextual filter but I can't find out a way to get, for instance, the NID of the last added issue.

Any help is welcome!
Thanks in advance.

Order by the date DESC and restrict the displayed items to 1 through your pager options.


Error with drush clear-cache: Base table or view not found There are similar questions out there, but I think this warrants a new thread.

I am getting the following error when running drush clear-cache all

PDOException: SQLSTATE[42S02]: Base table or view not found: 1146 Table 'dbname.cache_rules' doesn't exist: TRUNCATE {cache_rules} ;"

However, when I run the show tables command on the database, it clearly lists the cache_rules table.

Any ideas what is going on here and what I can do to fix it?

Here is how to reset your cache_rules table, using a stable Drupal installation.

Get cache_rules structure from clean database

You can get SQL text to drop/add the cache_rules table via the following steps:

Log in to phpMyAdmin on a functional Drupal site.
Click on the columns section under the cache_rules table
Click the Export button
Click 'Custom' to show all options
Under 'Output' click 'view output as text'
Under 'Format-specific options' choose 'structure'
Under 'Object creation options' check 'Add DROP TABLE / TRIGGER statement'
Copy the text displayed, or see below (sorry for the formatting)

Here is the SQL code to drop and add the table (thanks duckx!).

DROP TABLE cache_rules ;
CREATE TABLE IF NOT EXISTS `cache_rules` (
  `cid` varchar(255) NOT NULL DEFAULT '' COMMENT 'Primary Key: Unique cache ID.',
  `data` longblob COMMENT 'A collection of data to cache.',
  `expire` int(11) NOT NULL DEFAULT '0' COMMENT 'A Unix timestamp indicating when the cache entry should expire, or 0 for never.',
  `created` int(11) NOT NULL DEFAULT '0' COMMENT 'A Unix timestamp indicating when the cache entry was created.',
  `serialized` smallint(6) NOT NULL DEFAULT '0' COMMENT 'A flag to indicate whether content is serialized (1) or not (0).',
  PRIMARY KEY (`cid`),
  KEY `expire` (`expire`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='Cache table for the rules engine to store configured items.';

Drop/add the cache_rules table

Now navigate to the other database, using phpMyAdmin.

Make a full backup of the database
After the backup has been saved, click the SQL tab
Paste the text into the text box (removing any existing text)
Click 'Go'


How can I hide exposed filter control if the filter is not applicable to existing views results? I have created a view with three exposed filters. Now I have to hide these Fields dynamically - if field is not present in any of the content types of the nodes in current result, filter based on this field should not be visible. I am using Drupal 7.

You have to create a small module or add a function into template.php where you use a one of the hook alter functions. You test your view results for a given set, and if you at that result don't need the filter you unset it. Probably the best hook is: hook_views_pre_render.

"https://api.drupal.org/api/views/views.api.php/group/views_hooks/7"

Check out the comments on the hook_views_pre_render function to get an idea of how to use it. Hope this gets you on your feet.


Programmatically embed fields of one content type in the create/edit form of another content type and store all I have drupal 6.x.

How to programmatically (with a custom module) embed fields of one content type (content type X) in the create/edit form of another content type (content type Y) and store all the data for when the node is created/updated (store X and Y data when Y is stored).

If is not possible this in drupal 6.x I could be to work in drupal 7.x.

Thanks in advance.

I think it would be tricky as you would need a way of tracking a relationship between the two nodes as well. You would need to decide on which way the relationship would go if you were to use node reference as its only one way in drupal 6.

This is what I would do
1. Add a node reference field to Y
2. Use hook_form_alter to add the required fields (Embedding cck fields will be tricky better of just sticking to fapi fields)
3. add a custom validation handler for the x fields if required
3. Save x field values as a node programticaly when presave is triggered by hook_node_api http://api.drupal.org/api/drupal/developer!hooks!core.php/function/hook_nodeapi/6
4. Update the noderefrence in Y with the new X nid
5. Use hook_node_api to update X when Y is updated

Another possibility might be to use Rules to create and update for you


Multisite with i18n module enabled We have to build a multi lingual site(English and Spanish). There are 2 approaches to enable multi lingual site

Single site with i18n module

Content,Functionality and layout are almost same for both languages

Multi site (Parent English Site and Spanish sub site separate)

Content,Functionality and layout are mostly different for Spanish site
Parallel Enhancement needs to be done for both languages
English language site needs to be redesigned without affection Spanish language site

We are preferring to choose the second approach to build the multilingual site. Please feel free to recommend the Implementation approach using i18n module.

You should read Drupal 7's new multilingual systems compilation. There's even a full book about that matter: Drupal 7 Multilingual Sites.

When using a single Drupal instance to create a multilingual site, there are two different approaches: Content Translation and Entity Translation (Read: Node translation vs. Entity (field) translation). You may want a multi-site setup (With Domain Access or without it), especially if you require independent content to appear (not only translations). And the Internationalization suite of modules is a must, it provides the following modules:

Path Translation
String Translation
Taxonomy Translation
Block Translation
Variable Translation


What does the computed code do for a computed field in content type I have content type field called 'field_p_bo' and it have the computed code as follows

it causes some problem since it affect the saving of this content type , This code is there for some other fields too . What will happen when i remove the computed code ? will it affect any other part of the content type ?

The code fetches the id of the node_project.

For example if the node's project field is set 'Foo' it will get the id of that row where it was saved. As its not clear from where $node comes whether its current loaded node or any other node. But it seems that in computed field you are storing the ID of the project

What I think is causing the problem is if project names are FOO and FOO_BAR the query will result both the ids which can cause to store incorrect ids.

You can simply remove the like operator and add equality.


Clean URLs not working in Drupal 8.1.8 and IIS 8 I am working on a new installation of Drupal 8 (8.1.8) on a Windows Server 2012 running IIS 8. I have installed PHP v7.0.9 and MySQL v5.7.14. During the installation process, I must have done something wrong. Upon completion, the home page is just the HTML without any styling and all of the links return an HTTP Error 404.

The error:

I've tried as much as I can think of (eg reinstalling IIS/Drupal/PHP/MySQL, triple checking passwords for MySQL, making sure URL Rewrite is working, etc)

UPDATE: I have also tried using drush to clear the cache.

UPDATE #2: It would seem as though my HTTP problem comes from the URL Rewrite module not working properly.

UPDATE #3: The site now has styling!!!!!! After reading this post, I realized that there was no 'tmp' directory in '/sites/default/files'. However, there is still a problem with the URL Rewrite. I have to include '/index.php' in every url to go to any pages.

Probably it's a directory permission issue. Drupal is not able to write into web/sites/default/files. Give this file directory right permissions for your server user. (www-data in case of apache)


How can i print multiple query output in GLOBAL:PHP view field? I have custom global:php fields on which I put the following code as value.

$shop_url=db_query("select page_url from mytable1 where user_id=$row->uid");
return $shop_url;

As output code, I put the following one.

foreach($shop_url as $data) {
  print($data->page_url);
}

I am getting no output. How can I achieve printing multiple database results in GLOBAL:PHP?

There are many errors in your code :)

First, don't use $data variable, as it's already used in your view ; check the available variables section under your php inputs. Normally, it's advised to use $static.

Second, did you check elsewhere that

$shop_url=db_query("select page_url from mytable1 where user_id=$row->uid");

returns something ? Because I would have thought that only

$shop_url=db_query("select page_url from mytable1 where user_id=:uid", array(':uid' => $row->uid));

would work.


Where DHTML Menu link's title is getting printed I would like to replace the title attribute of DHTML menu's link with a javascript tool tip. But i could not find the place where the link attributes are printed. ie. where  test  is mentioned.

Kindly help me.

By implementing theme_menu_link(), you can adjust the menu links to whatever you need.


How can I limit an entity reference selection to a specific field value on the reference I have a content type Research which has a an entity reference type of People.
The problem is that I don't want to show ALL people but only people which have a certain value under their field named type.
I was trying to find it here:

Anyone an idea how to only show a content-type for a certain field value of that content type

You can create an Entity Reference display in a view and use that to generate the available options.

In your view of choice, create a new display of type Entity Reference and configure it so that it only shows the content you want.
Navigate back to your field configuration screen (the one in your screenshot) and change Reference Method from "Default" to "Views: Filter by an entity reference view" and choose the display you created in step 1.


Let anonymous view dpm() when using Omega subtheme I need to debug a D7 site from the anonymous user. What settings need to be changed to allow anonymous to view dsm(), dpm(), krumo(), etc. commands?

Note: I have already enabled Access developer information under the Devel module for all roles.

Give them Access developer information permission at admin/people/permissions.

Note that this opens a huge security risk so make sure you revoke it when you are done with debugging.


Commerce Price: Hide formatted amount if empty I have a view with a regular commerce price and a discounted one. When using the Raw amounts everything works fine but when I use the formatted ones the hide if empty, Count the number 0 as empty and Hide rewrite if empty even though they are checked the amount of 0,00€ is shown!

What can I do to hide it?

This should be fixed in Drupal commerce, but until it gets fixed you could add a custom template file to your theme. Copy /sites/all/modules/views/theme/views-view-fields.tpl.php to /sites/all/themes/[YOUR_THEME]/templates/views-view-fields--[YOUR_PRODUCT_TYPE].tpl.php and edit it.
Add something like: <?php if($id == 'commerce_price' && empty($row->commerce_price)) continue; ?> to your template file.

<?php foreach ($fields as $id => $field): ?>
  <?php if($id == 'commerce_price' && empty($row->commerce_price)) continue; ?>
  <?php if (!empty($field->separator)): ?>

...


Using the modules Rules and Facebook Autopost, the previous post body summary is used instead of the current post UPDATED 8/29/2016

Thank you so much for everyone that responded and special thanks to Pierre.Vriens for the detailed explanation. I am sharing my answer in case anyone finds this useful.

After much research I found that the summary field was not available so I created my own summary (which is not nearly as good as the built in summary from Durpal) but it fits my own needs. It will break in the middle of a word but that is ok for me and also it breaks on 250 characters no matter what but that is ok in my case as well.

In my case I used the following for the facebook-description field (with php wrappers, or course).

    print substr(strip_tags($node->body['und'][0]['value']), 0, 250) . " . . ."

thanks again to everyone!

----- original question -----

When I add a new article my facebook autopost uses the correct image, correct title, and the correct URL but the body summary is from the previous article?

If I rebuild the rules cache it works correctly but only for the next entry then I need to rebuild the rules cache again.

{ "rules_fb_new_artice" : {
    "LABEL" : "FB - New Artice",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "TAGS" : [ "facebook" ],
    "REQUIRES" : [ "rules", "php", "fb_autopost_entity" ],
    "ON" : { "node_insert--article" : { "bundle" : "article" } },
    "DO" : [
      { "entity_create" : {
          "USING" : {
          "type" : "facebook_publication",
          "param_type" : "post",
          "param_user" : [ "site:current-user" ]
          },
          "PROVIDE" : { "entity_created" : { "entity_created" : "Created entity" } }
        }
      },
      { "data_set" : {
          "data" : [ "entity-created:field-facebook-name" ],
          "value" : [ "node:title" ]
        }
      },
      { "data_set" : {
          "data" : [ "entity-created:field-facebook-picture" ],
          "value" : "\u003C?php\r\n if($node-\u003Efield_image) {\r\n if(array_key_exists(0, $node-\u003Efield_image[\u0027und\u0027])) {\r\n $fid = $node-\u003Efield_image[\u0027und\u0027][0][\u0027fid\u0027];\r\n\t $result = db_select(\u0027file_managed\u0027, \u0027fm\u0027)\r\n\t\t-\u003Efields(\u0027fm\u0027, array(\u0027uri\u0027))\r\n\t\t-\u003Econdition(\u0027fm.fid\u0027, $fid,\u0027=\u0027)\r\n\t\t-\u003Eexecute()\r\n\t\t-\u003EfetchAssoc();\r\n $path = $result[\u0027uri\u0027];\r\n $style_name = \u0027large\u0027;\r\n print (image_style_url($style_name, $path));\r\n }\r\n }\r\n?\u003E"
        }
      },
      { "data_set" : {
          "data" : [ "entity-created:field-facebook-link" ],
          "value" : [ "node:url" ]
        }
      },
      { "data_set" : {
          "data" : [ "entity-created:field-facebook-description" ],
          "value" : [ "node:body:summary" ]
        }
      },
      { "publish_to_facebook" : {
          "USING" : { "publication" : [ "entity-created" ], "pages" : "140044559353737" },
          "PROVIDE" : { "facebook_publication_id" : { "facebook_publication_id" : "Facebook publication returned ID" } }
        }
      },
      { "entity_save" : { "data" : [ "entity-created" ] } }
    ]
  }
}

Here is a screenprint of the above rule with proper formatting.

Some more details: When a new article is submitted a Facebook post is made using the article title, article url, article summary and article image.

Your publish_to_facebook is NOT your very last Rules action. In fact, as per the save_entity which follows it, it appears that you are publishing to Facebook something that hasn't been saved yet. So that at least seems to explain what you see happening.

Any attempt to get it to work should ensure that you only publish something that has been saved. So you may want to try by just swapping the last 2 rules actions.

The above is just a quick and dirty attempt, and I doubt you'll actually get it to work like that. But your question reminds me about issue # 430274, and somehow explains that "after saving something" actually happens "before saving something". This is not a bug, but simply how the Rules module works.

A possible compromise to avoid these kind of issues, is to move your  publish_to_facebook action into a second Rules or component in order to ensure that the node is definitely saved correctly.

Method 1: Your original Rule "schedules the execution" (using the
Rules Scheduler sub-module) of that Rules component. For example
after only a few seconds or minutes if your cron job runs frequent
enough (otherwise it'll be next time cron runs). This compromise will
ensure that, at the time the Rules component is executed, the entity
is for sure saved (so that can't be the reason anymore then why
things don't work as expected).
Method 2: Add a Boolean field to the node type and when using Rules
to create the node, set it to "off". Then add a redirect to the
created node as the last action.
After that, create a second rule for "Content is viewed" which will make the Facebook post.
Condition: "Boolean field == Off".
Action 1: Post to Facebook using viewed node's data.
Action 2: Set a Data Value: Boolean field == "On".

If none of the above helps, maybe it's worth to do some Rules debugging, as detailed in "How can I display the value of a variable inside a condition?".

Note: In 1 of your (moved to chat) comments, you also added this:

  Facebook returns a unique identifier that must be saved as part of the entity so I can further code updates or deletes if necessary.

If I was to make this work, I would first make the original question work, which is about "add a new article" (updates or deletes is an additional challenge). Because as long as you've not succeeded in that, there is nothing to update or delete ...


How do I add a payment view block to Commerce Order page? At example.com/user/123/orders/993 the customer sees an Order #993 page to review the history of a particular order.

I already have a View with a block display of the payment information for a given order.

How can I attach this block to that particular form/page (which is generated in code) such that I can pass the UserID and OrderID to the view?

EDIT: What I want to do is 'inject' the Payment view/block I've created -inside- the form generated in commerce_cart.module (after the line items entity reference) so that I can theme it in a decent looking way.

For the block, you can set the visibility to user/*/orders/*

For the info in the block, you can use a contextual filter that checks the user and displays the needed info.


Webform Worflow notifaction I'm using D7, WebForm Module and Workflow Module.
When the user submit, the state change automatically to the first state.
Users to notify and the submitter user should receive normally the notification.
When i try nothing received!
Can anyone suggest to me, What can i do to prevent this problem from happening?

Without more information on the issue, there could be a lot of causes for this. For example, most emails are sent when cron runs, is cron set to run periodically?

Are you able to see your logs on the site?

If so, are there errors associated with email not being sent (Go to http://your-site-url/#overlay=admin/reports and select recent log messages)? Is your server configured to sent emails?

Some error logs are found on your /etc/httpd/logs/error_log folder, looking there would be helpful too while you try and submit a form to see what gets logged.

As I mention above, more info perhaps can help us troubleshoot it.

Hope this helps.


Drupal Form to Choose Embedded View I'm trying to create a form that will allow a user to select a View from a list and then display that View on the same page. For instance:

$options = array();
$options['view_one'] = 'view_one';
$options['view_two'] = 'view_two';
$options['view_three'] = 'view_three';

$form['chooseview']=array(
    '#title'=>'Choose a View',
    '#description'=>'Which View do you want to display?',
    '#type'=>'select',
    '#name'=>'chooseview',
    '#required'=>TRUE,
    '#options' => $options,
    );

print views_embed_view($form_state['values']['chooseview'],'block_1');

My question is how do I accomplish this? Drupal is not printing the embedded View from form_submit. I don't need Ajax.

Method #1: (No subit button, requires JS, loads all views at once but shows conditionally)

<?php
function MYMODULE_my_custom_form($form, &$form_state) {
  $options = array();
  $options['view_one'] = 'view_one';
  $options['view_two'] = 'view_two';
  $options['view_three'] = 'view_three';

  $form['chooseview']=array(
    '#title' => t('Choose a View'),
    '#description' => t('Which View do you want to display?'),
    '#type' => 'select',
    '#name' => 'chooseview',
    '#required' => TRUE,
    '#options' => $options,
  );
  foreach ($options as $view_name) {
    $form['display'][$view_name] = array(
      '#type' => 'markup', // Not necessary - just to be clear.
      '#markup' => views_embed_view($view_name, 'block_1'),
      '#states' => array(
        'visible' => array(
          ':input[name="chooseview"]' => array('value' => $view_name),
        ),
      ),
    );
  }
  return $form;
?>

(short, eh)

Method #2: (Submit button, JS-independent, loads only view when necessary)
Note we pass $form_state to the form builder function by reference.

<?php
function MYMODULE_my_custom_form($form, &$form_state) {
  $options = array();
  $options['view_one'] = 'view_one';
  $options['view_two'] = 'view_two';
  $options['view_three'] = 'view_three';

  $form['chooseview']=array(
    '#title' => t('Choose a View'),
    '#description' => t('Which View do you want to display?'),
    '#type' => 'select',
    '#name' => 'chooseview',
    '#required' => TRUE,
    '#options' => $options,
  );
  $form['show_me'] = array(
    '#type' => 'submit',
    '#value' => t('Show me, please!'),
  );
  if (!empty($form_state['values']['chooseview'])) {
    $form['display'][$view_name] = array(
      '#type' => 'markup', // Not necessary - just to be clear.
      '#markup' => views_embed_view($form_state['values']['chooseview'], 'block_1'),
    );
  }
}

function MYMODULE_my_custom_form_submit($form, &$form_state) {
  $form_state['rebuild'] = TRUE;
}
?>


Drush error when running dmu-analyze to update drupal modules I'm using drupal module upgrader with drush to update the modules which are drupal 7 compatible at the moment. I'm getting this error when I try running drush dmu-analyze MODULE_NAME

I can't seem to find a solution on the net to fix this issue. I have tried re-installing the module or drush. Even when I type drush status I'm also getting this error.

One of the modules in your installation is incorrectly using references to services without quoting them.

e.g.

[@container.namespaces]

instead of the valid:

['@container.namespaces']

The error message doesn't provide enough details to be able to identify which module is causing the problem. It's going to be a contrib/custom one, though, so check the .services.yml file for the extra modules you have installed and you should find the culprit. It's likely to be under a service whose name begins with plugin.manager..


How to views-filter attached field value by calculated values? I just want to create a simple "IN" filter for my taxonomy field with values that I calculate in the views_handler_filter subclass.

My subclass of views_handler_filter implements the function views_handler_filter->query(). I need to require that the tid of a taxonomy_term_reference field is in an array that I build there. How can I build the query to filter by field value?

views_plugin_query_default::add_where($group, $field, $value = NULL, $operator = NULL)

When calling $query->add_where(), the $field argument is simply described as "The name of the field to check." How can I join the filter query to the field data table and build my $field argument correctly for the taxonomy_term_reference field I need to filter by?

I solved my current problem in a similar way to the solution here: http://drupal.org/node/1259914

Added a filter to the view with my taxonomy field as "not empty"
Implemented hook_views_query_alter() to call $query->add_where with my field_table_name.field_data_column and the values I wanted to accept with the 'IN' operator.

That said, I'm still interested in the views_handler_filter->query() solution(s).


Loop through nested array in Twig I have created a variable to use in my twig template. The variable consists of a nested array. If I dump the variable I get the following result:

dump(gallery_images)
array (size=2)
  'img' =>
    array (size=15)
      0 => 'path-to-file.jpeg'
      1 => 'path-to-file.jpeg'
      .....
   'alt' =>
    array (size=15)
      0 => 'img 1 alt text'
      1 => 'img 2 alt text'

I want to loop through gallery_images and map the alt text to the image. My loop was working fine before I added the nested array / alt text. This is how I expected it to work:

{% for gallery_image in gallery_images %}

{% endfor %}

That did not work, then I tried to call the src and alt with

{{ gallery_image.0 }}
{{ gallery_image.1 }}

Then I only got 1 file and 1 alt text. What is the correct way to loop through the nested array? Also bear in mind I may want to add title text next.

Do you have control over your array structure?

Why not just change it to this:

[
  0 => ['alt' => 'alt text', 'img' => 'image-path'],
  1 => ...?
]

Because then your logic would work, but right now you have the reversed structure. What you could do is loop over the image paths with {% for key, path in gallery_images.img %} and use the key toaccess gallery_iamges.alt[key]` (not 100% sure about the exact syntax). Certainly more complicated that way.


How to get notified when a user is locked? After 5 unsuccessful logins, a user gets locked. How can I get notified? I tried with the Rules module without success.

You can use Login Security module for D7. It has notifications.

Form the project page :

  A set of notifications by email or Nagios may help the site
  administrator to know when something is happening with the login form
  of their site:


Expiration date for static files I don't understand the following:

In Drupal 7's default .htaccess file the Apache module mod_expires is ordered to let files without a .php extension expire after two weeks.

How is web development with this setting possible? When I change a .css file, I want the changes to be reflected immediately. Do browsers ignore the expiration setting?

I've stumbled upon this issue because I'm currently experiencing troubles with a Varnish caching system. I currently do not know what causes my files not to be refreshed immediately.

The Cache-Control header which mod_expires sets tells the browser when a set of cached content should expire and be redownloaded. If you are interested in learning more about how that header works, read http://blog.httpwatch.com/2007/12/10/two-simple-rules-for-http-caching/ it explains it really well. Browsers do not ignore this setting. But if you "shift reload" or do something which forces the browser to ignore the cache and redownload anyways you'll ignore it.

A common approach for this is to implement a timestamp based update for CSS/JS. For example you have the following stylesheet link

<link rel="stylesheet" type="text/css" media="all" href="style.css">

You would append a last changes tag to it, something like

<link rel="stylesheet" type="text/css" media="all" href="style.css?c=20131001">

and then you can just auto increment this every time you change the css. This will force ALL browsers to redownload, but won't destroy the cache benefits.


Some templates are not properly compiled to Twig I have a few templates that are failing when compiling them in twig.
What is happening is that the \Drupal\Component\PhpStorage\MTimeProtectedFastFileStorage::save method will create a temporary file like files/php/twig/.0c781c5196 and then it tries to rename this file into something like files/php/twig/DIRECTORY/FILE.php but it fails with No such file or directory.

The target directory exists, it even has .htaccess. On each page refresh, I get different temporary and target file names.

I tried to manually copy and rename the file but on each page load the ID's change so it never works.

The template hasn't been edited and it always worked just fine(it renders properly  even without compiled twig). Any idea what can be causing this?

It looks like this is only a single template issue. Due to the ever changing IDs, I thought there were more.

This is happening on my local windows machine right now so I though there might be an issue with those crazy long directory and file names but I can manually rename the file.

The length of the directory name is 134 characters which are well below 260 maximum.

UPDATE 27.6: I have experienced this same issue on another Drupal 8 project. So it looks like it is not a unique problem but rather universal but I still haven't figured out what the issue is.

OK!
So I have figured it out. I think this is a Windows-specific bug because, on another project where I have experienced this as well, people with macs do not have this issue.

Anyway, what is causing it is \Drupal\Component\PhpStorage\MTimeProtectedFastFileStorage::getFullPath, specifically return $directory . '/' . hash_hmac('sha256', $name, $this->secret . $directory_mtime) . '.php';

If the template name is too long, which can easily happen with theme suggestions, it will cause PHP to fail to perform the rename() operation successfully. I don't know why it stores the code in a temporary file and then it copies it into target directory instead of creating it directly in the target directory and/or file but that's how it is.

I have no idea why we need so freaking long directory and file names when they only hold a single file but beside this, Drupal 8 is great.


combining drupal commerce product display page with checkout page I am trying to find a good way of combining the Drupal Commerce Product Display page with the checkout page. I am trying to eliminate a page, so that the user would choose the product variation and fill in his profile data all on the same page.

I see that there is a hook_commerce_checkout_page_info_alter() which looks like it may be a start, but it would need more thought of how to actually combine these two pages.

You can't get to checkout pages without products in your cart ( try visiting /checkout with an empty cart). At least, not without extensive hacks.

I'd recommend keeping the catalogue browse / add to cart separate from the checkout process.

If suitable, you can redirect straight to checkout with a Rule after the product is added to the cart, for user detail input and order completion.


How do I asynchronously run things? I used Drupal 7.14, Video Module 7.x-2.5, VideoJS 7.x-2.0 HTML5 player, and ffmpeg 0.7.2 to transcode a 200mb mp4 video into Ogg, Flv, MP4 formats. The process worked, but took over 1 hour. Using the command line, I can file transfer and transcode same file in under 15 minutes.

Aside from upping server processing power, or wishing that Drush handled video transcoding via ffmpeg, is anyone else off-loading Drupal processes via PhP Process Forking, or Asynchronously via Javascript, ie. node.js?

Ideally, once I click save on any Drupal form, a child process should spawn and work on the side, as I go about doing other things, without my admin interface locking up to process one thing (synchronous coding). Thanks for your time,

Look into the HTTP Parallel Request & Threading Library. The Imageinfo Cache module uses it to generate imagecache presets when a file is uploaded on a node form, and does a final check on node save; all in the background. The other module to look into using is Background Process, it does similar thing as HTTPRL and the 2 modules are actually looking to merge together (http://drupal.org/node/1357652).

An example of how to flush caches in the background is in the httprl readme


Using theme hook suggestions for webform confirmation page I've been trying for the last couple of hours and failing to use theme_hook_suggestions for custom webform confirmation templates.  I want all webforms on a specific content type to use a particular confirmation page template.

So I've got the following in webform_confirmation.preprocess.inc (I'm using Omega4 which puts preprocess functions into include files):

function foeomega_preprocess_webform_confirmation(&$vars) {

  $vars['theme_hook_suggestions'][] = 'webform_confirmation__' . $vars['node']->type;
  ...
}

Then I have 2 template files:

webform-confirmation.tpl.php = The generic one I want to override
webform-confirmation--myspecialnode.tpl.php = The new one I want to use instead

No matter how many times I 'drush cc all'/'drush cc theme-register' the suggestion template is never picked up :(

However, I did get the suggestion to work if I commented out the following in webform.module file:

function webform_theme() {

...

  'webform_form' => array(
  'render element' => 'form',
  'template' => 'templates/webform-form',
  // I COMMENTED THIS OUT: 'pattern' => 'webform_form_[0-9]+',
),

...

}

Leading me to believe that pattern and suggestions are not compatible - however I can't find any information on this by Googling - can anyone confirm/deny?

Thinking that 'pattern' and 'theme_hook_suggestions' don't mix, I tried implementing the following in my template.php file:

function foeomega_theme_registry_alter(&$theme_registry) {
  if($theme_registry['webform_confirmation']['pattern']) {
    unset($theme_registry['webform_confirmation']['pattern']);
  }
}

This did seem to remove it from the registry, but alas, the generic template file was still being used (after make 'drush cc ...' commands...).

Any ideas?  I'd really like to have nice content-type specific confirmation pages?

Many thanks,
Chris :)

I think your problem is due to the use of $vars['theme_hook_suggestion'] (no trailing s) by webform.
This value overrides any that you could put in the $vars['theme_hook_suggestions'] array

I was having the same problem, I just unset this $vars['theme_hook_suggestion'] and my others suggestions in $vars['theme_hook_suggestions'] have been used.

Note: $vars['theme_hook_suggestion'] is a string NOT an array


Replace Standard Node Path in Drupal 8 I am still new to all the Symfony semantics. What would be the easiest way to change node canonical urls to be /article/[node-title] instead of /node/[node-id]?
Following this documentation I tried the code (which I expected to produce at least a url structure like /article/[node-id])

<?php
/**
 * @file
 * Contains \Drupal\example\Routing\ExampleRoutes.
 */

namespace Drupal\example\Routing;
use Symfony\Component\Routing\Route;
/**
 * Defines dynamic routes.
 */
class ExampleRoutes {

  /**
   * {@inheritdoc}
   */
  public function routes() {
    $routes = array();
    // Declares a single route under the name 'example.content'.
    // Returns an array of Route objects.
    $routes['entity.node.canonical'] = new Route(
      // Path to attach this route to:
      '/article/{node}',
      // Route defaults:
      array(
        '_controller' => '\Drupal\node\Controller\NodeViewController::view',
        '_title' => 'Hello'
      ),
      // Route requirements:
      array(
        '_permission'  => 'access content',
      )
    );
    return $routes;
  }

}
?>

But unfortunately it is not changing anything…

While theoretically now supported, that is not possible not like this.

You can not reliable load a node based on the node title, it is not guaranteed to be unique, and to become a practical URL, a number of replacements should be made, like replacing spaces, lowercasing it and so on.

Use the path alias system for this, just like in Drupal 7. We're maintaining an inofficial port of the pathauto module, that allows you to configure token patterns to automatically generate an alias for each node. You also need token.module, which you can get from here.


Exposed filter only allowing content types in list I have a view called (Resources) that displays content filtering by content type. These are the selected options:

Expose this filter to visitors, to allow them to change it: ✅
Filter type to expose: Single filter
Operator: Is one of
Content types: Article, Post, Story (NOTE: I have other content types, such as Basic Page that shouldn't be included in this view at all)
Allow multiple selections: ✅

However, when none of the options are selected, it also brings in other content types, such as Basic Page, which shouldn't be.

How can I make it so that when none of the content types in the exposed filter are selected, the results are still filtered such that the nodes must be of one of the chosen content types (Article, Post, Story)?

In other words, I would like the view to behave such that, when none of the content types are selected, it acts as though all of them are checked.

OK, I figured it out.

I simply added a duplicate of my "Content type" filter, except this filter is not exposed. Same settings as above ("Is one of", Article/Post/Story, etc.), just an extra restriction on the results to always filter by all of the desired content types, with the exposed filter being an additional option to further narrow down the results.


Reverse entity reference lookup I have a data structure where content type research has an entity reference field scientists.
The content type scientists does not have any research reference entity field though.
I can get all scientists that a particular research has through research.
But is there a way to get all researches one particular scientist has? When content types were created I wasn't involved, so I'm trying to see my options whether I can somehow click a checkbox to make this applicable.
When I tried to set up a field with type of entity reference and pointed it to research for scientists, they were empty.
Any help is highly appreciated.

Is there a way to get all researches one particular scientist has?

Yes, search for the scientist target id:
$nodes = \Drupal::entityTypeManager()->getStorage('node')->loadByProperties([
  'type' => 'research',
  'field_scientists' => $scientist_id,
]);


remove second admin menu This is a pretty basic problem I think but i can't seem to find the solution. I've install the adminimal menu and I would like to remove the second menu on the bottom of this image. I've disable toolbar.

navbar was enable. I disable it and the hambuger menu was gone.
Thanks for your help.