passing argument from one view to another view I have created two views , View1 has a list of city names (drop down select box) and View2 displays all the pharma shops across multiple cities. What i am trying to do is , when a city is choosen from view1 i need to display only the pharma shops in that city using view2. I am using drupal 7 and have no knowledge on php. Is there a way to achieve this without doing any coding? Any help would be highly appreciated.

You do not need two separate views for that.

Step 1: Install Address Field Module

Step 2: "Create a content type let say "Pharma Shops" , add adress field to this content type.

Step 3: Add some nodes to this content type, so you can see the results filtering with your views.

Step 4: Create view of type content for "Pharma Shops", add fields you want to show for the nodes in the display and search to find views setting for exposed filters,where again you will be exposing address field to all users to filter down the results.

As a Note: Consider view as ui to make database queries.


Using Feeds module to import to User_Reference fields? I'm been trying to come up with a mechanism to insert/update certain nodes in our Drupal system.  When I try to do the field mapping in Feeds most of the fields are listed and selectable.  But, for those fields which are defined as User_Reference fields, they ARE NOT listed in the target field list.  I can find no other reference to this.

So, how does/can one map a csv field to a user_reference type field defined in a content type?

TIA

Did you try patch from this thread?

The patch is http://drupal.org/files/userreference-mapper-748582_0.patch.


Kint works in pre_process but not in Twig On my site, I'm able to use print variables using kint in my pre-process functions.

However, when I try to do the same in twig, nothing happens.  I do have debug mode turned on.  Has anyone ever ran into this fact pattern? Any ideas?

To clarify:

It does not work in any of my templates
The specific template I'm using is for styling the output of a view, which is a page and has unformatted HTML as its type.

This is how I use kint  kint()

This is what I have seen on tutorials.

In php you use kint like this, kint($variable), but in twig you use kint like this, {{ kint(variable) }}.

This is the only problem I can spot by looking at your question.

Hope it helps.


Understanding behaviors I created a custom theme (a sub-theme of Radix base theme).

I am loading a custom Javascript file (radix_sub.script.js) using the module libraries.yaml file like below:

style:
  version: VERSION
  css:
    theme:
      assets/css/radix_sub.style.css: {}
  js:
    '//cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js': { type: external }
    '//stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js': { type: external }
    assets/js/radix_sub.script.js: {}
  dependencies:
    - core/drupal
    - core/jquery
    - core/jquery.once
    - core/drupalSettings

In that file, I want to register some JavaScript events (Bootstrap modal).

(function ($, Drupal) {

  Drupal.behaviors.portfolio = {

    attach: function (context) {

      console.log('CONTEXT', context);

      $('#portfolioModal', context).once('bootstrap-modal-shown', console.log('*** REGISTER SHOWN.BS.MODAL')).each(function () {
        $(this).on('shown.bs.modal', function () {
          console.log('SHOWN BS MODAL EVENT TRIGGERED');
        });
      });

      $('#portfolioModal', context).once('bootstrap-modal-hidden', console.log('*** REGISTER HIDDEN.BS.MODAL')).each(function () {
        $(this).on('hidden.bs.modal', function () {
          console.log('HIDDEN BS MODAL EVENT TRIGGERED');
        });
      });
    }
  }
}(jQuery, Drupal));

It works. I see both SHOWN BS MODAL EVENT TRIGGERED and HIDDEN BS MODAL EVENT TRIGGERED logs when I show/hide the modal.

First, am I doing that the correct way?

This is what my developer console looks like when I load my page.

This happens only when I am logged in (as admin). When I am anon, I see the REGISTER logs only once but here my code seems to be executed 11 times.

Is this normal behavior? And/or why is it doing that?

The answer lies here:

$('#portfolioModal', context).once('bootstrap-modal-shown', console.log('*** REGISTER SHOWN.BS.MODAL'))

The code that comes after the call to $.once() will only be executed once. However, $.once() can and will be executed multiple times. That's why you are seeing your calls to the console being called multiple times. If you change this:

$('#portfolioModal', context).once('bootstrap-modal-shown', console.log('*** REGISTER SHOWN.BS.MODAL')).each(function () {
  // Do some stuff.
});

To this:

$('#portfolioModal', context).once('bootstrap-modal-shown').each(function () {
  console.log('*** REGISTER SHOWN.BS.MODAL');
  // Do some stuff.
});

You will see that your call to the console is only shown a single time.
Note that you also will not use $.on() here, as the Drupal behaviors API replaces any necessity of it. Each time Drupal.behaviors are executed, a context argument is passed to it. This will be either the full DOM, or any HTML being newly inserted into the DOM. So where in normal jQuery you might do this:

$(".some_selector").on(someCallbackFunction);

In Drupal, you would do this:

Drupal.behaviors.someArbitraryKey = {
  attach: function(context) {
    $(context).find(".some_selector").once("some-arbitrary-key").each(someCallbackFunction);
  }
};

This is the Drupal way of achieving the same goals as using $.on() in normal jQuery, while tying in with the Drupal APIs.

---- Edit ----

Original answer below, which turned out to not answer the question. Left for posterity's sake, and because it actually adds on well to the end of the above answer.

Drupal behaviors are called on page load. It is also called upon AJAX load. You need to wrap code in $.once() if it should only be executed a single time:

function someElementListener(context) {
  // Call to $.once():
  $(context).find(".some_selector").once("arbitrary-key").each(function () {
    // Code here will only be executed a single time on
    // each .some_selector element found
    $(this).click(function() {alert("clicked");});
  });
}

Drupal.behaviors.someModule = {
  attach: function (context) {
    someElementListener(context);
  }
};

If you wrap your code in $.once(), your console calls will only be logged a single time.


Could someone explain the 'hit' and 'miss' status in memcache per page output? I've instructed memcache to append stats to each page. Someone did an excellent job explaining the memcache reporting page. However, I've since stumbled upon this appended information shown below and am curious.

Specifically what are miss and hit status?

(enlarge picture)

The hit/miss statuses are the result of the cache being touched as the result of the operation. For the given operations:

Get: (for a single key) Hit: data was retrieved from the cache; Miss: data was found not in the cache.
Set: Hit: data was stored in the cache; Miss: data was not stored in the cache.
GetMulti: (for multiple keys) Hit: data was retrieved in the cache; Miss: data was found  not in the cache.
Delete: Hit: data was removed from the cache; Miss: data was not removed (for a missing key) in the cache.


Panels default content when creating a new page When I'm creating a new panel page within the Panels module I want the new page to automatically load up with the content and layout and settings of my default site template.

For example, I want the site name, logo, main menu and a few other things to show on every single page without manually adding it every time I create a new page.

Should I not be creating a new Panel page for each section of my site?

You want to create a new page by cloning (AKA copying) the one you've already made with all your content/layout/settings chosen.

Under admin/structure/pages, navigate to the Edit form for the page you've already created and would like to replicate (See screenshot).

Then, click on the Clone button on the top, right-hand menu of the page's Edit form (See screenshot).

Then just follow the wizard's instructions for cloning the page. Once you've cloned the page, you'll have a brand new page with all the same content, layout, and settings as the previous one.


View statistics with colorbox module So I'm building a community website for a local photography group and I'm trying to set up a "well equiped" group photo grallery that registered members can upload photos to. The gallery should include basic gallery features such as a view counter, to record how many people viewed a certain image. As well as the ability to comment on the photo.

I am a complete Drupal noob, this is my first Drupal project migrating over from WordPress because I believe Drupal has better flexibility and features as a CMS. I've created a view for our gallery, and am using the colorbox module for a stylish and professional presentation of the photos when clicked. I am also using the statistic module.

The road block I am at is that using the statistics module in partnership with the colorbox module image views are not being recorded. I believe this is because when you click on the image you don't actually navigate to the node, instead the image is pulled from the node and displayed in a colorbox modal. So, no matter the web traffic to the gallery and the photos being clicked or not, it always displays 0 views.

Is there a way to make it so when a image is clicked in the gallery and colorbox presents the image to the viewer it counts as a view?

The in-progress site I'm working on is beta.semiphoto.org The gallery can be found here. Please don't judge, I haven't addressed themeing and am still learning drupal. :-)

You cannot since colorbox calls the image directly and not through a node page to register the hit. Your going to have to custom code in a js script. when an image is clicked it would report back to the server via ajax to record that hit per image.


How to make exposed filters more readable in the URL? I'm trying to make my URLs a bit more readable (and persistent) which includes query parameters of a view's page. Usually the URL would look like this when I define an exposed filter which is addressed by the parameter vocabulary-foo: https://www.example.com/view?vocabulary-foo[]=1234. As you might have noticed, this is a filter for taxonomy terms of a specific vocabulary. There are two problems with the usage of IDs in the URL, which I'd like to solve:

If I uninstall my custom module that creates the taxonomy terms, these are gone and will get another ID when I install the module again. So I can't assume a link to a specific filtered view page would then still be the same.

It's not readable (and memorizable). Using the term's value instead of the ID would probably already help me. On the other hand, if it is possible to define a query parameter preset=something which translates to vocabulary-foo[]=<The id of the term which has a specific value>, I'd rather do that as it enables me to combine multiple query parameters to one preset, which makes it shorter.

In my specific case, the view exposes a form which can be used to search for content. A preset as described would pre-select some form controls with only one clean URL parameter.
One idea that came to my mind was somehow using PHP's $_GET variable and conditionally changing its content before the view is created. Unfortunately, I don't know which hook would be suitable for that.
Has somebody faced a similar issue in the past? How could I solve these problems in Drupal 9? Thanks!

There's no easy way to do that .. views better_exposed_filters is quite nice, but does not provide clean urls. Drupal 7 had query_parameters_to_url, for Drupal 8 they link to a sandbox! project ... This may be a starting point for you.
There may be a simpler approach here: Redirect based on query string using a redirect event subscriber:
<?php
    static function getSubscribedEvents()
    {
        $events[KernelEvents::REQUEST][] = array('Redirect', 20);
        return $events;
    }

So you could provide at least clean urls to "somewhere".


Drupal Commerce: IPN received - When order paid in full not triggered Problem

I'm testing on a live website and the trigger "When an order is paid in full" is not triggered by Paypal. I'm receiving the IPN and the payments are successful. Is there some set-up I'm missing?

Set-Up

I have Drupal Commerce and Commerce Paypal installed, I've got the latest versions of both of them and rules.

