title: Custom styling TB-Megamenu

text:
# Question
Title: Custom styling TB-Megamenu
I'm attempting to custom style the TB-Megamenu because there are a lot of color changes I would like to make. I would also like to change how when the mouse leaves an item it stays that color for a moment before changing back to it's default state. I understand that I can always change the css in a custom stylesheet that's also included like

```
#main-menu-wrapper .tb-megamenu .mega-nav > .active a, #main-menu-wrapper .tb-megamenu .dropdown-menu .mega-nav > .active a {
    background-color: #000;
    color: #fff;
}

```

But hunting down everything I need to change is quite the task. Especially when trying to hunt down what selections I need to make for things elements are active, or elements that the mouse just left. The fact that the TB-Megamenu is changing the classes also makes it difficult. At the same time the TB-Megamenu is being used elsewhere, and I'd like to keep the default style for them, without affecting other sites that are on the same instance of drupal. Is there a better way to accomplish this? Or do I need to continue trying to search and override each element?

# Answer
TB Mega Menu module has a CSS folder. Use that as your reference. It also has a styles sub-folder that IMO would be of greatest benefit. Just copy one of the whole styles/\*.css files over and adapt it. No need to **hunt** it down.

To target a menu on a specific page you will need to inject a CSS class into that page via a preprocess\_page hook or Context or some other preferred method. You need to set it closer to root level (ie html or body tag) than that of `.tb-megamenu` class occurence in the html. Having done that all you need do is prepend your injected class to every single selector that you use, as in:

```
.tb-megamenu.style-black .nav > li > a:focus,
.tb-megamenu.style-black .nav > li > a:hover {
  background-color: #222;
  color: #7bb9e0;
}

```

becomes:

```
.my-page-class .tb-megamenu.style-black .nav > li > a:focus,
.my-page-class .tb-megamenu.style-black .nav > li > a:hover {
  background-color: #222;
  color: #7bb9e0;
}

```
> 1 votes

---
Tags: 7, theming, navigation
---


# Question
Title: Umlauts grouped in summary (U and Ü, A and Ä etc)
I faced the problem with summary attachment which includes umlauts like: *U and Ü*, *A and Ä*; *O and Ö* etc. For example if two nodes starting with letters U and Ü

```
Umlauts
Ümlauts

```

only U letter will be displayed in summary. In case when some of nodes starting only with Ü, this letter Ü in correctly displayed in summary, problem appears when nodes have both *U and Ü* as capital letters.

---

Later I figured out that it's caused by GROUP BY query part

```
SELECT SUBSTRING(node.title, 1, 1) AS title_truncated, COUNT(node.nid) AS num_records
FROM node node
GROUP BY title_truncated
ORDER BY title_truncated ASC

```

Nodes with first *U and Ü* letters are treated were treated as U. How can I manage this problem?

# Answer
> 0 votes
If I had to take a guess at this it would be that your database is using utf8 and the default collation of utf8\_general\_ci. If I understand correctly, this collation does not handle diacritics very well, and would consider U and Ü the same. You may have better luck with utf8\_unicode\_ci. That said, most of my Unicode experience is with Elasticsearch, so I know less about MySQL collation (assuming that is your database). You may have more luck running this by a database-specific stackexchange.

Here is a reference on the two collation types: https://stackoverflow.com/questions/1036454/what-are-the-diffrences-between-utf8-general-ci-and-utf8-unicode-ci.

---
Tags: views
---


# Question
Title: What are the modules / pages / panels / or other features in Drupal which can be used to display an object which is made up of several content types?
I know views can be used, I have a functioning view which displays the relationship between the content types, using a limited number of fields.

Next I would like the hyperlink to resolve to a display of the **contents** of a "composite object" which includes a number of content types. What can I use?

Using: Views, Entity Reference, Panels, Page Manager

The first view is a **LIST** (alphabetical) of story titles, showing Relationships to other content types, as follows:
\- Person (firstname, lastname, etc.)
\- Story (field\_story\_title, orig copyright, description, etc.) Note: \[content:title\] is automatically generated and not used.
\- Series (field\_series\_title, body)

and these content types which are join tables
\- PersonStory (field\_personstory\_person\_id, field\_personstory\_ story\_id, relationship \[e.g. author\])
\- StorySeries (field\_storyseries\_story\_id, field\_storyseries\_series\_id, field\_storyseries\_logical\_order)

Person to Story is many to many, Story to Series is many to many.

I would like the hyperlink to resolve to a "page" which shows all of the fields from **multiple** content types which relate to that **one** story. This will be quite a lot of data: title, author, copyright, short blurb, synopsis (1K words) and a couple of images. So Views Megarow doesn't feel like an appropriate destination to me.

What are possible methods to show data from multiple content types?

# Answer
what's the best way to...

That is subjective. Here is a way to do it, not necessarily the best:

Views Megarow

> This module allows you to display content coming from a menu callback between two items of a views result set as a modal-like. You can use it to display a preview of your node or to build an administrative form.
>
> Said otherwise, you can dynamically display content below a row of a table of results coming from a view. This content is shown when you click on a link, it means that you can display anything from a preview of your node for instance to a moderation form of an entity.
> 1 votes

# Answer
The extra step between Story and Series with StorySeries will make this tricky. Why not link directly to series and person from story with an unlimited entity reference field?

One way that should work with your current configuration is to build a view with a block display that takes the entity reference field (field\_storyseries\_story\_id) as a contextual filter/argument (http://cl.ly/1S330x270j1J) with the default value as the "content id from url" (http://cl.ly/1S2C0l3o0K1q). Then include that block on the stories node and it only show the StorySeries nodes that relate to that story through the reference field. Then you'd need a add a relationship in the view to the series through the field\_storyseries\_series\_id to be able to display the series info. Then do the same with the PersonStory.
> 1 votes

---
Tags: 7, views, panels
---


title: Redirect legacy URL

text:
# Question
Title: Redirect legacy URL
I migrated a site not using Drupal to Drupal. Now I need to make sure that some legacy URLs are redirecting to the right node URL.
The node has the node ID (nid), the legacy ID (field\_leg\_id), the item ID (item\_id), the title (headline\_of\_the\_item), and the body.

The legacy URL example.com/type1/201203080034 should redirect to the new URL example.com/type1/2012/03/08/headline\_of\_the\_item/item\_id.

201203080034 is the legacy ID corresponding to 20120308 in the new URL.

How do I redirect users to the new node when I just have the legacy ID?
**update**

```
 // Redirect based on legacy ID.
$query = db_query("select lid.entity_id, lid.field_legacy_id_value, sid.field_site_content_id_value
                   from field_data_field_legacy_id lid
                   inner join field_revision_field_site_content_id sid on lid.entity_id = sid.entity_id
                   where lid.field_legacy_id_value = $content_id
                   LIMIT 1");

while ($row = db_fetch_object($query)) {
  $s_id = $row->sid.field_site_content_id_value;
  $item = node_load($s_id);
  if ($item) {
    drupal_goto("node/{$item->nid}", array(), 301);
  }
}

```

}

This is giving me 500 error. Tried to debug it without success.

**update based on @greendemiurge** Below is what worked for me.

```
   function my_item_redirect_item() {
       $args = arg();
       $content_id = end($args);
       $item = my_item_by_legacy_id($content_id);
      if ($item) {
         drupal_goto("node/{$item->nid}", array(), 301);
      }
   }

   function my_item_by_legacy_id($id) {
   // First, check if we have an imported item with this $id (field_legacy_id).
   $query = new EntityFieldQuery();

   $query->entityCondition('entity_type', 'node')
         ->fieldCondition('field_legacy_id', 'value', $id, '=')
         ->range(0, 1)
         ->addMetaData('account', user_load(1));

   $result = $query->execute();

   if (isset($result['node'])) {
      $nids = array_keys($result['node']);
      return node_load($nids[0]);
   }

 // Check if there is a node with Nid = $id
 return node_load($id);
}

```

# Answer
The first question on this is, how many URLs do you need to redirect? If it is a small number you may be better off using .htaccess. I doubt this is the case given your patterns.

The next question is, is there enough info in the old pattern to resolve to a current node, or do you need to create the mappings yourself?

If there is enough info, it may be possible to use Match redirect - https://www.drupal.org/project/match\_redirect. If that isn't exactly what you need you may want to implement some custom code based on match\_redirect\_init() in that module.

**edit**
The above additions give me enough to make a couple suggestions: First, the query would be better off done as a db\_select or an entity field query for the standard reasons. More important than that it is much more efficient, if possible, to let SQL do the matching and not the while loop.

Second, the hook that seems to work best for me is hook\_menu\_get\_item\_alter(). Others with more experience in menu routing may want to give some feedback on this approach, but it does work for me in a sandbox.

So, assuming a module called 'custom', this is what seems to work for me:

```
function custom_menu_get_item_alter(&$router_item, $path, $original_map) {
  $query = new EntityFieldQuery();

  // $path is everything after your base URL. I am assuming that this is what
  // you have in field_legacy_id.
  $query
    ->entityCondition('entity_type', 'node', '=')
    ->propertyCondition('status', 1, '=')
    ->fieldCondition('field_legacy_id', $path);

  $results = $query->execute();
  $results = array_keys($results['node']);
  $result = reset($results);

  if (!empty($result)) {
    $node = node_load($result);

    // This will retain your aliased path if you are using one. Important for
    // SEO, especially if you are using a 301.
    $path = drupal_get_path_alias("node/{$node}");
    drupal_goto($path, array(), 301);
  }
}

```

I wasn't able to test this ahead using your described setup, so it may need some tweaking. Please let me know if you need additional info.
> 2 votes

# Answer
This works for me. I need to check `current_path` to assure thats the raw url parameter and `menu_get_item` to assure that we're looking at the a random url as opposed to `/node/10` vs `1234-legacy-url`.

```
function legacyredirect_menu_get_item_alter(&$router_item, $path, $original_map) {
    $query = new EntityFieldQuery();

    $path = current_path();

    $query
        ->entityCondition('entity_type', 'node', '=')
        ->propertyCondition('status', 1, '=')
        ->addTag('nicedpq')
        ->fieldCondition('field_legacy_content_id', 'value', $path);
    $results = $query->execute();

    if (isset($results['node'])  && !menu_get_item($path)) {
        $results = array_keys($results['node']);
        $result = reset($results);
        if (!empty($result)) {
            $node = node_load($result);

            // This will retain your aliased path if you are using one. Important for
            // SEO, especially if you are using a 301.
            $path2 = drupal_get_path_alias("node/" . $node->nid);
            header("Location: $path2", 301);
            exit;
        }
    }
}

```
> 1 votes

