# Question
Title: How to prevent multiple logins for administrator?
I have my Drupal website whose admin account is shared. But I want to limit the multiple logins, that is, only one should be able to login at a time. I have already used Session Limit Module. This works for non-administrator accounts, but not for admin account.

How can I prevent multiple administrators logins?

# Answer
Session Limit allows to put restriction on session based on user role, it could be admin role also, with an exception that it does not restrict user with uid 1 which is kind of rescue point in case you misconfigure the module.

I would say instead of finding any module or building any custom solution which can put restriction on uid 1, you use different account with admin role which this/any module can handle gracefully.

**As a thumb rule I don't put any restriction on uid 1.**

If you see the code of session\_limit.module line 248

```
function session_limit_init() {
  global $user;
  if ($user->uid > 1 && !isset($_SESSION['session_limit'])) {

    if (_session_limit_bypass()) {
      // Bypass the session limitation on this page callback.
      return;
    }
    ..

```

**It clearly shows uid 1 is left intentionally.**
> 4 votes

# Answer
While it's better not to allow UID 1 login for other admin users, instead creating separate administrator user accounts, if you *really* want to restrict UID 1 to a single session, it's possible.

You could basically copy `session_limit_init` to a custom module (with a dependency on the session\_limit module), preserving the existing logic, and tweak it to apply only to UID 1. The UID 1 user will need one of the roles configured in the session limit module, e.g "administrator"

For example:

```
/**
 * Implements hook_init().
 *
 * This is a copy of session_limit_init
 * It extends the default session_limit functionality to apply to UID 1
 */
function MYMODULE_init() {
  global $user;
  // The only difference is $user->id == 1 instead of $user->uid > 1
  if ($user->uid == 1 && !isset($_SESSION['session_limit'])) {

    if (_session_limit_bypass()) {
      // Bypass the session limitation on this page callback.
      return;
    }

    $query = db_select('sessions', 's')
      // Use distict so that HTTP and HTTPS sessions
      // are considered a single session.
      ->distinct()
      ->fields('s', array('sid'))
      ->condition('s.uid', $user->uid);

    if (module_exists('masquerade') && variable_get('session_limit_masquerade_ignore', FALSE)) {
      $query->leftJoin('masquerade', 'm', 's.uid = m.uid_as AND s.sid = m.sid');
      $query->isNull('m.sid');
    }

    $active_sessions = $query->countQuery()->execute()->fetchField();
    $max_sessions = session_limit_user_max_sessions();

    if (!empty($max_sessions) && $active_sessions > $max_sessions) {
      session_limit_invoke_session_limit(session_id(), 'collision');
    }
    else {
      // force checking this twice as there's a race condition around session creation.
      // see issue #1176412
      if (!isset($_SESSION['session_limit_checkonce'])) {
        $_SESSION['session_limit_checkonce'] = TRUE;
      }
      else {
        // mark session as verified to bypass this in future.
        $_SESSION['session_limit'] = TRUE;
      }
    }
  }
}

```
> 2 votes

---
Tags: 7, sessions
---


title: How do I modify the "has_js" cookie?

text:
# Question
Title: How do I modify the "has_js" cookie?
I have a web application deployed through Drupal 7.43. I need to modify the *has\_js* cookie that is set by Drupal to make it both Http-only and Secure for a site security review.

What are pros and cons of making the *has\_js* cookie Http-only and Secure?

# Answer
> 2 votes
The *has\_js* cookie is set, to indicate JavaScript is enabled, in drupal.js with the following code.

```
// 'js enabled' cookie.
document.cookie = 'has_js=1; path=/';

```

The *HttpOnly* flag makes the cookie not available from JavaScript. For that reason, it's not possible to set the *HttpOnly* flag when creating a cookie from JavaScript. It may cause issues if there is code that checks for that cookie to determine if JavaScript or cookie support is enabled.

The *Secure* flag is used to make the cookie only available over HTTPS, which may cause issues with checking for JavaScript support on non HTTPS pages. Nevertheless, if your site is fully HTTPS, that should be fine.

With that being said, you could look into setting the *HttpOnly* flag on the *has\_js* cookie server side, by checking for that cookie and updating it to use the *HttpOnly* flag via `setcookie()`.

---
Tags: 7, security, cookies
---


# Question
Title: How do I cache a custom module that has points?
I am making a site with users that have points. I have a custom module that calculates points for each user, but the page is slow when is calculating the points in real time, so what I want to do is making a cache the points so they don't need to be calculated anytime someone open the page. The page will be cached; if users want the status for their points, they can update them pressing the "Update" button. So I will write a function for that button to clear the cache.

# Answer
> 0 votes
Yes, you can use the Drupal cache API to set and get the data from cache.

Assuming D7, The following resources have some good information on that:

For example:

```
function MYMODULE_function() {
  global $user;
  $user_point_data = &drupal_static(__FUNCTION__ . $user->uid);
  if (!isset($user_point_data)) {
    // User per user cache id for points.
    $cid = 'user_point_data:' . $user->uid;
    if ($cache = cache_get($cid)) {
      $user_point_data = $cache->data;
    }
    else {
      // Do your expensive calculations here, and populate $user_point_data
      // with the correct stuff..
      cache_set($cid, $user_point_data, 'cache');
    }
  }
  return $user_point_data;
}

```

You can then clear the cached data, based on specific user id or all items, with:

`cache_clear_all`

```
// Clear all user point data from cache
cache_clear_all('user_point_data', 'cache', TRUE);
// Clear specific user point data from cache
$cid = 'user_point_data:' . $GLOBALS['user']->uid;
cache_clear_all($cid, 'cache');

```

---
Tags: caching
---


# Question
Title: Altering body text of a node before the page is rendered
I am using the Zen theme. I want to alter the body text before it is rendered as a page. In particular, I want to replace a string with another string. I thought that the general solution for this would be to place the code in the the theme\_preprocess\_node hook in my sub-theme's template.php. Here is the code that I've got so far:

```
<?php
function mytheme_preprocess_node(&$variables) {
    if ((isset($variables['body'][0]['value'])) && (preg_match('/suppose/i', $variables['body'][0]['value']))) {
        dpm('string was found in "value"');
        $variables['body'][0]['value'] = preg_replace('/suppose/i', 'new tring', $variables['body'][0]['value']);
    }
    if ((isset($variables['body'][0]['safe_value'])) && (preg_match('/suppose/i', $variables['body'][0]['safe_value']))) {
        dpm('string was found in "safe_value"');
        $variables['body'][0]['safe_value'] = preg_replace('/suppose/i', 'new tring', $variables['body'][0]['safe_value']);
    }
}
?>

```

However, this has no effect what so ever. I do get a positive match - this I can verify by the debug dpm() display.

Am I simply trying to rewrite the wrong sub-array?

Thanks in advance,
Valera Rozuvan

# Answer
> -1 votes
This is not a good solution but it works fine.

In node.tpl.php

```
<?php print hide($content['body']); ?>
<?php print render($content); ?>
<?php print $newbody; ?>

```

In template.php

```
function mytheme_preprocess_node(&$variables) {
 if ((isset($variables['body'][0]['value'])) && (preg_match('/suppose/i', $variables['body'][0]['value']))) {
   $variables['newbody'] = str_replace('suppose', 'new string', $variables['body'][0]['value']);
 }
}

```

As I've said this is a patch solution and I don't recommend this.

# Answer
> 8 votes
Try this in mytheme\_preprocess\_node:

```
function mytheme_preprocess_node(&$vars) {

  // Collect / create / adjust new body content
  $new_body = 'xyz';

  // Assign to output
  $vars['content']['body'][0]['#markup'] = $new_body
}

```

After looking through the vars array a bit, I'm a little surprised at the amount of redundant data there. There are a few different places where the body text is recorded, usually as an array.

Note that the node body will likely have a 'safe value' and a 'value'. You'll probably want to use safe almost all the time, but it might be good to check on the filter type selected in $vars\['body'\]\[0\]\['format'\] to select which of the body values you'll want to output and display.

# Answer
> 0 votes
try this

```
function mytheme_preprocess_node(&$variables) {
  $contenue = $variables['body'][0]['value'];
  $variables['content']['body'][0]['#markup'] = $contenue;
}

```

---
Tags: theming
---


# Question
Title: Faceted search show tid instead of taxonomy name
I need to create a facet search using taxonomies, I have as a index the taxonomy term name but when I go to search, in the facet I see the tid and not the taxonomy term name. I follow a tutorial but I can't found the solution.

***Search Index***

***Facet***

***Search***

There is one issue in drupal.org talking about a TranslateTaxonomyProcessor callback processor but I don't know how to use it. Another issue talkin about the same processor: https://www.drupal.org/node/2673888

***This is the list of my Processors:***

# Answer
> 4 votes
You need to check "**Translate entity label**" option to see the name.

By editing Tag facet block you can see that option.

If you have still same issue.

You need to install Core Views Facets module.
Then select Facet source.

```
View Search content, display Page

```

Added One example o/p screenshot.

---
Tags: 8, search
---


# Question
Title: Mutliple rewrites/redirects in settings.php on a Pantheon hosted site
We are in the process of migrating a Drupal site to Pantheon. The site uses about 55 rewrites and redirects rules in its pre-migration NGINX configuration. Most of them (32) include widlcards (eg. `^/something/(.*)` redirects to `/something-else/`) and an handful even keep the matching substring into the redirect-to URL (eg. `^/another/one/(.*)$` redirects to `/something/else/$1`).

Pantheon does not support redirects at the web-server levels and suggests doing redirects in the `settings.php` (to avoid boostraping Drupal). But 55 redirects seems enough to start worry about maintainability of a bunch of `if` blocks. There is also the performance cost of 32 pattern matching for each request. So a little care has to be taken to avoid maintenance nightmare in the future.

I'm not too worried about performances since the site is mostly cached anonymous traffic. But in addition to requiring a full bootstrap, the Redirect module (already used on the site) is not an option as it does not support wildcards.

I'm toying with the idea of crafting something with nikic/FastRoute to be used from `settings.php`. But this seems a bit overkill for 55 redirects.

I'm curious what options have been used on other sites with similar requirements.

# Answer
> 1 votes
If you have a reverse proxy service/server sitting in front of your Pantheon instance, it seems like that's the place to place your redirect rules. Rewriting/redirection is a common feature of reverse proxies.

For example, CloudFlare supports redirect patterns under its *Page Rules* manager. Pantheon has a few doc pages that bring up using CloudFlare so it looks to be a common configure they see used with their service.

If you have a Varnish instance in front your Pantheon instance, you can configure rewrite/redirects in VCL.

# Answer
> 1 votes
Turns out a solution based on nikic/fast-route is quite simple. The actual code is about 30 LoC (not counting the redirections rules themselves):

