title: drupal 8.5 no toolbars active

text:
# Question
Title: drupal 8.5 no toolbars active
I am new to drupal. I installed 8.5. via web-download, transferred it via ftp and extracted the tar-file via ssh. I managed to setup a mysql database and install it with drupal. Wonderful. I can add users and remove them, have administrative privileges.

There is a header with Toolbar items, but then only a link list is shown - tested with firefox and chromium. I have access to themes, can even install new ones. I tried to install Admin toolbar - no change.

I installed a mysql-percona-server Server version: 5.7.20-19-log - Percona Server (GPL), Release '19', Revision '3c5d3e5d53c'

What am I doing wrong?

# Answer
After extensive search (logfiles) and meddling about with access rights, modifying the file .htaccess did the trick.

https://www.drupal.org/forum/support/post-installation/2015-11-22/drupal8-after-installation-no-theme-applied

I commented the option line (first line) and set the file to read only.
> 0 votes

---
Tags: installation, toolbar
---


# Question
Title: Call to undefined function t() in an Unit test
I'm trying to test a method from the dev version of the Allow a content type only once (Only One) module that have a `t()` call inside:

```
<?php

namespace Drupal\onlyone\Utility;

class InternalFunctions {

  public static function getLanguageLabel($language) {
    switch ($language) {
      case 'und':
      case '':
        // If the language is empty then is Undetermined.
        return t('Not specified');

      case 'zxx':
        return t('Not applicable');

      default:
        return ucfirst($language);
    }
  }

}

```

With the following Unit test:

```
<?php

namespace Drupal\Tests\onlyone\Unit;

use Drupal\onlyone\Utility\InternalFunctions;
use Drupal\Tests\UnitTestCase;

class InternalFunctionsTest extends UnitTestCase {

  public function testGetLanguageLabel($language_code, $expected) {
    $this->assertEquals($expected, InternalFunctions::getLanguageLabel($language_code));
  }

  public function providerGetLanguageLabel() {
    $tests[] = ['', 'Not specified'];
    $tests[] = ['und', 'Not specified'];
    $tests[] = ['zxx', 'Not applicable'];
    $tests[] = ['es', 'Es'];
    $tests[] = ['en', 'En'];

    return $tests;
  }
}

```

and when I run the test I receive these errors:

```
1) Drupal\Tests\onlyone\Unit\InternalFunctionsTest::testGetLanguageLabel with data set #0 ('', 'Not specified')
Error: Call to undefined function Drupal\onlyone\Utility\t()

/Users/adriancid/Sites/drupal84-test/modules/drupal.org/onlyone/src/Utility/InternalFunctions.php:26
/Users/adriancid/Sites/drupal84-test/modules/drupal.org/onlyone/tests/src/Unit/InternalFunctionsTest.php:30

2) Drupal\Tests\onlyone\Unit\InternalFunctionsTest::testGetLanguageLabel with data set #1 ('und', 'Not specified')
Error: Call to undefined function Drupal\onlyone\Utility\t()

/Users/adriancid/Sites/drupal84-test/modules/drupal.org/onlyone/src/Utility/InternalFunctions.php:26
/Users/adriancid/Sites/drupal84-test/modules/drupal.org/onlyone/tests/src/Unit/InternalFunctionsTest.php:30

3) Drupal\Tests\onlyone\Unit\InternalFunctionsTest::testGetLanguageLabel with data set #2 ('zxx', 'Not applicable')
Error: Call to undefined function Drupal\onlyone\Utility\t()

```

But the `t()` function is always defined inside Drupal. If I remove the `t()` calls inside the method the test works fine.

I found in Unit testing more complicated Drupal classes that:

> ... global functions do not exist in the testing environment.

And a method to made this works, but I find that this is complicate things just to use a test and method with the `t()` function inside.

So, there is not a simple method to test a class method that have a `t()` call inside?

# Answer
> 3 votes
Thanks to @mpdonadio I have one way to solve this:

In the test file you need to add a namespace with the same namespace where is the method that you're trying to test and then define the function.

```
namespace Drupal\onlyone\Utility;

/**
 * Shadow t() system call.
 *
 * @param string $string
 *   A string containing the English text to translate.
 *
 * @return string
 */
function t($string) {
  return $string;
}

```

Maybe there are another method because I'm still wondering how is possible that in the Webform module a test named testToString() don't use this approach and works for a method with a `t()` call inside: WebformArrayHelper::toString().

# Answer
> 3 votes
You should not be using t() inside classes. The string translation trait should be included instead (if it is not already part of a parent class). Then you will use:

```
$this->t()

```

Then you can use the answer I provided here as to how to do unit tests with string translation trait: How to unit test a class which uses a trait?

---
Tags: 8, testing
---


# Question
Title: How to render Entity Reference fields in the current language
I am trying to render fields from an entity reference in a twig template but they are displaying in the default language instead of the selected one. My twig code:

```
{% for location in node.field_locations %}
  <div class="home-location">
    <div class="wording">
      {{ location.entity.title.value }}
       <span>{{ location.entity.field_sub_title.value }}</span>
     </div>
   </div>
 {% endfor %}

```

# Answer
> 9 votes
You can use the following procedure for translated fields

Add language in your `THEMENAME.theme`

```
function dru8_preprocess_node(&$vars) {
  $language = \Drupal::languageManager()->getCurrentLanguage()->getId();
  $vars['lang'] = $language;
}

```

And in your `node.html.twig` to get translated fields

```
{% if node.field_stories.entity.hastranslation(lang) %}
  <p>{{ node.field_stories.entity.translation(lang).title.value }}</p>
{% else %}
  <p>No translation<p/>
{% endif %}

```

Thus in your case you will need

```
{% for location in node.field_locations %}
  <div class="home-location">
    <div class="wording">
      {{ location.entity.translation(lang).title.value }}
       <span>{{ location.entity.translation(lang).field_sub_title.value }}</span>
     </div>
   </div>
 {% endfor %}

```

---
Tags: 8, theming, entities
---


# Question
Title: How to the set permission of content types for a specific user role?
How to set the permission of content types for a specific user role?

# Answer
If you want to set permission from admin panel then goto **/admin/people/permission** after find your **content** (view/edit) and set the user role **(anonymous/ Authenticated/ Administration)** permission. but if you want to set it problematically then visit https://docs.drupalcommerce.org/commerce2/developer-guide/products/theme-product (Drupal 7 - A Simple Content Type: Permissions & Access)
> 0 votes

# Answer
For D7 you can use the Content Access module.

As an alternative (which I recommend), for D7 or D8, you can use the Group module.
> 0 votes

---
Tags: users
---


title: How do I update to latest version?

text:
# Question
Title: How do I update to latest version?
I used drupal-composer/drupal-project to install Drupal 8. Drupal 8.4.7 was installed, and the website was functioning as expected.

Today, I got the message that Drupal 8.5 was ready for prime time, so I did some research and found Update core via Composer (option 4) for updating code.

This is not updating core.

# Answer
The instructions to update Drupal when you used drupal-composer/drupal-project as Composer template are given in their README.md.

> 1. Run `composer update drupal/core webflo/drupal-core-require-dev symfony/* --with-dependencies` to update Drupal Core and its dependencies
> 2. Run `git diff` to determine if any of the scaffolding files have changed. Review the files for any changes and restore any customizations to .htaccess or robots.txt
> 3. Commit everything all together in a single commit, so web will remain in sync with the core when checking out branches or running `git bisect`
> 4. In the event that there are non-trivial conflicts in step 2, you may wish to perform these steps on a branch, and use git merge to combine the updated core files with your customized files. This facilitates the use of a three-way merge tool such as kdiff3. This setup is not necessary if your changes are simple; keeping all of your modifications at the beginning or end of the file is a good strategy to keep merges easy.

You need to at least to follow the first two steps. The other two are necessary for a particular setup.
> 3 votes

# Answer
Option 4 is when you have composer installed and working.

I have tried this way: https://www.drupal.org/docs/8/update/update-core-manually-via-cli-option-2
> 0 votes

# Answer
In your drupal 8 root issue the following commands:

```
rm -rf vendor/
rm -rf sites/default/files/php/
composer require drupal/core
composer update
drush updb
drush cr

```

If it does not work just copy the files overwriting the old ones as usual...
> 0 votes

---
Tags: 8, updating
---


# Question
Title: How do I get the path alias without the language code?
Suppose I have an alias like http://www.example.com/en/the-new-webpage.html.

I want to get the *the-new-webpage.html* part in `hook_preprocess_html()`. The language code might change into 'ja' or some other code due to the language availability. So I can't get the URL and pass it to `str_replace()` to replace the language part. Is there a function or a way to get the alias part without the language code?

# Answer
> 2 votes
Since you just need the last part of the path, you can use the following code in a `hook_preprocess_html()` implementation.

```
$current_path = \Drupal::service('path.current')->getPath();
$alias = \Drupal::service('path.alias_manager')->getAliasByPath($current_path);
if (basename($alias) == 'the-new-webpage.html') {
  // Your code here
}

```

Starting with Drupal 8.8.0, some Drupal core service has been renamed, as described in The Path Alias core subsystem has been moved to the "path\_alias" module. As consequence of that, in Drupal 8.8.0, Drupal 9.x, and Drupal 10.x, the *path.alias\_manager* service has been replaced by the *path\_alias.manager* service.
The previously shown code needs to be changed to the following one.

```
$current_path = \Drupal::service('path.current')->getPath();
$alias = \Drupal::service('path_alias.manager')->getAliasByPath($current_path);
if (basename($alias) == 'the-new-webpage.html') {
  // Your code here
}

```

The *path.current* service has not been renamed, neither in Drupal 9.x nor in Drupal 10.x.

---
Tags: 8, path-aliases
---


# Question
Title: User authentication handled by a web service
I seek your help and advice. By default, Drupal manages user authentification using the user module that resides in the "core/modules" and through the main Drupal Database. In my case, the user is authenticated through an external webservice, the process is as follow: 1- The user enters his credentials and click submit 2- the credentials are then sent to the webservice 3- the webservice checks the data(credentials) to the one he has in his database 4- upon validation the webservice sends a token (JWT) otherwise it sends 401 Unauthorized

PS: the admin will have normal login (through Drupal Database)

The question is how can I proceed to elaborate this process of authentification?

* Is there some existing modules that could help with this?
* should I override the existing user module or create a new module?

Any info will be of great help.

# Answer
> 0 votes
Remote authentication can range from moderately complex to major complex.

In general, you will need Drupal users that match your external DB users. Drupal security and coding is tied to this. The easiest way is to create users that match your remote DB and then only do authentication.

How you syncing the remote to the local can quickly add complexity.

Other things you will need to deal with are overriding the password reset functionality. Changing it in Drupal will not change it in your remote DB.

Some reference material / modules to look at:

Authentication API (incomplete)