---
Tags: 7, nodes, redirection
---


title: Inline entity form prepopulate

text:
# Question
Title: Inline entity form prepopulate
I have a content-type A which has a reference field to another content-type B. When creating/editing content with type A I let the user create/edit content of type B using the inline\_entity\_form module.

In this scenario, I like to pre-populate one field in content-type B. Here I'm using the entityreference\_prepopulate module, but when I add the field to my URL its not populated? As example, if the field in B has the name field\_myfiled , I write in the URL:

```
example.com/mypage?field_myfield=value1

```

This has worked before on fields which are rendered "normally". Is there something I'm missing since the filed is rendered by the inline\_entity\_form module?

# Answer
Please try Entity reference autofill with Entityreference prepopulate Module.

1. Add an entity reference field in your entityform.
2. The entity reference autofill will automatically fill reference value into field. We can load default value from URL. (`?field_name = value`)
3. Entityreference prepopulate will prepopulate the values. (you have to add existing fields for that.)

Hope this will help you.
> 0 votes

# Answer
These fine gentlemen had the answer I needed. Went with an custom code approach in the end.

form\_alter: Inline entity Form
> 0 votes

---
Tags: 7, entities
---


title: Change the warning message

text:
# Question
Title: Change the warning message
how to change the message "you must be logged in to place an order." I can not find in the rules and in the translation? thank you

# Answer
> 0 votes
In that case, what you'll want to do is set this variable: `commerce_checkout_redirect_message`. This variable is used by the module to populate the message.

For example:

```
variable_set('commerce_checkout_redirect_message', 'You must log in to continue.');

```

---
Tags: commerce
---


# Question
Title: Drupal 8 REST - How to export Drupal 8 Main navigation menu with REST service (JSON)
I have tried to **GET** main menu with rest path "/entity/menu/{menu}" but all I get in response JSON is a menu properties as uuid,language,id... without menu structure (links...).

```
{
  "uuid": "93d5d0a9-a962-4448-af01-c38aa3ebda22"
  "langcode": "en"
  "status": true
  "dependencies": [0]
  "_core": {
    "default_config_hash": "Q2Ra3jfoIVk0f3SjxJX61byRQFVBAbpzYDQOiY-kno8"
  }
  "id": "main"
  "label": "Main navigation"
  "description": "Site section links"
  "locked": true
}

```

I have also tried to **GET** menu through block (main menu is also a block) with "/entity/block/{block}" but without luck.

```
<br />
<b>Fatal error</b>:  Call to a member function access() on null in    <b>C:\Apache\work\test\core\modules\rest\src\Plugin\rest\resource\EntityResource.php</b> on line <b>52</b><br />

```

Is it possible to GET whole main menu with it's sub-menus in JSON format?

Thanks in advance. Danijel

# Answer
There is no such thing. Even if it would work, getting a menu would just give you the menu config entity, there's really nothing useful in there except the label.

You have to write your own rest resource plugin or simply a controller and return the data you need.
> 1 votes

# Answer
I ended up creating a module that does the basics for getting a menu via rest. I can just put the menus machine name in the URL and it will give me the title, url and weight in JSON format. I uploaded it to github so you can test it out. It is by no means ready for productions web sites. I was just messing around with angular and REST in D8.

Using angular, I would get the menu using the new URL resource after enabling the module and route resource `'entity/restmenu/{menu-name}?_format=hal_json` in your case `entity/restmenu/main?_format=hal_json`

```
app.controller('MainController', function($scope, $http) {
  $http.defaults.headers.common.Authorization = 'Basic YWRtaW46YWRtaW4=';
  $scope.menuData = $http.get('entity/restmenu/main?_format=hal_json').then(function(response) {
    $scope.menuData = JSON.parse(JSON.parse(response.data));
  });
});

```

https://github.com/rondog/rest-menu

```
<?php

/**
 * @file
 * Contains \Drupal\rest_menu\Plugin\rest\resource\rest_menu.
 */

namespace Drupal\rest_menu\Plugin\rest\resource;

use Drupal\Core\Render\HtmlResponse;
use Drupal\Core\Menu;
use Drupal\Core\MenuTreeParameters;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Entity\EntityStorageException;
use Drupal\Core\Session\AccountProxyInterface;
use Drupal\rest\Plugin\ResourceBase;
use Drupal\rest\ResourceResponse;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Psr\Log\LoggerInterface;

/**
 * Provides a resource to get view modes by entity and bundle.
 *
 * @RestResource(
 *   id = "restmenu_resource",
 *   label = @Translation("REST Menu Resource"),
 *   uri_paths = {
 *     "canonical" = "/entity/restmenu/{menu}"
 *   }
 * )
 */
class RESTMenuResource extends ResourceBase {
  /**
   * A current user instance.
   *
   * @var \Drupal\Core\Session\AccountProxyInterface
   */
  protected $currentUser;

  /**
   * Constructs a Drupal\rest\Plugin\ResourceBase object.
   *
   * @param array $configuration
   *   A configuration array containing information about the plugin instance.
   * @param string $plugin_id
   *   The plugin_id for the plugin instance.
   * @param mixed $plugin_definition
   *   The plugin implementation definition.
   * @param array $serializer_formats
   *   The available serialization formats.
   * @param \Psr\Log\LoggerInterface $logger
   *   A logger instance.
   * @param \Drupal\Core\Session\AccountProxyInterface $current_user
   *   A current user instance.
   */
  public function __construct(
    array $configuration,
    $plugin_id,
    $plugin_definition,
    array $serializer_formats,
    LoggerInterface $logger,
    AccountProxyInterface $current_user) {
    parent::__construct($configuration, $plugin_id, $plugin_definition, $serializer_formats, $logger);

    $this->currentUser = $current_user;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
    return new static(
      $configuration,
      $plugin_id,
      $plugin_definition,
      $container->getParameter('serializer.formats'),
      $container->get('logger.factory')->get('rest'),
      $container->get('current_user')
    );
  }
  /**
   * Responds to GET requests.
   *
   * Returns a list of bundles for specified entity.
   *
   * @throws \Symfony\Component\HttpKernel\Exception\HttpException
   *   Throws exception expected.
   */
  public function get($entity) {
    $menu_name = $entity;
    $menu_parameters = \Drupal::menuTree()->getCurrentRouteMenuTreeParameters($menu_name);
    $tree = \Drupal::menuTree()->load($menu_name, $menu_parameters);
    $result = array();

    foreach ($tree as $element) {
      $link = $element->link;
      array_push($result, array(
          'title' => $link->getTitle(),
          'url' => $link->getUrlObject()->getInternalPath(),
          'weight' => $link->getWeight()
        )
      );
    }
    return new ResourceResponse(json_encode($result));
  }
}

```
> 4 votes

---
Tags: routes, 8
---


# Question
Title: https - Works for the homepage but fails for all other pages
Running D7 7.43 on Debian 8 with Apache 2.4.10. Everything seems to be set up properly to run https. I go to my dev site https://example.com and all is great. But the moment I go anywhere else (e.g. https://example.com/WhatEverpage\_I\_go\_To I get error 404,

The requested URL /WhatEverpage\_I\_go\_To was not found on this server.

I seem so close but yet not there yet. Where do I look to get this thing working for any page on my site, not just the homepage?

Important note, I changed /etc/apache2/site-enabled/default-ssl.conf

From DocumentRoot /var/www/html

To DocumentRoot /var/www/drupal

Before doing that not even the homepage would work.

Thanks.

# Answer
> 0 votes
Check to make sure you are using the default .htaccess file. It sounds like your mod\_rewrite settings are not working properly and/or not handling the https url.

---
Tags: uri
---


# Question
Title: Problem with Facebook Feed: Warning: file_get_contents(): https:// wrapper is disabled
I'm having a problem with my Facebook pull feed. It works fine on a development server, but on my live server the block doesn't appear on the page, and I get two php errors, and a single Facebook pull error in my recent logs.

The first php error, which I think is significant is:

```
Warning: file_get_contents(): https:// wrapper is disabled in the server configuration by allow_url_fopen=0 in _facebook_pull_feed() (line 280 of /home/phislub9/public_html/sites/all/modules/facebook_pull/facebook_pull.module).

```

The second php error is related to the first one:

```
Warning: file_get_contents(https://graph.facebook.com/oauth/access_token?client_id=1392108967676515&client_secret=563ff2dd27ddec75d9b79dc918fe93d4&grant_type=client_credentials): failed to open stream: no suitable wrapper could be found in _facebook_pull_accesstoken() (line 299 of /home/phislub9/public_html/sites/all/modules/facebook_pull/facebook_pull.module)

```

And the Facebook Pull error doesn't give any diagnostic information beyond that the module isn't working.

# Answer
> 0 votes
Put this in your settings.php:

```
ini_set('allow_url_fopen' , 1);

```

If that solves the issue you will want to hard code that into your php.ini.

---
Tags: social-network
---


# Question
Title: How to Display popup block when user scrolls down to the bottom of node
I am using drupal 7. I want to display a popup block for a user to share the node on social media, but i want this popup to appear as the user scrolls down to the bottom of the node. Any module(s) possible to achieve this?

I have tried the Popup and Popup On Load modules but none seems to achieve this objective.

Any help or suggestions appreciated. Thank you

# Answer
You could do It without modules using some CSS and javascript.

You can create the block with the content you want to show, keep it hidden by CSS and, once the user scrolls down enough, trigger a js event that toggles the blok class to a visible one.

Here You can find how to trigger an event when scrolling to a certain point:

https://stackoverflow.com/questions/21561480/trigger-event-when-user-scroll-to-specific-element-with-jquery

Using the example code, you could use something like:

```
$(window).scroll(function() {
   var hT = $('#scroll-to').offset().top,
       hH = $('#scroll-to').outerHeight(),
       wH = $(window).height(),
       wS = $(this).scrollTop();
   if (wS > (hT+hH-wH)){
       $('#yourblock').toggleClass('visible');
   }
});

```
> 1 votes

---
Tags: 7, javascript
---


# Question
Title: How to use current user object in Drupal 8?
The answer to "Is there a function to get the current user object that avoids accessing the global variable?" includes this:

> In Drupal 8, you simply use the static method \Drupal::currentUser() to get the equivalent of Drupal 7 $GLOBALS\['user'\]

I tried to use the following code:

```
$user = \Drupal::currentUser();
$name = $user->get('name')->value;

```

But that results in an error like so:

> Fatal error: Call to undefined method Drupal\Core\Session\AccountProxy::get() in /home/remindme/uhoc.org/modules/testmodule/src/Form/FruitForm.php on line 173 (Line 173 is `$name = $user->get('name')->value;`

Do I need to used some namespace or there is some other way to access the user object?

# Answer
Yes you need to use a name space, you can include the name space directly like this

```
$user = \Drupal\user\Entity\User::load(\Drupal::currentUser()->id());
$name = $user->get('name')->value;

```
> 6 votes

---
Tags: users, 8
---


# Question
Title: Views contextual filters for user term references
I have two user roles that have term reference fields tied to profiles. One has a single select (user role A) and the other a multi select (user role B), but they reference the same taxonomy.

I have a view that lists all nodes of type C submitted by various users with a single user reference to user role A. My goal is to filter this to those with a user reference who has a term reference in common with a user of role B. The view is accessed by visiting user B's profile page and displayed as a block.

My thinking was to first add a relationship to the single select taxonomy term reference for role A. Then, add a contextual filter that loads the user id from the current URL and puts all the term IDs from the multiselect into the arg, for example 3+5+9. Finally, I would do custom PHP or Taxonomy term validation to see if user role A is in this list.

Setting the argument works fine. I can dsm this and see the correct TID. For validation, custom PHP doesn't seem to work at all. No rows are returned even when I simply do a "return true;" in there. For taxonomy term, I have it set to

* Validator: Taxonomy term
* My vocab is checked
* Filter value type: term id
* Action: no results found

Any idea what I'm doing wrong or the correct way to solve this problem?

EDIT: There was a problem with htaccess which explains why return true was failing. However, I still can't quite get the contextual filter and relationship logic down.

# Answer
> 1 votes
I can try this on a view, but I think the way to do it is to add the relationship, then add a Contextual filter of the Taxonomy Name. That works

with one Relationship to Contextual Filter, so why wouldn't it work with two.

---
Tags: views
---


# Question
Title: Loading bootstrap.inc in external PHP file in a subdirectory
I'm trying to check if there is a user logged into drupal in a PHP script that resides within a subdirectory of the drupal root. I know that there can be issues with calling the bootstrap anywhere apart from in the drupal root, so I've created a `drupal_bridge.inc.php` file inside the root containing the following code, which I then call in the PHP script using `include`.

```
<?php

define("DRUPAL_ROOT",     "/var/www/vhosts/mysite.com/httpdocs/");

$current_wd = getcwd();

chdir(DRUPAL_ROOT);

print getcwd();

require_once DRUPAL_ROOT . '/includes/bootstrap.inc';

global $base_url;

$base_url = (array_key_exists('HTTPS', $_SERVER) ? 'https://' : 'http://') . $_SERVER['HTTP_HOST'];

drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);

chdir($current_wd);

global $user;

if ($user->uid) {
    print "Logged in";
} else {
   print "Logged out";
}

echo 'INCLUDED';

?>

```

However, when I visit the PHP script in the browser it says I am logged out. Strangely though if I visit the `drupal_bridge.inc.php` file directly it can access the user information and it says that I am logged in.

I have set `$cookie_domain = .mysite.com` in the settings file as well. I have password protected the directory containing the PHP script but I didn't think that made a difference at this level.

Any ideas?

Also, I have looked into turning this in a module but it is not really practical so I would appreciate it if you did not advise doing so.

**UPDATE**: I just did a `print_r($GLOBALS);` to see if I could find out what was actually available and I found the following errors, if that helps. http://pastebin.com/YtHPGD75 (too long to post here)

# Answer
> 1 votes
The bare minimum required is:

```
define('DRUPAL_ROOT', '/var/www/vhosts/mysite.com/httpdocs/');
$_SERVER['HTTP_HOST'] = 'mysite.com';
$_SERVER['REMOTE_ADDR'] = '127.0.0.1';
require_once DRUPAL_ROOT . '/includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);

```

If you don't want to fully bootstrap and only get the session, see the technique defined in Getting the current user without bootstrapping to DRUPAL\_BOOTSTRAP\_SESSION

# Answer
> 1 votes
After some time, and lots of experimentation, I have a solution at last thanks to a discussion on osTicket. Unfortunately the issue was less due to Drupal, more down to osTicket and the fact that I had *included* the 'drupal bridge' in the wrong file. However an important note to make is that a drupal bridge - a file residing inside the Drupal root directory including bootstrap code - must be used to access session information in external scripts, rather than using the bootstrap code directly.

I hope that somebody will find this useful.

# Answer
> 0 votes
setting the `$base_url` in settings.php rather than leave Drupal to resolve it will solve the problem.

---
Tags: 7, users, bootstrapping
---


# Question
Title: how to Display author and date information according to my requirement?
I am created a content type with field **Title**, **Project code**, **Advertise** and **Body**.

I want to display Author name and date information after Project code but by default it showing after title field so please let me know how to display according to my requirement.

# Answer
**Steps to change the order**

* Override node.tpl.php in your theme template.
* Rename it to **node--\[content\_type\_machine\_name\].tpl.php** if you want this for a specific content type.
* Remove

code and place it after the Project code field is rendered.

* Clear the cache after making the change.

Hope that this helps.
> 2 votes

# Answer
**Override the node.tpl.php file in your themes template files sites/all/themes/template say(node--article.tpl.php)**

after overriding template file comment this line **print $submitted;**

place obove commented line whevever you want to display.
> 0 votes

---
Tags: datetime
---


title: Understanding `file_managed` table

text:
# Question
Title: Understanding `file_managed` table
I am trying to understand the Drupal database schema because I need to access the database via MySQL by another system and I do not have access to the original Drupal developer of the site nor do I know Drupal well at this point (I did work with it 8 years ago) and it will be much easier to access with MySQL than to set up a server to have to host a PHP-based API or similar.

## `file_managed`

In the `file_managed` table there is a field `uri` where the data all appears to be in the same of two formats:

* `public://<filename>`, OR
* `public://<directory>/<filename>`

My two questions related to `file_managed` are:

1. What is `public://` mean here? Does it translate to some root URL like `http://example.com/files` or similar?
2. When there is a directory in the `uri`, what do they represent?

**UPDATE:** I do not have access to the working Drupal system, I only have access to the database.

# Answer
> 2 votes
I am just going to answer your first two questions (about `file_managed`). Please ask a separate questions for the second set (about `file_usage`) and about the relation between the tables.

> What is public:// mean here? Does it translate to some root URL like http://example.com/files or similar?

Navigate to *Administration » Configuration » Media » File system*. Take a look at the value for "Public file system path" (default is `sites/default/files`). this is the path to `public://` from your site root.

> When there is a directory in the uri, what do they represent?

The path *below* the public file system root.

So, given the that the public path is the default, `public://foobar/image.jpg`, this expands to the path `sites/default/files/foobar/image.jpg`, or the URL `http://example.com/sites/default/files/foobar/image.jpg`

---
Tags: database, files
---


# Question
Title: How to get Address Field to display correctly with Autocomplete?
I want to create a postal field for addresses in the Philippines.

I have set up a sandbox site with a content type that has just one field, of type addressfield and using the autocomplete widget. Only one country is allowed. However, when I create content, all I can see is the field for entering the address and the Google map, I cannot see the Address Field fields. When I enter an address in the Philippines, it gets coded correctly by Google and displays properly on the map. However, if I then try to save the field, it tells me that obligatory fields ("Address 1" and "City" in this case) are missing.

If I click on "enter one manually", then nothing happens.

This is only accessible by a logged-in user, so I presume that caching is not the problem.

I have tried using FF45 and the lastest release of Chromium, all to no avail

I also presume that I must have made a mistake setting something up, but i cannot work out what that might be...

# Answer
> 0 votes
Turns out that there is an incompatibility between Addressfield Autocomplete and/or the geocomplete.js library it uses, and the version of JQuery that gets bundled with Drupal 7.

The solution is to install the JQuery Update module, and set the JQuery version to 1.10

---
Tags: ajax, entities
---


title: How to create queue for email sending

text:
# Question
Title: How to create queue for email sending
I am using PepiPost mail service and I created custom mail system class for integrating PepiPost service. I can successfully send email from Drupal site. If a connection timeout 504 occurs during email sending process, email is not triggered how can I handle this scenairo. This is the code I used for email sending

```
class CustomMailSystem implements MailSystemInterface {

  public function format(array $message) {
    // Join message array.

      $message['body'] = implode("\n\n", $message['body']);
      return $message;
  }

  /**
   * Implement mail method to send mail via Sendgrid.
   *
   * @param array $message
   * @return bool
   */
  public function mail(array $message) {
    $email = new Email();

    $data = array(
      'api_key'   =>  '****************',
      'recipients'    =>  $to
      'email_details' => array(
        'from'          =>  $from,
        'subject'       =>  $subject,
        'content'       =>  $body,
    ),

  try {
    $response = $email->sendJson( $data );

  catch(Exception $e){
      print 'Call failed due to unhandled exception/error('. $e->getMessage().')'."\n";
    }
  }
}

```

# Answer
you should always use some or the other Mail Transfer Agent (MTA) like Postfix, which helps in managing queue in-case of emails getting lost
> 0 votes

---
Tags: 7, emails, queue
---


# Question
Title: How do I execute a function every 3 months?
What's the proper way to execute a function every 3 months? Watchdog variables don't seem to be available after a certain time. I could create another table to insert the execute function date to compare, but it doesn't seem to be the best approach.

The functionality of such functions are:

* Send an eMail
* Tag an inactive user

# Answer
`watchdog()` is not appropriate place for storage; the `$variables` parameter is for formatting the display of variable data (e.g. the *USERNAME* in "User *USERNAME* has logged in"), not for long term storage of application data.

Instead, use a combination of `hook_cron()` and the persistent variable functions (`variable_get()` and `variable_set()`) to execute a cron task that remembers when it was last run.

```
/**
 * Implements hook_cron().
 */
function MYMODULE_cron() {

  // Look up last time MYMODULE_function() was run compared to 3 months ago.
  if (variable_get('MYMODULE_function_last_run', 0) <= strtotime('-3 month')) {
     // Run my function
     MYMODULE_function();

     //Store the time when MYMODULE_function() was last run.
     variable_set('MYMODULE_function_last_run', time());
  }
}

```
> 4 votes

# Answer
The Rules module together with `Rules Scheduler` (a sub-module of it), can be used for executing functions such as ***sending eMails*** (as in your comment below the question), as explained in the steps below,.

### Step 1: Create a field to store the "next renewal" date

Add a field to the "user" entity with machine name (say) `field_next_renewal`. Allow only 1 date (to store the "next" date for a sending an eMail to some user, eg about some renewal).

### Step 2: Create a Rules "Component"

Here is the Rules **Component** to be created (in Rules export format, just import it in your own environment via copy-paste):

```
{ "rules_send_email_notification" : {
    "LABEL" : "Send eMail notification",
    "PLUGIN" : "action set",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "USES VARIABLES" : { "user_to_notify" : { "label" : "User to be notified", "type" : "user" } },
    "ACTION SET" : [
      { "mail" : {
          "to" : [ "user-to-notify:mail" ],
          "subject" : "Reminder about your next renewal",
          "message" : "This is a reminder about your next renewal on [user-to-notify:field_next_renewal] ...",
          "from" : "[site:mail]",
          "language" : [ "" ]
        }
      }
    ]
  }
}

```

Obviously, the ***Subject*** and ***Content*** of the eMail may need review / tuning, while you might also want to use some other ***From*** eMail ID.

### Step 3: Create a "Rule" using the Rules Component

Here is the **Rule** to be created, in Rules export format (just import it in your own environment via copy-paste):

```
{ "rules_email_user_every_3_months" : {
    "LABEL" : "eMail user every 3 months",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "rules_scheduler" ],
    "ON" : { "user_insert" : [] },
    "IF" : [
      { "entity_has_field" : { "entity" : [ "account" ], "field" : "field_next_renewal" } }
    ],
    "DO" : [
      { "data_set" : { "data" : [ "account:field-next-renewal" ], "value" : "+6 month" } },
      { "schedule" : {
          "component" : "rules_send_email_notification",
          "date" : {
            "select" : "account:field-next-renewal",
            "date_offset" : { "value" : 7776000 }
          },
          "identifier" : "[account:name]",
          "param_user_to_notify" : [ "account" ]
        }
      }
    ]
  }
}

```

The above rule refers to the *Rules Component* from the previous step.

Note that the `7776000` is the equivalent of 3 months in seconds. You may want to reduce that a bit, e.g. with a number of seconds equivalent to a few days (or a week or so). That way the eMail will be triggered a few days before the actual renewal.

### Step 4: tagging inactive users

By creating an extra rule similar to the rule in step 3, you could also "flag" inactive user using the integration of Rules with the Flag module. That would be a solution for ***tagging such users*** (as in your comment below the question) also. The only remaining challenge about that would be to find the Rules Condition to identify "*inactive*" users.
> 2 votes

---
Tags: 7, cron, log-messages
---


title: Access user fields?

text:
# Question
Title: Access user fields?
`$account = \Drupal::currentUser()` loads the user object into `$account`, but how do I access custom fields I've created on the user object (via the admin UI)?

With `dpm($account)` I can't see any of my custom fields.

# Answer
> 36 votes
`\Drupal::currentUser()` returns an `Drupal\Core\Session\AccountInterface` object. That could be a full user (that would be a `Drupal\user\UserInterface`), but right now, for the default authentication method, it is not.

Use this to get the user entity and all the fields:

```
$user = \Drupal\user\Entity\User::load(\Drupal::currentUser()->id())

```

D7 had exactly the same behavior, the difference now is just that in D7, they were simply different stdClass'es, now you have explicit interfaces to differentiate the two.

# Answer
> 25 votes
And here is how to get it out of that object:

```
// Load the current user.
$user = \Drupal\user\Entity\User::load(\Drupal::currentUser()->id());

// Get field data from that user.
$website = $user->get('field_website')->value;
$body = $user->get('body')->value;

// Some default getters include.
$email = $user->get('mail')->value;
$name = $user->get('name')->value;
$uid= $user->get('uid')->value;

```

# Answer
> 1 votes
`Drupal::currentUser()` returns an object implementing `Drupal\Core\Session\AccountProxyInterface`. That is different from what returned from `User::load()`, which is an object implementing `Drupal\user\UserInterface`.

This means it's not assured you get a full `User` object with its fields loaded, but it's not even assured you get a `User` object. As consequence, you call call some of the methods available from the `User` class, such as `User::get()`. You can call `AccountInterface::id()`, which returns the user ID; with that, you can then load the full `User` object with `User::load()` and have access to all the fields modules attached to the entity.

```
use Drupal\Core\Session\AccountProxyInterface;
use Drupal\user\Entity\User;

$account = User::load(\Drupal::currentUser()->id());

```

With `$account`, you can then access all the fields associated with a user account.

---
Tags: users, 8
---


title: Understanding `file_usage` table

text:
# Question
Title: Understanding `file_usage` table
I am trying to understand the Drupal database schema because I need to access the database via MySQL by another system and I do not have access to the original Drupal developer of the site nor do I know Drupal well at this point (I did work with it 8 years ago) and it will be much easier to access with MySQL than to set up a server to have to host a PHP-based API or similar.

## `file_usage`

In the `file_usage` table there are two (2) field `module` and `type` and using a `GROUP BY` query this is what I get:

```
module | type
-------|-------
 file  | node
 imce  | file
 user  | user

```

So it is pretty obvious that `module` means that entry was added by either the `file`, `imce` or `user` modules, right?

My questions are:

1. What does `node`, `file` and `user` mean in this context?
2. Is `file/node` effectively the same as `imce/file`, or is it something different?
3. Does `user/user` mean it is a file associated with the user?
4. Further `file_usage` has an `id` column; can I assume:
    1. That `nid` for `file/node` and `imce/file`?
    2. And `uid` is for `user/user`?
    3. Or something else?

**NOTE:** I do not have access to the working Drupal system, I only have access to the database.

# Answer
> So it is pretty obvious that module means that entry was added by either the file, imce or user modules, right?

Right, it's just the name of the module that added the record.

> What does node, file and user mean in this context?

They're arbitrary strings used by each module to identify the "type" of file usage the current record relates to. A single module might keep to track of files in several different contexts, so this is important.

> Is file/node effectively the same as imce/file, or is it something different?

They're different. file/node is for usage of files attached to a file field on a content type; imce/file is for tracking files uploaded and (potentially) inserted into a WYSIWYG.

> Does user/user mean it is a file associated with the user?

It doesn't have to necessarily, just because it's called user/user, but in this case yes, it does.

> Further file\_usage has an id column; can I assume:...

Yes, that assumption is correct. The ID can relate to anything at all though, not just an entity that lives inside Drupal, it's up to the module using the table to be able to resolve which object/item is being referred to from the data in that table.
> 3 votes

# Answer
> So it is pretty obvious that module means that entry was added by either the file, imce or user modules, right?

Yes. The `module` column tells you what module is using this instance of the file.

> What does `node`, `file` and `user` mean in this context?

This is the name of the entity that is using this is instance of the file. So if it is `node`, then the file is attached to a node, if it is `file` then it is a standalone file entity, if it is `user` it attached to a user (typically a profile image) and so on.

> Is `file/node` effectively the same as `imce/file`, or is it something different?

Different. `file/node` are a file attached to a node (main Drupal content). `imce/file` is managed by the `imce` module as standalone files.

Each entity using the file has its own primary key identifying instance, The `id` column identifies this instance. For instance the `id` associated with `imce/file` identifies the specific *file* entity (and just reuses the file `fid` for the `id` column), while the `id` associated with the `file/node` identifies the *node* entity.

> Does `user/user` mean it is a file associated with the user?

It tells you that the file was added to Drupal's manged files by the core `user` module, and is attached to a `user`entity.

> Further `file_usage` has an id column; can I assume:
> 1. That `nid` for `file/node` and `imce/file`?

It is `nid` for `file/node`, but `fid` for `imce/file`.

> 2. And `uid` is for `user/user`?

Yes.
> 2 votes

---
Tags: users, database, files
---


# Question
Title: drop migration tables after migration ended
After uninstall migration modules the tables created not removed and still exist and can not be reasonable to deploy without remove that tables.

**Problem:**

The 3 modules Migrate, Migrate\_drupal, Migrate\_drupal\_ui didn't implement Hook\_uninstall() to remove these tables or other data related to migration and have no use after complete migration

The issue on drupal.org

# Answer
> 1 votes
**Motivation:**

List all tables prefixed with migrate\_ in hook\_install. Implement hook\_uninstall to remove all tables prefixed with migrate\_ except those listed when install the same prefix.

**Solution:**

The migrate core module must list all tables prefixed with migrate\_ during installl. The migrate module must remove all tables prefixed with migrate\_ during uninstall.

drop\_migration\_tables\_during\_uninstall.patch implemented the hook\_install && uninstall hooks in migrate.install to drop all tables prefixed with migrate except those where found during module installation (may be other contributed or custom modules defines tables prefixed with migrate) which is not a good decision

---
Tags: 8, migrations
---


# Question
Title: How to display a Leaflet map in modal window?
I produce geospatial data in a content type with addressfield and geofield. I can display this data in a Leaflet map as field without any problem. But I have to use here a modal, therefore I render the map programmatically:

```
<?php
$map = leaflet_map_get_info('google-high-res');
$map['settings']['zoom'] = 15;

$lon=$entity->field_terkep['und'][0]['lon'];
$lat=$entity->field_terkep['und'][0]['lat'];

$features = array(
   array(
        'type' => 'point',
        'lon' => $lon,
        'lat' => $lat
      )
    );
print leaflet_render_map($map, $features, $height);
?>

```

When I display this map as a field, everything is OK, visitors can see the map as intended (marker in the middle etc.) But if I place it in a modal, multiple issues appear (see in the attached screenshot): Only one map tile is generated and the marker is in the wrong place in the modal as well, it's in the top left corner. I have tried Bootstrap Modal and Colorbox, it doesn't make any difference.

# Answer
I found similar issues either with Leaflet or Google maps, like this one here. So I have to reload or re-render the map after the modal window become visible. For this purpose I inserted this jQuery code which does the trick:

```
drupal_add_js('
jQuery(function($) {
$(document).ready(function(){
$(\'#myMap\').on(\'shown.bs.modal\', function(){
var map = Drupal.settings.leaflet[0].lMap;
map.invalidateSize();
});
});
});
', 'inline');

```
> 0 votes

---
Tags: 7, javascript, modal-dialogs
---


title: Drupal as Framework

text:
# Question
Title: Drupal as Framework
I am working on a project where I decided to use Drupal as the backend, but I didn't wanted to use anything else, but the entities API. The project is working like a charm and everything is working smooth.

I am a bit batter by the fact, that even when not using nodes, I can not disable the node core module and therefore I still have a ton of extra tables I will never use. Some time ago I remember people talking about "small core".

What happen to that?

# Answer
> 2 votes
In Drupal 7, the Node module is always enabled, even if the profile you are using for installing Drupal doesn't actually declare it as dependency. See the content of minimal.info and standard.info.
In Drupal 8, profiles requiring the Node module need to explicitly define their dependencies from it. (See the content of standard.info.yml.)

If you don't need to use the Node module, you need to create a Drupal 8 profile that doesn't declare the Node module as its dependency. The necessary changes to Drupal 7 that allows decoupling the rest of the core modules from the Node module will not be backported, so your only chance is using Drupal 8 with a profile that doesn't depend from the Node module.

---
Tags: 7, entities
---


# Question
Title: Limit the number of levels (depth) of a taxonomy vocabulary
I would like to limit the depth of a taxonomy vocabulary to a maximum number parent/child nestings. I would like my users to not be able to add at most 4 levels deep of taxonomy terms per tree. Is there a module for this or what code is needed to enforce this depth on the tree?

# Answer
After a lot of Googling and trial and error I came up with the following means of limiting a vocab's depth. You can make it as specific as you like:

**Limit the depth of Parents on the term edit page:**

```
function MY_MODULE_form_taxonomy_form_term_alter(&$form, &$form_state) {
  if ($form['#bundle'] == 'MY_VOCAB') {
    // Limit parents to none or only top level items
    foreach ($form['relations']['parent']['#options'] as $tid => $option) {
      if (substr($option, 0, 1) == '-') {
        unset($form['relations']['parent']['#options'][ $tid ]);
      }
    }
  }
}

```

**Limit the depth of Tabledrag on the taxonomy terms listing page:**

I could not re-implement `theme_taxonomy_overview_terms()` as another module had already done this and it made no sense to do that.

```
function MY_MODULE_preprocess_page(&$variables) {
  if (current_path() == 'admin/structure/taxonomy/MY_VOCAB') {
    // Prevent tabledrag from allowing more than two levels in this hierarchy
    $settings['tableDrag']['taxonomy']['term-depth'][0] = array(
      'target' => 'term-depth',
      'source' => 'term-depth',
      'relationship' => 'group',
      'action' => 'depth',
      'hidden' => false,
      'limit' => 1,
    );
    drupal_add_js($settings, 'setting');
  }
}

```
> 1 votes

# Answer
No, there is no current way to limit a taxonomy depth using a 3rd party module that I know of. The maximum depth of taxonomies is limited by the database table structure, not just PHP code, to 9 levels in D7. You could add a custom validator on taxonomy term add/edit forms (and with extra logic certain Taxonomy Trees) to enforce a maximum parent depth. See Custom Validation while adding a term under taxonomy
> 0 votes

---
Tags: taxonomy-terms
---


# Question
Title: Is there a limit on taxonomy hierarchy depth by default?
Is there a limit on a taxonomy hierarchy depth by default? This question's answer states that the default limit is 9 due to database table structure, but I successfully nested 10+ terms in a vocabulary locally, so that doesn't seem to be correct.

# Answer
I just posted an answer to a similar question at https://drupal.stackexchange.com/a/199247/6488 but if you are wanting it to be a sitewide default you would:

1. remove the `if ($form['#bundle'] == 'MY_VOCAB')` from `hook_form_taxonomy_form_term_alter()`
2. Change the check against `current_path()` in the `hook_preprocess_page()`

Some clever person could turn this into a module!
> 0 votes

---
Tags: 7, taxonomy-terms
---


title: Search result is empty

text:
# Question
Title: Search result is empty
When I do a search, I got an empty result even though the result shouldn't be null. I even get a null result if I don't filter anything. However fulltext search works, only facets corresponding to a field seems to not work.

I copied a production database to a test server. Everything works fine on production, but I can make the test copy works.

I've seen there is some issue with facets if the user doesn't have the permission to create temporary table. I checked that, and I think I have the permission.

Any idea ? (I use drupal commerce)

# Answer
> 0 votes
The problem was due to different behavior between mysql 5.6 and 5.7. I thought I had the same environment between production and test but I was wrong. I use a docker image for mysql but didn't specify a version so I ended up with two different versions on the two systems, even though the provisioning looked the same.

---
Tags: commerce, search
---


title: how can I create special views search

text:
# Question
Title: how can I create special views search
I create advanced search with views. I want type one word and search it in 10 fields that I create in content and show all contents that use "word" in each fields

# Answer
You can create an exposed view filter using 'global: combine fields filter', and select all the fields where you want to search the 'hello' (or wathever word you want) word. As long as you don't specify a content type, you will get all the elements that contain one of those fields with the written word.

To add the fields to the combine filter you need to have them on the fields you are showing in the view, but you can hide them if you want.

> edit: this is a solution in D7 and but I think D8 may provide a very similar system.
> 0 votes

---
Tags: 8
---


# Question
Title: How to get the list of values and keys for a given list field
I want to programmatically get the list of possible key values for a field, along with their labels. For example:

```
1 => red
2 => blue
3 => Yellow
...

```

and so on. How do I do that?

# Answer
It's just a matter of getting the field basic data, then get a list of possible values using Field API function that is part of List module.

```
$field = field_info_field([FIELD_MACHINE_NAME]); // This one gets the field data
$field_values = list_allowed_values($field); // This one gets an array of values => labels
$field_key = array_search('red', $show_field_values); // This one gets the key for the value labelled "red", that is: 1

```
> 1 votes

---
Tags: 7, entities
---


title: Convert variable_set to d8 variables

text:
# Question
Title: Convert variable_set to d8 variables
i have a variable\_set defined in d6 as follows :

```
variable_set('cleanupeditform_formkeys', array(
 'menu' => t('Menu settings'),
 'revision_information' => t('Revision information'),
 'attachments' => t('File attachments'),
 'comment_settings' => t('Comment settings'),
 'author' => t('Authoring information'),
 'options' => t('Publishing options'),
 ));

```

How i can convert to drupal 8 form ? I know for a single case it would be like

```
\Drupal::state()->set('cleanupeditform_formkeys','my_value');

```

Thanks .

# Answer
> 1 votes
It's no different, you can also save an array in state:

```
\Drupal::state()->set('cleanupeditform_formkeys', ['foo' => 'bar']);

```

# Answer
> 1 votes
You should use `\Drupal::config()` instead of `\Drupal::state()`. States are used for hidden system values and are not deployed between environments, but configs store values/changes from site building process and could be synchronized between environments.

---
Tags: 8, configuration
---


# Question
Title: What causes my problem when trying to create multiple tables in hook_schema?
I'm working on a module that has 2 tables and this is my code:

```
function gen_schema(){
$schema = array();

//table cv
$schema['cv'] = array(
        'description' => 'table contenant les cv.',
        'fields' => array(
                'cvid' => array(
                        'description' => 'clé primaire de la table cv.',
                        'type' => 'serial',
                        'unsigned' => TRUE,
                        'not null' => TRUE,
                ),

                'uid' => array(
                        'type' => 'int',
                        'unsigned' => TRUE,
                        'not null' => TRUE,
                        'description' => 'Primary Key: Unique user ID.',
                        'default' => 0,
                ),
        ),

        'foreign keys' => array(
                'node_cv' => array(
                        'table' => 'node_revision',
                        'columns' => array('vid' => 'vid'),
                ),
        ),

        'primary key' => array('cvid'),
);

//table Information generale
$schema['information'] = array(
        'description' => 'table contenant les informations generales d\'un cv.',
        'fields' => array(
                'infoid' => array(
                        'description' => 'clé primaire de la table information.',
                        'type' => 'serial',
                        'unsigned' => TRUE,
                        'not null' => TRUE,
                ),

                'cvid' => array(
                        'description' => 'clé primaire de la table cv.',
                        'type' => 'serial',
                        'unsigned' => TRUE,
                        'not null' => TRUE,
                ),

                'uid' => array(
                        'type' => 'int',
                        'unsigned' => TRUE,
                        'not null' => TRUE,
                        'description' => 'Primary Key: Unique user ID.',
                        'default' => 0,
                ),

                'nom' => array(
                        'description' => 'nom et prenom du proprietaire du cv.',
                        'type' => 'varchar',
                        'length' => 120,
                        'not null' => TRUE,
                        'default' => '',
                ),

                'nationalite' => array(
                        'description' => 'nationalité du proprietaire du cv.',
                        'type' => 'varchar',
                        'length' => 120,
                        'not null' => TRUE,
                        'default' => '',
                ),

                'profession' => array(
                        'description' => 'profession du proprietaire du cv.',
                        'type' => 'varchar',
                        'length' => 120,
                        'not null' => TRUE,
                        'default' => '',
                ),

                /*'datenaiss' => array(
                        'description' => 'date de naissance du proprietaire du cv.',
                        'mysql_type' => 'datetime',
                        'not null' => TRUE,
                        'default' => '',
                ),*/

                'fonction' => array(
                        'description' => 'fonction du proprietaire du cv',
                        'type' => 'varchar',
                        'length' => 120,
                        'not null' => TRUE,
                        'default' => '',
                ),

        ),
        'foreign keys' => array(
                'node_cv' => array(
                        'table' => 'node_revision',
                        'columns' => array('cvid' => 'cvid'),
                ),
                'node_author' => array(
                        'table' => 'users',
                        'columns' => array('uid' => 'uid'),
                ),
        ),
        'primary key' => array('infoid'),
);

```

But I'm getting this error **PDOEXCEPTION**, and only the `cv` table is created.

Any suggestions about what I'm doing wrong?

# Answer
> 2 votes
The problem is that you have two auto-incrementing fields on the second table. Only the primary key should be auto-incrementing:

```
'infoid' => array(
  'description' => 'clé primaire de la table information.',
  'type' => 'serial',
  'unsigned' => TRUE,
  'not null' => TRUE,
),
'cvid' => array(
  'description' => 'clé primaire de la table cv.',
  'type' => 'serial',
  'unsigned' => TRUE,
  'not null' => TRUE,
),

```

What you want for cvid is type 'int' not type 'serial'

```
'cvid' => array(
  'description' => 'clé primaire de la table cv.',
  'type' => 'int',
  'unsigned' => TRUE,
  'not null' => TRUE,
),

```

That should go through without a PDO exception.

---
Tags: database
---


title: How to create a User search view?

text:
# Question
Title: How to create a User search view?
I am trying to create User search view (using Views). But when I create the view, I am not able to see the search option in filter.

What I am missing?

# Answer
Forgive me if this is more than you are looking for, or it is difficult to follow. Drupal's built-in search is bad for a number of reasons. One of them is how poorly it handles partial matches (i.e. 'appl' for 'apple'). Generally, search is done best when you use the search API module and integrate it with a search server. If you start down the path of looking into this you will find a lot of people saying you need to use SOLR, which is not the case. SOLR is great for more intensive applications, but you can make a very effective search system without it. This article details how:
https://www.webwash.net/drupal/tutorials/intro-search-api-part-1-how-create-search-pages

Following those instructions you will want to create an index of users. Then you will need to use the search views modules to create a view of the search results. The exposed filters (your search box is an exposed filter in this case) can even be placed in separate blocks. This article describes that portion of the process: https://www.webwash.net/drupal/tutorials/how-create-search-pages-using-views-drupal-7

This may be a little more work than you hoped for, but it will solve the problem.
> 0 votes

---
Tags: 7, views, users
---


# Question
Title: How to send the views record in an email to admin at regular time interval of 8 hours?
I have created a rule to sent the view results, by using this:

```
<?php
$view = views_get_view('VIEWNAME');
print $view->preview('default');
?>

```

But I want this Rules Action to occur every 8 hours.

My question: What should be the "React on event" for this rule?

**Edit**: Based on the suggested answer, I'm now also using the Rules once per day module. Here is my rule (in rules export format):

```
{ "rules_send_emails_to_fuel_company_approved_client_list" : {
    "LABEL" : "Send emails to fuel company approved client list",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "php", "mimemail", "rules_onceperday" ],
    "ON" : { "once_per_day" : [] },
    "DO" : [
      { "mimemail" : {
          "key" : "somebody@example.com",
          "to" : "ok",
          "subject" : "ok",
          "body" : "\u003C?php\r\n$view = views_get_view(\u0027calling_agent_summary\u0027);\r\nprint $view-\u003Epreview(\u0027default\u0027);\r\n?\u003E",
          "language" : [ "" ]
        }
      }
    ]
  }
}

```

But I'm still not receiving any emails. So I wonder what might be the cause of this.

# Answer
# Option 1: Using Rules and Rules Scheduler

Use the Rules module and Rules scheduler (submodule of Rules). What you actually need to do is a minor variation of what is explained in the tutorial Hourly tasks using rules scheduler: in your case you should use an offset of 8 hours (instead of just 1 hour).

And as explained also in that tutorial: *"Initially execute the component manually"* (from then on every other 8 hours the rule will be executed again).

# Option 2: Using modules Rules and Rules Once per Day

There is a fairly new module related to rules, i.e. the "Rules Once per Day" module. Here is how it works (as per the comment in issue 2495775, from the module owner):

* You specify a **trigger hour** on the administration settings page for this module.
* The Rule trigger will then **run when cron tasks are first run after the start of that hour**. The actual run time will depend on your cron task timings.

The way to understand/read this is like so:

* The "Event" will only be triggered when a cron job is run.
* And that event will only be triggered 1 time / day, i.e. "next time cron runs after the trigger hour has passed".

So by creating 3 similar rules, you could have 1 of them run around (say) 6 am, another one around 2 pm and the ast one at 10 pm. Adapt the 6am to any other timestamp you'd want, and do the same with the one from 2 pm and 10 pm
> 1 votes

---
Tags: views, emails, rules
---


# Question
Title: How to add up price values when group by month?
I have a Views table view that shows bank transactions. Each transaction has:

* A price field (which consists of a single positive OR negative amount)
* A date field

I would like to display the transactions grouped by month and then display a total of all the price fields for each month.

How can I do this?

---

## Steps I have tried

**1) Use Views built in tools**