```
$redirects = [
 'something/{anything:.*}' => 'something-else/{anything}',
 'another/one/{anything:.*}' => 'something/else/{anything}',
]
doDedirects($redirects);
function doDedirects($redirects) {
  // Collect redirects routes
  $dispatcher = FastRoute\cachedDispatcher(function(FastRoute\RouteCollector $r) use ($redirects) {
    foreach ($redirects as $source => $destination) {
      $r->addRoute('GET', $source, $destination);
    }
  }, [
    'cacheFile' => sys_get_temp_dir()  . '/route.cache',
    'cacheDisabled' => FALSE,     /* optional, enabled by default */
  ]);
  // Fetch method and URI from somewhere
  if (!empty($_SERVER['REQUEST_METHOD']) && !empty($_SERVER['REQUEST_URI'])) {
    $httpMethod = $_SERVER['REQUEST_METHOD'];
    $uri = rawurldecode(parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH));

    // Match method and URI with redirection rules.
    $routeInfo = $dispatcher->dispatch($httpMethod, $uri);
    if ($routeInfo[0] == FastRoute\Dispatcher::FOUND) {
      $replace = [];
      foreach ($routeInfo[2] as $key => $value) {
        $replace["{{$key}}"] = $value;
      }
      $dest = strtr($routeInfo[1], $replace);
      header("HTTP/1.1 301 Moved Permanently");
      header("Location: $dest");
      die();
    }
  }
}

```

This is likely a bit overkill as performances is not really a concern. I went with this solution for its simplicity. The code is quite simple and probably as readable/maintainable as a simple solution that would iterate over an array of regular expressions. FastRoute is supposed to scale pretty well, so I assume this solution would scale pretty well too.

Note: The Match Redirect module has been suggested too. It would have been a good solution if it had support for using the wildcards' values in the destination.

---
Tags: redirection, configuration
---


title: End User Database Management

text:
# Question
Title: End User Database Management
So, this is my first question on Stack Exchange! So, I'm currently working on a project in which users of my Drupal site are playing a game as art collectors, and have a collection of artworks, which they can trade and sell during the game. Since my users will need to be able to reassign ownership of works (which would be stored in a database, as each work has several fields attached to it (artist, date, value, material, size, etc.)

And while I want them to be able to change ownership, it'd be preferable if I could let them do this in some kind of GUI, where I could limit control of what fields they could edit. In an idyllic scenario, they would have a drop-down menu they could select from to choose the new owner of the work, but I'm not sure how realistic that is.

Any modules that could assist in this would be fantastic, or if you have a different approach (other than a database), I'm more than happy to hear. This Drupal site is currently running on Ubuntu 16.04 LTS with the latest Drupal 7.5 installed.

I hope I was concise enough in my first question, and that somebody can help!

# Answer
> 1 votes
In a nutshell, you could do this with a user reference field, but you would be exposing everyone in the system (assuming all of these people are Drupal users). Maybe that isn't a big deal, maybe it is. I would create a view reference for the user reference field to only show users who are of a given role only, which should limit results. Furthermore, they would have to know the Drupal username - but you can get around that by installing RealName which swaps usernames for a realname field.

A reason for tying nodes to user accounts would be built-in permissions. "Owner" as just a Drupal textfield wouldn't really cut it in terms of true ownership.

I have done this in the past, similar scenario, different circumstance, where the system would create listings for businesses in the local area, and the business owners would come, register, and 'claim ownership' of their listing node by contacting us (webform). After vetting, we would change the node author (owner) from the admin to their Drupal account. Since they could have multiple, their user account dashboard listed all nodes that belong to them, free to edit and update.

I would also advise using a revision workflow so admins can track the history of a node and revert mistakes (as they are bound to happen from time to time).

Note, I am assuming your game pieces are custom entities or content types. It will work in either case.

You would need to give users enough permission to 'edit own \____' entity, and be able to update the user reference field. On submit, you could fire a custom rule with Rules that looks at the user reference field value, and updates the entity owner to that value (uid). Alternatively, you could implement a custom submit handler via `hook_form_alter` on specific forms, and do the logic yourself. The referenced UID value gets set as the owner, and once that happens, that user will no longer have access to edit or anything.

See:

---
Tags: 7, database, users
---


# Question
Title: How can I programmatically get an entity's validation errors?
I'm submitting an entity programmatically through a custom, non-entity form. How can I validate the entity before submission, and report the validation errors to the user if they exist?

# Answer
This code worked for me, not sure if best approach:

```
    $errors = $my_entity->validate();
    //see if there were any errors
    if ($errors->count() == 0) {
      //there are no validation errors, move to next step
      $this->my_success_action($my_entity)
    }
    else {
      //there were validation errors, report them
      for($j = 0; $j < $errors->count(); $j++) {
        $error = $errors->get($j);
        //the entity field that failed validation
        $property = $error->getPropertyPath().'_my_weird_field_suffix';
        //the error message about how validation failed.
        $message = $error->getMessage();
        $form_state->setErrorByName($property, $message);
      }
    }

```
> 2 votes

---
Tags: forms, 8, entities
---


# Question
Title: How to setup views exposed filter with result between 2 fields values
I have content type called the materials with 2 temperature fields as **Max.** and **Min.**

in the views, there is between operator from filter and normally it use for user could input 2 values to the form for filter.

from my case, I want user could input 1 temperature value in the filter and the views result will be the termperaure between **Max.** and **Min.** fields.

is that any way could approach this function?

# Answer
> 0 votes
Use the Views Filters Populate module. It allows you to populate multiple field filters.

Create 2 filters:

1. **Min** (w/ ***Is less than or Equal to*** operator)
2. **Max** (w/ ***Is greater than or Equal to*** operator)

Add an exposed ***Global: Populate filters*** filter with both the **Min**/**Max** filters selected. This will create an exposed filter that will search for items between your **Mix**/**Max** fields.

# Answer
> 1 votes
The Range module allows you to add a numeric range field to a content type and provides Views filters allowing you to select values within or without the range.

---
Tags: views
---


# Question
Title: How can I change the display settings of the referenced field, programatically?
A paragraph entity references a media image field, and it needs to change its display options in code.

How can I achieve this?

# Answer
> 0 votes
One option is to alter the build array using entity\_view. You could then add conditional code there, to change image display settings.

```
/**
 * Implements hook_entity_view().
 *
 */
function mymodule_entity_view(array &$build, EntityInterface $entity, EntityViewDisplayInterface $display, $view_mode) {
  if ($entity->getEntityType()->id() == 'paragraph' && $entity->bundle() == 'my_paragraph_type') {
    if (!empty($build['field_image'][0])) {
      // $build['field_image'] =
       // make changes to your image field here
    }
}

```

---
Tags: 8, entities
---


# Question
Title: 50 Variations of a Node with Access Restrictions Based on User Login
I'm creating a site where there are 50 variations of a basic page node. The site is not viewable publicly and the user has to login in order to view the site.

I have enable the URL login module, its setup where you can login to the site by going to a url.

Now there are 50 different users and each user has access to view only one of the variations of the node. I setup a taxonomy vocabulary called **version** with 50 terms in it and assign one of them to the node.

* How do I restrict certain users to view only that content that matches the term they are allowed to?

# Answer
> 2 votes
There seems to be good handful of permission access type modules restricting users to a specific node.

I tried taxonomy access and taxonomy access lite and they dont do what I need as they limit access to a taxonomy to roles only and not doable for specific users. A work around would have been create a bunch of roles. But I have 50 different users that need 50 different access rights to certain pages.

I also tried https://www.drupal.org/project/permissions\_by\_term but that was a bit wonky as this didn't restrict via the access restriction table. So items still showed in the menu even though they didn't have access to it. Upon clicking on the menu, they do indeed not have access to it, but I wanted all node references to this restricted node removed from the page.

I finalized on the Flexi Access module: https://www.drupal.org/project/flexiaccess

This gives the ability to restrict specific users to a certain node page, but does not restrict by taxonomy terms or by role.

It will add a new flexi access tab on your content pages.

# Answer
> 1 votes
You could use `hook_node_access()` to check the user account and the node being accessed to see if they correspond.

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


# Question
Title: Drupal 7 Execute a mysql sql query in Views using Views PHP
I'm trying to do a custom sql query in Views for Drupal 7 and I have the following code in my views php, but I'm not sure if I'm doing this correctly.

```
<?php $xx = db_query('SELECT * FROM acl_node INNER JOIN acl_user ON acl_node.acl_id=acl_user.acl_id INNER JOIN users ON acl_user.uid=users.uid WHERE nid=201');

print_r($xx);
?>

```

After running that I get a big array, but none of the data in it. I tested the sql query and it is indeed working via my sql builder tool.

# Answer
You must avoid using php in UI.

As a solution
\- Either you can override the views template.
\- Or you can try implmenting hook\_views\_pre\_render.(Reference https://knackforge.com/blog/sivaji/how-alter-views-field-output-programmatically)

**Now, about fetching the results from query result object.**

Other than iterating through the result set, there are other ways to fetch results.
> 1 votes

# Answer
Was missing the foreach loop that apparently activates the sql querying:

```
<?php $xx = db_query('SELECT * FROM acl_node INNER JOIN acl_user ON acl_node.acl_id=acl_user.acl_id INNER JOIN users ON acl_user.uid=users.uid WHERE nid=201');

foreach($xx as $item) {
  if($item->uid != 1) {
    print_r($item->name);
  }
}
?>

```
> 0 votes

---
Tags: 7, views, database
---


# Question
Title: Displaying commerce product with all product variations and attributes
I’m building a drupal commerce store using product displays that reference multiple product variations. But i need the product display to show all of its product variations with all attributes one after another, not hiding the attributes by AJAX. And each product variation should have its own add-to-cart-button. So it’s a simple, flat design where a customer can see every variation and every attribute at a glance.

I know this could be easily accomplished using views, but for certain reasons views is not an option for me. I need a real node of the productdisplay with its variations. What’s the best and most performant way to achieve this?

*EDIT* According to @nvahalic it’s a mess to solve my issue without Views. So maybe i have to reconsider my decision not to use Views. To clarify, the products will be displayed like this:

```
+------------------------------------+
| Title Product 1                    |
| =====================              |
| General Text (for all variations)  |
| General Image (for all variations) |
|                                    |
|    Title Product Variation 1       |
|    =========================       |
|    Text                            |
|    Image                           |
|    *Add to Cart*                   |
|                                    |
|    Title Product Variation 2       |
|    =========================       |
|    Text                            |
|    Image                           |
|    *Add to Cart*                   |
+------------------------------------+
+------------------------------------+
| Title Product 2                    |
| =====================              |
| General Text (for all variations)  |
| General Image (for all variations) |
|                                    |
|    Title Product Variation 1       |
|    =========================       |
|    Text                            |
|    Image                           |
|    *Add to Cart*                   |
|                                    |
|    ...                             |
|    ...                             |
+------------------------------------+

```

As far as i know when using views to build this structure, i will need something like the module Views Field View to achieve the nested structure consisting of fields belonging to the product display as well as fields belonging to the variants. Since the shop will have very long lists of products, i’m concerned about performance issues coming along with this kind of modules. Or maybe i got it wrong and such module isn’t necessary at all?

*EDIT 2* Finally i solved the problem by using the EVA module: i created a view showing the attributes of all products as fields and added am add-to-cart field. This view i attached to my product display – it seems to me this approach is way more performant than using the Views Field View module …

*EDIT 3* It is a huge mess: using nested views is not a good idea, because commerce-add-to-cart buttons can not be cached, so caching views does not work as it is discussed here https://www.drupal.org/node/1926888 From my point of view it was a very, very bad choice to use views for this task. Now I can not use views for caching and the module commerce entity cache is not usable neither because the view does not rely on entities.

# Answer
> 1 votes
If you're insistent on not using Views, you might pull it off like this:

1. Create a new node type and then add an entity reference field that will reference the product displays for each of your products. Set the values to unlimited.
2. For each of your individual products, create a product display.
3. Set the renderer of the entity reference field on the new node you created to "rendered entity"
4. Theme the product display nodes that are linked to the entity reference field accordingly

```
  +------+     +------------------+     +----------+
  | Node |1---M| Product Displays |1---1| Products |
  +------+     +------------------+     +----------+
            ^     ^
            |     | Theme this entity appropriately.
            |
            | Set this display rendered to "Rendered entities"

```

At that point, you should have a list of rendered node entities that would each have their own add to cart form. You could also add a new view mode (using Display Suite) and use that view mode specifically if you still wanted to use the other view modes.

But honestly, this is an extreme amount of work for something that you could accomplish in 30 minutes with Commerce Add to Cart Extras and Views. And regardless of what I said above, that's still my recommendation.

Edit: You're on the right track with Views Field View. If you're worried about performance (how many products do you have?) then you can also:

1. Use Views cache. It's configurable under Advanced in the right-most column of the view configuration screen.
2. Enable Views Content Cache.
3. Implement Redis and perhaps Entity Cache.

# Answer
> 0 votes
I've just done it in this simple way using views:

1. Created a views block called "Product variation add to cart buttons"
2. Added a "Content: Product reference" relationship (Products referenced...)
3. Added a contextual NID filter (Provide default value, Content ID from URL)
4. Added the Add to Cart fields
5. Placed the block under admin/structure
6. Configured to only display on product/\* (which is the basic path pattern for my product displays)

Voila:)