The LDAP Project \- A full featured implementation with dynamic provisioning (creates local Drupal id's if user authenticated) and other stuff.

The External Auth Module \- Just ran across this. May or may not be applicable.

# Answer
> 0 votes
You have a few options depending on what you are trying to do with your webservice.

A good tutorial I've used to set this up is http://www.mediacurrent.com/blog/using-json-web-tokens-jwt-authenticate-endpoints

It sounds like you are already successfully returning a JWT. Congrats I found that to be the difficult part between CORS and restui.

I'm using React as my front end and use this code to then store the token.

`axios.post(apiLoginUrl, data, headers)
 .then(response => {
 console.log(response);
 let jwt = '';
 localStorage.setItem(jwt, response.data.token);
 console.log(localStorage.getItem(jwt));
 })
 .catch(error => {
 console.log(error);
 });` So a breakdown of what this does is as follows. It reaches out to your end point for the JWT and then stores it in localStorage.

I would then pass the token in with each of your subsequent post requests using `localStorage.getItem(jwt)`

You could then pass it in with all with all posts...

So with Axios - `axios.defaults.baseURL = 'https://api.example.com';
axios.defaults.headers.common['Authorization'] = localStorage.getItem(jwt);
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';`

Or with something like Apollo -

`const networkInterface = createNetworkInterface ({
 uri: 'http://examplesite.com/graphql'
});
networkInterface.use([{
 applyMiddleware(req, next) {
 if (!req.options.headers) {
 req.options.headers = {}; // Create the header object if needed.
 }
 // get the authentication token from local storage if it exists
 let jwt = '';
 const token = localStorage.getItem(jwt);
 console.log(token);
 req.options.headers.authorization = token ? `Bearer ${token}` : null;
 next();
 }
}]);
const client = new ApolloClient({
 networkInterface,
});`

Basically the JWT becomes your Authorization part of the Post request.

Hope this helps.

To handle signing up new users your could use something like this... after exposing the user endpoint via RestUI.

`handleSignup(event) {
 console.log("running handleSignup")
 event.preventDefault();
 const apiSignupUrl = "http://example.com/user/register?_format=json";
 const headers = {
 "content-type": "application/json",
 }
 let data =
 {
 "name": {"value": this.state.username},
 "mail": {"value": this.state.username},
 "pass": {"value": this.state.password},
 "field_name" : {"value:": "Name"}
 }
 axios.post(apiSignupUrl, data, headers)
 .then(response => {
 console.log(response);
 if (response.data.uid.length > 0) {
 console.log("Awesome!");
 this.handleLogin();
 }
 else {
 console.log("Back to the drawing board");
 }
 //If we return a successful creation log the user in.
 //handleLogin();
 })
 .catch(error => {
 console.log(error);
 });
 };`

# Answer
> 0 votes
I thought to share my solution hoping it may help some of you :D

In my case all users(agents/clients) needed to be authenticated through the web service in order to have a token with which they will authenticate all their future requests.

So for the agents i used the default login form that comes with drupal and tweaked it abit (ostensibly and internally), the way i tweaked it is that before the normal authentication process of drupal's happens i made sure that the agent authenticate first via the webservice and if it goes OK i let drupal's authentication process happens otherwise i raise an exception and therfore i cut the authentication off and display a login error. As for the client that have accounts within the website and all their data reside within the webservice, i created another page that has another login form and i authenticate them through the webservice and logged them into the site using sessions.

---
Tags: 8, users
---


# Question
Title: Multilingual article should display 404 when a translation is not available
I setup Drupal 8 with 2 languages English & Arabic. Now when an article (English for eg.) does not have a translation (in Arabic) and the user switches the language from the menu. The page loads in Arabic and the article loads in English. I need to return a 404 or something different.

Any advise would be helpful.

# Answer
> 3 votes
It can not be done using core or contrib

## To present 404 page not found (might create bad UX)

You could do something like this in your own module `MODULENAME.module` file

```
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Entity\Display\EntityViewDisplayInterface;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Drupal\Core\Language\LanguageInterface;

/**
 * Implements hook_entity_view().
 */
function MODULENAME_entity_view(array &$build, EntityInterface $entity, EntityViewDisplayInterface $display, $view_mode) {
  $lang = \Drupal::languageManager()->getCurrentLanguage(LanguageInterface::TYPE_CONTENT)->getId();
  $type_id = $entity->getEntityTypeId();
  $translated = $entity->hasTranslation($lang);
  if ($type_id = "node" && $view_mode == "full" && !$translated) {
    throw new NotFoundHttpException();
  }
}

```

but once you go to the **not found page** the language switcher will not be able to take you back to the translated page though

## To Hide untranslated languages in language switcher

There is a core issue about this and solutions are worked out but until it is solved you could create your own module

```
/**
 * @file
 * Hide language switcher links for untranslated languages on an entity.
 */
use Drupal\Core\Entity\ContentEntityInterface;

/**
 * Implements hook_language_switch_links_alter().
 */
function MODULENAME_language_switch_links_alter(array &$links, $type, $path) {
  if ($entity = MODULENAME_get_page_entity()) {
    $new_links = array();
    foreach ($links as $lang_code => $link) {
      try {
        if ($entity->getTranslation($lang_code)->access('view')) {
          $new_links[$lang_code] = $link;
        }
      }
      catch (\InvalidArgumentException $e) {
        // This language is untranslated so do not add it to the links.
      }

    }
    $links = $new_links;

    // If we're left with less than 2 links, then there's nothing to switch.
    // Hide the language switcher.
    if (count($links) < 2) {
      $links = array();
    }
  }
}

/**
 * Retrieve the current page entity.
 *
 * @return Drupal\Core\Entity\ContentEntityInterface
 *   The retrieved entity, or FALSE if none found.
 */
function MODULENAME_get_page_entity() {
  $params = \Drupal::routeMatch()->getParameters()->all();
  $entity = reset($params);
  if ($entity instanceof ContentEntityInterface) {
    return $entity;
  }
  return FALSE;
}

```

Above solution is taken from this post

## To Hide untranslated menu items

You can use menu\_multilingual which gives option when you create/edit a menu block to hide untraslated items.

---
Tags: 8, i18n-l10n
---


# Question
Title: Remove Admin Toolbar "Manage" item if User has No Access
I have created Tours for my users and allowed them to see the Admin Toolbar as a result. However, I have the following unpleasant toolbar:

I would like the "Manage" item to be gone altogether when there's only the Logout & Home link. How could I achieve such behavior?

Note: I've tried disabling the Tools item in the Administrative menu UI and that kinda works, but the Manage item is still displayed.

# Answer
TLTTP;

Is a core bug since 6.4 version (https://www.drupal.org/node/296693) you can use the latest version of admin\_toolbar (https://drupal.org/project/admin\_toolbar) which haves a submodule specific for that issue. Unfortunately this only works for 'admin\_menu' menu but not the toolbar menu (the black bar on top). To hide specific toolbar elements or toolbar element tray links (toolbar element links) you can implement `hook_toolbar_alter(&$items)` hook (https://api.drupal.org/api/drupal/core!modules!toolbar!toolbar.api.php/8.5.x).

Hope it helps someone.
> 2 votes

---
Tags: 8, navigation, toolbar
---


# Question
Title: What is causing "Object of class stdClass could not be converted to string"
I'm receiving the following error:

**Recoverable fatal error: Object of class stdClass could not be converted to string in DatabaseStatementBase-\>execute() (line 2227 of includes/database/database.inc).**

I've narrowed it down to this code but I am still able see what is wrong with the code, it worked before but now I am getting this recurring error.

```
case 'field_home' :
$tids =  field_get_items('node', $node, $key, $node->language);
$terms = taxonomy_term_load_multiple(array(), array('tid' => $tids));
// Gets Field Array Based on Term IDs
$name = array();
foreach($terms as $term){
$name[] = $term->name;}
$return[$key_clean] = $name;

```

# Answer
> 3 votes
Please pass $tids array direct to the function. E.g:

```
$terms = taxonomy_term_load_multiple($tids);

```

NOTE: Also before passing $tids to the function, please check it is include only tids. E.g:

$tids should be like $tids = \[10,11,12,13,...\];

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


title: import users from 7 to 8 without drush

text:
# Question
Title: import users from 7 to 8 without drush
I've been asked to import users from a drupal 7 site into an already-built drupal 8 site. I also need their order history from drupal commerce.

I tried using `drush migrate-upgrade --config-only` to do this, but as of drush 9, the migrate-upgrade etc commands don't work. There is a bug report about this and several patches, but my understanding of drush isn't advanced enough to properly patch & test.

Is there a way this can be done without needing to use drush?

# Answer
> 2 votes
> Is there a way this can be done without needing to use drush?

If you create a custom module with a migration group you don't need to run `drush migrate-upgrade --config-only`, but if you screw up, you'll have to uninstall and re-install, a bit annoying.

> I also need their order history from drupal commerce.

Custom migration is the way to go.

---
Tags: 8, migrations
---


# Question
Title: programmatically exclude new fields from render()
I need to render a limited number of fields from a given content type, without exposing the new ones I may add some day in the future.

Now I have:

`print render($page)`

When a new field is added to the content type, I have that added to the render($page) as well. I don't want this to happen. Aside hiding the field from "admin/structure/types/manage/CONTENT\_TYPE/display", how can I programmatically exclude new fields from render.

# Answer
A common way is to use hide() function in a preprocess hook as:

```
hide($page['field_machine_name']);

```
> 0 votes

# Answer
What you could do is not render out all of $page. So you could get rid of:

```
print render($page)

```

And instead just render the elements within it you want e.g. :

```
print render($page['field_my_field']);

```

That will mean no matter what other fields you add in the future only the ones you specifically render in your template will be shown
> 0 votes

---
Tags: 7, theming, entities
---


# Question
Title: How to restrict term view page for respective user roles programatically? is it possible?
I tried to using hook\_menu\_alter but it doesn't work. It doesn't call page callback function.

```
function mymodule_menu_alter(&$items) {
    $items['taxonomy/term/%taxonomy_term']['page callback'] = 'mymodule_taxonomy_term_page';
}

function mymodule_taxonomy_term_page($term) {
    echo "hello"; die;
}

```

# Answer
I think I understand... You can use a `hook_preprocess_page` and `global $user` to determine the page the user is viewing, and the roles the current user has, and then do a redirect or whatever if they aren't allowed.... Example:

```
/**
 * Implements hook_preprocess_HOOK().
 */
function mymodule_preprocess_page(&$variables)
{
  $current_path = current_path();
  $url_components = parse_url($current_path);
  $protected_taxonomy_term = "whatever_taxonomy_term_you_want";
  if (strpos($url_components['path'], $protected_taxonomy_term) !== FALSE) {
    // User is on the path
    global $user;
    $user_roles = $user->roles;
    // Change to whatever role you want...
    $allowed_role = "authenticated user";
    if (in_array($allowed_role, $user_roles)) {
      drupal_set_message("USER IS ALLOWED ACCESS");
    }
    else {
      // User not allowed, Redirect user to another page..
      drupal_goto("<front>");
    }
  }
}

```
> 0 votes

---
Tags: taxonomy-terms
---


title: Single path for multiple menus

text:
# Question
Title: Single path for multiple menus
I need to list nodes both in the main site navigation and within a section side navigation. Is it possible to target a specific menu for the Pathauto module to reference?

This is an example of the two menu structure.

```
Main Nav:
- Home
-- Page A
--- Page A Child 1
--- Page A Child 2
-- Page B

```

---

```
Page A Side Nav:
- Page A Child 1
- Page A Child 2

```

This results in *Page A Child 1* and *Page A Child 2* having /Page-A-Child-1 and /Page-A-Child-2 as respective paths.

What I want is for both menus to have /Page-A/Page-A-Child-1 and /Page-A/Page-A-Child-2 as paths.

The pattern I'm using is \[node:menu-link:parents:join-path\]/\[node:title\].

# Answer
> 0 votes
You can create multiple path aliases for a single node, but you can not re-use existing path alias to point to different node.

If Child 1 and Child 2 in your example point to the same nodes, then I I am not sure if I understood your problem correctly, because you can create multiple menus to point to the same nodes. Let's say you created both child nodes associating them with Main menu checking on the `Provide a menu link` in node's Menu settings. Then you could just create a new menu on `admin/structure/menu` and add menu items for the same nodes replicating the same or creating new path aliases.

Another way is to let Pathauto generate whatever path aliases you want for the first menu, then programmatically copy its items and override the second menu items with theme\_menu\_tree().

---
Tags: path-aliases
---


# Question
Title: Difference between content type and content entity
What is the difference between content type and content entity?

# Answer
> 1 votes
**Content Types** are one of the main building blocks within a Drupal site; as the name suggests, content types hold content. However, different content types can hold different kinds of content; an *event* can hold information that is specific to a time, where a *discussion* can be used for people to talk. Most sites have multiple different content types, and the name of a content type will ideally give information about how it is used.

An **Entity** is a piece of data within a Drupal site. Nodes, users, comments, and taxonomy are all entities; additionally, with custom code, you can create new entity types if/when needed. You can also add fields to entities, which allows for things like detailed user profiles, or more sophisticated comment forms.

---
Tags: entities
---


# Question
Title: How to add attributes to a specific field's image
```
subtheme/templates/image/image.html.twig

```

controls the style of every image at a website is there a way to overwrite the `image.html.twig` for a given field let's call it

```
field--profile--field-trainerfoto--trainer

```

The field template would be

```
field--profile--field-trainerfoto--trainer.html.twig

```

what would the templates name for the `image.html.twig` be that just overwrites the output of the img tag for the image in the field?

# Answer
One quick way of achieving this is to preprocess the field before it reaches Twig (in MYTHEME.theme) like this:

```
/**
 * Implements hook_preprocess_HOOK().
 */
function MYTHEME_preprocess_field(&$variables, $hook) {
  if ($variables['field_name'] == 'field_avatar') {
    if (!empty($variables['items'])) {
      foreach ($variables['items'] as $delta => &$item) {
        $item['content']['#item_attributes']['class'][] = 'foo';
      }
    }
  }
}

```

Core's template\_preprocess\_image\_formatter() then takes care of putting `#item_attributes` and the class into the `<img>` tag for you.

The normal way of offering alternative template names based on context is implementing `hook_theme_suggestions_HOOK()` or hook\_theme\_suggestions\_HOOK\_alter(). In this case the latter as `MYMODULE_theme_suggestions_image_alter()`.

But the problem here is that there's not much context about the field which will eventually wrap this image at this point. `template_preprocess_image_formatter()` only carries through the attributes that will end up on the image element itself.

You could be a bit sneaky and use the fact that we have already put the class (or some other identifier) into `#item_attributes` when preprocessing the field and use that to generate a new template name for the image once it gets to be rendered:

```
/**
 * Implements hook_theme_suggestions_HOOK_alter().
 */
function MYTHEME_theme_suggestions_image_alter(&$suggestions, $variables) {
  if (!empty($variables['attributes']['class'] && in_array('foo', $variables['attributes']['class'])) {
    $suggestions[] = 'image-foo';
  }
}

```

It has the side-effect of adding an extra class (or other attribute) in your tag by default, but since you could now create `image-foo.html.twig` you could probably compensate for that in the template by removing it there if absolutely needed.

Now just make sure your "field identifier" is fairly unique (and recognizable) so you can figure out where that template suggestion in your theme debug output comes from in the future.
> 5 votes

# Answer
I'm not aware of a way to do this. It's probably possible, but personally, I would create a custom field formatter (within a custom module).

Once the field formatter is created and the custom module enabled, you can then select it via the admin UI as the image field's formatter on the effected content type(s) display settings (and also for view fields, etc.). You'd want to select it for all displays you want to customize (e.g., full, teaser).

The docs for creating field formatters in D8 can be found here: https://www.drupal.org/docs/8/creating-custom-modules/create-a-custom-field-formatter

For me, the easiest way to create one, is to use Drupal Console to generate the required files and scaffolding (console generate:plugin:fieldformatter). You can either add this to an existing custom module if appropriate, or create a stand-alone custom module that just delivers the field formatter (this option is nice for re-using the formatter across mutltiple projects).

If you don't already have Drupal Console installed, you can download it here: https://drupalconsole.com/
> 0 votes

---
Tags: 8, theming
---


# Question
Title: Change URL of site, server and folder remains the same
I want access an old site on a new domain. The server and folder remains the same. I have pointed the new domain to the old Drupal site and updated settings.php to include

```
$base_url = 'http://www.newurl.com';

```

I can access the site, but all links in the theme and in the control panel point to http://oldurl.com. I can navigate around the site by manually altering each URL to reflect the new domain.

I'm under the impression that updating base\_url should work, and take effect immediately. Have I missed something?

# Answer
Seems the website was coded using absolute paths, which is not really good practice from Drupal coding standard's perspective. Please read the discussion on Absolute or relative URLs?. Your case is covered by the accepted answer:

> When moving a site from dev \> staging \> production a Wordpress site's URLs and image references have to be replaced in the DB, this can create an absolute mess.

Though Wordpress is mentioned, that concerns any type of websites, including Drupal.

Anyway, to address the issue you need to do two things:

1. Look for and replace all the instances of your old domain in the active theme's template folder. This is easier part as any decent text editor has Find&Replace feature.

Check the website again and if everything is working then you are lucky. If not proceed to the second step.

2. Search and replace all the instances of your old domain in the database tables. You can do it either using drush or UI like phpMyAdmin. The query is pretty simple:

`UPDATE table_name SET field_name = replace(field_name, 'old-domain', 'new-domain');`

To do so you first need to figure out the tables where your old domains could be stored. Most probably those are 'node' and 'comment' tables and their last revisions, however if content types have additional custom fields then more tables are involved. You could perform quick search for the old domain in the database to find all the tables where it is stored.

If step 2 is involved, then I would also suggest, using the opportunity, to turn all your paths from absolute to relative. In that case, you would run:

```
`UPDATE table_name SET field_name = replace(field_name, 'old-domain/', '/');`

```

instead.

I hope this helps.
> 0 votes

---
Tags: migrations
---


title: Defaut image value not showing up

text:
# Question
Title: Defaut image value not showing up
In my article content type, I've added a header image (field\_header\_image) field which I placed a default image into it so that all articles would have a default image used if one wasn't needed. However, when creating an article and leaving that field as the default value, it doesn't actually use that default value. The page is created as if that value is empty.

Is there any way to make sure that this default value is used?

Is there a way to do this through the .theme file? Is this the best way to do it?

# Answer
If the default image was set correctly then the newly saved article nodes should pick it up. Check if the website's log show any related error messages.

If you want to go with another method then just:

1. Copy `node.tpl.php` in your website's themes folder to `node--article.tpl.php`;
2. Open `node--article.tpl.php` in editor and place the following code just before `print render($content);`:

`<img src="/path-to/image/image_file_name.ext">`

3. Save.
4. Clear your website's cache and revisit any article node.
> 0 votes

---
Tags: 8, nodes, theming
---


title: List all Nodes a user ever edited

text:
# Question
Title: List all Nodes a user ever edited
I want to do display a list with Views, which shows all Nodes the current user have ever edited.

The workbench Module includes a list like I need, 'workbench\_edited', this view uses the Filter

```
(revision user) User: Current (Yes)

```

But the problem is that this View only checks if the user is the editor of the CURRENT REVISION, it does not check all revions of a node, just the current one.

Is there a way to list all Nodes a User ever edited? So that Views checks all revisions of a node?

# Answer
The "content revision : content" relationship in that view needs to be based on the nid rather than the vid. Remove that existing relationship and add back the one that has the same name but uses the nid.

Then you'll need to fix the relationships that have been broken since a number of the fields, filters, and sort options relied on that relationship. You can just step through each of the fields and filters, open their settings, then click "apply" to re-save them to fix the relationships.

In the settings for the title field you need to switch it to link to the revision rather than the node, in order to avoid an error.

And I also noticed that, for some reason, the exposed "published" filter got switched to having a default value of "no" after doing these steps. I have no idea why that happened, but switch it back to "any".

Here's an export of the View you should end up with: http://pastebin.com/a9tXXCqP
> 1 votes

# Answer
I was able to get a list of pages the user has edited (has made a revision on) by using the following setup:
> 0 votes

---
Tags: 7, views, workbench
---


title: Loading Webform Content into Select Box

text:
# Question
Title: Loading Webform Content into Select Box
So I have a Webform called "Department". It contains "Marketing" and "IT" as submissions.

I have another webform called "Person". It is a form that contains a dropdown. This dropdown should be loaded with values from the "department" Webform data.

So I add a new webform, and add a "Entity Select" called "Person Department".

I go to build, in "Person Department", in the "entity references settings", I select "Webform Submission" as the "type of item to reference", and select "Department" as Bundle.

However, when I go to my "Person" form, the drop down is loaded with Person:webform submission5.

How can I display the value of the Webform data in "department", not the key?

Thanks

# Answer
> 0 votes
I think you are going to use a View for the 'Select Entity' element's reference method but you might run into Issue #2174633: View output is not used for entityreference options

---
Tags: forms, entities, webforms
---


# Question
Title: 403 forbidden error when loading images in test server
Am working with drupal7.When images are loading below error is showing in my test site console:

```
GET sites/default/files/styles/slideshow_full/public/plans/30989/main-image/contemporary_house_plan_westbrook_30-065_front.jpg?itok=TkUdCJQ5 403 (Forbidden)

```

When I paste the above URL in browser it is showing that ***"You are not authorised to access this page"*** error.

I checked all the permissions and all has 777. But the same functionality is working with my local site.Can anyone give me a suggestion to solve this issue?

# Answer
This is a typical result of an incorrect url path.

That folder may/may not exist on the test server, but because it's outside of your user's folders, you 'don't have permission to access' it.

For example: Typical user's folders for cPanel are `/home/USER/` with the site root at `/home/USER/public_html`. But, typical for a local machine is `/var/www/...`.

So when you call `sites/default/...` from a local machine, it is possible that it's actually looking at `/var/www/sites/default/...`. When doing that on the test server, the path would be outside your user's folder and therefor no access permission.

It could be as simple as a missing `../` on your relative paths. So you could try 1. adding `../` to the start of your paths and see if that takes it to the correct location. or 2. Try explicitly setting the base url in your settings file `$base_url = 'http://foobar.com';` to force a starting point for relative paths.
> 0 votes

---
Tags: 7, media, files
---


title: Permission to Reply to Comments

text:
# Question
Title: Permission to Reply to Comments
How to allow posting replies to comments to certain user roles only?
The goal is to allow users to post comments but not reply to them and have only certain roles able to post replies.

Initially I thought of hiding reply link for certain roles. But it is not a very bullet proof solution. Anyone knows of better methods?

# Answer
Edit your **comments.tpl.php** file and delete the `<?php print render($content['links']) ?>`

Then all you gotta do is create your own reply, edit, and delete links

* reply is `/comment/reply/[nid]/[cid]`
* edit is `/comment/[cid]/edit`
* delete is `/comment/[cid]/delete`

So use PHP to load the nid and cid and replace the \[tokens\] with your PHP code.

Then use PHP if statement to check whether login (global) user is of role x, if true, you print the reply link.

For edit and delete links, you check if login (global) user uid is the same as comment author uid.
> 1 votes

# Answer
You could look at this module. It has more control on comments permission than what Drupal core does.

Another method is to add some code using hook\_alter

```
MODULENAME_form_alter(&$form, &$form_state, $form_id) {
if ( $form_id == 'comment_form') {
  global $user;
  if(//certain role)
     unset(//comment reply form);
 }
};

```
> 0 votes

# Answer
For a more robust solution, create a RouteSubscriber to take over the `comment.reply` route and provide your own controller.

Your controller can extend CommentController from the comment module in core and either just replace the `replyFormAccess` function, or call the parent first and then build on it.
> 0 votes

---
Tags: 7, users, comments
---


# Question
Title: Get node fields in Rules action programatically
How to get node field values and include it the Rules Action? If I have a custom content type that has taxonomy terms, and I want to display these terms in Action. Example output is simply logging the terms.

* Event: content type is created
* Condition: of node type: custom\_content
* Action: Log the taxonomy terms

Pseudo code:

```
 public function execute() {
    $term1 = field_taxonomy1_fromCustomContentType
    $term2 = field_taxonomy2_fromCustomContentType
    $this->setProvidedValue('concatenated', $term1 . $term2);
    \Drupal::logger('custom_rules')->notice("Rules Action");
  }

```

# Answer
> 0 votes
Just in case someone had the same approach as mine. Here is the solution from Drupal.org community.

---
Tags: 8, rules
---


# Question
Title: D8 - Using Composer to download git repo
I want to download my libraries (/libraries) via composer.

Content of my composer.json:

```
 "repositories": [
    {
        "type": "composer",
        "url": "https://packages.drupal.org/8"
    },
    {
        "type": "github",
        "url": "https://github.com/w8tcha/CKEditor-CodeMirror-Plugin.git"
    }
]

```

I call `composer require "w8tcha/CKEditor-CodeMirror-Plugin":"*"`

which tells me

```
Error -  The requested package w8tcha/ckeditor-codemirror-plugin could not be found in any version, there may be a typo in the package name.

```

What I am doing wrong?

Thanks

# Answer
As per @igorw's answer

```
{
        "repositories": [
            {
                "url": "https://github.com/w8tcha/CKEditor-CodeMirror-Plugin/blob/master/composer.json",
                "type": "git"
            }
        ],
        "require": {
            "ckeditor-codemirror-plugin": "~1.17.2"
        }

}

```

Then type

> composer require "ckeditor-codemirror-plugin":"1.17.2"
> 0 votes

---
Tags: composer
---


# Question
Title: how to send variable from .php file to .js file?
I hope someone is able to help me. The problem is the following one: 1)I have module in which a assign the variable in order to send to the template file php.tpl

```
<?php
...
$testvar="Hello from alex!";
$variables['testvar'] = $testvar;
...
?>

```

This variable can be shown in the php.tpl file like

```
<?php print $testvar?>

```

2)I have separated .js file How can i get access to this varuiable inside .js file?