In the setting for a table view, you can chose to group entries by a field. So I group my fields by month.

I then go to `other > Use Aggregation` and set it to `“on”`.

Finally I select `“Sum”` in the aggregation options of the price field.

*Results:*

* Entries are grouped by month Months are not in order (It goes March, January, February, December)
* The total of the prices fields for each month is not displayed.

**2) Use Views Calculation module**

This requires a patch to support Group fields. Unfortunately, the patch does not work with price fields (see comment #118). My own testing confirms this.

**3) Use Views Aggregator Plus**

Views Aggregator Plus module is designed to be an alternative to Views Calc.

In Views format, I select a “Table with aggregation options” I apply the “column function” to my price field and select “sum” I apply the “group function” to my date field and select “group and compress”.

*Results:*

* Only the first transaction for each month is show (The other transactions are hidden)
* The total is displayed, but it is incorrect and doesn’t seem to relate to anything.

# Answer
> 3 votes
You can use views date format sql with simple in built views aggregation. No need to use views aggregator plus.

# Answer
> 2 votes
When using "Views Aggregation Plus" as described in your question, you also need to change the date field to use a Custom PHP "Date Format" something like "F Y".

Then disable the "group function" for date column in the “Table with aggregation options”.

Also make sure views has "Use aggregation",

This should give you totaled rows for each month.