---
Tags: views, commerce, theming
---


# Question
Title: pm-update fails updating drupal-core and deletes everything
I need to update drupal install (core files + some contrib modules) through drush but as I run `drush up` it first correctly update the contrib modules but then fails on updating the core.

The main issue is that **everything in the root directory is deleted** and so is drush installation, plus a new folder (`drupal 7.39`) containing the new partial installation is created in the root.

This is the output:

```
(uiserver):uSOMENUMBER:~ > drush upc
Update information last refreshed: Ven, 08/21/2015 - 00:19
 Name                                  Installed Version  Proposed version  Message
 Drupal                                7.38               7.39              SECURITY UPDATE available
 Advanced CSS/JS Aggregation (advagg)  7.x-2.14           7.x-2.15          Aggiornamento disponibile
 Chaos tools (ctools)                  7.x-1.7            7.x-1.9           SECURITY UPDATE available
 Markup (markup)                       7.x-1.1-beta1      7.x-1.2           Aggiornamento disponibile
 Metatag (metatag)                     7.x-1.5            7.x-1.7           Aggiornamento disponibile

NOTE: A security update for the Drupal core is available.
Drupal core will be updated after all of the non-core projects are updated.

Security and code updates will be made to the following projects: Advanced CSS/JS Aggregation [advagg-7.x-2.15], Chaos tool suite (ctools) [ctools-7.x-1.9], Markup [markup-7.x-1.2], Metatag [metatag-7.x-1.7]

Note: A backup of your project will be stored to backups directory if it is not managed by a supported version control system.
Note: If you have made any modifications to any file that belongs to one of these projects, you will have to migrate those modifications after updating.
Do you really want to continue with the update process? (y/n): y
Project advagg was updated successfully. Installed version is now 7.x-2.15.
Backups were saved into the directory /*/*/*/*/htdocs/drush-backups/*/*/modules/advagg.                                     [ok]
Project ctools was updated successfully. Installed version is now 7.x-1.9.
Backups were saved into the directory /*/*/*/*/htdocs/drush-backups/*/*/modules/ctools.                                     [ok]
Project markup was updated successfully. Installed version is now 7.x-1.2.
Backups were saved into the directory /*/*/*/*/htdocs/drush-backups/*/*/modules/markup.                                     [ok]
Project metatag was updated successfully. Installed version is now 7.x-1.7.
Backups were saved into the directory /*/*/*/*/htdocs/drush-backups/*/*/modules/metatag.                                    [ok]

Code updates will be made to drupal core.
WARNING:  Updating core will discard any modifications made to Drupal core files, most noteworthy among these are .htaccess and robots.txt.  If you have made any modifications to these files, please back them up before updating so that you can re-create your modifications in the updated version of the file.
Note: Updating core can potentially break your site. It is NOT recommended to update production sites without prior testing.

Do you really want to continue? (y/n): y
Unable to load class \Drush\VersionControl\Backup                                                                                [error]
Unable to load class \Drush\VersionControl\Backup                                                                                [error]
(uiserver):uSOMENUMBER:~ > ls
drupal-7.39  logs  sites

```

I'm on a 1and1 shared hosting and followed this guide for a proper installation.

Minor changes I did from what the guide says are:

* Disregarding the paragraph on access from remote machine & aliasing (as I'm not interested in it)
* Using php5.5-cli instead of php5.5 for `DRUSH_PHP`export in my `.bash_profile`: this was done to fix this issue (anyway it fails even by using php5.5).

I'm using **drush 8.0-dev**.

This is the file structure **before** updating:

```
(uiserver):uSOMENUMBER:~ > ls -la
total 39808
drwx---r-t 16 uSOMENUMBER ftpusers     4096 Aug 21 00:56 .
drwxr-xr-t  6 root      root         4096 Aug 21 00:14 ..
-rw-------  1 uSOMENUMBER ftpusers      638 Jul 27 13:23 .bash_history
-rwx---r-x  1 uSOMENUMBER ftpusers      764 Aug 20 22:54 .bash_profile
-rwx---r-x  1 uSOMENUMBER ftpusers      507 Jul  2 15:36 .bashrc
drwx---r-x  4 uSOMENUMBER ftpusers     4096 Jul  2 15:36 .composer
drwx---r-x  3 uSOMENUMBER ftpusers       32 Jul  2 15:36 .drush
-rw----r--  1 uSOMENUMBER ftpusers      174 Jun 21 10:51 .gitignore
-rw----r--  1 uSOMENUMBER ftpusers     5826 Jul  2 15:52 .htaccess
drwx---r-x  3 uSOMENUMBER ftpusers      124 Aug 21 00:46 .subversion
-rw----r--  1 uSOMENUMBER ftpusers    98401 Jun 21 10:51 CHANGELOG.txt
-rw----r--  1 uSOMENUMBER ftpusers     1481 Jun 21 10:51 COPYRIGHT.txt
-rw----r--  1 uSOMENUMBER ftpusers     1717 Jun 21 10:51 INSTALL.mysql.txt
-rw----r--  1 uSOMENUMBER ftpusers     1874 Jun 21 10:51 INSTALL.pgsql.txt
-rw----r--  1 uSOMENUMBER ftpusers     1298 Jun 21 10:51 INSTALL.sqlite.txt
-rw----r--  1 uSOMENUMBER ftpusers    17995 Jun 21 10:51 INSTALL.txt
-rw----r--  1 uSOMENUMBER ftpusers    18092 Jun 21 10:51 LICENSE.txt
-rw----r--  1 uSOMENUMBER ftpusers     8167 Jun 21 10:51 MAINTAINERS.txt
-rw----r--  1 uSOMENUMBER ftpusers     5382 Jun 21 10:51 README.txt
-rw----r--  1 uSOMENUMBER ftpusers     9642 Jun 21 10:52 UPGRADE.txt
-rw----r--  1 uSOMENUMBER ftpusers     6604 Jun 21 10:51 authorize.php
drwx---r-x  2 uSOMENUMBER ftpusers       48 Jul  2 15:34 bin
-rw----r--  1 uSOMENUMBER ftpusers      720 Jun 21 10:51 cron.php
-r-----r--  1 uSOMENUMBER ftpusers 40437884 Aug 20 23:26 d.tgz
-rw----r--  1 uSOMENUMBER ftpusers      872 Jul 28 18:29 drupal-update.sh
drwx---r-x  4 uSOMENUMBER ftpusers       84 Aug 20 22:36 drush-backups
drwx---r-x  4 uSOMENUMBER ftpusers     4096 Jun 21 10:53 includes
-rw----r--  1 uSOMENUMBER ftpusers      529 Jun 21 10:51 index.php
-rw----r--  1 uSOMENUMBER ftpusers      703 Jun 21 10:51 install.php
drwxr-xr-x  3 root      root         4096 Aug 21 00:14 logs
drwx---r-x  4 uSOMENUMBER ftpusers     8192 Jun 21 10:53 misc
drwx---r-x 42 uSOMENUMBER ftpusers     4096 Jun 21 11:00 modules
-rw----r--  1 uSOMENUMBER ftpusers      105 Nov  3  2014 php.ini
drwx---r-x  5 uSOMENUMBER ftpusers       98 Jun 21 10:51 profiles
-rw----r--  1 uSOMENUMBER ftpusers     1479 Jun 21 10:51 robots.txt
drwx---r-x  2 uSOMENUMBER ftpusers     4096 Jun 21 10:52 scripts
drwx---r-x  4 uSOMENUMBER ftpusers      144 Aug 20 22:36 sites
-rwx---r-x  1 uSOMENUMBER ftpusers      128 Aug 20 22:11 test.sh
drwx---r-x  7 uSOMENUMBER ftpusers     4096 Jun 21 10:53 themes
-rw----r--  1 uSOMENUMBER ftpusers    19986 Jun 21 10:52 update.php
-rw----r--  1 uSOMENUMBER ftpusers     2178 Jun 21 10:52 web.config
drwx---r-x  2 uSOMENUMBER ftpusers       74 Nov  3  2014 webscripts
-rw----r--  1 uSOMENUMBER ftpusers      417 Jun 21 10:52 xmlrpc.php

```

How can this be fixed?

# Answer
> 4 votes
After some testing, I found a solution: although installing drush in the same drupal folder may work for updating single modules, it will break your site if you try to update the core.

Apparently, you should never install drush in the same folder of drupal. So the issue is solved by moving the drupal installation into `~/drupal/` and install drush into `~/`.

# Answer
> 5 votes
I was having a similar issue. I tried to run `drush up drupal` and it was returning `Unable to load class \Drush\VersionControl\Backup`. I can confirm that removing drush from my composer.json file solved this issue. My steps were: remove drush from the composer.json, run `composer update` and then re-run `drush up drupal`.

I'm also using Drupal 8.1.9. Just updated to 8.2.

Hope this also helps others.

Thanks Marco.

# Answer
> 2 votes
You are using Drush 8, but your Drupal is Drupal 7. Try to use Drush 7.

---
Tags: drush
---


# Question
Title: How do I modify the output of iframes generated by Media oEmbed module?
I'm trying to add a title attribute to all iframes outputted by the D7 media\_oembed module with Youtube videos, but can't find the write entry point for it. There aren't any templates with the raw structure to override.

Can someone point me to the right place please?

# Answer
The HTML is being generated by the YouTube oEmbed API.

If you inspect the **themes/media-oembed.tpl.php** template & the theme preprocess include **themes/media\_oembed.theme.inc**, you can see that `media_oembed_get_data()` looks up the plugin which pulls the data from the API. In the returned data, the `html` element is used to fill the `$content` variable in the template.

The module provides a few different means to hook into retrieval/process/display of the data:

1. `hook_media_oembed_request_alter($parameters, $plugin, $url)` can be evoked to alter data before plugin retrieval.
2. `hook_media_oembed_response_alter($embed)` can be evoked to alter data after plugin retrieval.
3. `hook_preprocess_media_oembed(&$variables)` can be evoked before processing the template for display.

Whatever means you use, it looks like you'll need to manipulate the HTML string directly to add the `title` element to your output.
> 0 votes

---
Tags: 7, media
---


# Question
Title: Use a variable defined from a custom form in a custom template
I created a custom form, a custom template, and I "linked" both with a theme hook.

In the `buildForm()` method, I used the following code.

```
public function buildForm(array $form, FormStateInterface $form_state) {
  $form['#foo'] = array("key_a"=>"value_a", "key_b"=>"value_b", "key_c"=>"value_c");
  // …
  return $form;
}

```

From the template, when I show all the available variables with `{{ dump() }}` or `{{ kint() }}` I see `#foo` is present, but I cannot print its value.

I tried the following code, but either I get an error or `NULL` is printed.

```
{{ element.#foo }}
{{ element.'#foo' }}
{{ 'element.#foo' }}
{{ foo }}

```

How can I print that value?

# Answer
Like javascript you need to use bracket notation to get hash key variables:

```
{{ element['#foo'].key_a }}

```
> 4 votes

---
Tags: theming, forms, 8
---


# Question
Title: Server 500 error in a View which is working perfectly outside of the admin area
I have a View which is affected by several hooks ( `views_pre_view`and `views_query_alter`, mainly). It works perfectly in the final user area, but when I am logged and go to the Views GUI, the browser displays the following error message:

```
 An AJAX HTTP error occurred.
 HTTP Result Code: 500
 Debugging information follows.
 Path: en/admin/structure/views/view/NAME_OF_VIEW/preview/block/ajax
 StatusText: Internal Server Error
 ResponseText:

```

I see no error loging in the recent log messages, the browser keeps working, I can modify the View, but I am worried that something may broke later in the final user area. How can I debug what is happening? I have no previous experience in Devel or similar.

# Answer
You are going to have to access the PHP error log file to determine the cause. Drupal may not always log an error since it the error may stop it from running. I would contact your host to see if they can provide you the log.
> 1 votes

---
Tags: 7, views, ajax, debugging, wsod
---


# Question
Title: How to create a chart using an uploaded CSV file as input?
I wish to generate a table and chart using an uploaded file (in Drupal 7).

I have uploaded the CSV file using the Feed Importer module and created a view (using the Views module). The view uses a display format of 'Chart', which is one of the possible views 'styles' you will have after enabling the Chart module.

**My question**: I don't know how to apply this to the uploaded CSV file.

# Answer
> 3 votes
You might want to use the Google Chart API module with Views integration. Here is a post that might help you - Add Charts To Your Drupal Site. It uses the Node Import module to create a node of statistics by way of importing a CSV file.

# Answer
> 0 votes
As a variation to creating charts using an "uploaded CSV file as input\*" (as in your question), you could also "*paste the data contained in such CSV file to create charts from it*". That's something that's supported by the Easychart module (which already has an official release for both Drupal 7 and Drupal 8).

It is a graphical user interface, using the Highcharts javascript library as its charting engine (which may require a commercial license though). It claims to support every Highcharts chart-type and option.

Some more details about this module:

* It defines a new content type (= *Chart*) used to add charts to your site.
* It creates a chart widget that can be used in your own content types.
* It integrates with the WYSIWYG module and provides an editor button to add charts to your WYSIWYG content (*CKeditor* and *TinyMCE* are supported).
* It provides an intuitive interface to configure charts through the Easychart plugin.
* It supports pasting of CSV data to create charts from it.
* overheid.vlaanderen.be contains some real world examples of a Drupal website with some charts created with Easycharts (ignore the text on that page if you're not familiar with this language, just concentrate on the charts).

# Resources:

---
Tags: 7, charts
---


# Question
Title: How to import (stream) data in Drupal and save the visualization as nodes - similar to datamasher.org)?
I am working on a data visualization Drupal website. I am looking for a functionality close to datamasher.org, a site that was built using Drupal.

But I cannot find a way that would allow me to create the same functionality.

**My Question**: How to import data/stream data in a Drupal site and save the visualization as nodes?

# Answer
> 1 votes
Nodes arent the best for storing data as such. I would suggest the data module for storing the datasets. (support for import via feeds is underway) To display some results and charts there is several ways - have a look at forena for example. You could then create a node type that would save the parameter values for forena reports and upon node node display show the report. Similar functionality can be achevied vith views (not so much fomratting though).

# Answer
> 0 votes
If you'd use the Forena module, you can use its **Feeds integration to create nodes** using Forena data blocks and/or reports. In other words: Forena can be used as a feeds importer, which enables Feeds to go read from al kinds of database tables, **external databases**, etc. which Feeds out-of-the-box does not support.

Forena's Community documentation includes a child page Video demos and tutorials containing a link also about using Forena to import data and reports based on data as drupal nodes. That video also demonstrates the creation of charts, so not just tabular reports, which seems pretty close (or identical?) to what you're looking for.

**Disclosure**: I'm a co-maintainer of Forena.

---
Tags: 7, nodes, charts, database
---


# Question
Title: How can I programatically change the content of a block and keep Full HTML formatting
I need to programmatically change the content of a ui configured block. I've partially figured out how to do this, ie:

```
$ids = \Drupal::entityQuery('block_content')
  ->condition('type', 'custom_block_type')
  ->condition('info', 'Specific block title')
  ->execute();

$my_block = BlockContent::load(array_values($ids)[0]);
$my_block->set('body','<h1>'.$my_processed_string.'</h1>');
$my_block->save();

```

This does change the content, but when I do this the block loses the Full HTML block format, and the new content in printed out verbatim as html encoded content (ie, the user literally sees '\<h1\>My altered value\</h1\>' on the screen). If I go through the ui and change the Text Format field manually to Full HTML, it renders correctly, but that doesn't really accomplish what I need to do.

How can I change the content programatically, without losing the html formatting?

# Answer
> 3 votes
The body field has at least two properties, `value` and `format`. To replace the complete field content, you have to use an array:

```
$my_block->set('body', [[
  'value' => '<h1>' . $my_processed_string . '</h1>',
  'format' => 'full_html',
]]);

```

Normally you don't need to do this. Set only the value property:

```
$my_block->body->value = '<h1>' . $my_processed_string . '</h1>';

```

So that you don't overwrite properties you don't want to change.

---
Tags: 8, blocks
---


# Question
Title: How to add a Library as a dependencies in another Library?
I'm building D3 libraries to visualize data. The visualizations require the topojson Javascript library to manipulate geo shapes.

I want to include the **topojson** javascript library as a dependency in my custom libraries and right now I'm simply including it in the `.info` file for the each library:

`files[js][] = 'js/topojson.v0.min.js'`

However, this adds the **topojson** file to `<head>` section of the page more than once when I have several of these includes.

I want to be able to load the file once and use it in anyone of my D3 libraries. How do I do that?

# Answer
You can add another dependency by using custom module

```
function hook_library() {
  // Library One.
  $libraries['library-1'] = array(
    'title' => 'Library One',
    'website' => 'http://example.com/library-1',
    'version' => '1.2',
    'js' => array(
      drupal_get_path('module', 'my_module') . '/library-1.js' => array(),
    ),
    'css' => array(
      drupal_get_path('module', 'my_module') . '/library-2.css' => array(
        'type' => 'file',
        'media' => 'screen',
      ),
    ),
  );
  // Library Two.
  $libraries['library-2'] = array(
    'title' => 'Library Two',
    'website' => 'http://example.com/library-2',
    'version' => '3.1-beta1',
    'js' => array(
      // JavaScript settings may use the 'data' key.
      array(
        'type' => 'setting',
        'data' => array('library2' => TRUE),
      ),
    ),
    'dependencies' => array(
      // Require jQuery UI core by System module.
      array('system', 'ui'),
      // Require our other library.
      array('my_module', 'library-1'),
      // Require another library.
      array('other_module', 'library-3'),
    ),
  );
  return $libraries;
}

```
> 0 votes

---
Tags: 7, theming
---


# Question
Title: How to translate facet filter view search assertions/statements into Russian?
How to translate facet filter view search assertions/statements into Russian? See the attached image. Want to write these statements in pure Russian to make friendly for the local shop customers. Thank you.

# Answer
I think you can just import your own translations, creating a simple \*.po file. The structure of that file you can get from https://www.gnu.org/savannah-checkouts/gnu/gettext/manual/html\_node/PO-Files.html (or just google the example). Import your own translations available by uri \[yoursite\]/admin/config/regional/translate/import
> 0 votes

---
Tags: views, i18n-l10n, search
---


# Question
Title: Why am I seeing "Undefined index: und" when I'm using LANGUAGE_NONE?
I've never seen this before, I'm getting an

> Undefined index: und in mymodule\_page\_alter...

on a line where I'm checking this

```
$node->field_override_ads[LANGUAGE_NONE][0]['value'] == 0

```

Is this a bug, or am I missing something?

# Answer
> 0 votes
```
if(count($node->field_override_ads) && $node->field_override_ads[LANGUAGE_NONE][0]['value'] == 0)

```

You need to check if a value even exists before checking the value. And I'd actually write it this way:

```
if(count($node->field_override_ads) && !$node->field_override_ads[LANGUAGE_NONE][0]['value'])

```

# Answer
> 0 votes
No it's not a bug, it's quite normal for a field to have no value.

You should check using Drupal's API though, it will bypass the issue your code introduces:

```
$items = field_get_items('node', $node, 'field_override_ads');
if (count($items)) {
  $val = $items[0]['value'];
)

```

---
Tags: hooks
---


title: How do I check login?

text:
# Question
Title: How do I check login?
I have a php file in my Drupal 8 module.The name of my custom module is fb. Within the fb folder I have a php file fb.php .The content of that file is loaded as an iframe using the follwing code

```
 public function buildForm(array $form, FormStateInterface $form_state) {
  $extpath = take_control_fb_ext_client_path();
  $fbpath = take_control_client_path(drupal_get_path('module', 'fb') . '/fb.php?extpath=' . $extpath);
  global $base_url;
  $form['#attached']['take_Control_fb']['library'][] = 'fb/fb';
      $form = array(
      'take_control_fb_container' => [
    '#type' => 'inline_template',
    '#template' => '',
    '#context' => [
      'url' => '/modules/fb/fb.php?extpath=/libraries/extjs/ext-3.4.1'
  ],
],

  );
return $form;
  }
```

.I need to check drupal login is set or not in the fb.php file. I have used the following code to check that

$logged\_in = \Drupal::currentUser()-\>isAuthenticated();

Ref link : https://docs.acquia.com/articles/there-drupal-function-check-if-user-logged

But it resulted the error 'PHP Fatal error: Class 'Drupal' not found'.

Please help me to figure out some solution to fix this.

# Answer
The correct approach for this would be to implement a service, in which you put the contents of the fb.php and there all the Drupal functions will be recognized. Here is an example of a service implementation: https://docs.acquia.com/articles/drupal-8-services-dependency-injection-and-service-containers
> 0 votes

---
Tags: 8
---


# Question
Title: How do I inspect mail messages in Behat tests?
I am writing a Behat Scenario that checks that an email generated by the Drupal system under test is sent to the correct recipient but I \[could not\] capture the mail messages from `test_mail_collector`. How do I do this?

**\[Update\]**
The code below is essentially my current working version and should work for you ... at least as long as you don't have an anti-spam module interceding ... in which case see the extra code in my answer.

In `FeatureContext.php` I switch over to the mail system sender `test_mail_collector` in the `@BeforeScenario` tagged with `@email` and revert to the site's original mail system sender in the `@AfterScenario` tagged with `@email`.

However, \[before I discovered my answer, there were\] never any messages in the array returned by `\Drupal::state()->get('system.test_mail_collector')` when a scenario should generate them,

Here's a typical scenario:

```
...
@email
Scenario: Send an email when a user resets her password
Given users:
  | name    | mail           | status |
  | Jo User | jo@example.com | 1      |
When I visit "user/password"
And I fill in "name" with "jo@example.com"
When I press the "Submit" button
Then an email should be sent to "jo@example.com"

```

And here are the `FeatureContext.php` snippets:

```
...
/**
*  @Then an email should be sent to :recipient
*/
public function anEmailShouldBeSentTo($recipient)
{
  // Reset state cache.
  \Drupal::state()->resetCache();
  $mails = \Drupal::state()->get('system.test_mail_collector') ?: array();
  $last_mail = end($mails);
  if(!$last_mail) {
    throw new Exception('No mail was sent.');
  }
  if ($last_mail['to'] != $recipient) {
    throw new \Exception("Unexpected recpient: " . $last_mail['to']);
  }
  $this->lastMail = $last_mail;
}

/**
 *  @BeforeScenario @email
 */
public function beforeEmailScenario(BeforeScenarioScope $scope)
{
  $this->m_config = \Drupal::configFactory()->getEditable('mailsystem.settings');
  $this->saved_mailsystem_defaults = $this->m_config->get('defaults');
  $this->m_config->set('defaults.sender', 'test_mail_collector')->save();
  \Drupal::state()->set('system.test_mail_collector', array());
}

/**
 *  @AfterScenario @email
 */
public function afterEmailScenario(AfterScenarioScope $scope)
{
  // revert mail system after scenarios agged with @email
  $this->m_config->set('defaults.sender', $this->saved_mailsystem_defaults['sender'])->save();
}

```

The website is normally set up to run with `swiftmailer` enabled but I have tried all the other available mail system formatters and senders - like `Default PHP Mailer` \- without success.

As a kind of "proof of setup" within `FeatureContext.php`, I can send test messages to the `test_mail_collector`:

```
$language_interface = \Drupal::languageManager()->getCurrentLanguage();
\Drupal::service('plugin.manager.mail')
    ->mail('test', 'test', 'jo@example.com', $language_interface->getId());

```

This shows me that the `test_mail_collector` is working - but messages generated from the website \[were\] not being collected.

# Answer
Ensure you don't have anti-spam modules installed and doing their job!

The `@BeforeScenario` and `@AfterScenario` code in the original question is correct except in the case where you have an anti-spam module that is interfering with a `Scenario`.

For example, if you've got `honeypot` installed, ensure that you disable the `time_limit` setting. `time_limit` is there to protect the Drupal site against spambots .... and test programs! ... on the assumption that humans can't enter stuff in less than a few seconds whereas bots and test programs do so almost instantaneously.

So, if you, as I did, have `honeypot` installed, then you will need to temporarily disable `time_limit` for the duration of the test. For example my `@BeforeScenario` and `@AfterScenario` code is now as follows:

```
/**
   *  @BeforeScenario @email
   */
  public function beforeEmailScenario(BeforeScenarioScope $scope)
  {
    $this->m_config = \Drupal::configFactory()->getEditable('mailsystem.settings');
    $this->saved_mailsystem_defaults = $this->m_config->get('defaults');
    $this->m_config
      ->set('defaults.sender', 'test_mail_collector')
      ->set('defaults.formatter', 'test_mail_collector')
      ->save();
    // Reset the state variable that holds sent messages.
    \Drupal::state()->set('system.test_mail_collector', array());

    // If we have honeypot installed then ensure that we disable time_limit
    // So that automated tests / bots can run
    $this->h_config = \Drupal::configFactory()->getEditable('honeypot.settings');
    $this->saved_honeypot_time_limit = $this->h_config->get('time_limit');
    if ($this->saved_honeypot_time_limit) {
      $this->h_config
        ->set('time_limit', '0')
        ->save();
    }
  }

  /**
   *  @AfterScenario @email
   */
  public function afterEmailScenario(AfterScenarioScope $scope)
  {
    // revert mail system after scenarios agged with @email
    $this->m_config
      ->set('defaults.sender', $this->saved_mailsystem_defaults['sender'])
      ->set('defaults.formatter', $this->saved_mailsystem_defaults['formatter'])
      ->save();

    // Ensure we protect against spambots again if honeypot is installed
    if ($this->saved_honeypot_time_limit) {
      $this->h_config
        ->set('time_limit', $this->saved_honeypot_time_limit)
        ->save();
    }
  }

```
> 1 votes

# Answer
If an anti-spam module like honeypot is disabling a test because it detects that the form completion is too fast to be human, consider adding a delay to your test steps.

```
When I visit "user/password"
And I wait for 2 seconds
And I fill in "name" with "jo@example.com"
And I wait for 1 second
When I press the "Submit" button
Then an email should be sent to "jo@example.com"

```

I suggest this gives a simpler and more realistic test than messing with the anti-spam settings. You'll need to add a step definition something like:

```
/**
 * @Given /^I wait ([0-9^"]*) seconds$/
 */
public function iWaitSeconds($wait) {
  for ($i = 0; $i < $wait; $i++) {
    sleep(1);
  }
}

```

(Borrowed from http://fuseinteractive.ca/blog/test-wrangling#.VqS6J\_mLQYs, also see http://docs.behat.org/en/v2.5/cookbook/using\_spin\_functions.html)
> 1 votes

# Answer
The above configuration did not work for me properly as it failed to swap the mail handler plugin to the test one. According to https://api.drupal.org/api/drupal/core%21modules%21system%21src%21Tests%21Mail%21MailTest.php/8.2.x?no\_cache=1475753055 the following worked for me

```
/**
   * Swaps the mailing system settings with a test one.
   *
   * @BeforeScenario @email
   */
  public function beforeEmailScenario() {
    $this->mailConfig = \Drupal::configFactory()->getEditable('system.mail');
    $this->savedMailDefaults = $this->mailConfig->get('interface.default');
    $this->mailConfig->set('interface.default', 'test_mail_collector')->save();
    \Drupal::state()->set('system.test_mail_collector', array());
  }

  /**
   * Restores the mailing system settings with the default one.
   *
   * @AfterScenario @email
   */
  public function afterEmailScenario() {
    $this->mailConfig->set('interface.default', $this->savedMailDefaults)->save();
  }

```

These are only the before and after scenario. The rest are working fine. Also, if you want to use the test plugin to work only for a specific case, you can use 'interface.mail\_key' instead replacing the 'mail\_key' with the mail key of your module.
> 0 votes

---
Tags: 8, emails, testing
---


title: How to use dash in namespace?

text:
# Question
Title: How to use dash in namespace?
I have installed a library using composer.json https://github.com/nuovo/spreadsheet-reader

Now in vendor I'm getting a folder structure like:

Now I want to use excel\_reader2.php class inside my controller.

and I'm using it like:

```
use nuovo\spreadsheet-reader\php-excel-reader\excel_reader2;
use nuovo\spreadsheet-reader\SpreadsheetReader;

```

but it is giving me fatal error

> Parse error: syntax error, unexpected '-', expecting ',' or ';'

Is there any way to use folders containing '-' (dash) in their names?

# Answer
> 1 votes
If that package is doing it correctly, then it registered its classes with composer and it should just work.

If it doesn't use namespaces (which you could see by opening the file), then just write new ClassName and it should work.

That is assuming you installed the dependency correctly, it needs to be in your main vendor folder, not the one of a module or so.

---
Tags: 8
---


# Question
Title: Redirect a form just if the form is loaded in specific page(url)
I've implemented a menu using hook\_menu(),the page callback function checks if user is login or not, if user is logged in a form for creating a content of type 'request' is loaded if not using drupal\_get\_form, user login block is loaded.

Now what I'm looking for is when user signed-in, he/she returned back to this page so now he can fill the form.

I don't want all user login event redirected to this page, so now my question is :

> How to redirect a form just if the form is loaded in specific page(url)?

# Answer
It can be accomplished adding 3 functions to your custom module:

The first one is to implement hook\_form\_alter():

```
function my_module_form_alter(&$form, &$form_state, $form_id){
  if($form_id=='user_login') { // It will be executed only on this form.
    // Check if the form is loaded in your custom path.
    if (current_path() == 'my_custom_path') {
      array_push($form['#submit'], 'my_module_login_custom_path_submit');
    }
    else {
      array_push($form['#submit'], 'my_module_login_user_submit');
    }
  }
}

```

The second one is to implement the redirect to your custom path:

```
function my_module_login_custom_path_submit(&$form, &$form_state){
  $form_state['redirect'] = 'my_custom_path';
}

```

The third one is to implement the redirect to user page:

```
function my_module_login_user_submit(&$form, &$form_state){
  $form_state['redirect'] = 'user';
}

```
> 1 votes

---
Tags: 7, forms, redirection
---


title: How do I export an entity?

text:
# Question
Title: How do I export an entity?
In Drupal 7, with the aid of features, we could do something like node\_export, or uuid\_features, etc.

I'm looking for a good way to create content / other entities using the UI and export it to code some how using Drupal 8 so that I can put into an install or update hook so that our site builders don't miss pieces of configuration.

I know we can do it programatically. And I'm all for that. I would just like an easy way to generate the Array we need to stick in our install or update hooks.

# Answer
> 3 votes
You want the Default Content for D8 module, which provides drush commands to export and installs the content on module install. From its project page:

> Default content gives your module and install profile a way to ship default content as well as configuration. Powered by core's serialization, rest and hal modules.
>
> Features
>
> * Supports entity-references between content.
> * Supports files if you have File entity
> * Easily export your content and its dependencies to yml using drush commands.

# Answer
> 0 votes
There is a new "configuration inspector" module that shows any configuration entity in various formats, one of which ("raw") I think it's called might suit you.

# Answer
> 0 votes
"Default content" module has very limited usage. It doesn't check for entity uniqueness in any sensible way, as it it doesn't create correct unique URLs.

I recommend:

1) if there are few entities to export, use update hooks to manually create needed entities.

2) if there are lots of entities, export them using default content with `drush dce` and then create **migrate** \+ **migrate\_plus** to create *json* migration where you'd skip entity ids and use uuids as object unique ids. That's a lot of work, especially if you have no experience with Drupal 8 migration, but it is the most reliable and managed way.