I know how it'll be if .js file is inside .php.tpl:

```
<?php
$testvar="Hello from alex!";
?>
<script type="text/javascript">
var myVar = '<?php print $testvar?>';
</script>

```

The problem is how to do the same if these two files .js and .php.tpl are separated?

# Answer
You should use `drupal_add_js()` in your module, there is no need to output the variable in your `.tpl.php`:

```
drupal_add_js(array('YOURMODULE' => array('testvar' => $testvar)), array('type' => 'setting'));

```

And in your JavaScript, you can the access the value in `Drupal.settings.YOURMODULE.testvar`:

```
alert(Drupal.settings.YOURMODULE.testvar);

```

Direct usage of global variables (as suggested in your code sample) is a discouraged practice in JavaScript as it clutter the global namespace. Also, if your code is triggered on page load, check the "Behaviors" section in Managing JavaScript in Drupal 7 documention (the whole page is worth reading).
> 70 votes

# Answer
In your MODULENAME.module file use the following code.

```
$testVariable = 'himanshu';
drupal_add_js(array('MODULENAME' => array('testvar' => $testVariable)), array('type' => 'setting'));
drupal_add_js(drupal_get_path('module', 'MODULENAME') . '/MODULENAME.js');

```

And in MODULENAME.js use the following one.