Also make sure views\_date\_format\_sql module is enabled.

# Answer
> 1 votes
I realise your question is not about creating a chart from these data. However there is an interesting Charts-issue you may want to look at (for which the challenge is similar to your question here). I.e. Graph node input over time (support date formatting on a continuous axis). In Comment #3 of that issue is stated: '*The trouble here is that neither Views nor Date modules provide aggregation options for date-based fields.*'.

Part of the recommended solution there is to (also) use the Views Date Format SQL module. Here are some details (from its project page):

> The Views Date Format SQL module allows to format date fields using SQL. This enables group aggregation for date fields using the choosen granularity.
>
> The core functionality is to remove the date formatting from render() and put it in query(). I.e. format date values using SQL's DATE\_FORMAT rather than PHP's format\_date. This is achieved by assigning a new default handler to node 'created' and 'changed' date fields. This handler extends and overrides views's build in views\_handler\_field\_date.
>
> The UI is completely unobtrusive, only a single checkbox "Use SQL to format dates" is added to the handler configuration popup.

Some more suggestions from that very same comment:

> If you're doing grouping by node post date or other built-in fields however, this problem can be solved by using the Views Date Format SQL module. It adds a nice little checkbox that allows you to group dates by a custom formatted string. In this screenshot, I set the custom date to be "M Y" (which translates to Oct 2012 for example), then checked the box for "Use SQL to format Date".