---
Tags: 8, importing-exporting
---


# Question
Title: How can I check to see if the current user has an an order in checkout?
I need to create a condition like the following:

```
 if (current user has an order in checkout){
    go to the checkout page
 }else{
    go to this other page
 }

```

So far, I'm using:

```
 if ($order = commerce_cart_order_load($user->uid)) {
      drupal_goto('checkout/')
 }else{
      drupal_goto('someotherpage/')
 }

```

but it doesn't seem to work. What am i doing wrong? Thanks!

# Answer
* Preload `$user` variable.
* Remove those `/` at the end of each url.
* Add a semicolon at the end of each PHP line.

```
global $user;
if ($order = commerce_cart_order_load($user->uid)) {
  drupal_goto('checkout');
}
else {
  drupal_goto('someotherpage');
}

```
> 0 votes

---
Tags: commerce
---


# Question
Title: How to get language specific path in twig?
In a twig template you are able to get a relative path by using `{{ path('entity.node.edit_form', {'node': nid }) }}`. The path will be in current language.

Now I need to get the path in a specfic language. I thought I could use `{{ path('entity.node.edit_form', {'node': nid }, {'language': langcode}) }}` but this results an error if I set `langcode` to a string like `DE`. According to the api docs `language` has to be a language object. How can I accomplish this in twig?