```
(function($) {
  Drupal.behaviors.MODULENAME = {
    attach: function (context, settings) {
      alert(settings.MODULENAME.testvar);
    }
  };

})(jQuery);

```

In this way, you can pass your PHP variable to JavaScript, and use it.
> 19 votes

# Answer
For **Drupal 8**, `drupal_add_js()` was removed (it was deprecated in Drupal 7 already) =\> see this for further information.

The way to send PHP information to Javascript is perfectly described by @4k4's answer to a similar question.

```
return [
  '#theme' => 'item_list',
  '#list_type' => 'ul',
  '#items' => $my_items,
  '#attributes' => ['class' => 'some_class'],
  '#attached' => [
    'library' => ['my_module/my_library'],
    'drupalSettings' => [
      'my_library' => [
        'some_variable1' => $value,        // <== Variables passed
        'another_variable' => $take_this,  // <==
      ],
    ],
  ],
];

```

In JavaScript, they can be used as follows:

```
(function ($, Drupal, drupalSettings) {
  Drupal.behaviors.my_library = {
    attach: function (context, settings) {

      alert(drupalSettings.my_library.some_variable); //alerts the value of PHP's $value

    }
  };
})(jQuery, Drupal, drupalSettings);

```
> 10 votes

---
Tags: 7, javascript
---


# Question
Title: How can i display tokens with html tags?
On assigning tokens(both custom and exisiting tokens) with values like

```
$replacements[$original] = "<b>Hello</b>";

```

and then using that token either in full html or any other text format(all the text formats) it displays on the screen `<b>Hello</b>` i.e actual tags are being rendered instead of **Hello** . Same is happening with other html tags i.e entire `<div> <p>` all the html tags get display. This although does not happen in Drupal 7.

Is there any configuration i am missing? How to render html values properly using tokens?

# Answer
Try this one -

```
$replacements[$original] = \Drupal\Core\Render\Markup::create("<b>Hello</b>");

```

Helpful links:

https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Render%21Markup.php/class/Markup/8.2.x

http://www.drupaldump.com/drupal-8-how-have-custom-tokens-html-them-properly-replaced
> 12 votes

# Answer
If you just need to access the token under the html tag then another way is that, you just create token as

```
  switch ($name) {
   case 'custom_token':
     $text = 'Hello World!';
     $replacements[$original] = $text;
   break;

```

After, into the body part you can access this token with html tags.

```
(i.e) <b>[custom:custom_token]</b>

```

even i used it as screen shot
> 1 votes

# Answer
After you replace, you have to use: 'htmlspecialchars\_decode' like this:

```
$body = htmlspecialchars_decode($token->replace($body, $data));

```
> 0 votes

---
Tags: 8, tokens
---


# Question
Title: composer update drupal/drupal does not work : Nothing to install or update
I’ve installed several Drupal 8 site with composer as it is strongly recommended.

I can update modules like this :

```
composer require drupal/pathauto:1.1

```

But I can't update core with

`composer update drupal/core --with-dependencies` (as seen in documentation)

or (think should be like this in my case) :

```
composer update drupal/drupal --with-dependencies

```

I try tu update from 8.4.2 to 8.5.0 in this website.

I’ve read a lot of topics on this, I’ve tried :

* remove folder /vendor
* remove composer.lock

But it didn’t work.

How can I update my classic Drupal (nothing fancy in it) with composer ? Should I gave up and update with Drush ?

Her is my composer.json

```
{
    "name": "drupal/drupal",
    "description": "Drupal is an open source content management platform powering millions of websites and applications.",
    "type": "project",
    "license": "GPL-2.0+",
    "require": {
        "composer/installers": "^1.0.24",
        "wikimedia/composer-merge-plugin": "^1.4",
        "drupal/contact_block": "^1.4",
        "drupal/twig_tweak": "^1.9",
        "drupal/contact_ajax": "^1.4@beta",
        "drupal/pathauto": "1.1",
        "drupal/easy_breadcrumb": "^1.6",
        "drupal/redirect": "1.1",
        "drupal/views_slideshow": "^4.6",
        "drupal/bootstrap": "3.11",
        "drush/drush": "dev-master"
    },
    "replace": {
        "drupal/core": "^8.4"
    },
    "minimum-stability": "dev",
    "prefer-stable": true,
    "config": {
        "preferred-install": "dist",
        "autoloader-suffix": "Drupal8"
    },
    "extra": {
        "_readme": [
            "By default Drupal loads the autoloader from ./vendor/autoload.php.",
            "To change the autoloader you can edit ./autoload.php.",
            "This file specifies the packages.drupal.org repository.",
            "You can read more about this composer repository at:",
            "https://www.drupal.org/node/2718229"
        ],
        "merge-plugin": {
            "include": [
                "core/composer.json"
            ],
            "recurse": false,
            "replace": false,
            "merge-extra": false
        },
        "installer-paths": {
            "core": ["type:drupal-core"],
            "modules/contrib/{$name}": ["type:drupal-module"],
            "profiles/contrib/{$name}": ["type:drupal-profile"],
            "themes/contrib/{$name}": ["type:drupal-theme"],
            "drush/contrib/{$name}": ["type:drupal-drush"],
            "modules/custom/{$name}": ["type:drupal-custom-module"],
            "themes/custom/{$name}": ["type:drupal-custom-theme"]
        }
    },
    "autoload": {
        "psr-4": {
            "Drupal\\Core\\Composer\\": "core/lib/Drupal/Core/Composer"
        }
    },
    "scripts": {
        "pre-autoload-dump": "Drupal\\Core\\Composer\\Composer::preAutoloadDump",
        "post-autoload-dump": [
          "Drupal\\Core\\Composer\\Composer::ensureHtaccess"
        ],
        "post-package-install": "Drupal\\Core\\Composer\\Composer::vendorTestCodeCleanup",
        "post-package-update": "Drupal\\Core\\Composer\\Composer::vendorTestCodeCleanup"
    },
    "repositories": [
        {
            "type": "composer",
            "url": "https://packages.drupal.org/8"
        }
    ]
}

```