# Answer
> 0 votes
I made a site once that provided a service. Clients would log in and request the service, then the company would process them through a workflow and generate a report. The company wanted to know which clients were requesting how many of what type of report on a monthly and weekly basis. I wrote a statistics report set of views and bundled it into a feature for them. In order to get the sub totals by type and also the grand totals by client in each table, I had to use a combination of placeholders in a footer area and hook\_views\_pre\_render to do the summations and replace the placeholders.

This hook has the ability to rewrite the `rows[]` section of the view before render, so you can even change what the view is going to show as the data, but there are better ways to do that. This approach gives you access to all the data that the view has fetched and lets you change and/or add things before the theme gets to work on making it look pretty. I would recommend making the view data as simple as possible to give your custom processing more room to work. Empty global text fields in the table and in the header/footer give you somewhere to put the new information into the view when you are done processing it.

Having a look at the structure of the view object before you are manipulating it will make it easier to grab the data for your sums and also put it in place. I use this recursive print tool in a watchdog statement because not every hook can `print_r` to the screen. I think the hook\_views\_pre\_render can though, so you probably don't need the watchdog log.

# Answer
> 0 votes
Have you tried with

```
Force using fields

```

checked ? (Under *Format* -\> *Settings*)

Thsi is in german, but you'll find it under Format Format: Unformatierte Liste | Einstellungen (underlined)

# Answer
> 0 votes
Yo can do It using pre render hook in your theme `template.php` or in a custom module.

```
function your_theme_views_pre_render(&$view) {
  if ('your_view_name' == $view->name && 'your_display_name' == $view->current_display ) {
    foreach ($view->result as $key => $row){
      /* here you can acces each row data (view result) ,
      take all the values for the rows on each month
      (which you get from the date field) and sum them,
      you have the values you need */
      $date = $row->field_field_date[0]['raw']['value'];
      $month = /* get the month from the date */
      $month_price = $row->field_field_price[0]['raw']['value'];
      $_SESSION['month_sum'][$month] += $month_price
    }
  }
}

```

Once you have the values you can keep them and modify the output with a preprocess hook. Another (and easier way) if you won't use the price field for anything else, you can iterate again through the `$view->result` and change every price with the sum of all the prices on his month so, on the final output you will have it already, resulting in something like:

```
function your_theme_views_pre_render(&$view) {
  if ('your_view_name' == $view->name && 'your_display_name' == $view->current_display ) {
    foreach ($view->result as $key => $row){
      /* here you can acces each row data (view result) ,
      take all the values for the rows on each month
      (which you get from the date field) and sum them,
      you have the values you need */
      $date = $row->field_field_date[0]['raw']['value'];
      $month = /* get the month from the date */
      $month_price = $row->field_field_price[0]['raw']['value'];
      $_SESSION['month_sum'][$month] += $month_price;
    }
    foreach ($view->result as $key => $row){
      $date = $row->field_field_date[0]['raw']['value'];
      $month = /* get the month from the date */
      $row->field_field_price[0]['raw']['value'] = $_SESSION['month_sum'][$month];
    }
  }
}

```

---
Tags: 7, views
---


# Question
Title: View with contextual filter using a taxonomy reference from a node
In a view showing for example products (nodes) filtered by a taxonomy term (product type), I can easily set a contextual filter to select the product type term to be displayed.

Is there a way to get the value for a contextual filter in such a view from another node?

Usage example: Using the example above, I have a content type that presents a product type (taxonomy term) in depth with text, images etc. I want to specify a term in a reference field in the product type presentation and have a block that displays all product for the selected term.

Is that type of filter possible? I am guessing the same approach can be used in D7 as well as D8 if possible without using third party modules.

If my question is unclear I will be happy to elaborate my case further.

# Answer
Views are complicated, so pardon me if i don't have this entirely right in the first go.

So as I understand things, you have one node that references a taxonomy term representing a product type, and you need to get a view on this node page to show other nodes (possibly of a different content type) that reference this same taxonomy term (possibly along with others). If that is correct, you should be able to do this with two relationships and a contextual filter. Both are found under the advanced settings portion of the view edit pane.

The first relationship you want to add is 'Entity Reference: Referenced Entity - A bridge to the Taxonomy term entity that is referenced via field\_your\_taxonomy\_field'. This gets us from your 'result' nodes to the term you want to filter on.

