Backlinks from UUID hrefs The goal is to hack core so that the search module will populate the search_node_links table from uuid-link hrefs in node content.

Planned approach is to modify the parsing functions of search_index in the core search.module.

The targeted section of code is lines 633-643 of search.module.

if (preg_match($node_regexp, $value, $match)) {
  $path = drupal_get_normal_path($match[1]);
  if (preg_match('!(?:node|book)/(?:view/)?([0-9]+)!i', $path, $match)) {
    $linknid = $match[1];
    if ($linknid > 0) {
      $node = db_query('SELECT title, nid, vid FROM {node} WHERE nid = :nid', array(':nid' => $linknid), array('target' => 'slave'))->fetchObject();
      $link = TRUE;
      $linktitle = $node->title;
    }
  }
}

The plan is to use entity_uuid_load to grab the nid directly like so:

if (preg_match($uuid_regexp, $value, $match)) {
  $entity = entity_uuid_load('node',$match);
  $linknid = key($entity);
  if ($linknid > 0) {
    $node = db_query('SELECT title, nid, vid FROM {node} WHERE nid = :nid', array(':nid' => $linknid), array('target' => 'slave'))->fetchObject();
    $link = TRUE;
    $linktitle = $node->title;
  }
}

I've used this code to pull a node title with $value set to an HTML snippet containing a UUID-href link; however, this still seems to fail to populate the search_node_links table.

$uuid_regexp is working as expected, but here it is for reference along with $node_regexp for comparison.

$node_regexp = '@href=[\'"]?(?:' . preg_quote($base_url, '@') . '/|' . preg_quote(base_path(), '@') . ')(?:\?q=)?/?((?![a-z]+:)[^\'">]+)[\'">]@i';
$uuid_regexp = '@href=[\'"]?(?:\[uuid-link:node:)([0-9a-f]{8}-(([0-9a-f]{4}-){3})[0-9a-f]{12})(?:\])(?:[\'">])@i';

And here is the UUID link format:

UUID link

I'm sure there's something I'm just not seeing in search.module that is preventing this from working as desired. Any comments/support/pointers would be greatly appreciated.

UPDATE: Finding now that it's not UUIDs causing the issue, but aliased paths instead (probably combined with Global Redirect module). Tried the following code instead, still no change in search_node_links.

if (preg_match($node_regexp, $value, $match)) {
  $clean_url = preg_split('![(en)|(fr)]/!', $match[1])[1];
  $path = drupal_lookup_path("source", $clean_url);
  if (preg_match('!(?:node|book)/(?:view/)?([0-9]+)!i', $path, $match)) {
    $linknid = $match[1];
    if ($linknid > 0) {
      $node = db_query('SELECT title, nid, vid FROM {node} WHERE nid = :nid', array(':nid' => $linknid), array('target' => 'slave'))->fetchObject();
      $link = TRUE;
      $linktitle = $node->title;
    }
  }
}

Again, this code is able to pull a node title but is not contributing to search_node_links.

Ok, so this problem was being caused by the language prefix in our paths in conjunction with aliases. drupal_get_normal_path was returning aliases instead of node numbers, and it returned nothing when the path had a language prefix. Also found that the substitute function drupal_lookup_path only works for aliased paths. The final code replaces line 634 of search.module:

$path = drupal_get_normal_path($match[1]);

becomes

$clean_url = preg_split('!(^[a-z]{2})/!i', $match[1])[1];
if ($non_aliased = drupal_lookup_path("source", $clean_url)) {
  $path = $non_aliased;
} else {
  $path = drupal_get_normal_path($match[1]);
}

The search_node_links table is now being populated properly and the "What links here"/Backlinks views are working correctly.


Drupal::config to access Site default timezone Like the title says, I want to access the sites default timezone.

Guess

Drupal::config('system.date')->get('timezone')['default']

is the right function.
I really would love to know how to use the config-function. Is there a list with all the configs, settings or variables that can be called?

Whats the logic behind the keywords "system.date"? Is there a way to discover keywords by looking at the yml config structure? Can all values of them be returned?

Inspect the system.date configuration

You can navigate to the /admin/config/development/configuration/single/export path and inspect the configuration types and values. The default timezone is of type simple configuration and system.date is the cofiguration name.

Inspect all the configuration values

Go to /admin/config/development/configuration/full/export, here you can export all the active configuration, you can download and extract the bundle and then inspect the individual files. If you have the drush command line tool, you could use the command drush config:export.

Official Documentation

You should read the official documentation to better understand the logic behind the Configuration API. These are some links:

Simple Configuration API | Drupal 8 guide on Drupal.org

Configuration API | Drupal 8 guide on Drupal.org

Configuration API overview | Drupal 8 guide on Drupal.org


Add scrolling effect to hidden node title Here:
http://jsfiddle.net/sdleihssirhc/AYYQe/3/

There is a nice JavaScript code to ellipsize text when it’s too long. On hover, the text  slide to the left,  and show the hidden part.
I’m struggling to make this script work in a view, to ellipsize and show hidden part from node titles.
This is my  View  structure.

[picture]

[title]

this is the CSS I’m using:

#tweet, #tweet_js { border:1px solid red; width:25em; padding:.5em; }
#tweet_js { overflow:hidden; white-space:nowrap; }
.hiding { text-overflow:ellipsis; }

and this is the code:

var tweet = document.getElementById('tweet');
tweet.id = 'tweet_js';
tweet.className = 'hiding';

var slide_timer,
max = tweet.scrollWidth,
slide = function () {
    tweet.scrollLeft += 1;
    if (tweet.scrollLeft < max) {
        slide_timer = setTimeout(slide, 40);
    }
    };

tweet.onmouseover = tweet.onmouseout = function (e) {
e = e || window.event;
e = e.type === 'mouseover';
clearTimeout(slide_timer);
tweet.className = e ? '' : 'hiding';
if (e) {
    slide();
} else {
    tweet.scrollLeft = 0;
}
};

I added the JavaScript file in in the module's .info file using this :

scripts[] = script.js

but nothing is working, I have tested  this JavaScript code in HTML page, and its working  only when placed before  the ending body tag.