# Answer
> 10 votes
Finally, i could update with these modifications.

**Step 1**, optional in case your `composer.json`contains this. If it is ok, apply step 2

add

```
"require": {
        ---
        "drupal/core": "~8.5"
    },

```

remove

```
"replace": {
    "drupal/core": "^8.4"
},

```

**Step 2**

delete this folder :

```
vendor

```

delete this file :

```
composer.lock

```

run

```
composer update --with-dependencies

```

# Answer
> 0 votes
In your "require" section, change the version from drupal/core:"8.4" to drupal/core:"8.5" and run `composer update`

---
Tags: 8, updating, composer
---


# Question
Title: How to loop over OG group members from comment
I'm trying to set up a Rule to send a privatemsg to all group members when someone posts a comment on the group node itself.

One approach I've tried using existing options provided by the OG module:

```
**Events**
After saving a new comment

**Conditions**
Entity is a group
  Parameter: Entity: [comment:node]

**Actions**
Get group members from group audience
  Parameter: Group content: [comment:node]
  Provides variables: List of group members (group_members)
Loop
  Parameter: List: [group_members]
  List item: Current member (member)
    **Loop actions**

```

This method fails to find any members. I'm guessing this is because the "Get group members from group audience" function expects its parameter to be a node posted *on* the group rather than the node representing the group itself.

Another method I've tried is to define a new Rules action in a custom module:

```

/**
 * Implements hook_rules_action_info
 */
function mymodule_rules_action_info()
{
    return array(
        'mymodule_get_og_members' => array(
            'label' => t( 'Get OG members from group node' ),
            'group' => t( 'Custom' ),
            'parameter' => array(
                'nid' => array(
                    'label' => t( 'Group node NID' ),
                    'type' => 'integer',
                ),
            ),
            'provides' => array(
                'group_members' => array(
                    'label' => 'List of group members',
                    'type' => 'list',
                ),
            ),
        ),
    );
}

/**
 *
 */
function mymodule_get_og_members( $nid )
{
    $node = node_load( $nid );
    $uids = og_get_group_members_properties( $node, array(), 'members__' . OG_STATE_ACTIVE, 'node' );
    $members = user_load_multiple( $uids );
    // user_load_multiple indexes by UID which might be confusing the Rules loop. Reindex!
    $members = array_values( $members );
    dpm( $members ); // This works!
    return $members;
}

```

In Rules UI I've added this custom action followed by a loop. The loop suggests the *provided* members-list variable to iterate over and everything looks fine, yet when the Rule is run I get errors like this:

Unable to get variable group\_members, it is not defined.

Unable to evaluate loop.

I've asked an overlapping question here: https://www.drupal.org/node/905632#comment-10893894

Similar posts that I've read:

How to loop over a list of Organic Group users using Rules

I can't access a provided variable in rule action

https://drupal.stackexchange.com/a/170922/58279

# Answer
I found a work-around by implementing all of the desired functions in the custom action provided by my custom module:

```

/**
 * Implements hook_rules_action_info
 */
function mymodule_rules_action_info()
{
    return array(
        'mymodule_comment_notify_og_members' => array(
            'label' => t( 'Notify OG members of comment' ),
            'group' => t( 'Custom' ),
            'parameter' => array(
                'comment' => array(
                    'label' => t( 'Comment entity' ),
                    'type'  => 'entity',
                ),
            ),
        ),
    );
}

/**
 * Notify relevant OG group members of a new group comment
 *
 * @param   object (entity metadata wrapper)    $comment
 */
function mymodule_comment_notify_og_members( $comment )
{
    //~ dpm( $comment->getPropertyInfo() );

    // Get the nodes we need from the comment entity metadata wrapper
    $node = $comment->node->value();
    $author = $comment->author->value();

    // Get all active group members
    $uids = og_get_group_members_properties( $node, array(), 'members__' . OG_STATE_ACTIVE, 'node' );
    $members = user_load_multiple( $uids );
    foreach( $members as $member )
    {
        if( $member->uid !== $author->uid )
        {
            // We're not notifying the author of his own comment

            $subject = format_username( $author ) . ' commented on ' . check_plain( $node->title );
            $body = '';
            $body .= '

Hi ' . format_username( $member ) . ',

';
            $body .= '

' . l( format_username( $author ), 'user/' . $author->uid ) . ' just commented on the ' . l( $node->title, 'node/' . $node->nid ) . ' group.

';
            $body .= '

`' . l( 'View the comment', 'node/' . $node->nid, array( 'fragment' => 'comment-' . $comment->cid->value() ) ) ;

            privatemsg_new_thread( array( $member ), $subject, $body, array( 'author' => $author ) );
        }
    }
}`

```
> 1 votes

# Answer
Would "fetch entity by property" be an option?

Type: user / property: og\_user\_node / value: comment node nid

That action gives a list to loop over.
> 0 votes

# Answer
Ben, you were a huge help to me.

"I'm guessing this is because the "Get group members from group audience" function expects its parameter to be a node posted on the group rather than the node representing the group itself."

^^^ this is exactly right. Using "Get group members from group audience" when using node A that is an organic group does not work.

When node A contains node B, use "Get group members from group audience" using node B.

Thank you!
> 0 votes

---
Tags: 7, rules, organic-groups, comments
---


# Question
Title: how to link a created icon in a body field to another field?
With the fontawesome module I can easly create in CKEditor fontawesome icons in a body field. I want to link this icon to a telephone field (field\_call\_me)

A more specific example: If I created a whatsapp icon in a bodyfield. How could I link this to a telephone field?

# My steps:

# I installed:

`$ composer require 'drupal/fontawesome:^2.0'` `$ drupal module:install fontawesome`

# I created a contenttype

`admin/structure/types` name: call me description: add whatsapp number

# I add telephone field

label: call me default value: +12345678 machine name: field\_call\_me

I tried to link it with link icon module. but it didn't work.

# Answer
You need not add (should not be, rather) icon field to content type. You can display the whatsapp icon though css, it would be a matter of adding `<i class="fab fa-whatsapp"></i>` before showing the phone number. You might want to create a `field--node--field-name--content-type.html.twig` file for controlling the display aspects for the field.
> 0 votes

---
Tags: 8, entities, navigation
---


# Question
Title: Users cannot login. The username field is highlighted red, but there are no error messages. There is no password reset link
I've inherited a Drupal site and uploaded it to a new server but retained the existing domain name. The site is working, but when I try to log in as admin (or any other user) the login page just reloads with the username field highlighted red. There are no error messages and the username is definitely correct. I have tried to re-set the password manually in the database. I have also tried to add a new user directly into the database with admin privileges. Neither works. Also, there is no forgot password link on the login page. I have tried to change the base url and cookie url in the settings.php file but that did not work. I have tried repairing the sessions table but to no avail. I'm new to Drupal so not sure what to try next.

# Answer
> 0 votes
Perhaps User 1 (if that's the admin login you're using) is blocked somehow. There could be a module, or custom code somewhere that is blocking this account's login.

I'd try looking through the list of contrib (contributed/non-core) modules for any who's name looks like it might be responsible for limiting login access.

Also, look for any custom modules and look through their code for any hints that it may be limiting logins also.

If you find a suspect then try disabling the module to see if this resolves the issue.

Another place to look for possible culprit code is in the active theme's template.php file (usually located in /sites/all/themes/THEME\_NAME/template.php)

---
Tags: users
---


title: Hide products from a view

text:
# Question
Title: Hide products from a view
I know this may be very basic but I can't seem to figure out a way to hide a product that I've got set up in Drupal Commerce. I'm new to Drupal so thanks for your patience.

I am using the Expressa theme. In the product's edit screen, I go to 'Status' and choose 'Disabled' which prevents them from being added to carts (instead of Add To Cart, it displays 'Product Not Available' in the store) but it doesn't actually remove it from Product Display in the store. I've set the stock status to 0 on these products and made sure that they are not being displayed as 'Featured' yet they still show up.

Is there a simple setting where I can keep the product in the backend, in case I want to activate it later, but hide it from the store?

I've also navigated to the content list, found the list of content, checked all the relevant products and unpublished them.

Thanks for your help!

# Answer
In Drupal Commerce, to prevent a product displaying on the front end you either.

1. Unpublish the product display node (the node referencing that product)
2. Remove the product from the product\_reference field on the relevant product display node.
> 0 votes

# Answer
Not displaying certain products seems to be a two-step process. First, unpublish the product in its Publishing options.

Then you also need to create a Filter Criteria in the products list that respects the node's published status.
> 0 votes

# Answer
If you are using **Featured** as a Boolean field you can add this in the views filter options. Go to the view add the `field featured` in **FILTER CRITERIA** like below
> 0 votes

---
Tags: 7, commerce
---


# Question
Title: Table Sorting on "Content Indexed" View type
I'm working on maintaining a site that has a view of type (Content Index). This is the only site I've worked on that has had this view type on it. I may have traced that view type down to Search API.

The issue is I have a table that I need to be able to have the fields be sortable. Right now there is one field that is sortable, but when I go into the Format/table settings, that is the only field (with the exception of the Node ID) that has a checkbox for sortable.

To check to make sure there wasn't anything wonkey going on with the fields, I created a quick view of type content (so a basic view) and recreated it, and all the fields provided were sortable, not just this one.

Is there a reason that one field would be sortable and not the rest, and if so is there something special that needs to be done in order to get the Content Indexed views to have more fields be sortable?

EDIT: "Content Indexed" view type is generated by search API, not Views Aggregator Plus. The body of the question has been updated to reflect this.

# Answer
As indicated in the edit, the "Content Indexed" view type comes from the module Search API. After digging around I was able to find the page

```
admin/config/search/search_api

```

Which houses a bunch of search indexing. For me, I was able to go into the "Content Index" and find a list of fields, with options for how they are indexed. At the top of this page there is the help text:

> The datatype of a field determines how it can be used for searching and filtering. Fields indexed with type "Fulltext" and multi-valued fields (marked with 1) cannot be used for sorting.

I noted some the fields I was trying to sort on were listed ether as full texted, or did not have an option set for indexing at all. Setting these fields to something other than "Fulltext" allowed them to become sortable in the view.
> 0 votes

# Answer
In view, you need to add the fields showing as **Indexed content:** only these are sortable.

If you are unable to find the fields in the list you need to first index them, in **Search API** configuration page.