I'm using Paypal Sandbox for my payments and it's the only payment method. It's set-up according to http://www.drupalcommerce.org/user-guide/paypal-standard.

The payments are being paid and received in the sandbox.

I'm receiving the IPN's (here's the latest one from admin/reports/dblog) so why is the trigger not firing?

[mc_gross] => 12.38
[invoice] => 21-1380584852
[protection_eligibility] => Ineligible
[item_number1] =>
[payer_id] => ARQWQ9YGG73F4
[tax] => 0.00
[payment_date] => 16:46:30 Sep 30, 2013 PDT
[option_selection1_1] => 1
[payment_status] => Completed
[charset] => windows-1252
[mc_shipping] => 0.00
[mc_handling] => 0.00
[first_name] => Dominic
[mc_fee] => 0.62
[notify_version] => 3.7
[custom] =>
[payer_status] => verified
[business] => captain12a@msn.com
[num_cart_items] => 1
[mc_handling1] => 0.00
[payer_email] => captain14a@hotmail.co.uk
[verify_sign] => AiPC9BjkCyDFQXbSkoZcgqH3hpacAQf5aelWDuTPmoMQ5vx5hMDCzulp
[mc_shipping1] => 0.00
[tax1] => 0.00
[option_name1_1] => Product count
[txn_id] => 7Y390707M1183591C
[payment_type] => instant
[last_name] => Woodman
[item_name1] => Order 21 at drupaltest2
[receiver_email] => captain12a@msn.com
[payment_fee] =>
[quantity1] => 1
[receiver_id] => 2FHV6QVKKQXY4
[txn_type] => cart
[mc_gross_1] => 12.38
[mc_currency] => GBP
[residence_country] => GB
[test_ipn] => 1
[transaction_subject] =>
[payment_gross] =>
[auth] => A41o8UNEox9bol5SH7hvw4jIMV-gR-9qubh3WKMZ9hmLr7oTiHMUATibYSUjrjlHHqDUlwDOlwNt10ZLGJt8xDw

(I checked the trigger using ZioBuddha's idea and it works fine for cheque's)

It randomly started working. Here's what I did to debug in-case it helps someone else:

IPN only works on a live server not a localhost. Paypal can't talk to localhost.

Debug on Drupal Side - In Payment Rules

Enable Log notifications with the full IPN during validation and processing (used for debugging).

It'll get stored at example.com/admin/reports/dblogs. You can see a sample IPN in my post.

I was originally getting the IPN in a log that looked like:

commerce_paypal_wps  |  1 Oct 2013 - 12:48am  | Customer returned from PayPal with the following POST...  |   username

That log contained the IPN in my original post.

Paypal Settings

You don't need to enable IPN notifications because the module does it automatically when it needs to. But if you do then you can view your history and see if they were getting sent. (I put example.com in the PayPal URL field.)

The only thing I did here was try re-sending an IPN.

What you should have

When it works your log should have something like this in it

commerce_paypal      |  1 Oct 2013 - 11:46am  |  Attempting to process IPN 7Y390707M1183591C. Array...   |  Anonymous (not verified)
commerce_paypal_wps  |  1 Oct 2013 - 11:46am  | IPN validated for Order 21 with ID 7Y390707M1183591C...  |  Anonymous (not verified)
commerce_paypal_wps  |  1 Oct 2013 - 11:46am  | IPN processed for Order 21 with ID 7Y390707M1183591C.    |  Anonymous (not verified)


How do I record hook_menu() access statistics I have a standard menu hook function in a custom module which links to example.com/foo/bar, how do I record access statistics for this page?

There is no build in stat counter for this. Here is a workaround:

<?php
function mymodule_menu() {
  $items = array();
  $items['foo/bar'] = array(
    'title' => 'example',
    'page callback' => 'mymodule_foo_bar',
    'access callback' => 'mymodule_foo_bar_access_with_stat_counter',
    'access arguments' => array('Something', 'Something else'),
  );
}

function mymodule_foo_bar_access_with_stat_counter($something, $something_else) {
  //Log your stats here!
  // goddess_logs_stats_here($something, $soemthing_else);
}


How to "flag" product that had already been purchased before "flaging feature" was added? In reference to this question and answer: How to mark product if it has already been purchased by current user?

Now that I know how to "flag" the items in a way that lets me notify customer to avoid situation where customer buys two of the same product, remains one more question:
How can I now mark or "flag" all the products, that had already been purchased before the flaging feature was added to the shop?

If you can think of a way to create a view which contains 1 row for each product and the user who actually bought such product, and which wasn't flagged with this "already purchased" flag, then you can use such view as part of an actual solution for your question. In that case, you could get this to work by using the integration of VBO with the Rules module, as further detailed below.

Step 1: Create a Rules Component

Create a (rather basic) Rules component to flag a product by a user. Here is a variation of such component in Rules Export format (which processes nodes instead of products):

{ "rules_flag_node_by_a_user" : {
    "LABEL" : "Flag node by a user",
    "PLUGIN" : "rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "flag", "rules" ],
    "USES VARIABLES" : {
      "flagging_user" : { "label" : "Flagging user", "type" : "user" },
      "flagged_node" : { "label" : "Node to be flagged", "type" : "node" }
    },
    "DO" : [
      { "flag_flagnode" : {
          "flag" : "your_flag",
          "node" : [ "flagged-node" ],
          "flagging_user" : [ "flagging_user" ],
          "permission_check" : "1"
        }
      },
      { "drupal_message" : { "message" : "Node flagged for user  [flagging-user:name] (uid=[flagging-user:uid])" } }
    ]
  }
}

This Rules Component uses a flag with machine name your_flag. After you edit that machine name to fit the name of your flag, you should be able to import this rule in your own site (using the Rules UI, which needs to be enabled). You can then adapt (or clone) it to make it work for your products instead of for nodes.

BTW: the Rules Action to display a message is just to see it at work while QA-testing this rule, feel free to remove that if you want.

Step 2: Let VBO do the work

This step is pretty easy ... Just build an appropriate view (of all products that still need to be flagged) and transform it in a VBO view. The clue to what you want VBO to do as an operation is ... Execute the Rules Component from Step 1. Be aware: when creating that VBO view, you really need
to create a view to "List Commerce Products".

If your Rules Component (= variation of the one in Step 1, where you flag products instead of nodes) cannot be selected as the VBO-action to be performed, then it might be because you need to change the order of the parameters used by the Rules Component: make the flagged_node (or flagged_product in your case) the very first parameter. This might be needed because it's a Rules Component with several parameters, and only the first one will be auto-populated by VBO. That might help to be able to select that Rules Component as your VBO action.

If you're not familiar with how to use VBO, have a look at the video about Using Rules components with VBO". If you want even more, then also watch the subsequent "Using Rules components with more than one parameter" video.

Attention: to process like 100.000 records at once is quite a challenge (memory requirements, etc). Therefor you might want to also watch the video about "More details about VBO settings" ... Before you are tempted to use VBO for processing them all at once ...

Video tutorials

If you're not familiar (enough/yet) with Rules, checkout the 32 (!!!) great, and free, video tutorials Learn the Rules framework.

Happy VBO-ing while Rules-ing!


Migrate Alt and Title text from a D6 image file field to D8 I'm trying to migrate a multi-value D6 image field to D8. I've already migrated the files with d6_file and it worked. When I do the node migration with the image field works and I get all the values but the alt and title text are not migrated.

  field_image:
    plugin: sub_process
    source: field_image
    process:
      target_id:
        plugin: migration_lookup
        migration: upgrade_d6_file
        source: fid
      alt: alt
      title: title

So this worked for me not sure why. But my file migration id was upgrade_d6_file and when I change this in line 54 of Drupal\file\Plugin\migrate\process\d6\FieldFile and ran the migration with the settings below I got the correctly referenced files and the alt/title text.

Diff

  // Configure the migration process plugin to look up migrated IDs from
  // a d6 file migration.
  $migration_plugin_configuration = $configuration + [
-   'migration' => 'd6_file',
+   'migration' => 'upgrade_d6_file',
    'source' => ['fid'],
  ];

Migrate yml

field_primary_image:
    plugin: d6_field_file
    source: field_image
    process:
      target_id:
        plugin: migration_lookup
        migration: upgrade_d6_file
        source: fid
      alt: alt
      title: title

Or even better is write your own process plugin like this: https://github.com/mikeryan776/d8-migrate-example-001/blob/master/migrate_carlyle/src/Plugin/migrate/process/CarlyleCckFile.php


Are page caching and cache tags related? I'm working with a site which has page cache enabled.
I'd like the page cache for any given node to invalidate when that node is changed. There's a lot of examples out there dealing with cache tags, but I haven't had any luck figuring out the relationship between page caching and cache tags.
I've got a node which starts out being published. I then unpublish it, and publish it again. When I publish it for the second time, the page cache still treats it as unpublished. It does so until i clear the entire (page) cache.
It seems that the cache_page entry is updated when i update a published node, but whenever the node goes from unpublished to published - the page cache entry doesn't follow.
I've tried implementing hook_entity_update and do a Cache::invalidateTags(['node:19']);, but that had no impact.
Is it possible to use cache tags to invalidate page cache entries?

Page cache is just the cached values.
Cache tags are tags that are attached to a cached value (simplifying a little bit). This tells Drupal what cached values are related to what cache tags. When a cache tag is invalidated, all cached values that have the invalidated cache tag are invalidated as well. You can find more info on the Drupal documentation page about Cache Tags. The headline is:

Cache tags provide a declarative way to track which cache items depend
on some data managed by Drupal.

So, answering your question, yes, they are totally related and you can (and you should) invalidate page cache entries using cache tags. Because, as stated above, cache tags track content and cache dependencies and thus you can invalidate cached item when content (or the source data of a cached item) changes.
However, this can be tricky. For example, page cache entry of a node view page is always associated with the cache tag node:[nid]. When the node is updated, that cache tag is invalidated, thus making the page cache of that node's view page invalidated as well. Views that shows a list of nodes are not associated with each node's cache tag. Blocks are other display elements may not be related to that kind of tags. So you need to know which cache tag you want to invalidate.
The good news is Drupal takes care of the most common cases, so you don't have to care. Usually, you only need to deal with the cache tags when you are developing custom code.
In your case, you may be hitting another cache (browser cache? reverse proxy cache?).


How do I delete nodes older than X days? Does anyone have a snippet for deleting nodes that are older than 1 day? I would like to run this on cron tasks.

I had problems with D7 using Auto Expire, and ended up using HOOK_cron() in a custom module:

function mymodule_cron() {

// we only want to deal with messages (a content type)
$message_type = "message";

// grab all messages
$message_nodes = node_load_multiple(array(), array('type' => $message_type));
// set up the timestamp for the expiry
$message_search_date = strtotime("- 30 days"); // UNIX timestamp for 30 days ago

// now loop through messages, & if they are old, expire them
  foreach($message_nodes as $m) {

    $obj = entity_metadata_wrapper('node', $m);

    // when was it last updated, & is it still published?
    $last_update = $obj->changed->value();
    $published = $obj->status->value();

    // if it's still published & it's not recent, then unpublish it
    if(($message_search_date > $last_update) && $published<>0) {
        $obj->status = 0;
        $obj->save();
    }
  }
}


Command entity-updates needs a higher bootstrap level to run I am trying to make drush work on Debian 8 with Drupal 8.

Unluckily, executing drush entity-updates returns the following error messages:

  Command entity-updates needs a higher bootstrap level to run - you will need to invoke drush from a more functional Drupal environment to run this command.
  Command entity-updates requires Drupal core version 8+ to run.
  The drush command 'entity-updates' could not be executed.

drush -vd status executed from .../sites/default returns the following:

.../sites/default# drush -vd status
Starting Drush preflight. [0.04 sec, 2.09 MB]                        [preflight]
Loading drushrc "/etc/drush/drushrc.php" into "system" scope. [0.04  [bootstrap]
sec, 2.09 MB]
Cache MISS cid: 7.1.0-commandfiles-0-81cc86c1995ab7206f383ec28ad43baf    [debug]
[0.09 sec, 2.14 MB]
Cache SET cid: 7.1.0-commandfiles-0-81cc86c1995ab7206f383ec28ad43baf     [debug]
[0.12 sec, 2.16 MB]
Bootstrap to phase 0. [0.53 sec, 6.04 MB]                            [bootstrap]
Found command: core-status (commandfile=core) [0.54 sec, 6.05 MB]    [bootstrap]
Loading outputformat engine. [0.54 sec, 6.06 MB]                        [notice]
Calling hook drush_core_status [0.55 sec, 6.11 MB]                       [debug]
Returned from hook drush_core_status [0.55 sec, 6.11 MB]                 [debug]
 PHP executable         :  /usr/bin/php
 PHP configuration      :  /etc/php5/cli/php.ini
 PHP OS                 :  Linux
 Drush script           :  /root/.composer/vendor/drush/drush/drush.php
 Drush version          :  7.1.0
 Drush temp directory   :  /tmp
 Drush configuration    :  /etc/drush/drushrc.php
 Drush alias files      :

Command dispatch complete [0.63 sec, 6.25 MB]                           [notice]

Running drush sqlc executed from .../sites/default results in:

Unable to load class Drush\Sql\Sql                                   [error]
exception 'Drush\Sql\SqlException' with message 'Unable to find a    [error]
matching SQL Class. Drush cannot find your database connection
details.' in
/root/.composer/vendor/drush/drush/commands/sql/sql.drush.inc:597
Stack trace:
#0
/root/.composer/vendor/drush/drush/commands/sql/sql.drush.inc(454):
drush_sql_get_class()
#1 [internal function]: drush_sql_cli()
#2 /root/.composer/vendor/drush/drush/includes/command.inc(359):
call_user_func_array('drush_sql_cli', Array)
#3 /root/.composer/vendor/drush/drush/includes/command.inc(210):
_drush_invoke_hooks(Array, Array)
#4 [internal function]: drush_command()
#5 /root/.composer/vendor/drush/drush/includes/command.inc(178):
call_user_func_array('drush_command', Array)
#6
/root/.composer/vendor/drush/drush/lib/Drush/Boot/BaseBoot.php(62):
drush_dispatch(Array)
#7 /root/.composer/vendor/drush/drush/drush.php(70):
Drush\Boot\BaseBoot->bootstrap_and_dispatch()
#8 /root/.composer/vendor/drush/drush/drush.php(11): drush_main()
#9 {main}

I have read other topics but none of the solutions seems work.

I have installed Drush according to instructions provided here How to install drush 8 properly on Debian 8?.

Same problem here.

In my case I discovered that drush uses native mysql commands, not php lib. Then I've installed by

  apt-get install mysql-client

and works great.

For windows users, I think must install mysql cli commands here.


Design query for job site using subdomains I'm designing a job site in D7. Ideally for better SEO each state or city should be in separate subdomain(this what I've learnt).