# Answer
> 6 votes
For a twig only solution you can define a custom twig function `path_lang()`, which adds the language object to options, if a language code is provided as additional parameter:

**src/TwigExtension.php:**

```
<?php

namespace Drupal\mymodule;

use Drupal\Core\Language\LanguageManagerInterface;
use Drupal\Core\Routing\UrlGeneratorInterface;

class TwigExtension extends \Twig_Extension {

  protected $languageManager;

  protected $urlGenerator;

  public function __construct(LanguageManagerInterface $language_manager, UrlGeneratorInterface $url_generator) {
    $this->languageManager = $language_manager;
    $this->urlGenerator = $url_generator;
  }

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

  public function getFunctions() {
    return [
      new \Twig_SimpleFunction('path_lang', [$this, 'getPathLang']),
    ];
  }

  public function getPathLang($name, $parameters = [], $options = [], $langcode = '') {
    if (!empty($langcode)) {
      if ($language = $this->languageManager->getLanguage($langcode)) {
        $options['language'] = $language;
      }
    }
    return $this->urlGenerator->generateFromRoute($name, $parameters, $options);
  }
}

```

**mymodule.services.yml:**

```
services:
  mymodule.twig.extension:
    arguments: ['@language_manager', '@url_generator']
    class: Drupal\mymodule\TwigExtension
    tags:
      - { name: twig.extension }

```

**In twig:**

```
{{  path_lang('entity.node.edit_form', {'node': nid }, {}, 'en') }}

```

# Answer
> 2 votes
This won't work because I think that you need the language object and not only the langcode.

The best way to do this I think it's to do it in a THEME\_preprocess\_node in your yourtheme.theme file :

SOLUTION 1 (get translation of the node and then get the proper link) :

```
function yourtheme_preprocess_node(&$vars) {
    $node = &$vars['node'];
    // TO HAVE NODE URL IN ANY OF YOUR NODE TEMPLATES FOR CURRENT LANGUAGE
    $vars['node_url'] = $node->toUrl()->toString();
    // SOLUTION 1
    $node_de = $node->getTranslation('de');
    if ($node_de && is_object($node_de)) {
        $node_url = $node_de->toUrl()->toString();
        $vars['node_url_de'] = $node_url;
    }
}

```

SOLUTION 2 (get the url object of the node and then get translation of the url object) :

```
function yourtheme_preprocess_node(&$vars) {
    $node = &$vars['node'];
    // TO HAVE NODE URL IN ANY OF YOUR NODE TEMPLATES FOR CURRENT LANGUAGE
    $vars['node_url'] = $node->toUrl()->toString();
    // SOLUTION 2
    $language_manager = \Drupal::service('language_manager');
    $language_de = $language_manager->getLanguage('de');
    $urlNodeObject = $node->toUrl();
    $urlNodeObject->setOption('language', $language_de);
    // IF YOU WANT AN ABSOLUTE URL
    $urlNodeObject->setAbsolute();

    $vars['node_url_de'] = $urlNodeObject->toString();
}

```

Although I put `$vars['node_url'] = $node->toUrl()->toString();` to print `{{ node_url }}` instead of `{{ path('entity.node.edit_form', {'node': nid }) }}` because I think it's better.

Then in your TWIG template you just have to print `{{ node_url_de }}` for your aliased german node link.

---
Tags: theming, 8, routes, i18n-l10n
---


# Question
Title: Programatically untick generate automatic URL alias for new node
I am creating a new node and then adding a new menu link. I have the code to correctly add the new node and menu link (below).

```
$node = Node::create([
              'type' => 'standard_page',
              'langcode' => 'en',
              'created' => REQUEST_TIME,
              'changed' => REQUEST_TIME,
              'uid' => 1,
              'title' => 'new_node',
              'body' => [
                'summary' => 'new_node',
                'value' => 'new_node',
                'format' => 'full_html',
              ]
          ]);

  $node->save();

$source = '/node/' . $node->get('nid')->value;  \Drupal::service('path.alias_storage')->save($source, '/new_node', 'en');

$link = MenuLinkContent::create([
      'title'      => $title,
      'link'       => ['uri' => 'internal:/new_node'],
      'menu_name'  => 'main',
      'weight'     => 10,
    ]);

```

The problem is that when I go to edit the node, "generate automatic url alias" is always ticked. So whenever I go to update the node, it destroys the alias that I have already created.

I have tried the following code.

```
$node->path['pathauto'] = FALSE;
$node->save();

```

This doesn't seem to work in Drupal 8 as I get the following error:

> InvalidArgumentException: Unable to set a value with a non-numeric delta in a list. in Drupal\Core\TypedData\Plugin\DataType\ItemList-\>set() (line 112 of core\lib\Drupal\Core\TypedData\Plugin\DataType\ItemList.php).

Hoe do I programatically untick the "Generate automatic URL alias" option in Drupal 8?

# Answer
> 14 votes
Save your node twice, once to generate the alias and the second time to turn off that option for the node.

```
 // Save node to generate alias
 $node->save();
 // Turn off pathauto
 $node->path->pathauto = 0;
 // Save again.
 $node->save();

```

Then open edit form and " Generate automatic URL alias" will be unchecked.

---
Tags: 8
---


# Question
Title: Can't get the key of webform's select field in the results
Im facing a problem with Durpal Webform, Ive created a select field and added options like said in the description (safe\_key|Readable value)

The options are like :

```
w|Woman
m|Man

```

When I submit my webform, I would like to get the key in the results ('w') or at least in the excel file when I export it. But the Drupal default behavior is to display the selected readable value in the result ('woman') ...

How can it be done ?

For me it doesn't seem like a normal behavior, since when you create an html form with a select list, you can define the 'value' attribute (in which you can put a key) and you can define the displayed value (which will not be submit). Drupal seems to use only the Readable value ...

Thanks !

# Answer
It is a bit of a pain. Looks like you have to do this each time, but here goes...

Go to your **Webform** in question...

* Click the **Results** tab
* Click the **Download** button
* Open the **Select List Options** section
* Under **Select Keys**, choose "Short, raw options (keys)"
* Set any other options as you need and then click **Download**

You should have a file where the select option columns are populated with the keys rather than the values.
> 1 votes

---
Tags: webforms
---


# Question
Title: How to autoload, so composer packages work correctly?
I'm trying to load in a composer package: archwisp/php-encrypt-data, and while I'm able to use it in a test php script, using it in Drupal itself doesn't seem to be working.

This is the test script:

```
require __DIR__ . '/vendor/autoload.php';

$encryptionKey = 'IyJQdVtyNClqQ+ybuxHWNhJnw93ocxJuLruRztQPNI0=';
$macKey = 'pbJqXp4YhhtRYv/Ntt/i+O4KbO1F4/2bktO08m0+Exo=';

$phpcrypt = new \PHPEncryptData\Simple($encryptionKey, $macKey);

$ciphertext = $phpcrypt->encrypt('Foobar');

echo $ciphertext . "\n";

echo $phpcrypt->decrypt($ciphertext) . "\n";

```

But, I don't understand what I have to do in a Drupal class to make this work. I tried to `use archwisp\PHPEncryptData;` at the top of the file, and I tried doing `require DRUPAL_ROOT . '/vendor/autoload.php';` as well, but no matter what, it always says: `Call to undefined function PHPEncryptData\\mcrypt_get_key_size()`

Is it because it didn't do the autoload the same way, or is it getting mixed up because of namespaces? The error is coming from the composer package itself, so it is locating that, but for some reason it's not calling the mcrypt function correctly, even though the extension is enabled and working in the test script.

# Answer
> Call to undefined function PHPEncryptData\mcrypt\_get\_key\_size()

mcrypt is a php function of the mcrypt extension. Autloading is working perfectly fine, or you wouldn't get that far. You're simply missing that extension.

The error message is a bit confusing because PHP always looks for functions in the global namespace and in the namespace the code is in and then prints the error for the one with the namespace.
> 1 votes

---
Tags: 8
---


title: What is wrong with my hook_schema code?

text:
# Question
Title: What is wrong with my hook_schema code?
I am pulling my hair for the past half of the day trying to figure out what is wrong. Here is my `hook_schema` function:

```
<?php

function image_gallery_schema() {
  $schema = array();

  $schema['gallery'] = array(
    'description' => 'The main store for gallery entity',
    'fields' => array(
      'id' => array(
        'description' => 'Primary key for our table of gallery',
        'type' => 'serial',
        'unsigned' => TRUE,
        'not null' => TRUE,
      ),
      'uid' => array(
        'description' => 'User id',
        'type' => 'int',
        'not null' => TRUE
      ),
      'title' => array(
        'description' => 'Title of the gallery',
        'type' => 'text',
        'not null' =>TRUE,
       ),
      'created' => array(
        'description' => 'Creation time',
        'type' => 'int',
        'default' => 0,
        'not null' => TRUE
      ),
      'changed' => array(
        'description' => 'Changed time',
        'type' => 'int',
        'default' => 0,
        'not null' => TRUE
      ),
      'gall_description' => array(
        'description' => 'Description of gallery',
        'type' => 'text',
        'not null' =>TRUE,
       ),
    ),
    'primary key' => array('id'),
  );

  $schema['photos'] = array(
    'description' => 'For storing photos',
    'fields' => array(
      'id' => array(
        'description' => 'Primary key for photo',
        'type' => 'serial',
        'unsigned' => TRUE,
        'not null' => TRUE,
      ),
      'g_id' => array(
        'description' => 'Gallery id',
        'type' => 'int',
        'unsigned' => TRUE,
        'not null' => TRUE,
      ),
      'full_path' => array(
        'description' => 'full photo path',
        'type' => 'text',
        'unsigned' => TRUE,
        'not null' => TRUE,
      ),
      'short_path' => array(
        'description' => 'short photo path',
        'type' => 'text',
        'unsigned' => TRUE,
        'not null' => TRUE,
      ),
      'img_description' => array(
        'description' => 'Image description',
        'type' => 'text',
        'unsigned' => TRUE,
        'not null' => TRUE,
      ),
    ),
    'primary key' => array('id'),
    'indexes' => array(
      'g_id' => array('g_id'),
    ),
    'foreign keys' => array(
      'gid' => array(
        'table' => 'gallery',
        'columns' => array('g_id' => 'id'),
      ),
    ),
  );

  return $schema;
}

```

I checked all the brackets and everything seems to be in place. It does create `gallery` table, but fails to create `photo` table. Error I get:

> Syntax error or access violation: 1064 You have an error in your SQL syntax;

I was trying to see how `gallery` schema is different from `photos` but I can't find anything. Maybe something is wrong with `indexes` and `foreign keys`? I checked multiple examples and everything seems to be the same. If someone could help me out, I would be more thank thankful.

# Answer
> 2 votes
It must be because you are adding the `unsigned` attribute to `text` fields.

# Answer
> 0 votes
Simply remove the indexes array in photos array. It should look something like

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

  $schema['gallery'] = array(
    'description' => 'The main store for gallery entity',
    'fields' => array(
      'id' => array(
        'description' => 'Primary key for our table of gallery',
        'type' => 'serial',
        'unsigned' => TRUE,
        'not null' => TRUE,
      ),
      'uid' => array(
        'description' => 'User id',
        'type' => 'int',
        'not null' => TRUE
      ),
      'title' => array(
        'description' => 'Title of the gallery',
        'type' => 'text',
        'not null' =>TRUE,
       ),
      'created' => array(
        'description' => 'Creation time',
        'type' => 'int',
        'default' => 0,
        'not null' => TRUE
      ),
      'changed' => array(
        'description' => 'Changed time',
        'type' => 'int',
        'default' => 0,
        'not null' => TRUE
      ),
      'gall_description' => array(
        'description' => 'Description of gallery',
        'type' => 'text',
        'not null' =>TRUE,
       ),
    ),
    'primary key' => array('id'),
  );

  $schema['photos'] = array(
    'description' => 'For storing photos',
    'fields' => array(
      'id' => array(
        'description' => 'Primary key for photo',
        'type' => 'serial',
        'unsigned' => TRUE,
        'not null' => TRUE,
      ),
      'g_id' => array(
        'description' => 'Gallery id',
        'type' => 'int',
        'unsigned' => TRUE,
        'not null' => TRUE,
      ),
      'full_path' => array(
        'description' => 'full photo path',
        'type' => 'text',
        'unsigned' => TRUE,
        'not null' => TRUE,
      ),
      'short_path' => array(
        'description' => 'short photo path',
        'type' => 'text',
        'unsigned' => TRUE,
        'not null' => TRUE,
      ),
      'img_description' => array(
        'description' => 'Image description',
        'type' => 'text',
        'unsigned' => TRUE,
        'not null' => TRUE,
      ),
    ),
    'primary key' => array('id'),
    'foreign keys' => array(
      'gid' => array(
        'table' => 'gallery',
        'columns' => array('g_id' => 'id'),
      ),
    ),
  );

  return $schema;
}

```

Lemme know if you have any confusions.

---
Tags: 7, database
---


title: Change field key

text:
# Question
Title: Change field key
I'd like to change the keys for a list (text) field type that already has content. Through the admin interface Drupal will tell you that "There is data for this field in the database. The field settings can no longer be changed." Is there any way to do this safely? Here's what I'm considering:

1. `db_change_field`
2. Direct SQL manipulation
3. Changing values of content

I haven't messed with `db_change_field` before and am not even sure about it.

# Answer
> 2 votes
`db_change_field()` is for changing the schema of a single column in a table, it doesn't relate to the field system as such.

The only way to change the name of a field is through direct (or pseudo-direct, using db API functions) manipulation of the database. These are things that need to change:

* Name of the field in `field_config`
* Name of corresponding field in `field_config_instance`
* Name of the `field_data_FIELD_NAME` and `field_revision_FIELD_NAME` tables
* Names of the data columns in the data and revision tables (probably `FIELD_NAME_value` and `FIELD_NAME_format` in your case)

After that clear the cache (preferably manually, i.e. truncate all tables that match the name `cache_*`) and you should see the changes in the site.

That should work on a stock install, but your mileage will likely vary if you have any contrib modules installed that provide functionality based on a field's name. I can't think of any except Field Collection of the top of my head, which won't apply to a text field, but there are probably others.

Whatever you do, take a backup of the database before you start playing around with it!

# Answer
> 1 votes
The user interface and API won't let you do this directly so you have to do it with direct queries. I had to do it and this seemed to work. there are 2 big steps. Luckily the second has already been covered on StackOverflow.com so this answer will focus on the second.

1. Change the field definition in `field_config` table
2. Change the field data in the `field_data_field_name` tables

To change the field definition I did:

1. Get the field definition information from the db: `select * from field_config where field_name = 'field_name' limit 1 \G`
2. I copy and pasted the `data` column from the output and used a small PHP script to modify it as I wanted. In my case I was deleting some values, so I used unset. But the

```
// Unserialize the data.
$a = unserialize('a:8:{...... the actual data here...');
// Modify the array as you need it.
$tids = [524, 13, 20, 523, 19, 17, 703, 2312];
foreach ($tids as $tid) {
  unset($a['settings']['allowed_values'][$tid]);
}
// Print the serialized resule.
print serialize($a);

```
3. In an update hook on the site you can update your db:

```
  db_update('field_config')
      ->condition('field_name', 'field_name')
      ->fields(['data' => '...your modified-and-serialized data goes here...'])
      ->execute();

```
4. Clear **all** the caches.

And, as Clive pointed out and as is always a good idea: make a backup.

---
Tags: 7, entities
---


# Question
Title: How do I create sub-pages for a custom content type?
In Drupal 8, I'd like to create a set of page that relate to a parent content type as so:

1. Movie (site.com/movie-name)
    * Reviews (site.com/movie-name/reviews)
    * Actors (site.com/movie-name/actors)
    * ...

I'd like each child to be it's own page, but retain some information from the parent (e.g. Movie Title, Movie Image, etc.). Also, I'd like to display a menu navigation that is smart enough to adapt to each parent (perhaps a simple menu with relative paths would suffice?).

I imagine that I'll want to use views to accomplish this. Any pointers?

# Answer
Take a look at pathauto and Entity Reference field
> 2 votes

# Answer
In order to have reviews, you can use Comments entity on your movie content type.

For Actors you can create a separate content type and keep a reference of actors content type on movie, so that you can reuse actors on different movies.

and then views will help you in bulding different flavours of pages.
> 0 votes

---
Tags: views, 8, navigation
---


# Question
Title: How do I add a super admin, either programmatically or directly through the database or another
```
$new_user = array(
  'name' => 'Sg',
  'mail' => 'sg@email.com',
  'pass' => 'password123',
  'status' => 1,
  'field_custom_first_name' => array(LANGUAGE_NONE => array(array('value' =>'S'))), // This becomes $account->field_custom_first_name[LANGUAGE_NONE][0]['value']
  'field_custom_last_name' => array(LANGUAGE_NONE => array(array('value' => 'Doe'))),
  'access' => REQUEST_TIME,
  'roles' => array(), // No other roles than Authenticated
 //'roles' => array('10' => '10', '11' => '11'), // If you want to specify additional roles, the numbers are role_id's
);
user_save(NULL, $new_user);

```

I've seen this above code but where should I implement this code? I tried adding it and I got the error:

> user\_save() is an undefined function.

I just need to be able to login to the system as a super-admin.

# Answer
> 0 votes
I found what I was looking for. You can use drush to generate a one time login link which allows you to get into the system.

`drush user-login` or its alias `drush uli`

# Answer
> 1 votes
You have to create a super admin role`(admin/people/permissions)` and check all the boxes. And then you need to assign this role to the user.

---
Tags: 7, users
---


# Question
Title: Conditional Fields with multiple conditions
I am using Conditional Fields module. I need some guidance when setting dependencies for multiple fields (accepting unlimited values). Here is the situation:

In my entity form I have two fields:

1. Assignment Status --\> This is Select List type with two values DRAFT and FINAL
2. Upload File --\> This field is required field for accepting documents from student ONLY when Assignment status is FINAL else it is optional field.

Now my question is when I am using this case and creating Dependent and Dependee relation only for one assignment this work fine but when I give an option for accepting unlimited values the Conditional Fields doesn't work.

Because one student is required to submit more than one assignment I used Paragraph Module and also tested this case also with MultipleFields Module. I am not able to find any answer to my query. Please help me to find this answer.

# Answer
> 0 votes
You can try the module Reference Option Limit

With this module you can try to make a reference.

The documentation of this modules is here

Documentation

Is a Great module, hope i can help you

---
Tags: entities
---


# Question
Title: How to create search indexes by path in Drupal 8?
For a relatively small Drupal 8 website, I need to enable a search box, with multiple indexes based on the path or menu value.

For example; the main menu has 2 menu items linking to basic pages: `Employers` and `Employees`, and rest of the website pages are created under these two pages, and each page has a menu item with matching hierarchy.

* **Employers**
    + Section A
        - Sub-section A-1
        - Sub-section A-2
        - Sub-section A-3
    + Section B
        - Sub-section B-1
    + Section C
        - Sub-section C-1
        - Sub-section C-2
* **Employees**
    + Section D
        - Sub-section D-1
        - Sub-section D-2
    + Section E
        - Sub-section E-1
        - Sub-section E-2
        - Sub-section E-3
        - Sub-section E-4
    + Section F
        - Sub-section F-1
        - Sub-section F-2
        - Sub-section F-3

I need to be able to search only in `Employers` or `Employees`. And the search results must be limited to those indivual landing pages.

Thoughts?

# Answer
> 2 votes
I was able to resolve the issue by using the Views, not through the search indexes as I initially thought was the path for a solution.

Created a required field for the content-types that would be searched against. Let's call it **Section** for now, with the values of *Employers* and *Employees*. This will be used in the view to filter content by section. (Taxonomy terms can be used for this as well.)

Then created a view page for each section.

In the view, used **Content** for the row style with **Search result highlighting input** option, and sorted content by **Search: Score (asc)**.

The real trick for this to work is enabling **Search result highlighting input** display mode and configuring it with the fields we want to be searched within.

Hope this helps who needs a similar solution in their projects.

# Answer
> 1 votes
Thee is no out of the box solution available.

Nodes have a "Path" field, but it's a special field at the moment that doesn't load data when requested.

Using the Search API project, you could implement your own code to make the path available at index time, so that you can filter by it.

What's more common is to not have the path be the primary data for this but have reference fields or list fields where you store this information and based on that generate an automated alias (menu still needs to be set up manually). Then you are close to being able to create a view that allows to search and filter by that field.

---
Tags: 8, search
---


# Question
Title: hook_modules_enabled called before hook_menu
(Note: the code and module names have been simplified for demonstration)

I have a number of custom modules in a Drupal 7 site. One of the modules (a 'base' module enabled during site installation) creates a custom menu (operations-menu) along with a hook (hook\_operations\_menu()) for customizing the menu. Other custom modules (I'll refer to them as implementing modules) with a need to add menu links into the operations-menu can simply implement hook\_operations\_menu() and return the appropriate menu item definitions.

Example: Assuming my base module is called 'base' and my implementing module is called 'implements'.

**base.module**

```
/**
* Implements hook_modules_enabled()
*/
function base_modules_enabled($modules) {
  $links = [];
  foreach ($modules as $module) {
    $module_links = module_invoke($module, 'operations_menu');
    if(is_array($module_links))
      $links = array_merge($links, $module_links);
  }
  foreach ($links as $link) {
    menu_link_save($link);
  }
}