The second relationship to add is 'Entity Reference: Referencing entity - A bridge to the Content entity that is referencing Taxonomy term via field\_your\_taxonomy\_field\_on\_the\_entity\_we\_are\_viewing\_the\_view\_from'. You set it up to use the first relationship as its relationship.

Last, you set up a contextual filter on 'Content: Nid' using the second relationship.

**Edit**
Since you are inside a block, you will also want to tell the view how to get the context (node ID) from the URL. Under the 'WHEN THE FILTER VALUE IS NOT AVAILABLE' you will want to select 'Provide default value' and in the resulting dropdown, select 'Raw value from URL'. Path component 1 should be correct. Save and update the view.
**End Edit**

To test this, pick the NID of a node where you might be viewing the view and put the NID in the 'Preview with contextual filters' box and click update preview. Did you see what you wanted to see? If so, great!
> 2 votes

---
Tags: views, 8
---


# Question
Title: Add a checkbox on registration page for subscription newsletter with Simplenews
I'd like to add a checkbox for subscription to a newsletter on the user registration page.

I'm using Simplenews.

How could I do that?

# Answer
> 1 votes
After you have created a Newsletter category, go to `admin/config/services/simplenews` and click on **edit newsletter category** next to your newsletter category.

You'll see subscription settings. Select "Default On" or "Default Off" to display a checkbox on user registration form.

see image below for detailed explanation of setting mentioned above

---
Tags: 7, emails, notifications
---


# Question
Title: Create a page with database data in a module
I am new to drupal and in a process of developing a custom module. My module will do a couple of things:

1. (ADMIN) User will be able to select a zip file and upload it
2. (ADMIN) The module will than take that file, extract it to files folder
3. (ADMIN) Upload the content from a certain file to the database table
4. (ADMIN/front end) Create a link/page/node on the front page in navigation where the data will be displayed with some additional js required

I got first 3 things going but I am struggeling with the last one.

Any pointers in the right direction will be much appreciated.

# Answer
> 0 votes
if all the uploaded Zips contain similar data you could expose the custom table to Views using hook\_views\_data and then make a View path with a contextual filter to show the content of a given table.

If you really need a link look at the hook\_menu function and make a menu entry that loads a custom page ... which can then load a custom View to show your data on a page.

---
Tags: database
---


title: Comments are Posted anonymously

text:
# Question
Title: Comments are Posted anonymously
I am using Services Module in Drupal 7. When I try to POST comments, these comments are Posted anonymously.

I am sending POST request to ?q=endpoint/comment.json

with this Body

```
{   "nid":"401","subject":"Comment Subject sdfsdf ",   "comment_body":{
    "und":[{
      "value":"Comments body sdfsnd fsd fds "
    }]   } }

```

Comments are getting posted but anonymously. I want to comments to be posted by the name of logged in user.

# Answer
> 1 votes
The default for an unprovided `uid` property to a comment entity is 0, so with your current code it will always be owned by an anonymous user. If you want a specific user, you have to be specific in the request.

It can just go straight in the payload though:

```
{
  "nid": "401",
  "uid": "123",
  "subject": "Comment Subject sdfsdf ",
  "comment_body": {
    "und": [
      {
        "value": "Comments body sdfsnd fsd fds "
      }
    ]
  }
}

```

You have access to `uid` from the return value from the login, so it's easy to get hold of.

---
Tags: comments, services, 8
---


# Question
Title: "Non-existent service" errors after clearing the cache
After clearing the cache in Drupal 8 (via the UI) I got "The website encountered an unexpected error. Please try again later." error. It happened for the first time. I haven't introduced any heavy changes to the site, basically only created a field and some features (via the Features module).

I've found this error in the logs:

> Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException: You have requested a non-existent service "password\_migrate". in /.../app/vendor/symfony/dependency-injection/ContainerBuilder.php on line 800

To fix this was trying different things: clearing cache tables directly in the DB, trying drush rebuild (rebuild wasn't successful since it yelds the same error). After some time the error is different (and I don't know why):

> Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException: The service "ctools.paramconverter.tempstore" has a dependency on a non-existent service "user.shared\_tempstore". in /.../app/vendor/symfony/dependency-injection/ Compiler/CheckExceptionOnInvalidReferenceBehaviorPass.php on line 58

I can *temporarily* get the site back to life by loading {cache\_container} table from the old backup. But the site breaks again after clearing the cache and the first error reapers in logs.

The site is basically broken. How can I restore it? How is the {cache\_container} populated, so I can reverse the process and restore what's missing based on the cache? Thanks!

# Answer
> 4 votes
It took me a while, but I managed to find the issue and to solve it.

The problem was directly caused by the Features module (or maybe rather it was directly caused by careless me...). Anyway, a couple of hours before I cleared the cache (this is when the issue manifested itself) I had exported some configuration as new features. Normally I would use some custom names, but this time I've just swum with the tide and added the configuration to the features that Features module proposed. And one of the proposed features was "User" with machine name "user", which is exactly the same as the core module! This is why "password\_migrate" service couldn't be found, Drupal was looking at the new feature instead of the core module.

Because the module name was already in core.extension configuration I didn't even have to enable it, as it was already enabled (unlike in the old {system} table there's no path to the module in the config so probably Drupal just used the first definition it found). After exporting the feature the problem was there, sleeping, and it was just when I cleared the cache some time later when the site broke (probably if the problem appeared right away I could track it down much earlier).

The problem went away as soon as I deleted the feature.

# Answer
> 3 votes
It seems that a class is requesting the password\_migrate service which does not exist.

This is usually caused when the module that supplies this service is not installed.

I suggest you search the project code for the string password\_migrate to find both the requester and the provider.

---
Tags: 8, dependency-injection
---


# Question
Title: Can't save location when posting node through services module
I am using services module to post nodes using rest/json. The nodes also contain images and location. So far I can upload the image and save the node, but the location is not saved. I receive no errors in logs.

Any ideas? Is there something I have to add,maybe permissions, in order to be saved?

This is the json that creates the article but doens not save the location.

```
{
    "title": "some title",
    "type": "article",
    "language": "el",
    "body" : {
          "und": [
              {
                  "value": "some text"
              } ]
    },
    "field_tags": { "und": "9" },
    "field_image": {
        "und":
          [{
            "fid": "1364"
          }]

    },
    "locations":{
        "und":[
                {
                  "country":"gr",
                  "latitude":"55.7046601",
                  "longitude":"13.191007300000024",
                  "name":"TEST LOCATION",
                }
            ]
    }

}

```

# Answer
> 0 votes
How are you storing the location? Node location? Location CCK field?
take a look at:

https://www.drupal.org/node/906968

If you are using a CCK location field you should disable node location module.

* Or if you aren't you could switch to a location field.

As a last option you could put latitude and longitude in their own text fields (like field\_latitude and field\_longitude) since gmaps module can take lat and lng from text fields.

> you can use CCK location which allows you a geolocation field, it comes with location module:
>
> https://www.drupal.org/project/location

---
Tags: services, location, google-maps, 8
---


title: Libraries require jQuery and not work

text:
# Question
Title: Libraries require jQuery and not work
I load some libraries in my module by using this hook :

```
function food_truck_form_views_pre_render(&$view) {
  if ($view->name == 'marqueurs_admin') {
    drupal_add_css(libraries_get_path('animate') . '/animate.min.css');
    drupal_add_js(libraries_get_path('bootstrap_notify') . '/bootstrap-notify.min.js');
    drupal_add_js(drupal_get_path('module', 'food_truck_form') . '/js/food_truck_form_admin.js');
  }
}

```

But when I write a notify in my food\_truck\_form\_admin.js (this code) :

```
(function($) {
    $.notify({
    icon : 'fa fa-exclamation',
    message : 'TEST'
    }, {
    animate : {
        enter : 'animated flipInY',
        exit : 'animated zoomOutUp'
    },
    type : 'danger'
    });
})(jQuery);

```

I get this error :

> 2bootstrap-notify.min.js?o68oa5:1 Uncaught TypeError: this.$ele.find(...).on is not a function

have you got an idea ?

PS : is it the best method to load libraries ? I see on libraries API there was libraries\_load... method but i don't understand how to use them :/

# Answer
I suppose you should be loading the libraries through the libraries API:

It is in the Libraries API documentation

```
libraries_load($name);

// Usually, you'll want to do something after the library has been loaded.
// Because you cannot always depend on the library being installed you have
// to check first if the loading was actually successful:
// Try to load the library and check if that worked.
if (($library = libraries_load($name)) && !empty($library['loaded'])) {
  // Do something with the library here.
}

```

Since you say you don't understand this. The above check makes sure the library is loaded correct. So you will not run into weird errors or exceptions. Just put all the code that depends on the libraries inside that if-statement. (As a matter of fact is it much important for PHP than it if for JS, but nevertheless it prevents errors.)

UPDATE:

Oh wait. The problem is that `jQuery.on()` the function that throws the error was added in jQuery 1.7. Stock Drupal runs on 1.4, so in order to get this to work, have a look at jQuery update and make sure Drupal runs at leat 1.7.
> 0 votes

---
Tags: 7, javascript
---


# Question
Title: Getting views contextual filter from url for display suite block
I have a URL for an event content type that concatenates two other content types, namely "name-of-venue" and "name-of-performer" with "date-of-event", so the url is "name-of-venue/name-of-performer/dateofevent".

I wish to place a block on the event content type that shows only the events for that venue.

I have tried to configure the contextual filter as shown on the screen shot,

using the PHP code:

> $np = explode('/', drupal\_get\_normal\_path($argument)); if (!empty($np\[3\])) { $handler-\>argument = $np\[3\]; return TRUE; } else { return FALSE; }

However this does not return just those events for that specific venue, but for all venues.

Consequently I fear that I am not actually exploding the url and so failing to obtain the NID for "name-of-venue" that I need for the contextual filter.

Any suggestions would be very much appreciated.

Thank you.

# Answer
Here is a kind-of-complex sketch for your problem, using only Views:

1. Create a block view displaying Content of type Event
2. Add a "Content: Nid" contextual filter, using the default settings. You may need to set the default value to "Content ID from URL" for the case "When the filter value is NOT available"
3. In your View configuration, under "Relationships", create a "Entity Reference: Referenced entity" relationship for your reference field (e.g. field\_venue) and click on "Require this relationship": This relationship will retrieve the venue of the Event that is defined from the contextual filter.
4. Create a second relationship, one of type "Entity Reference: Referencing entity", again for your reference field (e.g. field\_venue) and click on "Require this relationship". Important: Use the first relationship (step 3) for this one: This second relationship will retrieve the events that reference the venue we got from the first relationship.
5. Set your Views format to use fields (either by using a Table or by ticking the "Force using fields" option).
6. Add the fields you want to display and select the second relationship you created for them.