For city Paris it'd look like: paris.myjobsite.com

I'd post jobs using taxonomy categorization e.g. city,state, zip code, field, salary, qualifications.

Now I can host a new Drupal site on each sub domain so for 100 city/states it'd have 100 separate Drupal databases using multi site setup.

The other solution is to have a rewrite rule translating subdomain to site's internal url.

I'm unable to think beyond this.

I'd appreciate help as to how this design issue can be met in Drupal.

You are looking for Purl, and would perhaps also benefit from using Spaces.


Fatal error: Call to a member function difference() on string in error on tpl file I'm trying to calculate the value between two fields in my custom node.tpl file. I am trying to convert the code show on http://drupal.org/node/1364744, and I wrote the following one.

$birthday = format_date(strtotime($content['field_date_de_naissance']['#items'][0]['value']), 'custom', 'd/m/Y');
$today = date('m/d/Y');
$age = $birthday->difference($today,'years');
print $age;

I get this error.

  Fatal error: Call to a member function difference() on string in

What is wrong in my code?

The error is calling a method (difference()) on a string, while just PHP objects and classes implements methods. format_date() is documented to return a string, not a DateObject.

  Return value

  A translated date string in the requested format.

The code I would use depends from what modules you have installed, and which PHP version you are using.

If you have the Date module installed, and you enabled the Date API module, I would use the following one.

$birthday = new DateObject($content['field_date_de_naissance']['#items'][0]['value']);
$age = $birthday->difference(date_now(), 'years');

If you don't have the Date module installed, but you have a recent version of PHP 5 (which means higher than 5.2.0), then I would use code similar to the following one.

$birthday = new DateTime($content['field_date_de_naissance']['#items'][0]['value']);
$age = $birthday->diff(new DateTime())->format('y');

If you are still using a PHP version lower than 5.2.0, or you just want code you can use without to worry about the PHP version, I would use the following code.

$birthday = strtotime($content['field_date_de_naissance']['#items'][0]['value']);
$age = format_interval(time() - $birthday, 1);

I am not using format_date() since it returns a translated string, which is not necessary to strtotime() (and probably, it would confuse it).
format_interval() consider a month made of 30 days; for this reason, the code shown above is probably giving a different value than the other methods.

Reference

DateTime::__construct()
DateTime::diff()
DateInterval::format()
format_date()
format_interval()


Issue with Entity Reference and Views I'm needing to change the 'Entity Selection' mode on an entity reference field for a content type from 'Simple' to 'Views: Filter by an entity reference view'.

However, the 'Views: Filter by an entity reference view' option does not appear. 'Simple' is the only option. I have tried creating new test fields to see if it's an issue with that particular field, however this issue persists across new fields as well.

Additionally, I've noticed that if I try to create a new view, the option to change the display type to 'Entity Reference' is also missing.

I've been unable to determine what is preventing these options from appearing, and I'm wondering if the issue might be with either the Entity Reference or Views modules themselves. I haven't been able to locate someone with a similar problem on Stack Overflow or the Drupal forums yet.

Any thoughts on what I might be overlooking that could be causing this?

Looks like it was an issue with the Entity Reference module after all.

This site is part of a multi-site setup that was using an older version of Entity Reference which I was hesitant to update due to potential repercussions. After updating the module, everything is working as intended.


Form submit handler not working I'm developing a pretty basic module catalog_request that creates a form. I'm replacing the form's default submit button <input ..type="submit" /> with a <button ...>click</button> using following in form definition.

function catalog_request_form($form, &$form_state) {

    /**
     * form fields here
     */

    $form['fieldset_submit']['the_submit_button'] = array(
       '#type' => 'markup',
       '#prefix' => '<button class="btn submit">',
       '#markup' => 'Send Request...',
       '#suffix' => '</button>',
    );

    /* ... */
}

and have defined other two form related functions

function catalog_request_form_validate($form, &$form_state) {
    drupal_set_message(t('The form was validated'));
}

function catalog_request_form_submit($form, &$form_state) {
    die('submitted');
    //drupal_set_message(t('The form was submitted'));
}

The problem

My submit function catalog_request_form_submit isn't being called. I've read numerous articles online but none resolved my issue. Following didn't work

Adding '#submit' => 'catalog_request_form_submit', to
the_submit_button key
Adding '$form['#submit'] => 'catalog_request_form_submit'; to end
of catalog_request_form function
Adding '$form['#submit'][] => 'catalog_request_form_submit'; to
end of catalog_request_form function

I've read that adding something along the lines of $form['actions']['#submit'][] = 'custom_function'; could solve the problem but I'm not sure how to adapt it for my form.

I know that having '#type' => 'submit' for the submit button makes the form work but I want a button tag.

My problem is exactly When altering the submit button, the form does not work but it doesn't have a solution (only an answer that ignores the question's point)

P.S. I do not develop for drupal frequently so I might be missing something very obvious.

Any help will be greatly appreciated. thanks

In order to add another submit handler you have to add something to hook_form_alter(): check for your particular form ID, and then add a submit handler in one of the following ways:

OPTION 1:

To add a submit handler that is called as the next callback after processing the default submit handler callback you can use this:

function mymodule_form_alter(&$form, &$form_state) {
  if ($form_id == 'form-id-of-your-form') {
    $form['actions']['submit']['#submit'][] = 'mymodule_whatever_function';
  }
}

OPTION 2:

If OPTION 1 is not working for you, replace the third line with this:

form['#submit'][1] = 'mymodule_whatever_function';

This will add a second submit handler, or replace the second one with yours if there is already more than one.

OPTION 3:

To remove the default submit handler completely (so that "nothing will happen" on submit, or so that you can replace it with your own), use code like this:

function mymodule_form_alter(&$form, &$form_state) {
  if ($form_id == 'form-id-of-your-form') {
    unset($form["actions"]['submit']);
  }
}