(JavaScript and CSS are not mine, they were posted by sdleihssirhc as an answer to this question: https://stackoverflow.com/questions/4755593/css-jquery-powered-sideways-scrolling-text-on-hover )

There should be no direct errors if you got it working on a HTML page. I would suggest checking from the html source that your js file is actually loaded (if not clear the caches). Additionally try wrapping the javascript code inside

jQuery(document).ready(function() {
  //code here
});

or a possibly better option with Drupal 7:

Drupal.behaviors.exampleModule = {
  attach: function (context, settings) {
    // code here
  }
};

You might find additonal useful info about managing javaScript in Drupal 7 here.


How can I tell Drupal to add autocomplete=off to the login form I'm under pressure to close out some issues from a Qualys scan. One issue flagged was

  150112 Sensitive form field has not disabled autocomplete

Suggestions include adding autocomplete="off" to the username and password fields.

What would be the best practice way to achieve this?

It seems there is a module for this, No Autocomplete.
As a sidenote (copied from the module's page:

  However, browsers and password managers and the like may very well not
  respect the "autocomplete=off" attribute anyway. For example, Chrome
  seems no longer to respect it and Lastpass ignores it by default.

Well, good luck with Qualys!


How to Display a Block on a Page with a Variable URL I want to show a block only on these user pages: .../user/USER_ID/recurring-fees. What will be the code to be placed in the PHP box to make this work?

I'm not sure what you mean by the PHP box.  You could do this with the block's visibility settings.  For example, if you wanted to show the "Powered by Drupal"
 block on only the URLs you mentioned, you would go to...

/admin/structure/block/manage/system/powered-by/configure

...and in the Pages tab of the Visibility Settings, enter...

user/*/recurring-fees

Also make sure you have ticked the radio button for "Only the listed pages".

If you are coding the block yourself, you could do something toward the top of your block function like...

if ('user' !== arg(0) || !is_numeric(arg(1)) || 'recurring-fees' !== arg(2)) {
 return array();
}

See http://api.drupal.org/api/drupal/includes!bootstrap.inc/function/arg/7

But the usual approach is to use the visibility settings.


Geolocation Click Marker Event I'm using a Geolocation Fields View with Drupal 8 and need to manipulate the Style of the Marker Info Window.
there is no class to style the pop-Up-window for the Info Text.
The Info Text has a class named gm-style-iw.
I would like to do this:

var popupcontent = $('.gm-style-iw');
popupcontent.parent().addClass('gmap-popup');

But I can't get the right event.
I can get the Click on Map Event with this:

   if (typeof Drupal.geolocation !== 'undefined') {
     Drupal.geolocation.googleCallbacks.push({'callback' : function () {
        Drupal.geolocation.maps[0].googleMap.addListener('click', function() {
        console.log('Clicked on the map.');
        });
     }});
    }

But I need to get the Click on Marker Event.
I can not figure out the Marker Objekt and the right syntax for the click event.

Try this:

if (typeof Drupal.geolocation !== 'undefined') {
            Drupal.geolocation.googleCallbacks.push({'callback' : function () {
                Drupal.geolocation.maps[0].googleMap.addListener('tilesloaded', function() {
                    $('.geolocation-common-map').on('click', function() {
                        console.log('Clicked on the map.');
                    });
                });
            }});
        }


How to create Country, State, City and Zip Code field in D6 I am having a registration page which contains the field Country, State, City and Zip Code Which needs to be hierarchical select.

My question may be very basic. But kindly clear it.

I have used content profile module to create all the registration fields.

My question is what field type i need to give for the above fields what i mentioned (Country, State, City and Zip Code). Which needs to be hierarchical select.

Is there any examples or tutorials related to this topic will help a lot for me.

Any help will be thankful and grateful.

thanks in advance..

Try the Hierarchical Select Module which works with Taxonomy Terms, Menus, User Profile Fields, Generic Lists and External APIs.  The field types you use for storage would not matter.

There are demos available on the module developer's blog.

Warning: In the case of City Names and Zip Codes there is no hierarchy (at least in the States).  Many Zip Codes have multiple city names, many cities have multiple Zip Codes. For any hope of keeping this all current you'd have to use an external API.


How to prevent a user from deleting an entity referenced node before deleting the referencing (child) node first? I have a Content Type called ItemRequest, and another Content Type called ItemOrder. One of the fields in ItemOrder is "Related Item Request" that is an Entity Reference to ItemRequest. Each ItemOrder has at least one Related Item Request.

How do I ensure that a parent ItemRequest node can only be deleted if it does not have any ItemOrder nodes relating to it? What hook can I use that can test for the existence of these child nodes and call form_set_error to abandon node deletion?

You can use hook_node_access:

  Modules may implement this hook if they want to have a say in whether
  or not a given user has access to perform a given operation on a node.

The second parameter for this hook is $op:

  $op: The operation to be performed. Possible values:

  "create" "delete" "update" "view"

And the return values are:

NODE_ACCESS_ALLOW: if the operation is to be allowed.
NODE_ACCESS_DENY: if the operation is to be denied.
NODE_ACCESS_IGNORE: to not affect this operation at all.

So, you should implement that hook, check if the node being deleted is of type ItemRequest and if yes collect all the ItemOrder that point to it. If none are collected you can return NODE_ACCESS_IGNORE, if there're ItemOrder pointing to the ItemRequest return NODE_ACCESS_DENY.

While you can hook into the node form and add a custom validator that doesn't prevent user to delete the node using other means (admin content view, for example). This method can prevent any action trying to delete a node.


Warning to user for including cursing words in private message Drupal 7.
Drupal 6 had a way to configure a rule to check for disallowed words inside the body or subject line of a private message.

I am trying to adapt that rule to Drupal 7.
The purpose of this check is to send a warning message to the sender (email or private message) if banned words are found in his message. This can be expanded to various actions, including a temporary ban then a permanent ban if the user persists.

Here is an export of the first rule (but I can't get it to work:)

{ "rules_warning_to_privatemsg_sender_about_curse_words_" : {
    "LABEL" : "Warning to privatemsg sender about curse words.",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "rules_i18n", "privatemsg_rules" ],
    "ON" : { "privatemsg_insert" : [] },
    "IF" : [
      { "text_matches" : {
          "text" : [ "privatemsg-message:body" ],
          "match" : "word1|word2|word3",
          "operation" : "regex"
        }
      }
    ],
    "DO" : [ { "drupal_message" : { "message" : "Bad word!", "type" : "warning" } } ]
  }
}

Word1, word2, and word3 are the words to check for. They are separated by the "|" (pipe or vertical bar) character.

This format was agreeable with Drupal 6 but I am not sure if that still works with Drual 7.

UPDATE: After studying the Regex website, I was able to get the rule to work changing the expression. See my answer below.

Finally found a format that works.

Contrary to what the Drupal documentation says, the format:

word1|word2|word3

does not work.

The proper syntax is:

^.*(word1|word2|word3).*$

i.e.: caret then dot then star then open parenthesis then the words to search separated with a vertical bar then closed parenthesis then dot then star then dollar sign.

Many words may be added between the parenthesis. No need to add the plurals as regex will match the singular inside the plural.

Reminder: Regex stands for REGular EXpression so this value must be selected at the bottom of the condition page.


Strip HTML tags from validation errors I am using Services 3.x for creating web services for mobile application, and I am using the JSON format.

The validation errors given from the user register services comes with HTML tags; for example the email already exists error is the following one.

<em> the@email.com</em> is already in use.  Have you forgotten your password?".

How do I strip those HTML tags from the error message?

hook_services_request_postprocess_alter() looks like a good candidate. I don't have an installation to test with right now but something like this ought to work:

function MYMODULE_services_request_postprocess_alter($controller, $args, &$result) {
  if (isset($result['form_errors'])) {
    array_walk($result['form_errors'], function(&$error) {
      $error = strip_tags($error);
    });
  }
}


Making a field sortable in Views What makes a field sortable in views?

I have 5 fields output in a table and only two (Node Title and an int) are sortable the rest (mixture of content taxonomy and node reference) are not sortable.

Is it possible to add in this functionality via code?

The query_alter function allows build a custom module with the posibility of change sort order of a view. With this function you can add directly to your sql the respective declaration to sort results.

look this guide http://www.adworkshop.com/blog/2011/05/drupal-6-tutorial-exposed-sort-views-2 that show you how to create your query_alter and create the respective html control to your view (in this case is a dropdown menu).

this is the query_alter function:

function example_exposed_sort_views_query_alter(&$view, &$query) {
if( isset( $_GET['sortoptions'] ) ) {
if ( $_GET['sortoptions'] == 'az' )
 $query->orderby[0] = 'node_title ASC';
else if ( $_GET['sortoptions'] == 'za' )
$query->orderby[0] = 'node_title DESC'; } }

and this is the example of html control using a dropdown menu using in this case the template views-exposed-form.tpl.php.

<?php
$sortOp = '';
if ( isset($_GET['sortoptions']) ) $sortOp = $_GET['sortoptions'] ;
?>
<label>Sort Name</label>:
<input type="radio" id="sortoptionsA" name="sortoptions" onchange="javascript:$(this.form).submit();" class="form-submit" value="az" <?php if ($sortOp == 'az') print "checked"; ?> />A-Z
<input type="radio" id="sortoptionsZ" name="sortoptions" onchange="javascript:$(this.form).submit();" class="form-submit" value="za" <?php if ($sortOp == 'za') print "checked"; ?> />Z-A


Private message to be saved as a draft I want a Functionality in Private message module drupal 7.x. That the message I am creating should be saved as a draft. how do I achieve this ?

There was a patch for this for 6.x but it has not been updated for D7.  If you want this feature now, you'll have to build it yourself.


Log output to syslog I run various Drush commands, including lots of queues, in a loop. I want to see the output in my syslog.

I am currently using drush -r /var/www queue-run my_queue_name_here 2>&1 | logger, which outputs the following line.

  Processed 2 items from the my_queue_name_here queue in 0.58

This is OK, but I feel like this must be wrong. Surely many people want to direct Drush messages to the syslog. Is it possible without using the logger as above?

This is not possible natively. You could write a Drush commandfile, and call drush_set_context('DRUSH_LOG_CALLBACK', 'my_log_function'); to intercept log messages. See drush_log() for details.

A pull request could be considered; it would need to fail gracefully if someone attempted to use it on a system that did not have syslog. Drush avoids platform-specific features where possible, though, which is probably why this has not been added as a standard feature to date.


Unable to create content I created a test account and added it to a numer of roles. Some of those roles (not all) have permissions to create content. I am unable to create or edit any content, but am able to view all published content.

When I log in as user/1 I am able to create new content.

What permissions am I missing in order to be able to create new content when logged in as a newly created user?

The only permission a role needs in order to create new content for a content type is Create new content.  This permission must be set for each content type you want the role to be able to create content for.

If your user belongs to a number of roles, then it is - in a default Drupal 7 configuration - neccessary that at least one of the roles have this permission granted.  Unless you have some node access module installed that breaks with the Drupal paradigm of grants being accumulative (e.g. Deny Access), then it should not matter if some of the roles the user belong does not have this granted.


How do I crop only height? I want to crop an image that is anchored at the center, but only crop the height.  How can this be done in Drupal 7?

EDIT: The process needs to be automated.  Basically I desire the functionality of the existing crop process for an image style, but without the requirement for having to enter a value for both width and height.

EDIT #2:  The width needs to be variable :)

You'll have to use custom GD methods I think.

Have a look at this module : https://drupal.org/project/imagecache_actions

With the embed "Custom Actions" module you'll be able to use any gd method you want.

Add a custom filter to an image filter, and find the gd function to use.

In example, to get a B&W picture, the php code to use is :

return imagefilter($image->resource, IMG_FILTER_GRAYSCALE);


How to order CKEditor plugins I'm implementing CKEditor Drupal plugins using CKEditorPluginContextualInterface in D8.

I wander if there is a way in which I can control the order/weight of the plugins so that I could change which plugin code executes first.

Indeed, all you can do is specify the other CKEditor plugins your CKEditor plugin depends on. It is guaranteed that those are loaded first. But beyond that, there are no guarantees. Nor should there be.

So, just specify the CKEditor plugins your plugin depends on in getDependencies(). This ensures Drupal informs CKEditor about where those plugins live.

Then, it is up to the CKEditor plugin itself (i.e. the JavaScript code) to specify the necessary dependencies, CKEditor then ensures the depended plugins are loaded first.


How to allow HTML attribute with namespace using filter One of the analytics providers requires all the links to have a specific attribute sc:linkname to track details. Drupal 8 filter works for linkname but not with sc: prefix. From  https://html.spec.whatwg.org/multipage/syntax.html#attributes-2 it looks like all attributes have default namespace (e.g. href => xlink:href).

One way to solve this problem is to have a custom filter which processes the linkname and convert to sc:linkname.

<?php

namespace Drupal\my_module\Plugin\Filter;

use Drupal\Component\Utility\Html;
use Drupal\filter\FilterProcessResult;
use Drupal\filter\Plugin\FilterBase;

/**
 * Provides a filter to correct faulty and chopped off HTML.
 *
 * @Filter(
 *   id = "filter_html_attribute_namespace_fixer",
 *   title = @Translation("Add 'sc' namespace to HTML attribute 'linkname'"),
 *   type = Drupal\filter\Plugin\FilterInterface::TYPE_TRANSFORM_IRREVERSIBLE,
 *   weight = 10
 * )
 */
class FilterHtmlAttributeNamespaceCorrector extends FilterBase {

  /**
   * {@inheritdoc}
   */
  public function process($text, $langcode) {
    return new FilterProcessResult($this->addNamespace($text));
  }

  protected function addNamespace($text, $namespace = 'sc') {
    $html_dom = Html::load($text);
    $xpath = new \DOMXPath($html_dom);
    foreach ($xpath->query('//a[@*]') as $element) {
      foreach ($element->attributes as $name => $attribute) {
        if ($name == 'linkname') {
          $element->setAttribute('sc:linkname', $attribute->value);
          $element->removeAttribute($name);
        }
      }
    }
    $text = Html::serialize($html_dom);
    return trim($text);
  }

}


Can't Write to Public Files but Permissions Appear Fine Need the internet to confirm my sanity. On a Drupal 7 site it's saying "The directory sites/default/files is not writable." So I checked every permission but I don't see the issue. Since this isn't a public server, I temporarily turned off SELinux. Another Drupal 8 site is running on the same server with the exact same permissions. What am I missing?

getenforce output:

Permissive

ps aux | grep httpd output:

root     29064  0.0  0.1 262224  6492 ?        Ss   18:26   0:00 /usr/sbin/httpd -DFOREGROUND
apache   29065  0.0  0.0 261884  3672 ?        S    18:26   0:00 /usr/sbin/httpd -DFOREGROUND
apache   29066  0.0  0.2 1188648 10040 ?       Sl   18:26   0:00 /usr/sbin/httpd -DFOREGROUND
apache   29067  0.0  0.2 1778408 8000 ?        Sl   18:26   0:00 /usr/sbin/httpd -DFOREGROUND

/sites/default/files is a symlink and the permission should be ignored

lrwxrwxrwx 1 root   root    31 Mar 18 18:14 files -> /mnt/efs/website/publicfiles/

So let's go down the tree

drwxr-xr-x 12 root root 6144 Feb 17 23:27 efs

drwxr-xr-x 4 root root 6144 Feb 17 23:28 website

drwxrwxr-x 110 apache web 141312 Mar 18 18:16 publicfiles

EDIT (from comment below):
/etc/httpd/conf/httpd.conf:

<Directory "/var/www/html">
    Options Indexes FollowSymLinks
</Directory>

<VirtualHost *:80>
... server info ...
<Directory "/var/www/html/website/public_html">
AllowOverride All
Require all granted
Options -Indexes +FollowSymLinks
</Directory>
</VirtualHost>

.htaccess:

# Follow symbolic links in this directory.
Options +FollowSymLinks

Finally managed to solve this. The entire purpose of this cloned server was to test out speed improvements from PHP-FPM. So since PHP evaluation is essentially offloaded to PHP-FPM, it doesn't matter if httpd has permissions, it matters whether the php-fpm process has permissions.

ps aux | grep php-fpm output:

root      5744  0.0  0.3 462268 14988 ?        Ss   16:45   0:00 php-fpm: master process (/etc/php-fpm.conf)
php-fpm   5745  0.0  0.9 467332 35196 ?        S    16:45   0:00 php-fpm: pool www
php-fpm   5746  0.0  0.4 466656 16528 ?        S    16:45   0:00 php-fpm: pool www
php-fpm   5747  0.0  0.3 466656 14032 ?        S    16:45   0:00 php-fpm: pool www
php-fpm   5748  0.0  0.3 466656 14028 ?        S    16:45   0:00 php-fpm: pool www

groups php-fpm:

php-fpm : php-fpm

So the ownership of my folder as apache:web is what doesn't fit. I just added the user php-fpm to the group web and changed things back to 775.

sudo usermod -aG web php-fpm

I would love comments on pros and cons of what I see as other possible solutions, especially from a security perspective:

1) Add php-fpm to the 'web' group.

2) Make php-fpm the owner, and httpd as member of web so it can still serve the files later.