At this point your block should list all events for the venue of your current event. The problem that still remains is excluding the current event from that list. Follow steps take care of that:

7. Add two "Content: Nid" fields, set one of them to use the second relationship and exlude them from display.
8. Set a "Global: Fields comparison" filter and set it to filter out rows when the two excluded fields from above are equal: This will take care of excluding the actual event from showing in the block.

Once you place this block inside an event node page, it should display a list of Events from the same venue excluding the current event.

Cheers and let me know how this goes.

---

**Appendix A**:

---

---

**Appendix B**:

---
> 0 votes

---
Tags: blocks, views, display-suite
---


# Question
Title: Why (or how) order number increases in Drupal Commerce
Does anyone know how the Order number increases in Drupal Commerce?

Obviously when someone puts in a new order the order number will be AT LEAST one larger than the previous order number, but other than that why would the order number increase?

For example while testing the site my first order # is 1 (duh), but then 19 days later when I tested it the order # was 19, without any other tests occurring in the interim. The following day I did a test transaction and the order # became 31.

It keeps going up every time I test it but it doesn't just increment by one every time. So I'm just curious why it might be behaving this way. Anyone know?

# Answer
> 2 votes
Orders are created as soon as a customer submits an Add to Cart form. There isn't a separate intermediate cart object in Drupal Commerce - from the first chance we use a full order object in the *Shopping cart* order status. You can see a list of cart orders from the *Shopping carts* tab on the order admin listing. Note that it will also show and orders that have not completely cleared the checkout process as well.

# Answer
> 4 votes
If you are certain there are no other users that have access to the order process, it might be caused by abandoned carts or failing payments.

Best is to have a look at `example.com/admin/commerce/orders`. It should give you a full list of all orders and the states they are in. Like I said if these were abandoned carts or half completed payments, orders might remain in a certain state, in which they are invisible in some other UI pages.

To answer your question. The Drupal Commerce order id is an auto increment field just as any other ID in Drupal, and it should increase with your auto increment value (mostly 1, though I sometimes have heard 5 as well).

---
Tags: commerce
---


# Question
Title: Access by role based on term referenced in the node
I'd like to restrict access to content based on a term referenced in the node.

For example, I have a content type 'submission' and I want users with the role 'curator' to be only able to view nodes that have the taxonomy term 'art'.

Any pointers towards a sustainable solution to this?

# Answer
> 1 votes
If you're wanting a custom module based solution, Drupal has `hook_node_access()` which lets any module control access to a certain node. In your case, you want check the `$node` object on a 'view' `$op` and return the appropriate `NODE_ACCESS_*` constant which tells Drupal when the user has access to the node.

```
// @TODO: Replace 2 with your curator RID.
define('MYMODULE_CURATOR_ROLE_ID', 2);

function MYMODULE_has_terms($node) {
  // @TODO: Define logic that checks if node taxonomy field has certain terms.
  return FALSE;
}

/**
 * Implements hook_node_access().
 */
function test_node_access($node, $op, $account) {

  // Only step in when curators are viewing 'submission' nodes
  // and allow access if a node is tagged with certain terms
  if (is_object($account) && user_has_role(MYMODULE_CURATOR_ROLE_ID, $account) ) {
    if (is_object($node) && $node->type == 'submission' && $op == 'view') {
      return MYMODULE_has_terms($node) ? NODE_ACCESS_ALLOW : NODE_ACCESS_DENY;
    }
  }
  return NODE_ACCESS_IGNORE;
}

```

---
Tags: users, taxonomy-terms
---


# Question
Title: Simple debug results in internal server error
All I want to do is print a view out so I can check the variables and see the structure of what's being created but it results in an internal server error.

I'm using Acquia Dev Desktop. I've checked the .htaccess file and it has the rewritebase uncommented. I've tried updating max\_execution\_time, and memory\_limit. Nothing helps.

I have Drupal 8 installed fine and haven't had any issues except when trying to inspect variables.

BTW here is my function in theme file:

```
function theme_preprocess_views_view(&$variables) {
  $view = $variables['view'];
  print_r($view);
}

```

What am I doing wrong?

# Answer
**Hi!!** you can use a official symfony dumper, insert this line on the file "composer.json"

```
"require-dev": {
    "symfony/var-dumper":"3.0.4"
  }

```

run the follow command:

```
composer install "symfony/var-dumper"

```

or

```
composer update

```

you can use in your code with these line:

```
dump($variable_name);

```

enjoy!!! ;)
> 1 votes

---
Tags: views, 8, hooks, debugging
---


# Question
Title: Canonical link for multidomain multisite
I have different domains in a site in Drupal 7, which is multidomain and multilanguage, using modules Domain Access and i18n. I have duplicate content in some URLs *accross domains*, and I want to avoid Google penalization by following the recommendations of using

```
<head><link rel="canonical" href="CANONICAL_SOURCE_URL" />

```

I will use a custom module. For the nature of Drupal 7, I undestand that I can check each node, and using the `node->id` and database call, to check the domains in which the node is active. Following an order of preferred domains, I will know that URL to set as the canonical.

Is that a good aproach? I have tried module MetaTag with Canonical, but it uses a wildcard approach so it repeats the domain in which I am, so we can have www.example.com/link1 and www.example.us/link1 as canonicals, when only one of them should be used.

How can I override MetaTag with my own link rel tag ?

# Answer
It is better to use Metatag module which has ability to override meta tags on each entity objects. Other tokens must be used.
> 1 votes

---
Tags: 7, meta-tags
---


# Question
Title: How to change query target when using EntityFieldQuery
I'm using EntityFieldQuery and want to change the query target to something other than 'default' (because I'm using DB replication with the help of autoslave module).

It's easy to do that when using db\_select or db\_query by setting 'target' key on third $options parameter.

EntityFieldQuery class doesn't have any method for that and I tried to use hook\_query\_alter but no luck there too.

# Answer
This is currently not possible (Drupal 7.43). EntityFieldQuery doesn't have any options for using a slave/replica database, nor does the module that actually executes the query, which is field\_sql\_storage.module in field\_sql\_storage\_field\_storage\_query().

Ultimately that function calls db\_select():

```
$select_query = db_select($tablename, $table_alias);

```

But it doesn't pass the 3rd parameter which is where the slave database would be targeted, so it will always use the master. It's also not possible to alter the query to add new options, as the `Query->queryOptions` property is protected.

I filed an issue against Drupal core, if it gets fixed the solution will be posted there: https://www.drupal.org/node/2714021
> 2 votes

---
Tags: database
---


# Question
Title: VotingApi function takes time to update the database
I have added a menu item that calls a function that calls `votingapi_set_votes` and delete votes. This function works locally fine but when uploaded to the hosting and when i call the function it takes like 5 minutes to update the database with the `votingapi_set_votes` function.

Menu\_item's callback calls a function that contains `votingapi_set_votes`. Locally: i call the menu item with the node id as parameter and the a vote is added to the node. On Hosting: When i call the menu\_item i need to wait five minutes or so to see the node vote updated.

# Answer
I hope this code may work for you Try this code in your theme's js file:

```
Drupal.behaviors.Your-Theme-Name = {

 attach: function (context, settings) {

//add your class in click function

    jQuery('.view-id-top_users.view-display-id-page .views-field-php .flag-link-toggle').click(function(){

        jQuery(document).ajaxComplete(function() {

         location.reload();

        });

    });

  }

    };

```
> 1 votes

---
Tags: database, rating
---


# Question
Title: How to disallow one domain path in robots.txt without any modules?
How to disallow one domain path in robots.txt? (there is a module which allows to do that but it is better to avoid it because of performance issues) For example, onedomain.com/path1/\* must be disallowed. Is it right to type like this in robots.txt (there is another domain twodomain.com for the same website):

Disallow: onedomain.com/path1/\*

Twodomain path must be allowed to be crawled and Onedomain path must be disallowed to be crawled (both of them are pointing to the same path).

# Answer
I don't have enough reputation to comment, so I'll just throw this out:

You can test the user agent and the URL in settings.php. Then, if it matches the crawler bot and the /path1/\* criteria, you could do a 301 Permanent Redirect for that URL within your settings.php file. Here is how:

```
  header('HTTP/1.0 301 Moved Permanently');
  header('Location: ' . $base_url . $redirect_path );
  exit();

```

where $base\_url is "Twodomain" and $redirect\_path is "/path1/URLfromtest"
> 0 votes

---
Tags: domain-access
---


title: Delete all empty orders on user login

text:
# Question
Title: Delete all empty orders on user login
**Case:** Delete all empty orders for a user when he/she login to the website.

We are using drupal commerce.

Please Help.

# Answer
> 1 votes
It seems that these orders, where in the shopping cart when the current user log off, and never proceed to pay. In order to not lose this product in the cart for the next login, there has to be a relation to the user and product.

If your eCommerce module doesn't have any configuration to delete products on logout, try using hook\_user\_logout

> Note that when this hook is invoked, the changes have not yet been written to the database, because a database transaction is still in progress. The transaction is not finalized until the save operation is entirely completed and user\_save() goes out of scope. You should not rely on data in the database at this time as it is not updated yet. You should also note that any write/update database queries executed from this hook are also not committed immediately.

# Answer
> 1 votes
Alternatively, you can use a module like commerce\_cart\_expiration which will automatically delete carts based on time criteria. The module also provides a default rule that can be configured via the Rules administration screen.

Edit: Should also add that they are probably due to abandoned shopping sessions. There is also another related module Commerce Order Timeout which may be of interest to you.

# Answer
> 0 votes
I wrote following code to acheive the same. It may help others too.

```
/* Implements hook user login */

function module_name_user_login(&$edit, $account) {

//Get all order ids for current user.
  $order_ids = db_select('commerce_order', 'o')
->fields('o', array('order_id'))
->condition('uid', $account->uid)
->execute()->fetchCol();

 if($order_ids >= 1){

  //Loop over order ids.
  foreach ($order_ids as $order_id) {

  //Load order
  $order = commerce_order_load($order_id);

  $wrapper = entity_metadata_wrapper('commerce_order', $order);
  //Get Order Total
  $total = $wrapper->commerce_order_total->amount->value();

  //If total is 0, Delete the order.
  if($total == 0){
      commerce_order_delete($order_id);
    }
   }
  }
}

```

---
Tags: 7, commerce
---