Solution for preventing indexing of content types? I have a custom content type that I simply want to not be indexed by the Drupal search engine.  Yes, I can hide it from the search results, but there are hundreds of thousands of these nodes and rebuilding the index takes days.  After much searching and trial/error, I came across this solution from ChrisPliakus.

You can see my query below in the update_index hook, where I exclude MY_CONTENT_TYPE from the query. I've tested the query manually and it seems to show nodes other than the one I want to ignore, which I think is the goal there.

However, when I run drush cron --verbose, I still see those nodes getting indexed :(

/**
 * Implements hook_module_implements_alter().
 */
function MYMODULE_module_implements_alter(&$implementations, $hook) {
  if ('update_index' == $hook) {
    unset($implementations['node']);
  }
}

/**
 * Implements hook_update_index().
 *
 * @see node_update_index().
 */
function MYMODULE_update_index() {
  $limit = (int) variable_get('search_cron_limit', 100);

  $result = db_query_range("SELECT n.nid FROM {node} n LEFT JOIN {search_dataset} d ON d.type = 'node' AND d.sid = n.nid WHERE (d.sid IS NULL OR d.reindex <> 0) AND n.type != 'MY_CONTENT_TYPE' ORDER BY d.reindex ASC, n.nid ASC", 0, $limit, array(), array('target' => 'slave'));

  foreach ($result as $node) {
    _node_index_node($node);
  }
}

Any ideas?  Thanks in advance!

Rather than coding a custom solution, I would use a supported module. The answer I believe will help you: Restrict Drupal Search to few content types

So for Drupal 7 you can use Custom Search, Search Config or Search API Exclude if you are using Search API. For Drupal 8 you can use Search Exclude.


Why are users seeing edit pages outside of Admin UI I just tested the editorial process for authors on our new web site.  For some reason, although admins and editors see pages in the normal Admin UI (using the Seven theme) when editing a page, members of the author role see it in the public UI that displays for non-logged-in users browsing the web site.

At /admin/appearance I have Administration theme set to Seven, and I have 'Use the administration theme when editing or creating content' checked.

Why would this setting take effect for admins and editors, but not authors?

D'oh.  I somehow missed this before in the permissions:

View the administration theme

Admins and editors had this permission enabled, but authors did not.  Enabling it for authors fixed things.


Change page.tpl.php in a shared theme based on domain I keep finding snippets like this:

function MYTHEME_preprocess_page(&$vars) {
  $alias_parts = explode('/', drupal_get_path_alias());

  if (count($alias_parts) && $alias_parts[0] == 'mydirectory') {
    $vars['theme_hook_suggestions'][] = 'page__mycustomtemplate';
  }
}

But, what I'm trying to figure out is how to switch to a different page.tpl.php file entirely within the same theme when a domain is different.

So if I had:

http://www.example1.com/stuff AND

http://www.example2.com/stuff

Using domain access module and other rules, the content is slightly different for example1 than example2 but the paths are identical so I can't simply access arg[0].

The ham-fisted way is to dupe the theme, change the name and be on my way but I'm sure I'm not getting something...the actual basic page.tpl.php template has to be modified because of existing content at the same path but different domain.

On example1, there are no side bars for example so those regions are not in the .info file nor rendered but on example2, there are sidebars. However, since I want to apply an existing theme, I just thought I'd restructure the actual page.tpl.php file for example2 so as to keep the majority of css/jquery and custom html implemented into the theme.

Is this more trouble than just duping the theme, rename and make the changes there?

You could do aomething like this:

function MYTHEME_preprocess_page(&$vars)
{
    $domain = domain_get_domain();

    $vars["theme_hook_suggestions"][] = "page__" . $domain["domain_id"];
}

Feel free to explore what other values are in the $domain array and use it accordingly to make your theme suggestions as complicated as required. The above example is just to demonstrate injecting domain information.

There are developer notes on the Domain Access module as well which you may find useful


How to place a block in two different regions? Working on a project I faced with a problem , in this project the front page looks completely different than the other pages and it consists some regions which are not exist in other pages.

Now the problem is that when I put an instance of a block in a region which only exist in front page then I cant use this block in other pages.Any idea how to solve this problem?

As stated above you can certainly use Multiblock but the are a few other ways as well.

One is to use the Context module where you can create different contexts where any given context can render the same block or sets of blocks but with different conditions.

The other method I use is to use the module_invoke function. You could invoke the module and block in a node or page preprocess function by creating a variable for the block display and then call the variable in a node or page template. An example would be something like this:

In your theme's template.php file. This example calls the Disqus module's comment block:

/**
 * Override or insert vars into the node template.
 */
function mytheme_preprocess_node(&$vars) {

  // Define the node.
  $node = $vars['node'];
  $nodetype = $node->type;

  // View mode check (Optional).
  if ($vars['view_mode'] == 'full') {

    // Content type switch check.
    switch ($nodetype) {

      case 'blog_post':
        // Disqus comments block.
        $block = module_invoke('disqus', 'block_view', 'disqus_comments');
        $vars['block_disqus_comments'] = $block['content'];
        break;

    }
  }
}

Here we created a template variable called block_disqus_comments for use in a node template. This calls a block that was created by the Disqus module called disqus_comments. You can now call that on one region in one template and in another region within another template. We set a case of the content type blog_post but theoretically you could add other content types or conditions depending on your needs.

We then can render this in our blog node template as:

<div class="disqus-wrap">
   <?php print render($block_disqus_comments); ?>
</div>

The nice thing about either of these methods is that they can be carried forth in code and sent to your code repo via Git. (For Context, you would need the Features module to do that).


Image link in views exposed filter gallery I created a content type which contains among other infos, some pictures

I'm using views with exposed filters to render them on the page (the images are thumbnails)

How can i create a link on the thumbnails that will start a gallery (big pop-up modal img slider) that include only the pictures in each content?

Here is what i can link pictures to atm (i'm looking for some other options for this drop down menu)

Try  the Colorbox module; it is great and very configurable, and it has also an image-format option for the Views module.


How to filter a View by Date Range (start, end)? In Drupal 7 with Views an Date module enabled, it was pretty easy to filter a view by Date: The UI just gave you the option to do so.

In Drupal 8, however, the date field and views are part of core, but if you choose a date range field as filter in views it does not offer you date specific options anymore, but shows you only filtering options for text fields:

The date specific options, however, are available for internal date values like ´Content: Changed´

As I would like to show only specific nodes, with a date before or after the actual date, where the date is specified by a custom date range field, this does not suit my needs.

How can I filter a view in Drupal 8 by a date field with date specific operations?

Surprisingly this is not possible with Drupal 8 yet. But there is a long history of trying to make it work: https://www.drupal.org/node/2786577
The last patch, you find in this post, seems to work. You can download and apply it, using the following commands:

wget https://www.drupal.org/files/issues/improve_the_views-2786577-76-core.patch
git apply improve_the_views-2786577-76-core.patch

If git isn't available on your server, try:

patch -p1 < improve_the_views-2786577-76-core.patch

TO apply the patches you have to navigate to the core folder first. And be aware that you have to reapply this patch, after committing a core update. (This sucks!) So let us hope, the Drupal Gods will get this into core soon!


Content links are breaking I've been hired by a firm as an entry level developer/seo/content marketing person and part of my responsibility includes their Drupal (6.X) CMS. I'm working my way through the 'The Definitive Guide to Drupal 7' and I've been making only small iterative changes so far while I'm getting the hang of everything. Today though, I have a bit of an issue which I could use some help on.

Some of the content links are breaking and it is due (I believe) to the way they have Drupal configured as well as my own green-ness. For example, the site's content area (the <front>) is called www.drupal.com/blog but the name of the server that hosts Drupal is server.drupal.com. Newer content and some of the older content is being automatically aliased to server.drupal.com and so is only viewable when a user (admin) is logged in. So, when a video node is posted, it is aliased as, for example, server.drupal.com/videos/awesome-video but when www.drupal.com/videos/awesome-video is entered into the URL as an anon user it throws a 404. No bueno.

The URL Alias module automattically sets server.drupal.com as the default base pathway and only allows me to set the /videos/awesome-video part of the alias.

Your woes are most likely coming from apache (or whichever web server you are using) unless you are using the domain module. Either your .htacces file or virtual host (depending on whether you have "AllowOverride" on in apache) should be setup to route requests through 'example.com' and not 'server.example.com'.

Are you on a VPS or shared host? What flavor of Linux are you using?


Pathauto does not trigger on node_save when programatically creating nodes I am programatically saving nodes. From my reading, it sounds as if Path auto is trigged to autmatically create a URL alias when node_save() is called.  However, this is not happening.

I later read that I needed to set $node->path_set_alias = TRUE. However, this is not working correctly either.

Using 7.12 and the latest versions of pathauto.

Here is my code.

$node = new stdClass();
        //set other defaults
        node_object_prepare($node);

        $node->type = $page_data['content_type'];
        $node->body[LANGUAGE_NONE][0]['value'] = $page_data['description'];
        $node->body[LANGUAGE_NONE][0]['summary'] = text_summary($page_data['description']);
        $node->body[LANGUAGE_NONE][0]['format']  = 'filtered_html';
        $node->title = $page_data['title'];
        $node->field_product_price[LANGUAGE_NONE][0]['value'] = $page_data['price'];
        $node->field_item_location[LANGUAGE_NONE][0]['postal_code'] = $page_data['zipcode'];
        $node->uid = "1";
        $node->status = 1;
        $node->active = 1;
        $node->pathauto_perform_alias = TRUE;

    //the name of my actual field is 'product images'
    $node->field_product_images[LANGUAGE_NONE] = $images;
    unset($images);

    $node->field_baby_clothes_category[LANGUAGE_NONE][0]['tid'] = $page_data['category'];

    if($node = node_submit($node)) { // Prepare node for saving
        node_save($node);
}

Thoughts on how to get this to work correctly? Thanks!

We discussed on Drupal.org that not setting the $node->language property causes this issue to happen. Either setting $node->language = LANGUAGE_NONE or $node->language = 'en' should fix this.

Also using $node->path['pathauto'] = TRUE rather than $node->pathauto_perform_alias for Drupal 7.


Checking for User Role in Views Field with Twig I'm currently building a view, where different Links should be displayed in a field, based on the currently logged in users role.

I've read a bit into Twig, but haven't found anything similar yet (if it is even possible).

First, you should not do security by role.  It should be done by checking for a permission.

In general...Twig gets passed a user variable from Drupal that can be used for this.  There is a hasPermissions method.  Here's a sample code snippet.

  {% if user.hasPermission('administer eck entities') %}
      Add tab
  {% endif %}

If you must use roles, there should be an hasRole() method on the user object that is passed in.  (See User Object api docs)

For Views:

Views has limited twig like support in the GUI but does not support all the functions of the underlying twig functions.  To check for user permissions in a header, you will either need to use the hook_preprocess_views_view() or create your own view specific template, e.g. views-view--view-name.html.php in your theme. You will need to process the header (or footer) variables in these to get the permission specific info into the view.

If you want to limit specific fields, you can use the field specific hook and templates as well.


I just want to add a radio buttons to my content type I am creating a new content type in Drupal 7 and I would like to add some radio buttons as content types.  This is surprisingly difficult to do.  I have enabled field and options modules but I have yet to see radio buttons show up as an option for numeric or text fields.  How do I do this?

Update: I do not have 'select option' or 'list' as a select-able field type

You can choose the list field type - this will display radio buttons.  List core module will need to be enabled.


Programmatically publishing and unpublishing nodes: anonymous access We have several nodes that serve as open job postings which need to "open" and "close" on specific dates.
In order to accomplish this, we publish and unpublish them accordingly.

We have a query (based on publish unpublished node programmatically) that successfully updates both the node table and the node_revision table:

$result = db_query('update node n
JOIN field_data_field_jobs_date d ON d.entity_id = n.nid and d.revision_id = n.vid
JOIN node_revision r ON n.nid = r.nid and n.vid = r.vid
# Update the node_revision table
SET r.status = IF(
    (
    CURDATE() >= d.field_jobs_date_value
    AND
    CURDATE() <= d.field_jobs_date_value2
    ),1,0
),
# Update the node table
n.status = IF(
    (
    CURDATE() >= d.field_jobs_date_value
    AND
    CURDATE() <= d.field_jobs_date_value2
    ),1,0
)
# Only update our custom content type
WHERE n.type = \'job_posting\'');

This successfully updates the node status and node revision status in the database.

However, once a node has been published through this method, anonymous users still cannot see it (and are presented access denied if given a direct link to the node).

We have to manually edit each node and hit the save button for the published status to "take." This leads me to believe that we are omitting some sort of call to node access or something similar that updates the permissions on the node appropriately.

Any ideas besides the status field that may be preventing anonymous users from seeing programatically published nodes?

Most probably caching. Directly changing something in the database is, though the fastest, not really the safest / most reliable way of doing things in Drupal.

I'd suggest to use enity_query (or in this case even direct database access) to retrieve node ids of nodes you want to update and then use 'correct' drupal way of doing things -> load all the nodes, individually change their publish status and save them.

Something along these lines...

$nodes = node_load_multiple($nids);
foreach ($nodes as $node) {
  // set status property to 1
  $node->status = 1;
  // re-save the node
  node_save($node);
}


Ternary Flags? Or possibly cancelling flags In my Drupal site, users can be in 1 of 3 states. They will always be in one of these three states. This would be easy to do if the flag module could have three states. However, it only has 2. Is there a flag add on that allows for three states? Could I potentially have 3 flags that, when selected, cancel the others out? Or will I have to write my own module?

This is not available in the Flag module (as you already know) and won't be available in the future (Issue: Flag States).  I have not seen an add-on module that will allow you to do this either.

An easy way would be to use Flag with Rules.  You would have to create multiple flags to use, and when a user flags one of the states, have set rules to unflag the other 2 states.

Another option would be to write a custom module.  Maybe even utilize the Voting API


Where are entities stored in MySQL by default? Drupal 8 has a powerful entity API that manages all the content of the entities.

How can these entities be accessed outside of Drupal? Which are the tables and what is the format?

There's no default as such; each entity type defines its base table and field data table via the *EntityType annotation. See Structure of an entity annotation for examples.

The Entity API and its power don't just live in the database, there's also plenty of code involved to prepare things sensibly for the system to use inside a request.

With that in mind, you might consider that using the built-in REST API is a more efficient way to communicate with Drupal than direct database manipulation, which won't give you the full picture of an entity without re-implementing at least some of the PHP logic in SQL


Directly adding data in MYSQL tables made through drupal I have a simple three fielded (name, address, country) content in drupal. I have a csv containing 1,000,000 row lines of data. I need to fill up  all drupal content type I made with the csv data.

First, I used FEEDS module but the importing is unacceptably too long. I tried to insert the data directly into MYSQL (ex: field_data_field_name and field_data_revision_name). It is successfully inserted into MYSQL but it does not show/update in the DRUPAL content.

How to make the Drupal synchronize with the newly added data in the table of MYSQL?

Not sure but could you design your view fields [name, address, country] the way you want to use them. Then enter unique data.

Then look in the DB for the unique data to be sure you have the right fields.

After backup and site shut down you could import your csv right into mysql. With the db interface. Make sure you backup The tables before starting.

A bigger question perhaps is how will you work with the data.


How to display specific blocks for specific roles alone w.r.t domains and subdomains I want to display specific blocks for specific roles alone with respect to domains and sub-domains. I know i can give permission for roles in the block to be displayed.How do i differentiate anonymous users with respect to domain and sub-domains in the permission of roles. Help really appreciated.Thanks in advance:)

Hope this will help you,

In Drupal 7 you can use these modules

Domain Context - It allows administrators to set specific settings for each of their domains that are using the same code base.
Domain Blocks - Enables domain specific visibility settings for blocks.
And for specific roles for each block you can select the roles. Go to your specific BLOCK configuration and select the ROLE in BLOCK VISIBILITY SETTINGS


Custom view mode issues My goal is to switch between different view modes based on the node path (pattern). In my case, the patterns would be:

dossier/node-alias => default template
dossier/node-alias/cover => cover template
dossier/node-alias/abstract => abstract template

I have created the custom view modes with hook_entity_info_alter (simplified here to only one custom view mode):

/**
 * Implements hook_entity_info_alter
 */
function dossier_config_entity_info_alter(&$entity_info) {

  $entity_info['node']['view modes']['cover'] = array(
    'label' => t('Cover view mode'),
    'custom settings' => TRUE,
  );
}

Here is how I declared the path pattern in hook_menu:

/**
 * Implements hook_menu
 */
function dossier_config_menu() {

  $items = array();

  // Cover entity view mode
  $items['dossier/%/cover'] = array(
    'title' => 'Default title', // overridden in template.php preprocess_node function
    'page callback' => '_dossier_config_switch_viewmodes',
    'page arguments' => array(1, 2), // arguments from uri are 1 => node alias and 2 => cover
    'access arguments' => array('access content'),
    'type' => MENU_CALLBACK,
  );

  return $items;
}

And here is my custom callback:

function _dossier_config_switch_viewmodes($alias, $view_mode) {

  // Get the node path based on the alias
  $path = drupal_lookup_path('source', 'dossier/' . $alias);

  // Return the node if the path exists
  if ($path !== FALSE) {

    $node = menu_get_object("node", 1, $path);
    $node_view = node_view(node_load($node->nid), $view_mode);

    return array(
      'content' => array(
        'node' => $node_view,
      ),
    );
  }

  return drupal_not_found();
}

It works. However, when looking at these nodes in the custom view modes, I lose the node edition tabs (View, Edit, Translate, etc.) and I also seem to lose all the standard classes that are added to the <body> such as node-type-xxx or page-node-12345 etc.

I believe that this is a normal behavior with such a custom callback in hook_menu (?). So what would be the right way to achieve what I want?

Any help on that will be highly appreciated! Cheers!

Edit: I forgot to mention that of course I have 3 different node templates and that I have added the theme_hook_suggestions accordingly in my theme template.php.

The path for your additional pages should be node/%node/abstract and node/%node/cover with something like

$items['node/%node/abstract'] = array(
  'title callback' => 'node_page_title',
  'title arguments' => array(1),
  'page callback' => 'MODULE_node_view',
  'page arguments' => array('abstract', 1),
  'access callback' => 'MODULE_node_view_access',
  'access arguments' => array('abstract', 1),
  'type' => MENU_LOCAL_TASK,
);

$items['node/%node/cover'] = array(
  'title callback' => 'node_page_title',
  'title arguments' => array(1),
  'page callback' => 'MODULE_node_view',
  'page arguments' => array('cover', 1),
  'access callback' => 'MODULE_node_view_access',
  'access arguments' => array('cover', 1),
  'type' => MENU_LOCAL_TASK,
);

If you don't want your additional pages to be available as tabs (like View, Edit and Translate), you can probably use 'type' => MENU_CALLBACK. By doing so, you ensure Drupal knows these pages are below the normal node view page.

MODULE_node_view($view_mode, $node) and MODULE_node_view_access($view_mode, $node) are your page and access callbacks. They receive the $node already loaded (thanks to the %node in the menu item path). If you don't have specific access rules (such as restricting access to only certain content type), you can replace the access callback and arguments by node_access and array('view', 1).

Given the question, your likely want to automatically create aliases for your nodes so you can use paths like dossier/node-alias/cover instead of things like use node/1234/cover. You can implement hook_path_insert() and hook_path_delete() to automatically create and delete abstract and cover aliases for any aliased node.

/**
 * Implements hook_path_insert().
 */
function MODULE_path_insert($path) {
  // If this is an alias to a node view page
  if (preg_match("/^node\/\d+(\/view)?$/", $path['source'], $matches)) {
    // Create aliases for the supported suffixes.
    foreach (array('/abstract', '/cover') as $suffix) {
      $new_path = array_merge($path, array(
        'source' => $matches[0] . $suffix,
        'alias' => $path['alias'] . $suffix
      ));
      unset($new_path['pid']);
      path_save($new_path);
    }
  }
}

/**
 * Implements hook_path_delete().
 */
function MODULE_path_delete($path) {
  // If this is an alias to a node view page
  if (preg_match("/^node\/\d+(\/view)?$/", $path['source'], $matches)) {
    // Delete aliases for the supported suffixes.
    foreach (array('/abstract', '/cover') as $suffix) {
      $new_path = array_merge($path, array(
        'source' => $matches[0] . $suffix,
        'alias' => $path['alias'] . $suffix
      ));
      unset($new_path['pid']);
      path_delete($new_path);
    }
  }
}


Long wait time for website and taking too much CPU+Memory My drupal site is taking too long wait time, and it uses CPU + memory. My server setting is

16GB RAM, 8 processors. So it is good.

I am using Commerce Kickstart distribution have enabled 180 modules all are required cant disable a single module, I cant use caching coz content is mostly dynamic. My site loads in 8 second (most pages) in which wait time is only 6-7 seconds. Multiple hits takes CPU usage to 100%. I have checked reports with xhprof, top command on server, database tuning script, front page executes 4,52,600 functions, PDO commit taking 31% CPU, Database connections are not properly closed.

I have tried database tuniing module, database tuning script but nothing is working fine right now for me.

Cant use caching even default drupal views caching.

Please suggest some steps, any help will be a big big favor. Website i am building is dynamic so caching is prohibited.

There are tons of performance options, I think with the beefy server resources you have we can tune it tremendously by doing the following:

Database tuning

MySQL - make sure QueryCache is setup, and InnoDB is the only table type being used. You'll want to look at the high performance sample my.cnf (config) that ships with MySQL.
Memcache - configuring Memcache will speed up tons of the queries and sub-queries Drupal is notorious for.
Session Cache - for handling a lot of concurrent [unique] login sessions you can consider using a NoSQL database engine like CouchDB/MongoDB, it'll free up your MySQL db from managing those sessions.

Web Serving tuning

OpCode Caching - speeds up PHP a lot, is basically a requirement on all Drupal servers nowadays. I use APC, and there are other solutions but APC will work reliably with very little setup; this one is a no brainer.
Caching - you seriously need to cache at least the home page for anonymous users, and when a user logs in their unique session will be handled correctly. Consider using Varnish (it'll allow your site to handle over 100x more anonymous traffic and there are tons of tips on how to use it with Drupal.

These are just the quick highlights of what you need to utilize. If someone says you can't use caching on your website then there is a flaw in either the product design or the system design. There are literally thousands of popular Drupal sites that manage tons of logins and anonymous traffic working just fine with this recipe.


How can I restrict libraries to attach to my custom controller only? I have a custom module that creates its own page and displays some stuff. I have some CSS and JS to add, and I'm using a library. The CSS and JS are being added, but to every page on the site. Can someone tell me how to restrict them to this page only?

The docs say "But what matters most is that we don't decide whether to attach a library based on which page we're on (i.e. which URL or route), but based on which things are visible on the page..." So, if that really is what matters most, then maybe I'm going about this all wrong?

MycontrollerController.php

<?php

namespace Drupal\mycontroller\Controller;

use Drupal\Core\Controller\ControllerBase;

/**
 * Returns responses for mycontroller routes.
 */
class MycontrollerController extends ControllerBase {
  public function content() {
    return [
      '#title' => 'My Controller',
      '#plain_text' => 'Here is some text.'
    ];
  }
}

mycontroller.info.yml

name: My Controller
description: It's a very nice controller
type: module
core: 8.x

mycontroller.routing.yml

mycontroller:
  path: '/mycontroller'
  defaults:
    _title: 'Mycontroller'
    _controller: '\Drupal\mycontroller\Controller\MycontrollerController::content'
  requirements:
    _permission: 'access content'

mycontroller.libraries.yml

mylibrary:
  version: 1.x
  css:
    layout:
      css/mycontroller-layout.css: {}
  js:
    js/mycontroller.js: {}

mycontroller.module

<?php
function mycontroller_page_attachments(array &$attachments) {
  $attachments['#attached']['library'][] = 'mycontroller/mylibrary';
}

My directory structure...

mycontroller
|-- css
|   `-- mycontroller-layout.css
|
|-- js
|   `-- mycontroller.js
|
|-- mycontroller.info.yml
|-- mycontroller.libraries.yml
|-- mycontroller.module
|-- mycontroller.routing.yml
`-- src
    `-- Controller
        `-- MycontrollerController.php

Your render array can return the #attached property:

$build = [
 '#title' => 'My Controller',
 '#plain_text' => 'Here is some text.'
];

$build['#attached']['library'][] = 'mycontroller/mylibrary';

return $build;

See: https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Render%21theme.api.php/group/theme_render/8.2.x


Unexplained change in module weight in registry table caused site error EDIT: August 6, 2015

It turns out that this was actually caused by incomplete data of module_implements cached in the database by Drupal which caused a hook_init to not be called.  We changed the weight but also had cleared the cache and had incorrectly attributed the fix to correcting the weight.

We have a Drupal 7 site with mimemail and htmlmail modules installed. The htmlmail has a weight of 10 since it needs to be loaded after mimemail.

However, recently, the following PHP error started occur in the logs:

  PHP Fatal error: Call to undefined function mailsystem_html_to_text()
  in /path/to/sitefolder/sites/all/modules/htmlmail/htmlmail.mail.inc on
  line 62".

We were able to track it down to the "weight" column in the registry table where the weight for class "HTMLMailSystem" has a weight of 0 when it should have been 10. Manually changing it to back to 10 fixed the issue.

We confirmed that there has been no active development or any core/module updates around the site this error started to occur.

Does anyone know what could have caused the weight to change?

Futher investigation by running the following query revealed no discrepancies in module weight between the registry and system tables on the development site

SELECT r.*,
s.name,
s.weight
FROM `registry` r
LEFT JOIN `system` s ON r.module = s.name
WHERE r.weight != s.weight

However, on the production site, the following entries module entries have a different weight between the two tables so it's possible other modules were affected too by whatever caused this - it just hasn't caused additional errors (such as due to the default load order perhaps being fine for those).

views_plugin_localization_core
views_plugin_localization_none
views_plugin_row_user_view
WebformComponentsTestCase
WebformGeneralTestCase
WebformPermissionsTestCase
WebformSubmissionTestCase
WebformTestCase
webform_exporter
webform_exporter_delimited
webform_exporter_excel
webform_handler_field_form_body
webform_handler_field_is_draft
webform_handler_field_node_link_edit
webform_handler_field_node_link_results
webform_handler_field_submission_link
webform_handler_field_webform_status
webform_handler_filter_is_draft
webform_handler_filter_webform_status

An easy way to solve this problem is to set the status of that module to 0 in the system table. Then try to uninstall them completely and then try to install and set them again.

I know this is not the best way (there are other ways), but sometimes short and not optimal method is better that spend more time on debugging.


How do priorities work in the *.services.yml YAML file? In system.services.yml and many other services files, one can find priorities like this:

services:

  ...

  path_processor.files:
    class: Drupal\system\PathProcessor\PathProcessorFiles
    tags:
      - { name: path_processor_inbound, priority: 200 }

  ...

Are these priorities similar to the weight-system we know from Drupal 7, where a low weight means earlier in the processing order. Or do priorities work the other way around, where the items with the highest priority are processed first?

I am asking because I could not find a source explaining this.

Drupal uses the EventDispatcher from Symfony and there the priority is used to control in which order the event listeners are triggered:

  An optional priority integer (higher equals more important and
  therefore that the listener will be triggered earlier) that determines
  when a listener is triggered versus other listeners (defaults to 0).
  If two listeners have the same priority, they are executed in the
  order that they were added to the dispatcher.

So the priority in D8 is exactly the opposite of the weight in D7.

The example you used in the question is not an event subscriber, but it uses the same concept of priorities.


How to make strings from templates translatable on all pages they appear? I have some calls to t() in *.tpl.php files. For the sake of example, let's say I'm talking about products and product.tpl.php file.

Strings in templates are not recognized until the first time they are actually used. There was a thread on Drupal.org about that and I found it to be accurate. Sadly, if I go to, let's say, http://example.com/pl/product/200, then that string will be saved in {locales_source} table with location field set to /pl/product/200.

I need my users to be able to translate using Localization client module's on-site translation tool, so they can actually see what they are translating, having it in proper context. With source location set to /pl/product/200, the product with ID 200 is the only one on which the string is shown to be translated. And far worse, if I may be able to force users to translate on that particular product, I need them also to be able to translate to russian, and there is no product with location set to /ru/product/PID.

Is there a way to re-format location string in database, to make all strings visible on all products, all languages in l10n_client tool?

I tried setting it to:

; sites/default/themes/mytheme/product.tpl.php,
sites/default/themes/mytheme/product.tpl.php,
sites/default/modules/mymodule/mymodule.module (module that generates themed data)

But it only made them invisible for the translation tool.

I'm pretty sure it's not a bug in Localization client, it shows the string where it's told this string occurred. And it seems it's "just the way it works" for Drupal 7 translation system, too - was discussed and reported already, and nothing changed. So this isn't a bug report, I just ask how to work with what we have to work with.

I'm talking about texts that have nothing to do with the data module operates on. I don't want to translate products, just template strings that have nothing to do with product itself, like Previous - Next on product image gallery template.

For example, module returns 15 thumbnails, and it is a theme's job to show 5 a time. And previous / next links needs alt and title attributes. Translated. But my module does not know that. And never should need to.

Your requirement:
In order for my site to work in multiple languages
as a authenticated user
I need to be able to translate at once any and all translation calls found in my site's codebase that were done with the t() function.

Is that requirement description even close to what you're asking for?

Crawlers

Like someone said - a crawler could theoretically go through the entire site to force the registration of all t() calls. But 1) the crawler does not know which pages to crawl; 2) we are not looking to maintain a list of pages to crawl, therefore; 3) we don't want to use a crawler, period. Eww. Just, eww. Right?

The problem

We don't have a list of all translation strings.
Drupal/PHP is a dynamic language unlike C which is compiled. So we cannot go and say for example: compile this entire codebase, then find me all instances of this function t(), then register those instances in the database, then translate all those registered instances of t() in one go. I don't think is an option we have on our table.
A static code analysis tool would be helpless for the same reason a crawler would be helpless. I found this t() in this file. Great! What URL is it used in? What's the context?

Attacking the problem with the current tools (Drupal, and some contrib modules), and with the current constraints (relying on real-time theme calls -> template files -> t() calls), looks like a no-exit alleyway here. We might need to think a little bit out of the box.

What we need

We need a data source, a model, that tells me which current translation strings we have, and what is their context -
Proactive data model. The current data model is reactive (the model gets updated whenever a call to t() happens). We need a proactive data model - one in which the application takes care of looking for t() instances before they actually get executed by the customer.
We need context. t() alone does not cut it - because - we do not know we are translating 'foo', but the target language we are translating to depends on the URL of where the t() occurs on. Even if we could hardcode the target language into the t() call, say, using a wrapper call, it would not work for your purposes.

I have identified some of the tools that - if we had them - would help our problem. With these tools we could go into the data model and say: give me all the strings wrapped in t() that have not been populated yet. Now insert these translations. Thank you.

And the next time the customer comes, the translations are there in place.

How would we...build these tools?

Constraints

The target language cannot be on the template, that is decided by the URL. Assuming the string must support any language.
The translated string cannot be on the template. The translation will reside in a database.

Now that I've given the problem more thought, and identified some challenges and constraints, I can think about looking at any solutions available out there, or at making any custom solutions.

Solution brainstorm

I need something that ties "everything" together. What about...an entity?

An entity can hold the product that needs to be translated.
Entities can provide the relation - the glue - between the product that needs to be translated, and it's context.
The entity can specify say, in a field, the default URL location of the product.
Tokens can be used to specify alternative locations (languages?) that the product will appear on.
Entities provide us with the proactive data model that we need, and it's context. Which in turn allows us to do thing such as: go into the database, grab all the product entities, and if the do not have a translation string for fields X, Y, and Z, create those translation strings.

When the customer then grabs /pl/product/200, you take a trip to the db, look up product 200, and grab the already existing pl translation. You have a title and caption field for that product as well? The translations should be there also.

Note that I'm being very vague and generic here in terms of what translation module you're using. You could very well end up using your own translation module - most likely this is the case. All the translations models I've seen in Drupal so far (as of D7, haven't looked at D8 yet) are reactive, not proactive.

In a nutshell

In theory, the tools to build what you need are there, entities being the key component that would tie everything together:
 - data (translation string),
 - target languages. Don't have to be on the Entity itself, preferably a taxonomy vocabulary, say for product languages. or maybe a generic taxonomy for other entities as well.
 - Context. The URL that the entity appears on. The URL would contain a token, and the token in turn would reference the target language taxonomy.

With those three ingredients you can say: Grab all the product entities, go to the  URL alias field, get the taxonomy token, cycle through all possible term combinations, present all combinations to the current user using either a very large ugly form - or, AJAX - and multi-step forms (something like that), and as the currently logged in user translates the various languages for product 200, save those somewhere into the database

Somewhere in the database could be a Field API field in the entity, the settings field belonging to each entity (not exactly Field API, but it can still hold data), or a separate table that you use for this. I think saving the data into the Entity would keep both the code and data tidier and easier.

Building It: Possible solutions

D8MI (Drupal 8 Multilingual Initiative)
Custom code: "index" translations made available in templates by t() by programmatically querying and rendering available bundles and their related theme hook implementations.

Pseudocode

Foreach entity (of type x),
Find all languages (taxonomy or core language associated with product),
Render the entity,
     - in order to detect it’s t() translation strings
     - render calls theme(), which handles the multilingual presentation layer of the product, not the product data model itself.

Result:
     - First call to render entity template in each language returns the default language implementation for each call.
     - The t() parameters on the template are now cached in Drupal and ready for translation (for each language instance, not each product instance).
     - User with “translator” role can now go to translation interface and translate all available t() parameters, for each language.
     - Site owner does not need to wait for customers to visit each product page, or visit each product page manually, as this was done programmatically for him.

Open questions:
     - What is the context? If I do a programatic call to theme() for each “product” entity bundle, does it record the location from which the call was made? Does it record the URL of the node? Can the “context” be altered? Where is the context recorded? What happens when you have "dynamic" templates - i.e., when you have more than one template per product and how you go about detecting those variations?

As always, theorizing and pseudocode is only good for brainstorming. But in development we'll hardly know what we're really up against until we start prototyping. So having drawn up a couple of constraints, possible solutions, and possible problems or questions - I can now proceed to implement a proof of concept or working prototype. Some of the open questions above can only be answered this way, and the earliest we prototype (regardless of success or failure), we can start answering some of those questions - or change the approach altogether. Stay tuned ~


How do I get the current path of a block? I need the current path, where my custom block is visible.
So, i have written this code

class MyBlock extends BlockBase {

  public function build() {
    $currentPath= \Drupal::service('path.current')->getPath();
    return array(
        '#markup' => $currentPath,
    );
  }
}

It is displaying the path where it was visible for first time; if I visit node/1, node/2, node/3 consecutively, it will print node/1 every time, because that was what I visited that first.
It might be happening due to block caching, but how do I get the path for the page showing the block?

Yes, this is because of block caching. The block is built once for the first request and then will stay in the cache forever, until you clear the cache.

You have to set a cache context on the url path:

'#cache' => ['contexts' => ['url.path']],

Then the block will get a cached version for every path.


Cannot assign calculated value to user field in Rules Here is the situation and what I want to do:

Users have a "days left" field of type integer.
A user will set a date range while creating a "time off" content type.
When he hits the save button, a rule will intercept, subtract the date range from his "days left" field and save the result as the new "days left" value.

here is what I have done:

user clicks save button rule intercepts
action - gets the duration and divides it by 86400 (to convert it to days from seconds)
action - converts the result to integer
action - subtracts the converted value
from content authors "days left" field.

At this point I want to assign the result of the subtraction to the author's "days left" field. The node:author:field-days-left variable is available and I select it. But the result of the subtraction is not.

I also tried to convert the result of the subtraction to integer and then assign it, but it did not work too.

Any ideas why?

I could not figure out why the result variable was not available; my solution was to change the order of the actions to:

After the user clicks save button, rule intercepts:

get the value of author's "days left" field and multiply with 86400 (convert days to seconds)
get the duration of content and subtract it from the previous value
divide the result by 86400 (convert it back to days from seconds)
convert the result to integer
subtract one from this result (this turned out to be necessary, perhaps because of the rounding off during the type conversion)
assign the result to content author's "days left" field.

I do not like having to make two type conversions but this is a working solution.


How do I debug incorrect favicon showing on the front page in a custom theme? I'm working on a Drupal 8 site with a custom theme that I didn't code. The site is using the metatag: favicons module to control the favicons. The favicon seem to work correct on all except the home page, which has the default Drupal "Drop" icon. You can see the site here [Site no fav][1]. I am not sure how to begin debugging this since the behavior is not causing an error and the favicons work on the rest of the pages. I assume this has to be some sort of misconfiguration, somewhere, but I'm not sure if I should be looking in template files, something in the admin UI, or where exactly. Any help/guidance appreciated.

Update:
The issue is not a local cache issue, as it was brought to our attention by an external user and happens in Firefox and Chrome.

Update2: Closer inspection of the page source shows that the links for the favicons are indeed not loaded onto the homepage. Specifying a favicon in the Metatag UI for the front page loads one of the favicons. However, the favicons do not have global settings and are still loaded into every other page. The fix of course, is to specify all the icons I want, but this is tedious and doesn't answer why it works on the non-homepage pages.

In the metatag module the front page has it's own settings. I'm guessing you edited the "Global" settings. But you'll also see a "FRONT PAGE" under the /admin/config/search/metatag admin screen and the front page will be using those settings and not the global ones because the front page has its own set of settings


Can I create a keyword filter on emails sent from an email form with Rules? Can I make a Rule that will check content of an email sent from a contact form and block the send if a condition is met?

I was hoping I could set up a Rule to react on event Before Email Send, or something of that kind and then check the content, but that event doesn't exist: could I create it? Or is there a better way?

Context: I have a content type where each node is an advert for a local attraction. I have an email field which is set to display as an email contact form which can be submitted by anonymous users.  I am using Mail System and Mandrill to send the emails.

Although I have Spamicide module and Captcha already installed, the odd spam email is creeping through the form.  The spams are usually highly obvious and would be simple to eliminate if I could set up a keyword blacklist, but I am not sure how best to create one.

Using hook_mail_alter https://api.drupal.org/api/drupal/modules!system!system.api.php/function/hook_mail_alter/7 you can check/change all mails before they are being sent.

Setting $message->send = FALSE; will stop the mail system from sending out the mail.


How can I theme a form element with hook_preprocess_form_element()? I have an exposed form in a D8 view which includes several fields, output through form-element.html.twig (amongst others). I added a function:

function MYTHEME_preprocess_form_element(&$variables) {
...
}

This contains an 'element' key and I could add a class in there, BUT I see no way of identifying which form this is part of. The 'element' has a child '#parents' but this is simply the name of the field.

The whole point of this is to add some Bootstrap responsive classes to these different form items for layout. I tried template_preprocess_form and while I see the fields listed as elements, I don't see a way to add classes to the form element label.

What is best practice for theming D8 exposed forms?

Update: I used XDebug with PhpStorm to debug both MYTHEME_preprocess_form_element and MYTHEME_preprocess_form and explored the entire tree of $variables but could see nothing hinting at parent form ID or similar.

As @4k4 said, if all you want is to add some classes, then use hook_form_alter() or hook_form_FORM_ID_alter(). $form['your_element']['#attributes']['class'][] = 'your-class is all you need.

I'm pretty sure that single form elements don't have the form ID stored somewhere.


some images not displaying after migrating to local host I copied a website from the server to local environment and after seeing that everything is displayed I noticed that the images in all blog posts are not being displayed. I googled this problem and found that a lot of people had it before me and tried applying their ways to solve the problem but none of them were successful for me. I think I am missing something. Please correct me if there is something I might have missed.
Here's a list of things I have done

Compared the image paths and both are the same src="/sites/default/files/image.jpg"
Checked the .htaccess file in sites/default/files and no differences there too
Cleaned the cache

It is not a multisite and it is drupal ver 7.31

The reason you are having the problem is because you have your website on localhost/folders. And you Drupal installation expects your website to be in locahost. So there is to easy ways to solve this problem. Either you move everything up directory and all your files are in the localhost.

cd /Applications/MAMP/htdocs/testwebsite # Move to the website folder directory.
sudo mv * .[^.]* .. # Move everything up one directory.
cd .. # Move to localhost directory.
sudo rm -rf testwebsite     # Remove testwebsite directory.

Or you can created a temporary soft link on your localhost so your Drupal installation can find the sites folder on the localhost.

cd /Applications/MAMP/htdocs/ # Move to the webserver directory.
sudo ln -s testwebsite/sites sites/ # This is going to created the soft link .


Grouping or adding classes to CCK form fields I'm looking for a way to group sections of my CCK add/edit forms so that I can give users a form with sections instead of one long page. I'm already using Fieldgroup to group fields for display so what I'm looking for is something similar for grouping fields for editing.

I realize I can do this with large amounts of CSS, jQuery or adding custom templates but I'm looking for a more elegant solution.

You can use fieldgroup on the node edit form as well. Look just below "add existing field" and you will see "add new group"


Translate string passed to twig's macro does Twig provide any way to translate string which is passed to macro? I thought that it would work in similar way to Wordpress translation function where instead of string I just provide the variable. But it does not work.

Here is my macro:

{% macro input(type, name, placeholder, value, class) %}
<input type="{{ type|default('text') }}" name="{{ name }}" placeholder="{{ placeholder | t}}" value="{{ value | e }}"
       class="{{ class }}">
{% endmacro %}

Then I call it in this way:

{{ macro.input('text', 'name', 'Name...') }}

I want just to translate the placeholders but when I use | t filter drupal returns the error:

InvalidArgumentException: $string ("") must be a string. in Drupal\Core\StringTranslation\TranslatableMarkup->__construct() (line 140 of F:\xampp\htdocs\va\core\lib\Drupal\Core\StringTranslation\TranslatableMarkup.php).

I am aware that input is not great example and I should use form API, it's just the easiest to explain. Is there any way of translating strings which are passed to macros?

I found the solution. The |filter has to be included while calling macro like this:

{{ macro.input('text', 'name', 'Name...' | t) }}


How to mirror product date attribute availability on the availability calendar? I would like to mirror the available dates of the current product line item depending on the availability calendar of that specific product. The availability calendar is what the owner/admin of that product will fill up.

Then there is another date field that is on the line item (add to cart) of that product that will allow the customer to choose when to use/get/rent that certain product.

As you can see on the availability calendar, the 19th, 21th, 23rd, 26th, and 28th of Feb are fully booked. I want the same dates on the popup calendar to be disabled.

How can I achieve that?

These are modules I already tried:

Rooms - This is not fit for our website because of the forms/steps we are using.
Commerce Availability - This is exactly what I wanted but it's not working on my end. The date is still bookable on the line item even though my availability calendar is already fully booked. I already followed the instructions and fixed the settings of the module.

I also checked the demo of the Easy Booking, I had to guess which date is not available, which is not also good.

Thank you for the help in advance!

Unfortunately, there is not a particular bit of code that can be shared to fix your situation. But take heart! You're using libraries that are designed to be changed before display. That means with a little bit of custom php and javascript you can do this.

First you need to determine how to change your widget

Using Javascript: https://stackoverflow.com/questions/9742289/jquery-ui-date-picker-disabling-specific-dates

Using Drupal to send variables to Javascript: how to send variable from .php file to .js file?

Next you need to determine where your availability dates are stored

This is probably the most abstract issue. It sounds like you're storing the availability from within the node. I recommend you use the devel module and try to $node = node_load(123); dpm($node); to see what the availability field array looks like. We will do this in the next step. (Lynda series on the devel module)

Finally, you need to connect both your knowledge of how to tweak the calendar and where the availability is stored with your line item form.

Fortunately, this is quite straightforward. Unfortunately, it's not complete and will need a fair amount of trial and error to get to a working solution. Welcome to learning the hard way :)

<?php

/**
 * Implements hook_form_alter()
 */
function MODULE_form_alter(&$form, &$form_state, $form_id) {
  // Avoid bundle cart forms and other forms
  if (strpos($form_id, 'commerce_cart_add_to_cart_form_') === 0) {
    $current_node = menu_get_object();
    // view the current node structure for your availability
    dpm($current_node);
    // view the current product's form array
    // you may not actually need to change the form here, but
    // I anticipate you needing to attach a javascript snippet to the
    // form so that it gets run each time the ajax loads a new
    // product
    dpm($form);

    // add your js to the php form
    $js_settings = "js array for your availability?";
    $form['#attached']['js'][] = array(
      'data' => array('module' => $js_settings),
      'type' => 'setting',
    );
  }
}

?>


Skinr classes on  tag I would like to use page level skins in my theme, for example.

If I make Colors widget for my skin where I can choose Red/Green/Blue colors and I choose Blue, the class blue is added to body tag.

As far as I know, I've set up Skiner properly, the above is working for regions, blocks etc, but when I set it for page, the class is not showing anywhere.

I appriciate any help, thank you!

I solved the problem in the meantime.

In fact, there wasn't even a problem. I was adjusting the skins for the node, when I tought I'm doing that for the whole page. What I didn't notice at the time is that there is a contextual link icon in the top righ corner, and you have to use that in order to adjust the skin for the whole page.


How do I output a list of PDF files set up via a custom content type I set up a custom content type 'yam' where I upload a PDF file. Each file has a language of either "English" or "Spanish", along with a title, like "Winter 2016".

I've been playing with Views, but I cannot get it to output the equivalent of :

Title

I can only get a list of Titles or a list of file names URLs like:

Filename

.

Change the Formatter to be URL to file

Rewrite the field as attached image using the title to display link to file with the title as link text


Using '#type"=>'container' to create a div wrapper around nested elements? From my reading a render array can define a wrapper div by using the '#type'=>'container'. I am inserting a render array in the page_alter hook function in the page_bottom region. It appears that the container type does not work in this case. The code below does not wrap the two #markupelements with the div wrapper but instead outputs the div then the content at the same level.

$page['page_bottom']["notices"] = array(
  '#type' => 'container',
  '#attributes' => array(
    'id' => array('notices'),
  ),
);

$page['page_bottom']["notices"]['notices-placeholder'] = array(
  '#suffix' => "
",
  '#prefix' => '
',
);

$page['page_bottom']["notices"]['notices-tab'] = array(
  '#markup' => '
NOTICES &nbsp;10
',
);

What I want is the following.

NOTICES....

What I get is the following.

NOTICES....

--- Added
I did try #children earlier in the day and it didn't work as well. Before I left for the day I also tried with

$page['page_bottom']["notices"]['notices-placeholder'] = array(
    '#suffix' => "
",
    '#markup'=>"Empty String", // added to see what it would do
    '#prefix' => '
',
);

This resulted in a completely out of sync html with the #markup tag being outside the #prefix/#suffix. I don't have the results on me now to post but if you try it you will see the results for your self.

I was able to obtain what you wanted using the following code.

  $page['page_bottom']["notices"] = array(
    '#type' => 'container',
    '#attributes' => array(
      'id' => array('notices'),
    ),
  );

  $page['page_bottom']["notices"]['notices-placeholder'] = array(
    '#type' => 'container',
    '#attributes' => array(
      'id' => array('notices-placeholder'),
    ),
  );

  $page['page_bottom']["notices"]['notices-tab'] = array(
    '#markup' => '
NOTICES &nbsp;10
',
  );

The output I obtain using that code as implementation of hook_page_alter() is the following.

NOTICES &nbsp;10

I tried using your code, and setting $page['page_bottom']["notices"]['#tree'] to TRUE, or setting $page['page_bottom']["notices"]['notices-placeholder']['#type'] to 'markup', but I always obtained the same result as you.

The only explanation I have is that, using your code, theme_container() (the function defined as theme wrapper for the "container" element) doesn't get any value for $element['#children']. That would explain why the container HTML output doesn't contain any children element, as the code executed by theme_container() is the following one.

  $element = $variables['element'];

  // Special handling for form elements.
  if (isset($element['#array_parents'])) {
    // Assign an html ID.
    if (!isset($element['#attributes']['id'])) {
      $element['#attributes']['id'] = $element['#id'];
    }
    // Add the 'form-wrapper' class.
    $element['#attributes']['class'][] = 'form-wrapper';
  }

  return '
' . $element['#children'] . '
';

References

system_element_info()
drupal_render_page()


How to create a list of untranslated content in views? I want to create a list of all nodes that has not been translated into a specific language - how do I do that?

I'm using Drupal 8.

You can use the Translation Views module.


Theming property non-object when transversing the $node object I'm getting this error when I run the code below, in reference to $color module:

Notice: Trying to get property of non-object in cotyhouse_preprocess_html()

function cotyhouse_preprocess_html(&$vars){
  // Check if on an article node page
  $node = menu_get_object('node');

  $color = $node->field_title_color;

  print $color;

}

When i output it via dpm, it says its an object, so im a bit confused why it would throw an error. The field value does indeed come through.

menu_get_object('node') should be: menu_get_object()

No need for node as its implied when you call that function.

Also you need to put it in a conditional:

if($node = menu_get_object()) {       }


Is this SQL query even possible in Drupal 7? I'm trying to find a way to run this query in a custom drush command to dump chunks of data from the DB into CVS files.

The query works fine directly in the terminal but I was wondering how would you do it in code for Drupal 7? I guess I can transform a PHP array to a CVS file but wanted to know if Drupal has a way to write more complex queries like this :)

Big thanks in advance!

Query:

SELECT uid, name, mail INTO OUTFILE '/path/sqldumps/result.csv'
FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"'
ESCAPED BY '\\'
LINES TERMINATED BY '\n'
FROM users
WHERE uid != 0

Drupal has it's own abstraction layer to work with database , this method helps Drupal to work with different kind of databases like PgSQL or even oracle (just a database driver will handle everything).

You can get familiar with this api in : Drupal Database API

A more exclusive reference could be : Drupal Dynamic Queries


How do I remove taxonomy links from nodes? Lately, I've noticed an interesting situation related to my Drupal site.  When I enter the name of my site in Google's search engine, a list is retrieved with my site maintaining the first position in search results.  When I click the link that says "See more results from .com," it lists my Home page first followed by links to three Taxonomy pages.

/taxonomy/term/1
/taxonomy/term/2
/taxonomy/term/3

When I click the pagination links at the bottom of those taxonomy pages, I am taken to the following link locations :

/category/categories/<category_name>?page=<page_num>

I have nodewords installed to control metatags. I have set the NOINDEX and NOFOLLOW metatags for all taxonomy terms (and for taxonomy itself).

I don't mind using CSS to hide taxonomy terms. I use the taxonomy terms to determine which category to highlight via CSS by using jQuery's addClass/removeClass functions. I need to remove the link surrounding the taxonomy term so that it's not indexed in search engine results. Using jQuery to remove this link is ineffective and the results remain in search engine results. It's my understanding that there is a way to remove the link using the template.php file and the template_preprocess_node(&$vars, $hook) function.

I don't know how to go about doing this. All help is very much appreciated.

In the Manage Display page of your content-type i.e.: admin/structure/types/manage/product/display you should be able to set the output format for your terms to 'plain text'.