As you have already created the **Index** in Search API modify that.

Goto `edit` and `select fields tab` and **select** the `fields` you want to index (checkbox). **Save changes**

**Reindex** them, you must reindex to get `indexed fields` updated in the view.
> 0 votes

---
Tags: 7, views
---


# Question
Title: How to call preprocess functions from my custom module
I have created a custom module that declares a custom image formatter. Now I need to call the Core image module preprocess function 'template\_preprocess\_image\_formatter'. How would I do that?

I tried to add it in the list of preprocess functions of my custom theme but it doesn't fire unless I clear the cache:

```
 /**
  * Implements hook_theme().
  */
 function foo_theme() {
    'image_formatter_foo' => [
          'variables' => ['item' => NULL, 'item_attributes' => NULL, 'image_style' => NULL],
          'file' => 'foo.field.inc',
          'preprocess functions' => [
             'template_preprocess_image',
             'template_preprocess_image_formatter_foo'
          ]
    ],
 }

```

# Answer
Looking at template\_preprocess\_image\_formatter, I would try the following code below.

Replace mymodule with the machine name of the module. This assume foo is the machine name of your image formatter.

```
mymodule_preprocess_image(&$variables) {
  /* processing logic */
}

mymodule_preprocess_image_formatter_foo(&$variables) {
  /* processing logic */
}

```

I also recommend reviewing Drupal 8's Core Image module as it has some of the files that call the hooks you need.

1. image.field.inc contains template\_preprocess\_image\_formatter
2. template\_preprocess\_image
> 0 votes

---
Tags: 8, entities
---


# Question
Title: How to create permission to allow access to an admin form?
We have created a custom permissions that we want to use to prevent unauthorized access to an admin form. Only someone with "administer admin\_form" should have access to the page. There is a menu link that was created to allow access to the page.

How can I create a controller that will check if the user has the permission and hide the menu link if the user does not have the permission? If somehow they got access to the menu link path, we would also like to display a message "you do not have access to this page" and hide the form.

We have tried the following:

mymodule.permissions.yml

```
administer admin_form:
  title: 'Administer admin form'
  description: 'Allows the ability to change settings'
  restrict access: true

```

mymodule.links.menu.yml

```
mymodule.settings:
  route_name: mymodule.settings
  title: 'My module'
  description: 'some message'
  weight: 99

```

mymodule.routing.yml

```
mymodule.settings:
  path: /admin/config/user-interface/admin-form
  defaults:
    _title: 'My module setting'
    _form: \Drupal\mymodule\form\AdminForm
  requirements:
    _permission: 'administer admin_form'

```

# Answer
> 2 votes
I think you can omit `restrict access` and remove the `_` from your permission name.

Anyway, you have a typo in your permission key. It should be `_permission` instead of `_permissions`. See: https://www.drupal.org/docs/8/api/routing-system/introductory-drupal-8-routes-and-controllers-example

Make that change and clear the cache.

---
Tags: 8, forms, users
---


# Question
Title: How to alter the $item value in taxonomy_field_is_empty without altering core taxonomy module?
How to alter the `$items` value found in `hook_field_widget_form(&$form, &$form_state, $field, $instance, $langcode, $items, $delta, $element)` and pass it to `hook_field_is_empty($item,$field)`?

In a custom module,

```
function hook_field_widget_form(&$form, &$form_state, $field, $instance, $langcode, $items, $delta, $element){
$item = $items[$delta];
}

```

In taxonomy.module,

```
/**
 * Implements hook_field_is_empty().
 */
function taxonomy_field_is_empty($item, $field) {
  print_r($item);print_r($field);die('edd');
  if (!is_array($item) || empty($item['tid']) && (string) $item['tid'] !== '0') {
    return TRUE;
  }
  return FALSE;
}

```

The $item array structure in hook\_field\_is\_empty($item,$field) is $item\[0\]\['tid'\] whereas taxonomy\_field\_is\_empty($item,$field) expects to have structure as $item\['tid'\] .

Since its $item\[0\]\['tid'\], it gives undefined 'tid' which leads to returned value to be TRUE and hence field is said to be empty ,which is not the case usually.
I tried adding a custom hook in my module for hook\_field\_is\_empty but it did not execute the hook at all ,even I tried adding -1 weight so it executes before taxonomy\_field\_is\_empty (taxonomy module has weight 0) but still it did not help
So I need to alter $items value in hook\_field\_widget\_form in a way that taxonomy\_field\_is\_empty($item,$field) gets $item value such that $item\['tid'\] is defined(which was not case due to $item\['0'\]\['tid'\] )

Is there any way I can alter $item value in hook\_field\_is\_empty ?

# Answer
Altering `taxonomy_field_is_empty`'s behavior is, by definition, altering core, so the answer is no. Hacking core shouldn't be done (unless there's a clear **what** & **why** you're doing the hacking).

With that said, you should follow back on your original problem:

> I tried adding a custom hook in my module for hook\_field\_is\_empty but it did not execute the hook at all ,even I tried adding -1 weight so it executes before taxonomy\_field\_is\_empty (taxonomy module has weight 0) but still it did not help

The problem is, for some reason, your module's `hook_field_is_empty` implementation isn't firing so you'll need to troubleshoot that problem.

Look at other module implementations of the hook to see what those are doing that your module isn't and throw debug statements into `module_invoke_all` to see if your module's hook is even recognized by core.
> 1 votes

---
Tags: 7, entities, hooks
---


# Question
Title: Update entity ref field in parent form with new node created in ctools modal
I have a node\_add form for Foo node-type with an entity reference field to Bar node-type. I'm trying to allow users to create Bar nodes inline from the Foo create form.

So far I've been able to get the ctools modal to popup, create and process the new Bar node and dpm the new Bar-type nid. but I'm stuck on how to push that to the parent Foo form and add this new Bar node into the entity reference field.

Here's what I tried using ajax\_command\_append in my callback for the ctools modal, but it doesn't append the new Bar node to the entity reference field values in the parent form:

```
function mymodule_add_bar_callback($js = FALSE) {

ctools_include('node.pages', 'node', '');
ctools_include('modal');
ctools_include('ajax');

$node_type = 'Bar';
$node = (object)array(
    'uid' => $user->uid,
    'name' => (isset($user->name) ? $user->name : ''),
    'type' => $node_type,
    'language' => LANGUAGE_NONE,
);

$form_state = array(
    'title' => t('ADD A NEW BAR'),
    'ajax' => TRUE,
);

$form_state['build_info']['args'] = array($node);
$commands = ctools_modal_form_wrapper($node_type . '_node_form', $form_state);

// if the form was submitted, reload parent Event-Add form
if (!empty($form_state['executed'])) {
    $commands = array();
    $commands[] = ctools_modal_command_dismiss();
    $commands[] = ajax_command_append('#edit-field-bar-und-0-target-id', '<input type="text" id="edit-field-bar-und-1-target-id" name="field_bar[und][1][target_id]" value="" size="100" maxlength="1024" value="' .  $form_state['node']->title . ' (' .  $form_state['node']->nid . ')" class="form-text required form-autocomplete" autocomplete="OFF" aria-autocomplete="list">');

    $output = $commands;
}

```

# Answer
> 0 votes
There are few existing modules which gives the same functionality. \- https://www.drupal.org/project/entityconnect \- https://www.drupal.org/project/references

If you want to handle it in custom way, fetch the field and set the default (target\_id) value in the form array element and use drupal\_render/drupal\_render\_children to convert the form element array into html and try to replace it in the front end.

---
Tags: 7, forms, chaos-tool-suite
---


title: Enable dialog for non-admin user

text:
# Question
Title: Enable dialog for non-admin user
I'm building some modal pages using the `use-ajax` class plus the `data-dialog-type="modal"` attribute on link tags. It worked great as an admin user, but logging in as a different role(call it `parent`) and the links go directly to the pages.

It's pretty obvious from the sources panel in web inspector that the `parent` role isn't being served the necessary javascript (`dialog.jquery-ui.js, dialog.js, dialog.position.js, etc`).

There's nothing in the permissions that looks like it would limit the javascript added to the page.

I've tried this in my custom theme and in bartik, same result.

# Answer
> 1 votes
The answer is simple enough, though a little counter-intuitive coming from a Drupal 7 install where everything but the kitchen sink is included.

All I had to do was to inlcude the library in my theme's `.libraries.yml` file;

```
dependencies:
  - core/drupal
  - core/jquery
  - core/jquery.once
  - core/drupal.dialog.ajax

```

This will be more performent than including the entire core javascript system on every page. It was a little confusing since that is the behavior for the admin user.

---
Tags: 8, ajax
---


# Question
Title: Are there alternatives for striptags filter?
When printing a text field we just want to display the value. When printed as is in a twig template (`{{ content.field_subtitle }}`) we get the following output.

Currently we are attempting not to use the `|raw` filter so we are just using `{{ content.field_subtitle|render|striptags }}`.

Are there alternatives to this approach without having to create another twig template for the field? We are having a hard time finding an alternative.

Setup:

1. Basic page content type has field field\_subtitle where type is text(plain)
2. no twig template has been created on the field, only the content type `node--page.html.twig`

Current setup in twig template

```
<div class="myclass__subtitle>
  {{ content.field_subtitle|render|striptags }}
</div>

```

Current output:

```
<div class="myclass__subtitle">
  <div class="field field--name-field-subtitle field--type-string field--label-hidden field__item">Intrinsicly harness interactive functionalities.</div>
</div>

```

Desired output:

```
<div class="myclass__subtitle">
  Intrinsicly harness interactive functionalities
</div>

```

# Answer
I am vehemently against things like `render-array|render|striptags` etc. It feels very unnatural and un-Drupal. What you should do is create a field template that has no markup.

For example, either in `field.html.twig` which would affect all fields, or in `field--field-name.html.twig` or more specific variants, you can do this:

```
{#
/**
* @file
* Theme override to remove all field markup.
*/
#}

{% spaceless %}
{% for item in items %}
  {{ item.content }}
{% endfor %}
{% endspaceless %}

```

This will always render that field with no markup.
> 5 votes

# Answer
For a single value field, I often just do this: `{{ content.field_subtitle.0 }}`. This prints just the first delta, including whatever markup the field itself includes (e.g., works fine as well on reference fields or other more complex things) but does not use the field template at all.
> 2 votes

---
Tags: 8, theming, entities
---


# Question
Title: Drupal 8: "Page cache maximum age" is not working for anonymous users
I have set a page cache maximum age for anonymous users in Drupal 8, but it seems not to have any effects. Accesing the pages as an anonymous user, changes are visible immediately, and I can't see any headers about max-age on the source code.

I have installed some cache modules as Internal Dynamic Page Cache, Internal Page Cache and Supercache, but I don't think these should interfere with the cache on the client side.

Any suggestions?

# Answer
There was discussion in the chat, but there are still some things that can be answered.

The maximum age setting actually has not much to do with the built-in caching mechanisms of Drupal, as confusing as that is. It *only* controls the Cache-Control max-age header that is sent *if* the page is considered cacheable.