Get current language in a template file I tried to get the current language in the menu.html.twig template file.

The current language is not available in this template and a preprocess function is not existing for this template as far as I could see. So I did not manage to get the current language by using template_preprocess function as it is described here.

I tried a few things but ended up creating my own Twig function that delivers \Drupal::languageManager()->getCurrentLanguage()->getId() in this (and any other) template.

I could think of declaring a global variable maybe in template_preprocess(), but I believe this is not a good option if I only want it in one special template.

So my question is:
Is it a proper way for this to go via own TWIG function or is there another more easier way of doing this?

For reference I used code like this:

class MyLanguageCheckerExtension extends \Twig_Extension {

  public function getName()
  {
      return 'lang_check';
  }

  public function currentLang() {

    return \Drupal::languageManager()->getCurrentLanguage()->getId();
  }

  public function getFunctions() {
    return array (
      new \Twig_SimpleFunction('languagecheck', array($this, 'currentLang')),
    );
  }
}

The proper way is in a preprocess function and this does exist for the menu template. The reason is caching. In the preprocess function you can check if the caching metadata is in synch with the additional information you add to the twig.

In case of the language, you might get this working in a Twig function, because many templates are already cache dependent on the language, but not with other information like (for example) information from the current user.

This is an example for the menu preprocess function from the Bartik theme.

/**
 * Implements hook_preprocess_HOOK() for menu.html.twig.
 */
function bartik_preprocess_menu(&$variables) {
  $variables['attributes']['class'][] = 'clearfix';
}


How do I get the associated node from a webform entity? I'm preprocessing a webform using hook_webform_submission_form_alter. The webform is being rendered as a node field. How can I, from inside my form_alter hook access that node?

function MY_MODULE_webform_submission_form_alter(array &$form, FormStateInterface $form_state, $form_id) {
    $parameters = \Drupal::routeMatch()->getParameters();

    if ($parameters->has('node')) {

        // processing goes here
    }
}

I'm fetching it from the url parameter right now, but I would prefer to do this in a cleaner way.

After some digging, I've found out the answer.

This is how I get the webform submission, the webform object, and the associated node:

    function MY_MODULE_webform_submission_form_alter(array &$form, FormStateInterface $form_state, $form_id) {

        $entity  = $form_state->getFormObject()->getEntity(); // webform submission
        $webform = $form_state->getFormObject()->getWebform(); // webform object
        $node    = $entity->getSourceEntity(); // associated node

        // (...)
    }


How can I load webform content inside a custom webform composite element? I am using Drupal 8.7.3 and Webform 8.x-5.2.

I created a custom composite field in a multistep webform by extending WebformCompositeBase. My users select a subject in an earlier step. In this step I want to take the key of the user selection and request data based on this key.

class OtherExpectationsComposite extends WebformCompositeBase {
    public static function getCompositeElements(array $element) {
        return [
            'depending_content' => [
                '#markup' => 'content depending on earlier selections'
            ]
        ];
    }
}

How can I load the data insert to the form by the user in the earlier steps? $element doesn't contain anything helpful.

Finally I used the good old session.

My solution:

//mymodule.module
function mymodule_form_alter(array &$form, FormStateInterface $form_state, $form_id) {
    $session = \Drupal::request()->getSession();
    $session->set('value_from_earlier_step', $form_state->get('value_from_earlier_step'));
}

//\src\Element\ExampleComposite.php
class ExampleComposite extends WebformCompositeBase {
    public static function getCompositeElements(array $element) {
        $session = \Drupal::request()->getSession();
        $expectations = $session->get('value_from_earlier_step');
    }
}


How to show a link if the user is member of a specific OG group? I am not a coder but I'd like to do this line of code:

If the logged in user is a member of the Organic group team1
Then show a Link to node/add/team_1_content with 'Text' = create node
Else show nothing.

Create a block that includes that "Link to node/add/team_1_content with 'Text' = create node" as in your question.

Then use the Rules block visibility module. Here is a quote from its project page:

  The Rules block visibility module allows Rules components to be used to control block visibility. This provides Drupal administrators and developers extreme flexibility in controlling when blocks should be displayed on their websites, in addition to the default visibility options provided by Drupal.

  The general idea is that if you can do it with Rules, you can use it to control block visibility, so the possibilities are limitless:

  Need to show a block only for users registered more than a month ago?
  Perhaps you have a block that must be shown only between 8am-5pm on weekdays?
  What about displaying or hiding a block based on current weather conditions?

  All of this can be done by using Rules block visibility.

With that, and as per the "if you can do it with Rules, you can use it to control block visibility" above, you've reduced your question to making Rules "check if the logged in user is a member of the Organic group team1".

For an illustration of how to use this module, refer to my answer to "How to stop a Views block from displaying to admins, such as user/1?".


Convert exposed dropdown filter to links Drupal Views So I have a date filter for my view which filters the view by post date(year). I already used BEF(Better Exposed Filters) but the only available options there is Default select list or jQuery Date Picker. I've attached some pics here, the first one is what's the filter looks like currently and the second one is how it should look. Need to convert the dropdown to look like the second pic. Thanks!

You can use something like this:

Add a contextual filter to your view for 'Content:created year"

Add a Header Global Text Area (Full HTML) with this in it:

2012

2013

2014

2015

by-date is my view's path. Yours will be different.

Style it.

Looks like this without styling:

If you don't want a contextual filter you could create your date links with a query parameter like this:

by-date?date-filter=2015

Then use a views hook to read the query paramter and add the filter in code.


Batch operation for consuming data from API via drupal_http_request I am consuming data from an API which provides a URL similar to:
http://data.something.com/api/records?pageIndex=0&pageSize=25

The API will return XML which I will then use to create nodes.
There are many thousands of records, so I will need to do this via batch. I have used batch before but never for drupal_http_request. What would be the best approach for this? Is batch API the best solution, or would another method be preferable?

Thanks

Hi You're probably best off using the feeds module to import from feeds it can do them as one off imports imports or periodic batch jobs and create nodes from the feeds automatically. Even though they're beta/alpha they're well used and actively developed.


Intercepting when a page is requested I am trying to call a function every time a page is loaded. With Drupal 7, I used hook_init, now I'm using a subscribed event.
  public function logRegEntry(GetResponseEvent $event) {
    $request = $event->getRequest();
    $method = $request->getMethod();
    $path = $request->getPathInfo();
    $route_name = \Drupal::routeMatch()->getRouteName();
    if (($method == 'GET') && ($path == '/')) {
      // do it just for this module
      \Drupal::service('wdocsDebug')->logSiteEntry();
    }
  }

This works fine for the home page, but I want it for every page a user requests. This is getting called four times; first for the page I'm requestings, and then for:
/admin/coffee/get-data
/history/5/read
/quickedit/attachments
I did notice that on the first request, the $route_name is set to "entity.node.canonical" -- might this be a better way to check for a page? Probably not, since it would only get triggered by node pages.
I'm looking for a better way to do this, not sure why there are four request events. Thanks.