```

**implementing.module**

```
/**
* Implements hook_operations_menu()
*/
function implementing_operations_menu() {
  $links = [];

  // Define menu links here

  return $links;
}

/**
 * Implements hook_menu()
 */
function implementing_menu(){
  $items = [];

  // Define menu callbacks, etc.

  return $items;
}

```

This strategy works well to maintain a modularized custom menu with one exception. For some reason, when enabling the implementing module, `base_modules_enabled()` is called before `implementing_menu()`. This is a problem since some menu links defined in `implementing_operations_menu()` depend on routing established in `implementing_menu()`.

I've checked the source code, and `module_enable()` invokes `hook_modules_enabled()` at the very end. I don't understand how `hook_menu()` is getting called after `hook_modules_enabled()` and not before.

Any assistance is greatly appreciated!

# Answer
> 1 votes
So, here's the solution. Hopefully it helps save someone else some time. As it turns out, `hook_menu()` is not invoked during module enabling. As such, I had to force a menu rebuild which invokes `hook_menu()` and ensures all the proper routes exist prior to building my menu links.

**base.module\>**

```
/**
* Implements hook_modules_enabled()
*/
function base_modules_enabled($modules) {
  menu_rebuild(); // <--- Added this line to force hook_menu() to be called first
  $links = [];
  foreach ($modules as $module) {
    $module_links = module_invoke($module, 'operations_menu');
    if(is_array($module_links))
      $links = array_merge($links, $module_links);
  }
  foreach ($links as $link) {
    menu_link_save($link);
  }
}

```

---
Tags: 7, hooks
---


title: Views slideshow from single node

text:
# Question
Title: Views slideshow from single node
I'm trying to achieve working slideshow from images in single node. Images are uploaded from the image field. It's drupal 7. I made new content type and all I made now is slideshow from multiple nodes (with one image in every node). This works fine but thats too problematic to add new node for every single image.

# Answer
> 10 votes
In the views image field settings, under **Multiple Field Settings**, there is checkbox for **"Display All Values in the Same Row"** which is checked by default. If you uncheck this box it will place each image in a new row and it will work as you require. I know views has had this feature since at least version 2, but it might be called something slightly different in older versions.

I like doing it this way for simple slideshows, I can rearrange all of the images on one node/edit page. But for more complex slideshows, like where each image links somewhere or has alternate text, your best bet is probably still to use one node per row.

# Answer
> 7 votes
The Field Slideshow module is exactly what you need then. All images are contained within the node (no node bloat) and it uses jquery cycle (The same as views slideshow does) to produce a dynamic gallery and slideshow.

# Answer
> 2 votes
You might consider using the Galleria module. It uses a single node and displays the images from it as a slideshow.

# Answer
> 2 votes
I have recently built a site with simple galleries and I ended up not using additional slideshow modules at all. All I needed was jQuery Cycle and a little javascript, added to my custom theme. This site has a 'photo' content type and an 'album' vocabulary to assign photo's to different albums. A view creates a list of photo's filtered by album. In my theme I have a js file that looks like this:

```
(function($){

Drupal.behaviors.myAlbumSlideshow = {
  attach: function(){
    var slideshowContent = $('.view-fotoalbum.view-display-id-page_1>.view-content');

    slideshowContent.before('<div id="slideshow-prev"><</div><div id="slideshow-next">></div>');

    slideshowContent.cycle({
      fx:       'scrollHorz',
      next:     '#slideshow-next',
      prev:     '#slideshow-prev',
      timeout:  0
    });

    var slideshowHeight = slideshowContent.height() + 'px';
    $('#slideshow-prev, #slideshow-next').css('lineHeight', slideshowHeight);
  }
}

})(jQuery)

```

A touch of CSS finishes it:

```
.view-fotoalbum {
  width: 710px;
  margin-right: 10px;
}

.view-fotoalbum #slideshow-prev {
  color: #808080;
  border-right: 1px solid #808080;
  cursor: pointer;
  float: left;
  line-height: 300px;
  margin-left: -40px;
  text-align: center;
  width: 30px;
}

.view-fotoalbum #slideshow-next {
  color: #808080;
  border-left: 1px solid #808080;
  cursor: pointer;
  float: right;
  line-height: 300px;
  margin-right: -40px;
  text-align: center;
  width: 30px;
}

```

PS. IMHO, it's not always better to have a single node per image. It's true that this approach provides greater flexibility (for instance adding one image to multiple slideshows), but to some end users, unneeded flexibility is just pointless complexity.

# Answer
> 2 votes
I discovered a good way to have multiple images and multiple links per image in one single node:

What you'll want to do is make sure that both the image and link fields are set to unlimited in the content type. When you create your view also make sure that "Display all values in the same row" is NOT checked. Add a delta field for your image and for your link. Add a Global: PHP filter and set the filter code to this: return(! $row-\>delta == $row-\>delta\_1);

That should do it. You'll need to have the Views PHP module installed to use PHP as a filter.

# Answer
> 2 votes
To show multiple image of single node in slider, use Dynamic display block module and read the configuration setting. In this when you create view for showing slider block please don't check the checkbox in adding of image with "Show Multiple field settings" if it already checked then please uncheck it.

# Answer
> 1 votes
I recommend the Colorbox module

Also, take a look at the following video tutorial: Colorbox for Drupal 7, part 1: Installation and image field integration

# Answer
> 1 votes
Like nearly everything in Drupal, there are a bunch of different solutions to this, but I want to share a simple one I haven't come across anywhere yet.

Basically, I was searching for a way to display a bunch of different fields—all attached to a single node—in a slideshow. These fields included both image and text fields. So, in order to display all fields attached to a single node in a slideshow:

1. Create a view for your slideshow. Use the "Unformatted List" format.
2. Set the view to display only one item, so that you're only dealing with a single node (or use the Contextual Filter: NID)
3. Add all fields that you want to appear in the slideshow. **Exclude all fields from display.**
4. Add a custom field (make sure this field is rendered *after* all the fields you've excluded from display). This where you'll build the basic markup for your slideshow. Using the replacement patterns available, set each available field inside a `li` item like this:
```

<ul id="slider">
<li>[text_field_1]</li>
<li>[image_field_1]</li>
<li>[text_field_2]</li>
<li>[image_field_2]</li>
</ul>

```
5. Then you can run your prefered jQuery slider. If you've already installed in the jQuery Cycle Plugin, you can run that on the slider really easily. Just make sure the plugin is loaded on the page with your slider, and then run it on your newly created `ul`:
```

(function ($, Drupal, window, document, undefined) {

    $(document).ready(function() {
        $('#slider').cycle({
        // choose your options
    });
    });

})(jQuery, Drupal, this, this.document);

```

And you should be good to go.

# Answer
> 0 votes
There is a moduel https://www.drupal.org/project/field\_slideshow which is made for creating a slideshow from a single node.

Personally, I think this would be a great use of a node--type template, then each node of that type would be formatted as a slide show with a high degree of control, such as where to present the rest of the fields for that node...

---
Tags: views, nodes
---


# Question
Title: How to aggregate document.ready actions?
This may be as much a style question as anything, but: I'm building a site that uses the Bootstrap theme and a bunch of Bootstrap features -- popovers, dialogs, and the like. This means that I often need to run little bits of initialization code when the page loads; I'm doing these by using `drupal_add_js` to add the needed bits of jQuery, wrapped in a `document.ready()` handler. The usual sort of thing, I think.

This works fine, but they are all being added to the page in their own SCRIPT and `document.ready` blocks. Thus the page looks like:

```
<script>(function ($) {
        $(document).ready(function() {
            somejQueryCode();
        });
    })(jQuery);
</script>
<script>(function ($) {
        $(document).ready(function() {
            someMorejQueryCode();
        });
    })(jQuery);
</script>
<script>(function ($) {
        $(document).ready(function() {
            stillSomeMorejQueryCode();
        });
    })(jQuery);
</script>

```

as to what it seems like it might be:

```
<script>(function ($) {
        $(document).ready(function() {
            somejQueryCode();
            someMorejQueryCode();
            stillSomeMorejQueryCode();
        });
    })(jQuery);
</script>

```

You get the idea. Like I said, the individual blocks are working, but it seems a little wrong -- you'd surely never write the code by hand like that. I've explored various arguments to `drupal_add_js`, and have started experimenting with the AdvAgg module, but haven't found anything that works. Is there a better way to do this? Comments to the effect of "this isn't a big deal, don't worry about it" will also be accepted... Thanks!

# Answer
In Drupal, $(document).ready() is not used. The Drupal API uses Drupal.behaviors.

You didn't mention your version of Drupal. But you can read about the Drupal 7 JavaScript API here: https://www.drupal.org/node/756722

Here is Drupal 8: https://www.drupal.org/node/2269515

And here is a pretty comprehensive breakdown/tutorial I wrote on using the D7 API: http://www.jaypan.com/tutorial/high-performance-javascript-using-drupal-7s-javascript-api
> 1 votes

---
Tags: javascript
---