If you don't see a X-Drupal-Cache: HIT/MISS header in the response then that means your page is not cacheable. There are a number of things that can cause that, check if you have a session cookie (if yes, you need to figure out what's in there and who sets it), check that no module that you are using disables the page cache. For example captcha.module does that if you display a captcha as that can't be cached (not something like the built-in image captcha at least).

If you see that header then it is working. The Page cache modules actually don't care about that setting, they cache the page *forever*. However, any relevant change on the page automatically invalidates that page and fresh content is served. See https://www.drupal.org/docs/8/api/cache-api/cache-tags for more information on how that works.
> 1 votes

---
Tags: 8, caching
---


# Question
Title: What happens with modules and themes when I rebuild the cache?
Just for learning, this document explains me in a "ballpark" way how cache rebuild works, but I want to know more about *"Updates the system with latest information about extensions (modules and themes)."*

What happens with modules and themes when I rebuild the cache?

# Answer
> 0 votes
To create a page Drupal needs to make several database queries. This can slow down websites with a lot of traffic. To make websites faster Drupal stores web pages in a cache.

Before Drupal 8, the common mantra was **drush cc all (i.e. drush clear-cache)**. Now, in Drupal 8, it's **drush cache-rebuild** OR **drush cr**.

Caching is widespread in Drupal and creates many interdependencies. Improperly or incomplete cache flushing operations can cause the site to fatal error. In order to *guarantee that old data is properly flushed and the site stays up and running*, **drush cache-rebuild both rebuilds or re-bootstraps the Drupal site in addition to clearing the cache**

In-short, Drush's **cache-rebuild** command does the following:

* Clears the APC cache
* Bootstraps Drupal
* Calls drupal\_rebuild()
* Clears the Drush cache (to maintain consistency with Drupal 7's drush cache-clear command)

If you would like to dig more into this check out https://github.com/drush-ops/drush/blob/659f67712adab143a2c921f9f23828782e414e8d/commands/core/cache.drush.inc#L263 at the end of the file, look at function drush\_cache\_rebuild().

Thanks!

---
Tags: 8, caching
---


# Question
Title: How to alter the state of a radio button in an exposed filter to "checked" based on the view URL?
I have a D7 site where I have several main topics, each containing subtopics. I've made a views block which is shown on each of the pages of the main topics where you have two filter options:

* Filter on main topic
* Filter on subtopic

The idea is that when the user enters a URL like www.mysite.com/topics/maintopic, the main topic filter radio button is set automatically to the main topic the user entered and the first sub-topic for that main topic.

So how can I do that? I tried with a contextual filter, but unless I missed something I don't see an option to preselect a radio button in an exposed filter (nor in fact to filter basing on the last part of a URL, unless it's an argument). I also tried the following code.

```
function MYMODULE_form_views_exposed_form_alter(&$form, &$form_state) {
  // ...
}

```

I didn't see any option to alter which radio button is selected.

# Answer
You will need to use 2 contextual filters as each one takes a different argument, for example www.mysite.com/filter1/filter2.

You're confusing the difference between exposed filters and contextual filters, and their behaviour. An exposed filter is form based. As you want a radio button, that's perfect. However, an exposed filter passes its values either via POST or GET; the only way to get these values through the URL is via the query string.
> 0 votes

# Answer
You can use **hook\_form\_alter** or **hook\_views\_pre\_render** and check the url with **$\_GET** or **current\_path()** ,it's the fast and easy way.

Or you can play with **Views** create entity reference Filter (entityreference\_filter) add your **CONTEXTUAL FILTERS** after that in your view add **Reference Filter** in Filter Criteria.
> -1 votes

---
Tags: views
---


title: Security advisories api

text:
# Question
Title: Security advisories api
Is there an api to use to get data from https://www.drupal.org/security? I'm looking to get for example all vulnerabilities for older versions of a module.

# Answer
> 0 votes
There are three RSS feeds:

Using PHP, you can parse one of those RSS feeds to get the data you need.

---
Tags: community-official-site
---


title: Create a Modal popup with buttons

text:
# Question
Title: Create a Modal popup with buttons
I am having issues opening a modal with buttons using `OpenModalDialogCommand`. It says in the docs of that command, that it can take as it's 3rd param any Jquery UI option (from http://api.jqueryui.com/dialog/) and it works well, for width/height/class, but anything more advanced i hit a wall. I am trying to make a button but can't figure it out.

```
$response = new AjaxResponse();
$options = [
    'width' => '800',
    'height' => '300',
    'dialogClass' => 'no-close',
    'buttons' => [
      'text' => 'Proceed',
      'click' => 'function() {alert();}'
    ]
];

$response->addCommand(new OpenModalDialogCommand('Title', 'Body', $options));
return $response;

```

This returns a modal successfully, width is ok, height is ok, class is ok, but there is not button, i tried 3/4 variations of it with no luck.

~p.s. i know i can make a simple form with one button, and return that in the modal, but there has got to be a way to make this work.

# Answer
> 1 votes
Ok figured it out.

```
$options = [
    'dialogClass' => 'my-form',
    'buttons' => [
        'button1' => [
            'text' => 'Proceed',
            'id' => 'onClickDoSomething',
        ]
    ]
];

```

And then in the `.js` file just write a function which fires when clickcing on a selector with the id `onClickDoSomething` voila, it's working.

---
Tags: 8, ajax
---


title: How to add list of children in webform

text:
# Question
Title: How to add list of children in webform
I am using webform module to create a form for enrollment. End user will need to add the list of children. Since number of children is unknown for the users, I was trying to add "add child" button to add more children. I used webform add more module but it has known issue. I added a field set component in which I have name, age, ssn fields. Now, I am stuck how to add "add child" button under the fieldset for public to add childs as many as they need. How can I add "add child" button under fieldset component or is there other way I could accomplish that using the webform module?

# Answer
> 0 votes
For D7, you will need to use a contrib module.

For D8, you can use a 'Custom composite' element.

---
Tags: webforms
---


# Question
Title: Table with Add row option for external users
I am trying to build a training website. If the external user is booking a slot for a training class for 10 people he should be able to add 10 people details like the Name, address etc., at checkout. I am thinking to provide the ability to add each attendee details to the table with an "Add row" option dynamically by the external user.

Is this possible? Do we have any modules for this? I checked with datatable module I didn't find this option. Could anyone please suggest me on this.

Example View:

Thanks in advance!!!