Your event subscriber is also picking up AJAX requests (e.g. /admin/coffee/get-data is an endpoint the Coffee module uses when it's needed in the client browser) which explains why you're seeing multiple events for a page request.
You can filter out those events with the logic best fits your needs (e.g. a $request->isXmlHttpRequest() call to check for AJAX requests, or a route whitelist as you mentioned).


How to show a menu link that is hidden because the role has no permission to see the linked page? I need show a menu link that links to /node/add/article for anonymous users but they don't have access to that page.

I have seen solutions like:

Using an absolute URL (that way Drupal does not check user access).
Alter the menu access callback but I do not really want to give them access just to print the link.

Are there any other solutions?

In your case you can use two menu entries in the same menu:

One pointing to /node/add/article.
Another one pointing to /user/login.

First link is only visible to registered users, because anonymous users don't have permissions to add articles.

Second link is only visible to anonymous users because registered users don't have permissions to see the user login page (because they are already logged in).

The result is a menu with only one menu entry. Registered users see first link, anonymous see only second one.


How to delete a Grant by GID Typically grants are deleted by $nid whenever new grants are added.  In fact this function is baked into node_access_write_grants() (when $delete = TRUE).

I have been using custom GID's to represent different users's Address IDs ($aid).  When a user edits his/her address I want all the old grants with that GID/AID to be deleted but leave the grants on the particular node to be untouched.

It would appear to me that Drupal 7 has no built in way to delete grants by GID, only by $node. Because of this I'm advocating doing a simple database query very similar to the query in node_access_write_grants().

Original:

 if ($delete) {
    $query = db_delete('node_access')
             ->condition('nid', $node->nid);
    if ($realm) {
      $query->condition('realm', array($realm, 'all'), 'IN');
    }
    $query->execute();
 }

My code:

$query = db_delete('node_access')
         ->condition('gid', $address->aid);
$query->execute();

Perhaps there's something to be said for using the 'realm' field to circumvent this issue.  However, this seems to work.  I'd love to know what the community thinks.


How to not show user signatures in comments? In D7, user signatures appear in their comments. It can be very annoying for many, especially when the signature is long or contain big pictures. So I'm wondering how to disable this?

There is feature in admin panel of Drupal to disable signature option directly.
Follow the below steps:

Go to admin/config/people/accounts (admin > configuration > account
settings)
Uncheck "Enable signatures" checkbox under Personalization section.
Once finished, go down to the bottom of the screen and click the
Save Configuration button.


hook_menu not working with alias I have a hook_menu:

$items['node/%/tokens/%api_token'] = array(
    'title' => 'View an API Call',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('api_token_edit', 1, 3),
    'access arguments' => array('edit own profile'),
    'type' => MENU_LOCAL_TASK,
);

When visiting url: node/1229/tokens/1, it works as expected.

When visiting the friendly alias: mypage/tokens/1, it gives me a 404.

Why is this? I thought hook_menu used the internal arguments?

That behavior is not inclued in core. You can try this two modules:

Sub-pathauto (Sub-path URL Aliases): The Drupal Path module matches only full URLs when creating SEO-friendly aliases. This module extends that behavior by also matching known sub-paths and replacing them with their respective alias.
Extended Path Aliases: SImilar to previous module, but includes more functionlaity. The drawback is that it needs core patching (adding a line to nclude/path.inc) or installing PECL runkit library.


How to create field collection item fields programmatically? first of all, English is not my native language so sorry if this reads bad.

I'm trying to program a field collection with field collection item fields like the code as given by rbruhn here: https://drupal.org/comment/4653514#comment-4653514

I want to create it on an easier leavel for testing purposes. My goal is to create a taxonomy reference dropdown and a textfield.

I manage to reproduce the field_collection type. Hower, I can't reproduce any field collections item fields. Let's say I want a textfield in my field collection.

creating an ordinary textfield field collection item field, this would make sense to me (but it doesn't work). Can someone tell me what I do wrong? Instead of appearing inside my field collection it appears as a field inside my node which contains my field collection field

array(
  'field' => array(
    'field_name' => 'name_of_my_field',
    'type' => 'text',
    ),
  ),
  'instance' => array(
    'field_name' => 'name_of_my_field',
    'entity_type' => 'field_collection_item',
    'bundle' => 'name_of_my_field_collection_field',,
    'widget' => array('type' => 'text_textfield'),
  )
),

This works for me (my field collection is called field_fc_test). I imagine the problem is with the way you are calling field_create_instance.

$new_field = array(
  'field' => array(
    'field_name' => 'name_of_my_field',
    'type' => 'text',
    ),
  'instance' => array(
    'field_name' => 'name_of_my_field',
    'entity_type' => 'field_collection_item',
    'bundle' => 'field_fc_test',
    'widget' => array('type' => 'text_textfield'),
  ),
);
field_create_field($new_field['field']);
field_create_instance($new_field['instance']);


How do I collect field values of a submitted webform? I'm trying to integrate a Mailchimp mailing list into Drupal. The Mailchimp list requires:

First Name
Last Name
E-Mail

The client already has a list in this format so ideally I need to collect this data in Drupal.

I want to have a newsletter block that collects the email address and forwards a user to another page that has the full newsletter sign up with first name last name and the email but pre filled out.

I know I'm going to need Rules and Webform. But how can I collect the value of the webform field and use it again as a token later?

Note:  I am using this within the Drupal setup, but the list requires three fields of data (first/lastname/email). I want to have a block that initially collects the email and forwards them to the full newsletter signup page. I have the webform and rules working to direct the user from the page with the block to the signup page, but I need to find out how to create a custom token from the field.

Have a look at Webform Mailchimp , different approach but may be of use

  Provides a webform component that lets users subscribe to a Mailchimp
  newsletter as they submit a webform.


Is it possible to restrict the site search module to specific nodes? I am trying to figure out a way to provide a search for a specific set of nodes. Currently it seems that the site search is not configurable in this way. Is there any way to change this functionality, or other modules that provide a search for a defined group of pages/nodes?

Thanks!

You can use one of these 2 modules, Custom search Or Search restrict. Both these modules allow you to restrict the search on specific content types


How to find url of content-type? I am new in Drupal

I have an article website, and it has some category like History, Sport, Graphic, Music and etc.

But when I add some content-type for each of these and when I visit that post, I can't find the URL path of them. for example when I post a new Sport article that it's title is "Ronaldo's regimen" and when I click on save button on drupal, drupal show me an article that its URL is this :

  www.example.com/content/ronaldos-regimen

I need to add a link to my menu for each catagory, something like this:

  Sport | History | Graphic | Music

(I use pathauto module)

While creating node, Check on Provide a menu link. Add Menu link title and select Parent item where you want to add the current node.

That's it


How to aggregate field results to a chart? I installed the Chart module and I'm using it in my Views display.

I have a field: Score

I added a chart but it shows two different charts (see image) instead of just one with all the results from that field.

How can I put them together? If it's with aggregation, can you give me some guides?

Here is how another attempt looks like:

And this is how my View currently looks like:

The tabular format of its data to be charted looks like so:

Notes:

I'm using the Chart module because I need the "radar" type which only exists in that module.
I want to create a chart with all the scores displayed in the table, and not one chart per score.
I don't want all the fields to appear as data, as in the last pictures in my question. I want the text to be the legend and the number to be the data.

This kind of questions show up quite often. And each time I try to get them resolved with this very first attempt (if it is related to a Views display):

  You may find it easier to start with a "Table" display and convert it to a chart display after setting up the data. It can be easier to visualize what the result of the chart will be if it's been laid out in a table first.

In my experience, 90% of the issues turn out to be related to errors in the creation of the table that contains the data to be charted.

If this question is about creating a chart using the Views integration, then refer to the appropriate Community documentation resources with more details about how to do so:

For the Chart module: Create charts using Views
For the Charts module: Steps to create charts using the views UI.

Disclosure: I'm a (co-)maintainer of both Chart and Charts, and co-author of the documentation resources mentioned.


Check if entity reference field (user) contains current user I have a node page of Project content type which contains a multiselect enitity reference field of user type called field_team. I also have a block created by my custom module which is displayed at Project type pages only. What i'm trying to achieve is to do smth like this:

if ($current_node->field_team contains $current_user->uid) {
$output = 'some_specific_content';
} else {
$output = 'you are not a team member of this project';
}

How can I check if currently viewed node contains current user in its reference field?
Will be very thankful for any help or advice.

Check following code:

global $user;
$team_members = array();
foreach($current_node->field_team['und'] as $team){
$team_members[] = $team['target_id'];
}

if (in_array($user->uid, $team_members)) {
$output = 'some_specific_content';
} else {
$output = 'you are not a team member of this project';
}


What alternatives do I have to use the Computed Field module? I am currently using the Computed Field module to calculate field in Field Collection and use PHP code to generate the formula. The problem is that the user does not enough PHP skill to write that PHP code. So are there any alternatives that allow users to choose which fields and calculations instead of using PHP code?

Using rules you can do basic calculations with field values and write the result into an other field. If you do the calculation after an instance of your content type has been saved you make sure the value is always up to date.

Of course you can implement your own action as well and hook it into rules. See hook_rules_action_info.

Whether your users find rules easy to manage and you can trust them to give them access to the rules system is an other story. Depending on what you want to evaluate you might just add some fields to get all the information you need and add a custom action to do the evaluation.


Migrated Servers now 500 Error _db_error_page('Access denied f...') Moved servers, copied all files and database and set server settings to match old server. Updated settings.php with new database credentials and tripled checked them for the correct information. Console gives me a truncated error message so I don't know the exact problem.

[21-Feb-2019 15:02:21 UTC] PHP Fatal error:  Uncaught Error: Call to undefined function ereg() in /public_html/includes/file.inc:1034
Stack trace:
#0 /public_html/includes/file.inc(1032): file_scan_directory('themes/pushbutt...', '\\.info$', Array, 0, true, 'name', 1, 1)
#1 /public_html/includes/common.inc(2888): file_scan_directory('themes', '\\.info$', Array, 0, true, 'name', 1)
#2 /public_html/modules/system/system.module(868): drupal_system_listing('\\.info$', 'themes')
#3 /public_html/includes/theme.inc(493): _system_theme_data()
#4 /public_html/includes/theme.maintenance.inc(51): list_themes()
#5 /public_html/includes/bootstrap.inc(1221): _drupal_maintenance_theme()
#6 /public_html/includes/database.inc(176): drupal_maintenance_theme()
#7 /public_html/includes/database.mysqli.inc(78): _db_error_page('Access denied f...')
#8 /public_html/includes/database.inc(15 in /public_html/includes/file.inc on line 1034

and set server settings to match old server

That process went wrong - ereg() was removed in PHP 7.0, and Drupal 6 couldn't have been running on a version of PHP that high on your old server.

I think PHP 5.3 is about as high as you're likely to be able to get with Drupal 6, you should get your server admin to downgrade to that version ASAP.


How to use taxonomy vocabulary with terms and children using views module I have a problem with Views and Taxonomy and maybe can found the solution here. I have a vocabulary with 15 terms and each term have a few childs. I want to show that with a jump menu using views but the result is awful because I have a list with terms and childs but losing the hierarchical order. Please, check it here (http://cubarecipes.org/restaurants-guide), right column, Cuba Restaurants guide block.
Thanks in advance,
Alex

You are probably looking for the Simple Hierarchical Select module.

From the module's page:

  Simple hierarchical select defines a new form widget for taxonomy
  fields to select a term by "browsing" through the vocabularies
  hierarchy. The widget is available in node forms and as Views exposed
  filter.

  This module has been inspired by Hierarchical select but is much
  simpler (hence the name ;) ).

  Unlike Hierarchical select this module provides a simple widget for
  taxonomy terms only. As an addition Simple hierachical select works
  as Views exposed filter.

The Hierarchical Select module is still in development for D7 and the Views integration has not been ported, so SHS is the best choice at the moment.


Sync Drupal commerce order information Sync Drupal commerce order information between several drupal instances.

Here is my use case.

A business has a Drupal commerce website.
It also has several internal commerce sites.

Each of these has to have the ability to work independently of each other for certain periods of time.
At a later date there will be a mobile app doing the same thing.
So any sales information or orders need to be synced at later points throughout the day.

What is the recommended way to do that securely and also avoid and order related conflicts such as order number customer name changes etc?

I realize this is a fairly broad question but Im not looking for a specific answer,  Any general information or recommendations would be great.

Some general advice:

I had a similar situation on a project. I first tried various options for importing orders from the separate sites into a central site using modules like:

commerce_order_ftp_export
commerce_export
commerce_export_csv
commerce_feeds with patch for orders

But you will need custom code to resolve order IDs etc. Depending on the number of sites, this may be workable.

However, I eventually opted for a solution as follows:

Using a mobile POS app for sales
Sending sales from each instance of the app into a central drupal installation running maceij’s version of commerce_marketplace
This way,sales can be separated and/or aggregated by location, POS, etc.


DrupalGap BarcodeScanner Integration Does anybody have experience integrating external libraries with Drupalgap (in particular the BarcodeScanner)? I've been able to get BarcodeScanner working with Phonegap relatively easily but Drupalgap's architecture is more complicated and requires using a function to acces. Any help would be great!

Here's the BarcodeScanner info:

https://github.com/cfjedimaster/Cordova-Examples

I created a project from scratch using Cordova, added the plugin according to the readme, and then copied the contents of www from the repo to my project. This works great standalone. How do I add this button to Drupalgap so I can scan barcodes from within the app?

After setting up the plugin in phonegap simply add this to a page:

var html = theme('button_link', { text: 'Start Scan', path: null, attributes: { onclick: "startScan()" } });
$('#my_container').html(html).trigger('create');

Thanks to TylerFrankenstein for this one.


How do I display fields from a Commerce Cheque transaction using Views? We have been processing payments in Drupal Commerce using the Commerce Cheque module. For accounting purposes, we would like a view showing all checks received with check numbers, etc..

How do I configure a view to display fields from Commerce Cheque, specifically check number?

You can create a view of of Payment Transactions and filter by Payment Method = check.

The check reference number is stored in the field called Remote ID. Just add that field to the view.


How to place every node of a content type under a menu item? I'm looking for a module that will let me add every node of a content type as a link with a common parent link.

You can use Default Menu Link module for this and core menu settings for content type..

  Provides the user with a check box on all content types to set the
  "provide a menu link" value to true by default.

  This is basically a nice way to ensure the menu system is adhered to
  by all content authors.

You need to set Menu settings for content type..


Unsure how to define an entity type using Entity API I'm here because of this:

  EntityMalformedException: Missing bundle property on entity of type contacts. in entity_extract_ids()

I'm trying to create my own entity. Can you identify what is incorrect or missing about my entity configuration?

I am using the Creating your own entities with Entity API guide for setting up a new module using entities.

For my needs, I only need one entity type. The example creates two entity types, one called "task", and another called "task_type".  So I did my best to eliminate the "task_type" sections, but I'm getting the above error and am not understanding what to do about the bundle type.

This is my hook_entity_info().

/**
 * Implements hook_entity_info().
 */
function contacts_entity_info() {
  $return = array(
    'contacts' => array(
      'label' => t('Contact'),
      'entity class' => 'Contacts',
      'controller class' => 'ContactsController',
      'base table' => 'contacts',
      'fieldable' => TRUE,
      'entity keys' => array(
        'id' => 'ckid',
      ),
      'bundle keys' => array(),
      'bundles' => array(),
      'load hook' => 'contacts_load',
      'view modes' => array(
        'full' => array(
          'label' => t('Default'),
          'custom settings' => FALSE,
        ),
      ),
      'label callback' => 'entity_class_label',
      'uri callback' => 'entity_class_uri',
      'module' => 'contacts',
      'access callback' => 'contacts_access',
    ),
  );

  return $return;
}

This is my custom controller. (Do I even need this?)

class ContactsController extends EntityAPIController {
  public function create(array $values = array()) {
    global $user;
    $values += array(
      'mail' => '',
      'notes' => '',
      'created' => REQUEST_TIME,
      'changed' => REQUEST_TIME,
      'uid' => $user->uid,
    );
    return parent::create($values);
  }

  public function buildContent($entity, $view_mode = 'full', $langcode = NULL, $content = array()) {
    $wrapper = entity_metadata_wrapper('contacts', $entity);
    $content['author'] = array('#markup' => t('Created by: !author', array('!author' => $wrapper->uid->name->value(array('sanitize' => TRUE)))));

    // Make Description and Status themed like default fields.
    $content['notes'] = array(
      '#theme' => 'field',
      '#weight' => 0,
      '#title' =>t('Notes'),
      '#access' => TRUE,
      '#label_display' => 'above',
      '#view_mode' => 'full',
      '#language' => LANGUAGE_NONE,
      '#field_name' => 'field_contact_notes',
      '#field_type' => 'text',
      '#entity_type' => 'contacts',
      '#items' => array(array('value' => $entity->notes)),
      '#formatter' => 'text_default',
      0 => array('#markup' => check_plain($entity->notes))
    );

    return parent::buildContent($entity, $view_mode, $langcode, $content);
  }
}

entity_extract_ids() raises an exception when $info['entity keys']['bundle'] is not defined, or is an empty string. If you don't want to explicitly set the bundle property, you need to set it to  value that is considered empty from PHP, but it is not an empty string, such as an empty array, or FALSE. In such cases, the bundle property is set to the entity type name.

The following is the code contained in entity_extract_ids(), and which raises the exception you are seeing.

if (!empty($info['entity keys']['bundle'])) {
  // Explicitly fail for malformed entities missing the bundle property.
  if (!isset($entity->{$info['entity keys']['bundle']}) || $entity->{$info['entity keys'] ['bundle']} === '') {
    throw new EntityMalformedException(t('Missing bundle property on entity of type @entity_type.', array('@entity_type' => $entity_type)));
  }
  $bundle = $entity->{$info['entity keys']['bundle']};
}
else {
  // The entity type provides no bundle key: assume  single bundle, named
  // after the entity type.
  $bundle = $entity_type;
}

Keep in mind that entity_get_info() caches the entity information it gets. If you edit an enabled module, you need to disable it, and re-enable it. This forces Drupal to clean the cache it uses, and call the implementations of hook_entity_info() to get a fresh definition of the entity.

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

  // hook_entity_info() includes translated strings, so each language is cached
  // separately.
  $langcode = $language->language;

  if (empty($entity_info)) {
    if ($cache = cache_get("entity_info:$langcode")) {
      $entity_info = $cache->data;
    }
    else {
      $entity_info = module_invoke_all('entity_info');
      // Merge in default values.
      foreach ($entity_info as $name => $data) {
      // …
    }
    // …
  }

Installing a new module has the same effect, as Drupal should clear its cache in that case too. If it doesn't happen, you can always force Drupal to clear its cache with cache_clear_all('entity_info', 'cache', TRUE).


How do you add a PDF attachment to an email? Goal: I need to send an email with a pdf attachment in Drupal 8.

Progress

I am able to send an email with subject and message but have never been able to get the attachment. When I turn on the logic to attach the file to the email, the email never gets sent but the mail service returns True as if the email was sent anyway. There are no errors and the logs say nothing.

I have the following modules installed:

SMTP
MailSystem
MimeMail

What I've tried

Tried using $message['params']['files'][] = $params['attachments'] instead of $message['params']['attachments'][] = $params['attachments'] like some examples have recommended
Tried changing $file->uri to $file->filepath
Tried attaching the file like so:

$params['attachments']['filecontent'] = $this->generatePDF($foa_list);
$params['attachments']['filename'] = 'MyFormsOfAssistance.pdf';
$params['attachments']['filemime'] = 'application/pdf';

Tried attaching the file by path alone with an array:

$attachment = array(
    'filepath'=>'sites/default/files/MyFormsOfAssistance.pdf',
);

$params['attachments'] = $attachment;

Tried attaching the file a different way:

$attachment = array(
    'filepath' => 'sites/default/files/MyFormsOfAssistance.pdf',
    'filename' => 'MyFormsOfAssistance.pdf',
    'filemime' => 'application/pdf'
);

$params['attachments'][] = $attachment;

Setup

There is email landing page in which a user enters the recipient's email address, subject for the email, and message for the email.
When user clicks Send button, that data is routed to my Email Controller
Email controller creates the pdf file, attempts to attach the pdf to the email, and then sends the email.
I have the hook_mail() function defined in my module file.

Here is the code for my Email Controller:

public function submit_email($foa_list = null) {
    $lang = "en";
    $email_to = "blah@blah.com";
    $params['subject'] = "Test subject";
    $params['body'] = "Test body";

    // -------------------- Attachment Logic -----------------------
    // Create pdf file and store file
    file_put_contents('sites/default/files/MyFormsOfAssistance.pdf', $this->generatePDF($foa_list));

    // Attach pdf file to email params
    $file = new \stdClass();
    $file->uri = 'sites/default/files/MyFormsOfAssistance.pdf';
    $file->filename = 'MyFormsOfAssistance.pdf';
    $file->filemime = 'application/pdf';
    $params['attachments'][] = $file;

    // Send email
    \Drupal::service('plugin.manager.mail')->mail('email', 'email', $email_to, $lang, $params);

    $response = new Response();
    $response->setContent("true");

    return $response;
}

Here is the hook_mail() code in my Email module file:

// Note that print_and_email is what my module is called.
function print_and_email_mail($key, &$message, $params) {
    switch($key) {
        case 'email':
            $message['subject'] = $params['subject'];
            $message['body'][] = $params['body'];
            $message['headers'] = [
              'MIME-Version' => '1.0',
              'Content-Type' => 'text/html; charset=UTF-8; format=flowed; delsp=yes',
              'Content-Transfer-Encoding' => '8Bit',
              'X-Mailer' => 'Drupal',
            ];
            // $message['params']['files'][] = $params['attachments']; // Note: I have seen other examples implement attachments this way
            $message['params']['attachments'][] = $params['attachments'];
            break;
    }
}

The Drupal 8 documentation isn't really helpful and I would like to be able to figure this out without installing SwiftMailer, like some sources have recommended. Really not sure why this isn't working as it has worked for others. What am I missing?

FINALLY! 4 weeks later...

So the following code ended up working for me:

    $attachment = array(
        'filepath' => 'sites/default/files/MyFormsOfAssistance.pdf',
        'filename' => 'MyFormsOfAssistance.pdf',
        'filemime' => 'application/pdf'
    );

BUT, the key was that in the MailSystem Configuration I had to set the Formatter and Sender to "SMTP Mailer". MimeMail's config automatically pulled it's values from my SMTP's configuration.


Flush cache of individual node when updated? Is there any way to have an individual node's cache flushed if it gets updated? (instead of having to flush drupal's entire cache to show the changes to anonymous users immediately? (Rules or a module maybe?)

If you are using node_save, cache for the particular node will be cleared automatically. If you are using any other method to save the node then use the following,

entity_get_controller('node')->resetCache(array($node->nid));


How/where is the marker layer added to the Google Map with the Gmap Module? So,

I'm interested in trying to "export" a collection of markers from a Google Map generated by the Gmap module. Specifically, I'm looking for how to pull human-readable marker information from the js loaded into the page, not how to create an exportable list of the marker data.

From poking around in the javascript console, I can find what look like a series of related auto generated JS files in sites/default/files/js; but the JS looks like it contains the functions to create the markers and map definitions, not the geometry collection itself. Similarly, the gmap_markers.js doesn't provide much that's easy to decipher.

So, is drupal passing variables to those js scripts to create the markers on the fly? and if so, is there a place where a human-readable collection of those markers (ID, LatLon, popup info, and any other meta data) is stored and loaded into the Gmap?

So, I got the answer from reddit.com/r/javascript. All the map settings are stored in the drupal.settings js variable, you can access it from the console in drupal.settings.gmap.auto1map.markers


How can I automatically rotate images based on EXIF data prior to image styles being applied? I have a website where users can upload pictures of themselves.  Many of these pictures are taken with  mobile phones and as a result a lot of them are shot such that the picture is vertical, but it is uploaded as horizontal because Drupal ignores the EXIF data.  This can be fixed using the Image Cache Actions module (autorotate submodule), but if I do so, this breaks the Manual Crop module, which I use to trim the pictures as necessary.

Is it possible to somehow have Drupal automatically rotate all images upon upload based on their EXIF data if available, such that image styles would be applied to the rotated image, not the original image?

Another option is to process the images before they are uploaded. I wrote a windows script to do this 5+ years ago. It still works, but I won't be offering any support for it.
http://www.autoitscript.com/forum/topic/85891-imagemagick-batch-jpg-processor/


Update a menu link programmatically For a migration project, we had some links on the main menu stubbed out to an external site. Now I want to update the links with their actual final path. However, I can't do this beforehand, because I don't know what the node ids of the newly-created imported nodes would be.

I want to update the menu links with node ids in my import script, but I haven't found how to do that programmatically. We would like to avoid updating them manually during the final migration.

How can I do this?

I assume you know the path of the link you need to change and that's all?
If so this should work for you.
Note that I have put comments in place of any error/success reporting, which you can add if you want it.

It also assumes you know how to integrate this into the migration.
This shows the menu link saving only.
I can expand to show migrate integration although that is really a separate question.

Note: The paths used for menu items are drupal internal paths, not path aliases. To convert a path alias to an internal path you can use drupal_get_normal_path().

// Variables used below. Set these to the values you need.
// The current path of the link.
$path = '';
// The menu the link is in. If you don't want to be menu specific remove the menu_name part of the SQL below.
$menu = '';
// The new path for the link.
$new_path = '';

// Get the menu link ID for the given path in the given menu.
// If you donb't know the menu it is in you can omit that part of the query.
// This also handles the case where there are multiple menu links for the same
// path.
$mlids = db_query("SELECT mlid FROM {menu_links} WHERE link_path = :path AND menu_name = :menu", array(':path' => $path, ':menu' => $menu))->fetchCol();
if ($mlids) {
  // Loop through the matching menu items and update them.
  foreach ($mlids as $mlid) {
    if ($menu_link = menu_link_load($mlid)) {
      // Set the new menu link data.
      $menu_link['link_path'] = $new_path;
      // Save the menu link.
      if (!menu_link_save($menu_link)) {
        // There was an error saving the link.
      }
      else {
        // The link has been saved successfully.
      }
    }
    else {
      // Menu link $mlid not found.
    }
  }
}
else {
  // No menu links were found for this $path.
}


Display Suite layouts not available for field collections Edit\Add forms I'm using Drupal 7 with the Display suite and Field Collection contrib modules.

For nodes entities the "Layout for..." vertical tab provided by Display Suite is available in both "Manage fields" and "Manage display". This applies also to any node content type I created, so I'm able to rearrange forms layouts used when adding\editing and when viewing nodes.

But for field collections the "Layout for ..." vertical tab is missing in "Manage fields" and it's available only in "Manage display", so I'm not able to rearrange the layout used by the add\edit form specific to field collections.

Is this a limitation of Display Suite? Any other way to rearrange the edit\add form for field collections fields?

If you are using 7.x.1, you need rel module to edit forms from other entites than node type, like field collection, user, comment, etc.
If you are using 7.x.2 you don't need that because this branch offers this feature out of the box.
For editing forms, you must go to Manage fields of your entity.

edit: just to note that rel will stop this from working on the 7.x.2 branch.


Custom migration from external DB I'm trying to migrate content from an Expression Engine database to Drupal 8.

I set up a $databases['migrate']['default'] in settings.php and copied and modified BeerNode.php from migrate_plus migrate_example module in a custom module.
This is my query code in BlogNode.php.

  public function query() {
    // $this->configuration['ignore_map'] = true;
    $query = $this->select('exp_weblog_titles', 'tab1');
    $query->addField('tab1', 'entry_id', 'bid');
    $query->addField('tab1', 'title', 'name');
    $query->addField('tab2', 'field_id_10', 'body');
    $query->innerJoin('exp_weblog_data', 'tab2', 'tab1.entry_id = tab2.entry_id');
    $query->condition('tab1.weblog_id', 10, '=');
    return $query;
  }

Now Drush complains about a missing column:

  Migration failed with source plugin exception: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'b.bid' in 'on clause':

SELECT tab1.entry_id AS bid, tab1.title AS name, tab2.field_id_196 AS body, map.sourceid1 AS migrate_map_sourceid1, map.source_row_status AS
migrate_map_source_row_status
FROM
{exp_weblog_titles} tab1
INNER JOIN {exp_weblog_data} tab2 ON tab1.entry_id = tab2.entry_id
LEFT OUTER JOIN destinationdatabase.migrate_map_blog_node map ON b.bid = map.sourceid1
WHERE  (tab1.weblog_id = :db_condition_placeholder_0) AND( (map.sourceid1 IS NULL ) OR (map.source_row_status = :db_condition_placeholder_1) );

This is the implementation of getIds():

  public function getIds() {
    return array(
      'bid' => array(
        'type' => 'integer',
        'alias' => 'b',
      ),
    );
  }

I assume that the second part of the query should be ON tab1.entry_id = map.sourceid1 but I can't set anything other than bid.

I kind of resolved by temporarily setting $this->configuration['ignore_map'] = true; before the query losing some traking functionality though.

Remove 'alias' => 'b', from your getIds() call, that parameter is only needed if you need to remove any ambiguity from the source query.


recent content block with thumbnail? I want to theme the Recent Content block with associated thumbnail of each node. After researching for a long time I found the function node_get_recent(). This function selects data from table 'node', but this table doesn't include any url pointing to the url of an image, which means I am not be able to use $node->(url of this thumbnail) to fetch its thumbnail. I happend to find the url of the thumbnail is located in the table 'file_managed', but I still cannot associated it with table 'node' through leftjoin.

I do not know how to do it the right way. I do not want to use Views. Thanks!

When I put the following code into my .module file the title displayed for each node is the same.

function example_contents() {
  $number_of_post = 10;
  $result = db_query("select n.title,n.nid,f.entity_id,fm.fid,fm.uri from {node} n left join {field_data_field_image} f on n.nid=f.entity_id left join {file_managed} fm on f.field_image_fid=fm.fid   limit $number_of_post");
  $items = array();
  foreach ($result as $node) {
    $items[] = l($node -> title,'node/'.$node -> nid);
  }
  return array('#markup' => theme('item_list', array('items' => $items)));
}

$node -> title turned out to be same, however $node -> nid worked. That is to say the list of nodes used the same title but different urls. What was wrong with my code? Secondly, I do not know where to put my $node -> uri into $items[] in order to display the thumbnail.

to slecet image uri you have to do

selest uri from node
join field_data_filed_image on field_data_filed_image.entity_id = node.nid
join file_managed on filed_image_fid = fid

anfd you can use this function to get thumbnail using uri

<img class="image" src="<?php print image_style_url('thumbnail', $block->uri) ?>"/>


Taxonomy Tags Comments I am having a problem removing the comments link from a page.
I am using Taxonomy and Tags, I added a term to Tags and gave it a URL alias such as tags/sandy_repair.
I created a new basic page and added that term to the page.
When you display the page it lists that tag at the bottom.
When you click on the tag link it takes you to the alias you created that would display the teasers of all the

pages with the same tags. So the tag links to tags/sandy_repair
On this page there is a comment icon and a link to 0 comments ()
I would like to remove that icon and comments link entirely.
The structure of the Basic page is not set to display comments, manage display does not even show comments and the

Comment Display tab has the comment field hidden.
The only thing I can figure is that this comment display is not coming from the basic page settings.

What theme do you use?
Have your tried unsetting the comment links in your node template using something along unset($content['links']['comment']['#links']['comment-add']);?


Restrict commerce coupon by user role I am making a drupal commerce site. For coupon functionality I am using commerce_coupon module .

My question is How can I restrict a coupon by user roles i.e. a particular coupon should be applicable only for authenticated users .

I have already installed Commerce Coupon - Per user redemption installed which gives me coupon per user functionality . But I want commerce coupon by user roles.

How can I achieve this ?

The coupon's applicability is tied to the discount. Use Commerce Discount and Commerce Discount Extra. Commerce Discount Extra provides an inline condition that lets you specify a user/role condition for an order, which is exactly what you want.


How to translate Views exposed filters? I know you can translate a views title pretty easy as answered here: How do I translate a view page title?

Unfortunately I can't find a way to translate exposed filters buttons and labels properly. Using Drupal's User interface translation does never index those strings. Is there any known way (other than preprocessing the view to display translatable markup programmatically)?

Follow the procedure in the linked answer, which is, install the module Configuration Translation and add a translation to your view. Then you'll find these translation options:

EXPOSED FORM

FILTERS


Modify value only if node is new I am using the following function to alter the node's data before saving it to the database.

function mymodule_node_presave($node) {
  if ($node->type="mytype") {
    if ($node->is_new) {
      $node->status = 0;
    }
  }
}

How do I know that the node is new and not updated/edited? In the example, you may see I have used $node->is_new, and I need to make sure that is correct. So is it?

The is_new property is set by the node_save function, which is the same function that will invoke hook_node_presave - so your are safe in your assumption that this property will be present.

If you were not doing this in hook_node_presave, another way of testing if a node is new is by checking if the nid property is present and non-zero:

if (empty($node->nid)) {
  // ... this is a new node ...
}


Migrating Content Fields in Drupal 7 I have quite a few content types, and when I set it up I didn't think ahead and created an image field for each content type rather than one image field type.  Is there a way to add a common image field type and mass-convert the content types to use that one field?  Or do I have to manually migrate all of the currently populated fields?

The Migrate module will help you to export all your image fields, and import them into one unified field; then, you can delete your obsolete fields.


Schedule Migrate to import XML data regularly Is it possible to schedule Migrate to import/update my XML regularly, say, once an hour? Maybe in Rules?

EDIT: I have a skeleton of a module written for this now, to hook into Rules.

Event: If there are unimported nodes, or if it has been more than 15 minutes since the last import

Condition: Just the machine name of the Migration, and its enddate timestamp

Actions: I want two, one to do an import and rollback, and another to update and import.

I am having trouble trying to find what functions to call to initiate the actions, and which ones to get my arguments. Is there any good documentation on the core Migrate functions (not field handlers or anything) so that I can see which ones I need?

EDIT 2
I ended up with this cron function. Is this how it's written? And I can put it into my module where the rest of my migration is? I also need to specify that it should update any nodes already imported. How do I do that?

    function mymodule_cron() {
            $last_run = variable_get('mymodule_last_cron', 0);
            $interval = variable_get('mymodule_interval', 60);
            if(time() - $last_run > $interval){
                 variable_set('mymodule_last_cron', time());
                 $migration = Migration::getInstance('ImportNodes');
                 $result = $migration->processImport();
            }
     }

I think the best way to achieve your goal is to use Drupal's cron, not Rules.

Cron is a service that will trigger the execution of a function, depending on the frequency you want it to.

You just have to implement hook_cron in your custom module to execute your migration. You will have to take care of the frequency you need for your script. I found this example useful.

How to run migration programmatically? As stated here, it's very simple:

<?php
  $migration = Migration::getInstance($machine_name);
  $result = $migration->processImport();
?>


Adding tool tips to menu items and views I need to add tool tips to some of the primary links in my menus, and also to a link in a view, I tried to use the Tool Tips module, but it doesn't seem to be designed for this kind of use... is there another module I can use, or is there another way I can integrate tips to my dynamic content?

Take a look at the qTip module or the Tipsy module as alternatives to get "good looking" tooltips or simply add a description to the menu items for basic browser created tooltips


How to set count in "bundled" product? I have created a content type called "product". On this product, I need to create a "entity reference" field to other products, should this product be a bundled product.

For example, I might create a "Playstation 4" product, but add "Call of Duty" as a FREE bundled addon item. I want to then be able to specify the number of these "sub products" are applicable. For example, if you buy the playstation, I might have it come bundled with 2 copies of the exact same Call of Duty. So I need to be able to specify that all though Call of Duty is the bundled product, two of them are relevant.

How do I do that with Drupal, without using entity nodes (as they are very slow in practice)?

A solution that comes to mind is using the field collection module to create a collection with a quantity and entity reference field. I've not used that module with Drupal Commerce so there might be a more commerce-centric solution there.


Move location of drush Currently there is a .drush folder in my user profile on my mac. However, is it possible to move it into my git repo? How does one move it? If I drag and drop it, then run a drush command, the folder is remade in my user profile folder.

No.  Your Mac is running a version of the Unix operating system.

Files and directories starting with a dot (.) in Unix are hidden system files/directories and should not be moved or deleted unless you know what you're doing.


Gallery Jquery Pager I have created a "partners" block in the rightmenu of my theme .. it works perfect and all, but it shows only 6 partners (set from views settings) with newest first .. now my problem is i want to have a "view all" button, also i want to have a pager with jquery transition to view next 6 partners etc.

how can i do this? also, what modules do i need for this?

Thank you in advance


Get all users with specific roles using EntityFieldQuery I thought this was an easy task, yet there does not seem to be a Drupal-method for this. I came as far as knowing I have to use EntityFieldQuery for this - because the API said conditions for user_load_multiple() are deprecated.

So I tried this:

  $query = new EntityFieldQuery;
  $query
    ->entityCondition('entity_type', 'user')
    ->propertyCondition('rid',array(1,2,3);

  $result = $query->execute();

Yet I got this:

  PDOException: SQLSTATE[42S22]: Column not found: 1054 Unknown column
  'users.rid' in 'where clause': SELECT users.uid AS entity_id,
  :entity_type AS entity_type, NULL AS revision_id, :bundle AS bundle
  FROM {users} users WHERE (users.rid = :db_condition_placeholder_0) ;
  Array ( [:db_condition_placeholder_0] => 3 [:entity_type] => user
  [:bundle] => user ) in EntityFieldQuery->execute()

So my first thought was, that I'd have to join with users_roles-Table and so on, but that will lead to duplicates.

Does anyone have an idea how to do it?

To be honest, I have no idea on how to achieve this. Good examples of how to use the EntityFieldQuery are hard to find. Since noone has answered this question yet and I'm also interested in the solution I'll try to help you out. Described below is my best guess.

A thing to keep in mind: roles are stored in a different table than users. They are added using UserController::attachLoad.

There seem to be three different conditions that you can use with an EntityFieldQuery:

entityCondition (Entity specific conditions:'entity_type',
'bundle', 'revision_id' or 'entity_id')
fieldCondition (Conditions on fields maintained by the Field
API)
propertyCondition (Conditions on entity properties)

The most logical option (if there is one) would be to use a propertyCondition, but as roles are added to the user in UserController::attachLoad I don't think the EntityFieldQuery has access to it. I think the EntityFieldQuery just uses the schema defined in hook_schema().

This leads me to believe that what you're trying to achieve is impossible. A workaround would be to get all the uids with a normal query:

I don't have access to Drupal right now, so the code below might be off. I'm sure somebody will edit the mistakes.

// Use $query for readability
$query = 'SELECT DISTINCT(ur.uid)
  FROM {users_roles} AS ur
  WHERE ur.rid IN (:rids)';
$result = db_query($query, array(':rids' => array(1,2,3)));

$uids = $result->fetchCol();

$users = user_load_multiple($uids);

If it is possible to achieve what you want with EntityFieldQuery, I'll be enlightened.


Create custom table with pagination I have a function in a controller which shows data in table format. I need pagination and styling for the table. I tried as follow.

MyController.php

public function my_requests() {
        //load the current user details
        $user= User::load(\Drupal::currentUser()->id());
        $user_id = \Drupal::currentUser()->id();

        //Query the database
        $query = \Drupal::entityQuery('node')
           ->tableSort($header)
           ->condition('status', 1)
           ->condition('type', "forward_proxy_request")
           ->condition('uid', $user_id)
           ->sort('nid' , 'ASC');
        $table_sort = $query->extend('Drupal\Core\Database\Query\TableSortExtender')->orderByHeader($header);
        $pager = $table_sort->extend('Drupal\Core\Database\Query\PagerSelectExtender')->limit(10);
        $nids = $pager->execute();

        //creates the table header
        $header = [
                'Node id',
                'title',
                'Name',
                'Ip',
                'SLU',
            ];
        foreach ($nids as $nid) {
            $node = Node::load($nid);
            $row  = [
                'data' => [
                    $node->nid->value,
                    $node->title->value,
                    $node->field_p_name[0]->value,
                    $node->field_ip[0]->value,
                    $node->field_p_slu[0]->value,
                ],
            ];
            $rows[] = $row;
        }
        //Build the table
        $build = [
          'table'           => [
          '#prefix'        => '
My Requests
',
          '#theme'         => 'table',
          '#attributes'    => [
              'data-striping' => 0
          ],
          '#header' => $header,
          '#rows'   => $rows,
      ],
    ];
    //for pagination
    $build['pager'] = array(
        '#type' => 'pager'
    );

     return $build;
}

But it throws an error.

  Error: Call to undefined method Drupal\\Core\\Entity\\Query\\Sql\\Query::extend() in
  /var/www-drupal/modules/ga/src/Controller/MyController.php on line
  196

Without extendQuery, it shows a plain table without any style.

How do I resolve this issue?

Here is an example of sortable table with pagination.

$header = [
  'id' => [
    'data' => $this->t('ID'),
    'specifier' => 'nid',
  ],
  'title' => [
    'data' => $this->t('Title'),
    'specifier' => 'title',
  ],
  'created' => [
    'data' => $this->t('Created'),
    'specifier' => 'created',
    // Set default sort criteria.
    'sort' => 'desc',
  ],
  'uid' => [
    'data' => $this->t('Author'),
    'specifier' => 'uid',
  ],
];

$storage = \Drupal::entityTypeManager()->getStorage('node');

$query = $storage->getQuery();
$query->condition('status', \Drupal\node\NodeInterface::PUBLISHED);
$query->condition('type', 'article');
$query->tableSort($header);
// Default value is 10.
$query->pager(15);
$nids = $query->execute();

$date_formatter = \Drupal::service('date.formatter');
$rows = [];
foreach ($storage->loadMultiple($nids) as $node) {
  $row = [];
  $row[] = $node->id();
  $row[] = $node->toLink();
  $created = $node->get('created')->value;
  $row[] = [
    'data' => [
      '#theme' => 'time',
      '#text' => $date_formatter->format($created),
      '#attributes' => [
        'datetime' => $date_formatter->format($created, 'custom', \DateTime::RFC3339),
      ],
    ],
  ];
  $row[] = [
    'data' => $node->get('uid')->view(),
  ];
  $rows[] = $row;
}

$build['table'] = [
  '#type' => 'table',
  '#header' => $header,
  '#rows' => $rows,
  '#empty' => $this->t('No content has been found.'),
];

$build['pager'] = [
  '#type' => 'pager',
];


Transforming the external link with in the site sorry if the title is not apt, I'm new to Drupal. Here I'm working in drupal 7 the site has a news feed module, automatically updates the contents (links). When these links are clicked the corresponding links will be opened in the new tab or in the same tab (closing our actual site). So to avoid this, I would like display the corresponding link's page with in our drupal site. so that our drupal site will be active and the corresponding newsfeed link will be opened within our site (like wise displaying the web page in an iframe)

I tried of using iframes, but couldn't get what i wanted. I came across a module 'Fences' which looks good, but i couldn't know completely about the usage of fences module.

Can any one list out how to solve the issue.

Using iframes is not a good option. Besides, I suggest to start using jQuery and update the function for the specific 'div'. We can add jQuery using JSinjector module, Navigate to JSinjector as Configuration/development/JSinjector.

Hope It would work fine in such a kind of issues.


Drupal 6 CCK date field is saving current time when the time field is left blank I have a node type='event' that has a "text field with date popup calendar".  The date format is "05/13/2015 - 7:02pm".  On the edit page, the form renders as two fields: a calendar popup text field and a separate field for the time.  This field is mandatory; but, it has been requested that the time value not be mandatory.

The problem occurs when the node is saved.  It saves the date correctly; but, it inserts the current time if no time has been entered.   Is there a way to have it not enter a time or just default to midnight if no time has been entered?

Set your Default value for your event date field to Blank. This will make the date/time field empty upon default. A user has to enter date if it's a required field, but can leave the time field blank. If it's left blank it will default to 00:00.


How to give link to edit in user profile page and node page? I have removed all tabs of user's page and node page with the help of Tab Tamer module, but i want to keep only one tab enabled i.e "Edit".

how to enabled only tab(Edit) or a link to edit profile on the user's page and edit link on node page.

Go to admin/config/system/tabtamer and enable tabs as you want.


Website saves separate sessions for "www.domain.com" and "domain.com" I open a browser, type "www(dot)mydomain(dot)com"
I login as an admin
I open a new tab, type "mydomain(dot)com". I'm logged out, and i can login as a different user..

It's weird. I can't find anything helpful on google (or i don't know the right search keywords). Does anyone here have any idea?

Thanks :)

For usability (this problem) and SEO reasons you should redirect all visitors to a single version of the site. Look in the .htaccess file and you should see instructions on how to do a 301 redirect to send people to either the www or the non-www version of the site.

If you really really do want to make the site work on both versions, open your settings.php and find the line for $cookie_domain. Set it to be the "example.com" version and it should work.


Ajax loader when facet is selected When we add a facet block to the page, a filter is selected and the page starts to load the results. However there is no loading icon or indicator the change is being applied.

When we check the page, there is no JS error and nothing visible.

How do we get the loading icon or throbber to show when a facet is selected?

You can try the following.

Add in your JS file:

$(document).ajaxStart(function(){
  $('#ajax_loading').show();
});

$(document).ajaxStop(function() {
  $('#ajax_loading').hide();
});

Add the HTML in your page:

<div id="ajax_loading" style="display:none">

Add in your CSS file:

#ajax_loading {
  position: fixed;
  left: 0;
  right: 0;
  top: 0;
  bottom: 0;
  background: rgba(0,0,0,0.5);
  z-index: 9999;
}


Responsive Image Module not reducing the file size when resizing the browser (Drupal 8) I have an issue using Responsive Image Module for drupal 8 that I can't seem to solved or figure out. As shown in this screenshot the file size of the original image is 685kb. But once I started to resize to the first breakpoint which is around 1366px the file size jumps to 1023kb or 1mb. My expectations was the file size should be reduced to even smaller size. I tried the option Resize and setting different dimensions proportionally or even Scale. But I still get the same results

I guess the 685kB is your original, uploaded file and the 1MB file is generated on the webserver by GD or ImageMagick.

When your original file is heavily compressed and at the same time your JPG quality setting is very high, the generated (pixel-smaller) files can be (byte-wise) larger than your original. There is not much you can do against this except reducing JPG quality settings in Configuration > Media > Image Toolkit

Another option would be using a modified JPG library like MozJpeg, but this is beyond the scope of Drupal.


Most appropriate simple IP direct for Drupal 7 Having looked at the descriptions provided for the following modules

ip2cc
ip2country
geoip
smart_ip

I'm having trouble identifying which module would be the simple solution to my scenario.

I have established 'Landing Pages' which represent the different countries for my website. (initially)

e.g:
 - www.example.com/au (Australia)
 - www.example.com/us (United States)
 - www.example.com/uk (United Kingdom)

If a user lands at the www.example.com url and they are from IP addresses in Australia, United States or the UK, I'd want it to direct them to the appropriate landing page.

I'm not sure which module is the most appropriate for this scenario and how it would be applied.

Many thanks for your help.

All of the modules you have listed only provide APIs, choose one for which you need least maintanence. For geoIp you need to keep updating County List DAT file manually once in 3~4 months, I am not sure about others. Once you choose your module you have to write logic for your scenario, something like this

$cc = geoip_country_code();
if($cc == "AU"){
  drupal_goto(MY_AUSTRALIAN_SITE_URL);
}

You can use page--front.tpl.php or make use of drupal_is_front_page() in page.tpl.php to write your own logic.


Add taxonomy term image to a view Can anybody tell me how I add an image field of a taxonomy term to a view of nodes with reference to the vocabolary?

I have a content type called "Product" and one called "Distributors". And then a have a vocabolary called "Product categories", where a term has two fields: a title field and an image field.

I am using the NAT module to add a term to the "Product categories" vocabulary every time a product is created, so that the title and image of the product becomes a new term with the value of these two fields.

When I create a distributor I am using these terms as term reference to which products the distributor sells.

The problem I am facing now is that I want a view of distributors, and I cant seem to get the image of the terms associated with each distributor-node. I can only get the titles. I assume that I might have to make some kind of relasionship, but I cant seem to figure it out.

I hope someone can help me.

From what I understand you have a distributor node that has a term reference (multi value) to Product categories.

In your view that lists the distributors you must add a relationship: Content: Taxonomy terms on node. When presented with a choice of vocabularies you select 'Product Category'.

Then you add two fields: Taxonomy term: Name, and Taxonomy term: Image (your image field might be named slightly differently). For both of these fields, during the multi form process of adding them, you will be presented with a form that says for instance: Configure field: Taxonomy term: Name. Here you must select the Relationship as term.

This will create one row for each taxonomy term on the node, which might not be what you want. You can now group it under the content:title of the distributor.

There are two other ways that I can see by which you can group all of the images from one distributor under a single distributor.

First method:

Create a new field: global custom text. Make sure that it is below all of the distributor fields. Move the image field below it. In this global text field add all of the distributor fields (using html and replacement patterns) except for the image field. For instance, you might have something like this:

[title]

[address]

[phone]

Now go and hide all of the fields, the global text field as well, except for the image field. Then in your grouping, select this new global text field as the field to group on. Now apply some CSS to make it look good. And if you want to get rid of that pesky h3 tag around the grouping header, then override the theme view template. Click on Theme: Information in views and select one of the Style output templates.

Second method:

Install the Views Field View module. This allows you to create a field in a view that will be the result of another view.

Create a new view that takes as contextual filter the nid of the distributor, and then as before add a relationship to the terms etc. so that this view only outputs the pictures in groups.

In your original view remove the relationship to the terms, and insert a field to the new view, and make sure to pass it the parameter of the nid.


Unable to contact the Apache Solr server I followed README.txt and installed these :
apache solr 1.4.1 (Out side WWW Directory)
Apache Solr Drupal modules
SolrPHPClient r22 (placed inside module)
I copied over xml files(as mentioned in readme) to example folder
And after starting up SOLR as java -jar start.jar I am able to access localhost:8983/solr/admin,
But still i get

Apache Solr: Your site was unable to contact the Apache Solr server.

I am using windows :(

Since you're able to connect to ApacheSolr I am keen to know if you set the credentials correctly on Drupal side. Make sure that you added the local server correctly here admin/config/search/apachesolr/settings/add. After that use the Test connection button to verify that you are able to contact the ApacheSolr server.


'path' in array with special characters using imagecache I have a folder in my sites/default/files directory filled with product jpg's gathered from an external server and back end stock take system.

The files look like this...

Bread.jpg
Bakery.jpg
Cakes+and+Puddings.jpg
Chocolate+Bars.jpg
Chocolates+%26+Treats.jpg
Christmas+Fruit+%26+Veg.jpg

I am using theme_image_style in a custom block template to print the images using an image style from Drupal 7's core image handler like so...

<?php
    print theme_image_style(
        array(
            'style_name' => 'category_header',
            'path' => 'product_group_images/' . $productcategoryurl . '.jpg',
            'attributes' => array(
            'class' => 'category-header-image'
                 ),
            'width' => NULL,
            'height' => NULL,
        )
    );

?>

Where $productcategoryurl is the image name inside the product_group_images folder.

This all works great where the image is only one word, like bread.jpg or bakery.jpg

The trouble I am having is the "+" or "&" (%26) in the image names.

I have tried str_replace to swap the spaces in the product name with "+", but in the path, the "+" is always encoded, and the image is never saved in the new style.

So my path comes out like....

/sites/default/files/product_group_images/Chocolate%2BBars.jpg

Instead of...

/sites/default/files/product_group_images/Chocolate+Bars.jpg

And therefore, no image is created in the /sites/all/files/styles directory.

Is there a way using the "path" in the array to actually use the "+" as a space without encoding it?

I hope ive explained that well enough, its late!

I would use a hyphen "-" instead of plus "+" as it is URL safe and the standard MO on Drupal


How to list and store the value of hidden exposed filter of several views for anonymous user? I need to list vocabulary terms as text links, and then store the choice for anonymous user. Then the exposed filter of several views should get stored value. What is the easiest way to achieve that?

The User Alert module may provide a good starting point.  It stores a uniqueid for each visitor in a cookie and keeps track of whether an alert has been closed.  The logic for this would be similar, but you'll need to wire up the code in your own module to push the views-filter to the cookie and back.