# Answer
> 0 votes
I got it. We can use Matrix webform component module(https://www.drupal.org/project/webform\_matrix\_component) to achieve this.

---
Tags: commerce
---


# Question
Title: how remove required field from billing information into checkout
I need to add a checkbox to make billing information same as shipping information in drupal 8. So i want remove required fields into billing address and set this information programmatically after submit the form.

But is very hard to remove required fields from billing information into checkout panes. I also hack the Drupal\address\Element\Address.php at line 202 to set the #required attribute to FALSE but when i submit the form, i have always the message "... field is required."

Why the attribute #required =\> FALSE doesn't work? Why is so hard to modify this field? Why is not there a template for this field?

thanks

# Answer
> 1 votes
You have to use hook\_form\_alter to changing form elements options. This field is required because very often payments modules need this data to prepare correct post variables.

---
Tags: 8, commerce, entities
---


# Question
Title: Loading a jQuery plugin from the Libraries 2.X module in Drupal 7?
I am using the jQuery Easing plugin (http://gsgd.co.uk/sandbox/jquery/easing/) for one of my Drupal 7 themes. I see that there is a Libraries module that loads this plugin in a way that allows other modules and themes to use it: http://drupal.org/project/jqeasing.

Is this the correct way to load the library?

After loading the library, Do I need to explicitly call drupal add js from the template.php theme file? The documentation for the Libraries module for theme development is terrible. I may contribute to it, once I get this sorted out.

# Answer
> 1 votes
Yea using a module that exposes it as a library is totally the way to go.

And you certainly don't want to use `drupal_add_js` because `drupal_add_library` \[link\] will do it the proper way.

And for your case:

```
drupal_add_library('jqeasing', 'easing');

```

# Answer
> -1 votes
inside the template.php file

```
Mytheme_preprocess_html(&$variables) { if (drupal_is_front_page()) { libraries_load("easing"); } }

```

---
Tags: 7, javascript
---


# Question
Title: How do I set up jumbotron so that I can control it through a panel?
I am using the Panels and Panels Bootstrap modules, and I would like to have a Jumbotron block in a couple of pages.

How do I set it up so that I can control it through a panel, like shown in Drupal Restaurant: Add Jumbotron Page Banner?

# Answer
So I just recently created a jumbotron functionality for a site I worked on. I used panels, bootstrap and a custom node type to achieve this and it worked pretty well.

The video from the link you provided looks like they did something similar except they have some enhancements to panels and the node creation page that may be from a custom module or another module I am not familiar with.

What you will want to do is to create a new content type called Jumbotron and add the fields you want. You could also install the Field Group module to help with getting grouped fields together.

You will need to create a new template file for that node view but I am going to assume you know how to do that to get your fields to render correctly and that you know how to use a hook\_preprocess\_node function as needed as well.

You can then create as many jumbotrons you want the normal way of creating nodes, and using panels, you can add the same jumbotron entity to as many pages as you want using the "Add Existing Node" option.

To get the EXACT functionality from your link I don't know if there is a list of contrib modules to get you that without doing anything custom.

Hope that helps,
> 0 votes

---
Tags: 7, panels, bootstrap-theme
---


# Question
Title: Edit view link redirected to preview link automatically
I have opened **edit view** option on localhost using Drupal 7. firstly, the requested page i.e **http://localhost/xxx/drupal/admin/structure/views/view/products/edit/block\_14?destination=node** open successfully, however, It automatically redirected to edit preview link i.e **http://localhost/xxx/drupal/admin/structure/views/view/products/preview/block\_14**. I have tried to find the problem but not able to do.

kindly assist me.

Thanks in advance.

# Answer
It is not a problem, it's done on purpose for convenience of being able to quickly edit the view and return to the page where you were at initially.

If you want to stay at edit page then just remove the `?destination=node` part from the URL: `http://localhost/xxx/drupal/admin/structure/views/view/products/edit/block_14`
> 0 votes

---
Tags: views
---


# Question
Title: EntityFieldQuery doesn't work correctly in hook_cron
I am programming a new module in my Drupal 7 project. in my module hook\_cron is override.

in my hook\_cron function, I want to select a node type with specific filter for a cck field.

I am using **EntityFieldQuery** in order to run a query.

my specific content type is "order\_status"

here us the first code of query.

```
$query->entityCondition('entity_type', 'node')
    ->propertyCondition('type', array('order_status'))
    ->propertyCondition('status', 1);
$result = $query->execute();
dpm($result);

```

this code works with no problem. it collects all nodes with "order\_status" content type that are published. (status is 1)

but when I want to add a new cck filter to the query it doesn't work.

I have defined some cck fileds for my "order\_status" content type.

one of them is **field\_order\_status\_cr\_confirm** type of this field is boolean (TRUE/FALSE or 1 | 0)

for adding a new filter to my above query I used this code.

```
->fieldCondition('field_order_status_cr_confirm','value',1,'=');

```

so my final query is

```
$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'node')
    ->propertyCondition('type', array('order_status'))
    ->propertyCondition('status', 1)
    ->fieldCondition('field_order_status_cr_confirm','value',1,'=');
$result = $query->execute();
dpm($result);

```

but this code doesn't work. it returns nothing. also I changed value of the **field\_order\_status\_cr\_confirm** to 1 but it still returns no data.

Do you know what my problem is ?

here is the dpm function result for one node of "order\_status" type.

Please help me.

# Answer
I have also encountered this kind of issue that running EntityFieldQuery does not work sometimes in the cron job.

It turns out that EntityFieldQuery will run access check.

Cron job is run as anonymous user role and it cannot access to order\_status node.

To work around this issue you can add tag DANGEROUS\_ACCESS\_CHECK\_OPT\_OUT to bypass node access.

Here is the example:

```
$query->entityCondition('entity_type', 'node')
    ->propertyCondition('type', array('order_status'))
    ->propertyCondition('status', 1);
    ->addTag('DANGEROUS_ACCESS_CHECK_OPT_OUT');
$result = $query->execute();

```
> 8 votes

# Answer
Another workaround is running the query as user 1:

```
$query->entityCondition('entity_type', 'node')
    ->propertyCondition('type', array('order_status'))
    ->propertyCondition('status', 1)
    ->addMetaData('account', user_load(1)); // <- Skip access checks!

$result = $query->execute();

```

See documentation at https://www.drupal.org/docs/7/creating-custom-modules/howtos/how-to-use-entityfieldquery.
> 3 votes

# Answer
I had to combine 2 changes to make my query work in hook\_cron :

1. apply entityCondition instead of propertyCondition on the type column
2. use the addMetaData() method as previously mentioned

Code

```
  $query->entityCondition('entity_type', 'node')
    ->entityCondition('bundle', 'person')
    ->propertyCondition('title', '')
    ->range(0, 20)
    ->addMetaData('account', user_load(1));

```

instead of

```
  $query->entityCondition('entity_type', 'node')
    ->propertyCondition('type', 'person')
    ->propertyCondition('title', '')
    ->range(0, 20);

```

Apparenlty our production environment acted differently then our staging environment where the addMetaData() was sufficient to solve this.
> 0 votes

---
Tags: database, cron
---


title: Feeds unlock tab

text:
# Question
Title: Feeds unlock tab
I had one of my feeds freeze up and I can't unlock it. I did some searching and found a function for adding an unlock tab form this page:

http://drupalcontrib.org/api/drupal/contributions!feeds!feeds.pages.inc/function/feeds\_unlock\_tab\_form/7

```
<?php
function feeds_unlock_tab_form($form, &$form_state, $importer_id, $node = NULL) {
  if (empty($node)) {
    $source = feeds_source($importer_id);
    $form['#redirect'] = 'import/' . $source->id;
  }
  else {
    $importer_id = feeds_get_importer_id($node->type);
    $source = feeds_source($importer_id, $node->nid);
    $form['#redirect'] = 'node/' . $source->feed_nid;
  }
  // Form cannot pass on source object.
 $form['#importer_id'] = $source->id;
 $form['#feed_nid'] = $source->feed_nid;
 $form['source_status'] = array(
   '#type' => 'fieldset',
   '#title' => t('Status'),
   '#tree' => TRUE,
   '#value' => feeds_source_status($source),
 );
 $form = confirm_form($form, t('Unlock this importer?'), $form['#redirect'], '', t('Delete'), t('Cancel'), 'confirm feeds update');
 if ($source->progressImporting() == FEEDS_BATCH_COMPLETE && $source->progressClearing() == FEEDS_BATCH_COMPLETE) {
   $form['source_locked'] = array(
     '#type' => 'markup',
     '#title' => t('Not Locked'),
     '#tree' => TRUE,
     '#markup' => t('This importer is not locked, therefore it cannot be unlocked.'),
   );
   $form['actions']['submit']['#disabled'] = TRUE;
   $form['actions']['submit']['#value'] = t('Unlock (disabled)');
 }
 else {
   $form['actions']['submit']['#value'] = t('Unlock');
 }
 return $form;
} ?>

```

File

contributions/feeds/feeds.pages.inc, line 202 Menu callbacks, form callbacks and helpers.

So I know it goes in the feeds.pages.inc but not sure how to implement this. Can someone please point me in the right direction, thanks!

# Answer
You don't implement that function, it is already implemented by the feeds module.

feeds\_menu() adds a menu item that calls that function.

It uses a custom access control function feeds\_access(), which gives access to certain feeds actions based on your website's permission settings.

So if you don't have access to unlock a feed then it is likely that you need to give your role permissions to unlock the feed or else have the "administer feeds" permission or be user 1.
> 0 votes

# Answer
The easiest way to do this is to execute the following query for the importer that's "stuck", using PHPMyAdmin for example:

```
UPDATE feeds_source SET state='b:0;', fetcher_result='b:0;';

```

That's it.
> 0 votes

# Answer
Feeds get locked because of an incomplete import. To unlock, that import needs to be either canceled or completed. If you're not seeing those options, you don't have the proper permissions.
> 0 votes

---
Tags: 7, feeds
---


title: Use Drush to update multi-site setup

text:
# Question
Title: Use Drush to update multi-site setup
I have a multi-site setup where 3 different sites share the same codebase. All of the modules are in the `all/modules` folder so they all have the exact same modules. I want to update the modules and core for the codebase with `drush` but I can't find a way to do it.

There is no `settings.php` file in `sites/default` so `drush` is throwing an error. Do I need to just create a dummy database so `drush` can connect and update the modules? Obviously I will have to run `update.php` on the sites after the updates are made.

The databases are separated, they just share modules and core.

# Answer
> 6 votes
Instead of applying the updates to each individual site by using `@sites` which never worked, I was able to achieve it by running the updates on one specific site. Here is the code that worked for me:

`drush -l example.com pm-update`

example.com being the name of my symlink. Side note: I did not have to create a drush alias for this to work.

# Answer
> 0 votes
Do you have 3 different `sites/sitename.com/` directories? If so, you'll want to `cd` into each of them one at a time and run `drush up` in each.

The first time you run it it will download the new modules and run the update hooks on that site's DB and the next two times it will see that they're already downloaded so it will just run the update hooks on the other two sites' DB's.

# Answer
> 0 votes
I have a similar set up - multiple sites using the same codebase and different DBs. I use a shell script to run the same drush command through each site. The script is below - it's customised to my server set up. The relevant bits are:

My Drupal root directory is /var/www/drupal7

Each site (in drupal7/sites) contains ".d7." in the name.

The script below (called d7\_all\_sites) can run 3 drush commands on each of my sites: clear all caches, put sites in/out of maintenance mode, and update the database. The command is given by a parameter. So, when I update modules, I do this ...

```
$ d7_all_sites mm 1 ## puts all sites into maintenance mode
$ drush up ## updates the modules
$ d7_all_sites updb ## updates each site's DB schema
$ d7_all_sites mm 0 ## takes all sites out of maintenance mode

```

I'm a scripting novice, so any suggestions to improve the script are very welcome.

```
#!/bin/bash
# test that at least one parameter if given, else return error message & exit
if [ $# -eq 0 ]
then
echo -e "\n  You must supply a valid parameter ...\n    cc to clear caches.\n    mm [0 or 1] for maintenance mode (0=online, 1=offline).\n    updb to update databases.\n"
exit 2
fi
## clear all caches command
if [ $1 = "cc" ]
then
for SITE in `ls /var/www/drupal7/sites | grep ".d7."`;
do
echo
echo Clearing caches on $SITE ...
drush --uri=$SITE --root=/var/www/drupal7 cache-clear all
done
exit 0
fi
## maintenance mode
if [ $1 = "mm" ]
then
if [ $# -ne 2 ]
then
echo -e "\n  You must supply a parameter ...\n    0 for online.\n    1 for offline.\n"
exit 2
else
if [ $2 -eq 0 ]
then
text="online ..."
else
if [ $2 -eq 1 ]
then
text="offline ..."
echo -e "\n  You must supply a parameter ...\n    0 for online.\n    1 for offline.\n"
exit 2
fi
fi
fi
for SITE in `ls /var/www/drupal7/sites | grep ".d7."`;
do
echo
echo Putting $SITE $text
drush --uri=$SITE --root=/var/www/drupal7 vset --exact --yes maintenance_mode $2
done
exit 0
fi
# update databases
if [ $1 = "updb" ]
then
for SITE in `ls /var/www/drupal7/sites | grep ".d7."`;
do
echo
echo Checking $SITE for database updates ...
drush --uri=$SITE --root=/var/www/drupal7 --yes updatedb
done
exit 0
fi
# if no commands have been run, return an error message
echo -e "\n  You must supply a valid parameter ...\n    cc to clear caches.\n    mm [0 or 1] for maintenance mode (0=online, 1=offline).\n    updb to update databases.\n"

```

# Answer
> 0 votes
Here's what I do to update a multi-site setup:

```
for d in sites/*; do pushd $d; drush up -y; popd; done

```

# Answer
> 0 votes
It's in PHP, but this is what I use from inside my sites folder.

Example usage from the command line:

```
cd /path/to/drupal/sites
php drush_updates.php

```

The file:

```
<?php
/**
 * Run db updates on all of the sites in the multisite, using Drush
 */
print "\n\n***************************************************\n";
print "This script will find all of the site dirs and run drush updb -y on them.\n\n";

$start_dir = ".";
$files = scandir($start_dir);

foreach ($files as $file) {

  if (is_dir($file) && $file != "." && $file != ".." && $file != "all") {
    print "drush updb -y on $file...\n";
    chdir($file);
    system("drush updb -y");
    chdir("..");
  }
}

print "\n\n*******************************************\n";
print "Finished!\n\n";
?>

```

---
Tags: drush, multi-sites
---


# Question
Title: Why Content Path cannot be used to sort a view?
Using *Views* with Drupal **7**, how can I use the *content path* to sort a result table?

I have node *title*, *created date* and *path* as fields for a view. The first two fields have the checkbox to make them sorting options in the display settings, but the *node path* field doesn't.

# Answer
*Node path* is not a field from DB table. It is calculated dynamically.

In views you can only sort if a sorting can be applied to the underlying SQL query.
> 0 votes

# Answer
If I understand well, you want get results with URL. So you can follow screens to do that.
> 0 votes

# Answer
It's not possible to sort on something that isn't a DB field. Instead, you have to associate it with something else that is sortable. For example, if your URL aliases map to the node's NID, you could put them both in the same column, exclude the NID from the view, and sort on that.
> 0 votes

---
Tags: 7, views
---