# Question
Title: How to check whether one's current User Points are negative with the Rules module?
My question is pretty straightforward: how can I check whether a user's current amount of User Points is negative with the Rules module? I'd like to create an action that should be activated when the user is granted User Points. The event is set, but I don't know how I can set the condition.

**Edit:** I enabled the PHP filter module in order to get the 'Execute custom PHP code' option in my Rule's conditions. (I didn't know that I had to do this before...) I used this code to check whether the user's User Points are negative:

```
global $user;
$num_pts = userpoints_get_current_points($user->uid, 'all');
$neg_pts = $num_pts < 0;

```

Unfortunately, it's always evaluated as 'false', even when the amount of User Points is negative. I've also tried this:

```
$num_pts = userpoints_get_current_points([userpoints-transaction:user]->uid, 'all');
$neg_pts = $num_pts < 0;

```

But that didn't work either (same reason). I don't get any error messages in both cases.

Are these code snippets wrong? How does the correct one look like?

# Answer
> 2 votes
Have a look at this Rules example (in Rules export format):

```
{ "rules_display_userpoints_after_updating_content" : {
    "LABEL" : "Display userpoints after updating content",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "userpoints_rules", "rules", "rules_conditional" ],
    "ON" : { "node_update" : [] },
    "DO" : [
      { "userpoints_rules_get_current_points" : {
          "USING" : { "user" : [ "site:current-user" ], "tid" : "all" },
          "PROVIDE" : { "loaded_points" : { "total_points" : "Number of points in all categories together" } }
        }
      },
      { "drupal_message" : { "message" : "You now have [total-points:value] points" } },
      { "CONDITIONAL" : [
          {
            "IF" : { "NOT data_is" : { "data" : [ "total-points" ], "op" : "\u003C", "value" : "20" } },
            "DO" : [
              { "drupal_message" : { "message" : "You have sufficient points (you still have [total-points:value] ...)." } }
            ]
          },
          { "ELSE" : [
              { "drupal_message" : { "message" : "You DO NOT have sufficient points (you only have [total-points:value] ...)." } }
            ]
          }
        ]
      }
    ]
  }
}

```

It does retrieve, as the very first Rules Action (not Rules Condition!) the current amount of user points of a user. If the amount is at least 20, it will display a message starting with "You have sufficient points ...", otherwise the message starts with "You DO NOT have sufficient points ...".

So you do not need custom PHP code (in your Rules Condition) to get this to work. And you don't need to enable the PHP filter for this ...). Any time you can avoid enabling the PHP filter you should take it (have a look at "What are the downsides of using PHP Filter code in blocks, nodes, views-args, etc?" to understand why).

In this example I'm using the Conditional Rules module, though you could also rework the Rules Action to performing Rules Components (in which you add the appropriate Rules Conditions), so that you don't need this extra module. For more details on that, refer to the answer to "What's the alternative to using the Conditional Rules module?".

The clue to make this rule work is the very first Rules Action "***Load user points of a user***". Refer to my answer to "How to access current amount of earned userpoints in a Rules Condition?" for more details on this.

# Answer
> 2 votes
```
global $user;
$num_pts = userpoints_get_current_points($user->uid, 'all');
$neg_pts = $num_pts < 0;

```

# Answer
> 0 votes
I found the correct code, based on @tigerrussell's answer:

```
global $user;
$num_pts = userpoints_get_current_points($user->uid, 'all');
if ($num_pts < 0) {return TRUE;}

```

Just use this snippet in an *Execute custom PHP code* condition. It's as simple as that! However, it is recommanded to avoid PHP code in Rules. Therefore, I would suggest to install the Conditional Rules module, as explained in Pierre's answer.

---
Tags: 7, rules, userpoints
---


# Question
Title: CSS not applied on install, but loaded properly
I have installed Drupal 8, but the default CSS is not applied (see http://ec2-54-187-215-79.us-west-2.compute.amazonaws.com/user/1 for example).

Chrome's 'inspect' functionality reveals that the CSS is loaded properly from http://ec2-54-187-215-79.us-west-2.compute.amazonaws.com/sites/default/files/css/css\_4w6DyMZOD\_Fu1oxqpACBFcOPDgVYtgOuayu9S6-8btc.css?0

What is causing this issue? How can I solve it?

# Answer
When you installed it, for Installation Profile, did you select Standard? or did you select Minimal?

It seems like you selected Minimal, which I highly do not recommend, Standard is the way to go. Delete all the tables in your DataBase and go to http://ec2-54-187-215-79.us-west-2.compute.amazonaws.com/install.php and install again.
> 1 votes

---
Tags: theming, 8
---


# Question
Title: Unable to override ctools selection plugin class from my module
I am trying to add a custom ctools selection plugin for entity reference field as explained Here but it is never bing called but it is calling the parent class (EntityReference\_SelectionHandler\_Generic). Following is my code.

1) Implements hook\_ctools\_plugin\_directory

```
function mymodule_ctools_plugin_directory($module, $plugin) {

   if ($module == 'entityreference') {
    dsm($plugin);
    return 'plugins/' . $plugin;
  }
 }

```

Than I created "plugins/selection" folder in my module directory following is the code I have in this file respectively-

1) Base.inc

```
$plugin = array(
'title' => t('Simple (with optional filter by bundle)'),
'class' => 'myClass',
'weight' => -100,
);

```

2) myClass.class.php

```
class myClass extends EntityReference_SelectionHandler_Generic{
public static function getInstance($field, $instance = NULL, $entity_type = NULL, $entity = NULL) {
watchdog('getInstance', "print something for test ");
return new ExampleSelectionHandler($field, $instance, $entity_type,  $entity);

```

} public function buildEntityFieldQuery($match = NULL, $match\_operator =CONTAINS'){ } }

But Myclass is never getting called instate it is calling the parent class(I have added a watchdog in that class).

# Answer
> 1 votes
same problem, two days wasted according to http://lookalive.co.uk/blog/drupal-entity-reference-how-make-custom-entity-reference-selection-handler and all it's copies.

entityreference\_get\_selection\_handler() code dpm() showed that "\*.inc" should be named 'base.inc' as in your case.

After renaming in my case \*class.php started to execute.

So all i can advice to you - check if module has higher weight than 'entityreference' module, see here https://www.drupal.org/node/110238

And add the first line to '\*class.php' (for inheritance)

```
require_once drupal_get_path('module', 'entityreference') . '/plugins/selection/EntityReference_SelectionHandler_Generic.class.php';

```

If this helped to you - pleace vote \[+\] this answer (i need more scores, tks)

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


# Question
Title: Views Rewrite return html string instead of rendering them
I am using Drupal 8.1.3 and in simple views I want to use rewrite feature of views, and I put `<span class="stats">{{ totalcount }}<i aria-hidden="true" class="fa fa-eye"></i></span>` in rewrite section and on out put I see

Where is the problem and why view template engine not render HTML in rewrite section?

**UPDATE** Exactly it that views I try rewrite title field and for it works correctly is seems problem is with statistics total view field !!!

# Answer
I think it could be because of the `<i>....</i>` tags part, if you take that out, does it render? Seems like views uses Filter HTML, and only popular html tags are allowed on Custom Fields or Re-Write boxes.

You should be able to achieve your goal by creating a template file.

**views-view-fields--\[view-name\]--\[machine-name\].html.twig**

```
<span class="stats">{{ fields.totalcount.content }}<i aria-hidden="true" class="fa fa-eye"></i></span>

```
> 1 votes

---
Tags: views, theming, 8
---


# Question
Title: How do I add content type in taxonomy settings?
In Drupal 6, taxonomy can be added content type.

How do I add content type in taxonomy settings in Drupal 8?

Below is Drupal 6:

Below is Drupal 8:

# Answer
> 3 votes
Drupal 7 and 8 Core does not have that. I've never used Drupal 6, based on your question, it seems like they changed how tax terms are added to content types in D7.

For Drupal 8, all you have to do is go to Content Type (ex: Article) \>\> Manage Fields \>\> Add Field \>\> Select: **Taxonomy Term** \>\> Save Field Settings \>\> Checkmark your vocabulary \>\> Save settings.

---
Tags: 8, taxonomy-terms
---


title: Automatic Search with Search API

text:
# Question
Title: Automatic Search with Search API
I created a view block based search API module.

I want displayed in this block similar products to the product currently being viewed.

When I get the word "mint" in the value of fixed contexuel filter "full text search", I have products containing "mint" that appear in the right column.

I want the text title field and body field are sought instead of "mint".

I parameterize filters API search index, not to seek unnecessary words.

How to do this ? How to set the pop filter?

Thank you

# Answer
You are viewing a Product Display Page. Therefore your context is the nid of the Product Display you are looking at. You now need to load the title and body field and pass that as a string to your view's contextual filter.

You can do this in various ways:

1. Use hook\_views\_pre\_view in a custom module

> Allows altering a view at the very beginning of views processing, before anything is done.
>
> Adding output to the view can be accomplished by placing text on $view-\>attachment\_before and $view-\>attachment\_after.
>
> **Parameters**
>
> **$view:** The view object about to be processed.
>
> **$display\_id:** The machine name of the active display.
>
> **$args:** An array of arguments passed into the view.

* You implement this hook in a custom module
* check the $view argument for your view's name and display id
* load the Product Display using menu\_get\_object which will return the $node.
* Inspect $node to get the title and body, which you then concatenate and you then
* set this as the argument on **$args** which is one of the parameters passed by reference to hook\_views\_pre\_view

.

2. Use Views Field View

> There are a lot of cases in views where you want to embed a list inside each row. One example could be, you have a list of groups, and for each groups you want to list the first and last name of all of their members.
>
> This can be achieved with this module, as views\_field\_view allows you to **embed one view into another view and pass arguments along**.

For this method you create a parent view block of Product Display (nodes) and for the contextual filter take the node id from the url. This is the view that will display your related products. After you have constructed it test it so that it shows the exact same product as the product page you are embedding it on.

So now you have a block that shows the same Product Display as the main page shows. Now you need to link it to the search api view.

First change the fields. Make sure that you have title field and body field added to your parent view, then set them to be hidden. Add a global text field and using the tokens from the above two fields add them with a space between them as in : \[title\] \[body\] so that the title and body is now one field. Again set this field to be hidden.

Because you installed **Views Field View** you can now add another field **Global:View field**. This field allows you to select a view to embed. You now select your search api view. It also allows you to pass parameters to the view, so you select the token for the global text field that is hidden.

Lastly set caching to some time value for this view so that it performs quickly.

**ADDED**

For option 1 (custom module) the code will go roughly like this (I currently don't have Drupal installed so I can only provide pointers. You will have to inspect the $node object via dpm() to get to the body field, which may be on the Product Display node or on the referenced Product type)

```
function MYMODULE_views_pre_view(&$view, &$display_id, &$args) {
  if ($view->name == "VIEWMACHINENAME" && $display_id == "VIEWDISPLAYID") {
    $node = menu_get_object(); // defaults are fine
    dpm($node); // comment out when code works
    if (isset($node->content...)) {  // inspect output from dpm to get field
      $argument = strip_tags($node->content...); // same field from if statement
      $args = array($argument);
    }
  }
}

```
> 0 votes

---
Tags: views, commerce, search
---


# Question
Title: How can I make the taxonomy terms appear in a drop down list?
How to make the taxonomy term in drop down list?

Vocabul

Drupal 6 taxonomy term in drop down list while creating new article.

Drupal 8 taxonomy term can't show drop down list while creating new article.

# Answer
Thanks to @Bhuvana

I had just changed the setting, it's work.

***Home \> Administration \> Structure \> Content types \> Technology***
> 14 votes

---
Tags: 8, taxonomy-terms
---


title: IMCE module: list only image files

text:
# Question
Title: IMCE module: list only image files
I have a Drupal 7 with the IMCE module installed. It works good but it shows me every files in my media directory. I need to limit the listing to only image files, for example to only jpg, png and svg file.

Anybody know a way to do it? Thanks a lot.

# Answer
You can restrict by placing file extensions which you want to display in the permitted file extensions field. It will appear in the configuration of IMCE profiles. See below image for your reference.
> 0 votes

---
Tags: files
---


# Question
Title: How do I get Views PDF to Download a file?
I am using views-pdf to create a 'ticket' for people. Buy a ticket and they need to keep the ticket on their phone. I am using views-pdf to generate the ticket and would like to automatically trigger the download.

At the moment I have the following, which is not working:

```
function yhivepasses_views_pre_render(&$view) {
 if ($view->name != YOGAHIVE_PASSES_VIEW_NAME || $view->current_display != YOGAHIVE_PASSES_VIEW_DISPLAY) {
 return;
  }

//'Content-Disposition' => $disposition . '; filename="' . mime_header_encode($name) . '"',
  drupal_add_http_header('Content-Disposition', 'attachment; filename="yogahivepasses.pdf"');
}

```

# Answer
> 0 votes
The headers are returned from TCPDF. The argument 'D' for download needs to be passed from views to TCPDF.

To do this I created a menu entry.

```
function yhivepasses_menu() {
  $items['yhivepasses/download/yogahive_passes_user_balance/pdf_1/user/%'] = array(
      'title' => 'YogaHive Passes',
      'page callback' => '_yhivepasses_views_pdf_download',
      'page arguments' => array(2,5,5),
      'access arguments' => array('access checkout'),
  );

```

Called the view manually.

```
function _yhivepasses_views_pdf_download($view_id, $views_display, $arguments) {
  if (!empty($view_id)) {
    $view = views_get_view($view_id);
    if (!is_object($view)) {
       drupal_set_message("Sorry, couldn't load your YogaHive Passes.", 'error');
       return FALSE;
     }

    $view->set_arguments(preg_split("/\r\n|\n|\r/", $arguments));

  if (!$view->set_display($views_display)) {
    $views_display = 'pdf_1';
    if (!$view->set_display('pdf_1')) {
      return FALSE;
    }
  }

  $view->pre_execute();

  $display = $view->display[$views_display];
  if ($display->display_plugin == 'pdf' && isset($display->handler)) {
    // arguments '' and I
    // Setup rules to take you to the 'completed' page and then do a redirect.
    //header('refresh:0;url=' . $base_url . '/user/14');
     $display->handler->execute('', 'D');
     $display->handler->post_execute();
    }
  }
}

```

The way that views-pdf calls views, I don't see a way to set the argument 'D'. There are no hooks, just a conditional call.

---
Tags: views
---


# Question
Title: Do I need to download migrate upgrade module if use drush command?
Migration Drupal 6 to Drupal 8.

My Drupal 8 site is located at /domains/example.com/public\_html/drupal8site

**Step 1**: Install Drush

**Step 2**: Browse my drupal site `cd /domains/example.com/public_html/drupal8site`

**Step 3**: Use drush command `drush migrate-upgrade --legacy-db-url=mysql://user:pass@12.34.56.78/d6db --legacy-root=http://example.com`

If I using Drush migrate command above, do I still need to download the Migrate Upgrade module? If yes, where should the module file located?

# Answer
> 0 votes
To make it clearer: The migration system is part of Drupal core.
The Migration Upgrade module, whose 4.0.x branch is declared compatible with Drupal 9 and Drupal 10, only provides the front-end to the upgrade process from Drupal 6 or Drupal 7 to Drupal 8, Drupal 9, or Drupal 10. It also provides two Drush commands, described in the README.txt file.

* migrate-upgrade - performs a complete import of the source site's configuration and content into the target Drupal 8 site. Optionally, with the --configure-only flag, it may create migration configurations for such an import without actually running them, to permit customization of the import process.
* migrate-upgrade-rollback - removes content and certain configuration previously imported either by the migrate-upgrade command or by the core upgrade UI.

To answer to *Do I still need to download the Migrate Upgrade module?* I would check the usage statistics page for the module, which makes evident that the mostly used release is the 8.x-3.2, which runs in either Drupal 8 or Drupal 9, and it's installed in 5.000 sites. The 4.0.0 release (compatible with Drupal 9 and Drupal 10) is used from 716 sites. (Those data are updated to July 3, 2022.)
Those statistics make clear the module is still used; I take them as meaning that the module can still be used. Using it is up to you, but it seems there is still a need for it, at least in some cases.

The module is a normal Drupal module, you install it as any other module, and place its files as you would do with other modules.

As side note, for more Drush upgrade commands, there is the Migrate tools module, which implements the following commands.

* migrate:status - Lists migrations and their status
* migrate:import - Performs import operations
* migrate:rollback - Performs rollback operations
* migrate:stop - Cleanly stops a running operation
* migrate:reset-status - Sets a migration status to idle if it's gotten stuck
* migrate:messages - Lists any messages associated with a migration import
* migrate:fields-source - List the fields available for mapping in a source

---
Tags: drush, upgrading
---


# Question
Title: How to create a distribution list for sending eMail?
In my project I want to create distribution list. eg: while sending mail if I select drupal, then all drupal user should get mail. This means according to user group, mail will get created and if I selected any of the user group, then all mail id of that particular group will get selected and mail will send.

Any suggestions?

# Answer
You can use the Rules module for this, simply by using Rules Action "`Send mail to all users of a role`". So all you'd have to do is to create a role that corresponds to your "user group", and grant access to the role you created for it.

However, if your user group consists of many, many users, then you might want to use a more granular approach as details in my answer to "How to delay sending emails using Rules to avoid being considered as a spammer?".
> 2 votes

---
Tags: emails
---


title: Modules appear as themes in themes page

text:
# Question
Title: Modules appear as themes in themes page
Not serious but interesting. I entered into the themes page and besides themes I also found there modules.

Any suggestion what can cause this behavior?

# Answer
> 1 votes
All modules listed there are dependencies of the Dawn theme, and when we look at the Changelog there are entries like: `- Added jQuery Update, Honeypot modules`.

There is no way for a theme to define module dependencies (you'd need an installation profile for that), so my best guess would be the theme creators packaged the modules within the theme. Normally I would have checked that for you, but it is a little harder with commercial themes. You should browse through your Dawn theme folders and see if the modules are nested in a sub-folder somehow. (Perhaps there is even a README explaining you should move them?)

The reason they are listed as themes is because modules and themes both provide a \*.info file containing the details, and only the folder they are in is used to distinguish between module or theme. Since the module / theme detection in Drupal can scan multiple folders deep (eg. Views UI module is a subfolder of the Views module), it probably detects these modules's .info files and assumes they are themes since they are in the `sites/all/themes` folder.

# Answer
> 0 votes
Please check whether you have placed your modules in theme folder (sites/all/themes). I think it will be the issue.

# Answer
> 0 votes
My suggestion would be "recreate". So:

1. set up a brand new Drupal 7 installation (ie D7\_bis) aside your main installation.
2. check the themes page (F5)
3. Copy one contributed/custom module to D7\_bis installation

Loop steps 2 and 3, till you recreate the bug.

Once bug is recreated, you know which module is breaking your main Drupal installation. In case you cannot recreate the bug, you should investigate somewhere else (maybe a broken drupal core?)

# Answer
> 0 votes
I faced same problem, but the reason of this bug was in node.js.

The reason is in \*.info files, which drupal looks in all folders, no matter if he found it earlier. I used gulp gulp-sass and gulp-sourcemaps in my theme, some of them now contain a little \*.info file with author info, like README file. So, Dupal didn't understand that and there is problem. There is one more problem, site can crash on some page cause of this.

The easiest way to fix it, going to theme folder where you use node.js packages and execute command:

```
find node_modules/ -name '*.info' -type f -delete

```

If you always use node.js packages in theme, better to add this command into package.json file at the end

```
"scripts": {
  "postinstall": "find node_modules/ -name '*.info' -type f -delete"
}

```

After `npm install` command this will be executed automaticaly. You can see real example here.

---
Tags: 7
---


# Question
Title: Block not showing up in Custom Blocks for Panel
I've made a simple text block and now want to display this on a panel. However, the block does not appear on the list of available blocks on the Custom Block page. I've tried clearing the cache, and making different blocks, but it appears that all new blocks aren't showing up in that menu.

I'm not sure what I'm missing. I found this disucssion, Block doesn't show up in blocks listing. But I don't really understand what their solution was (manually edit db entry?).

# Answer
I made a custom block from code and it is listed in "miscellaneous" section insted of "custom blocks". Maybe your modules are there.
> 2 votes

# Answer
When my custom block wasn’t showing, it was because there were unsaved changes to the Panel and it was locked.

After clicking "cancel" to remove the changes and unlock the Panel, the custom block then appears within the "Miscellaneous" section.
> 2 votes

# Answer
This article should point you to right direction, specifically the `hook_block_info` that is implemented at the beginning of the article.

On panel menu, the created block should fall into "Miscellaneous" tab.
> 0 votes

---
Tags: blocks, panels
---


# Question
Title: Entityqueue - Handler drop down is empty after installation
I have just installed the Entityqueue module on my drupal 7x site. However, when I go to the `/admin/structure/entityqueue/add` page, the Handler dopwn down is empty and therefore the form will not validate so I cannot create a new list.

I've checked the `\modules\entityqueue\plugins\entityqueue\handler` folder and the simple handler is present along with it's class file.

Help!

# Answer
> 0 votes
I uninstalled the module but it was still appearing in the Modules list and I could not re-install it for this reason. However when I re-enabled it and saved, the Simple Handler appeared in the drop down. Good grief.

---
Tags: 7, entities
---


# Question
Title: Why does my selection gets only the last row?
I rewrote for Drupal 8 a Drupal 6 query on 3 custom entities (see here):

```
$database = \Drupal::database();
$query = $database->select('amap_distributions_dates', 'amdd');
$query->leftJoin('amap_distributions_inscriptions', 'amdi', 'amdi.datedistributionid = amdd.id');
$query->leftJoin('association_personne', 'ap', 'ap.id = amdi.amapienid');
$query->fields('amdd', ['id', 'datedistribution', 'nombreproduits'])
    ->fields('amdi', ['id', 'datedistributionid', 'amapienid', 'role'])
    ->fields('ap', ['id', 'nom', 'prenom'])
    ->condition('nombreproduits', 0, '>')
    ->orderBy('datedistribution', 'ASC')
    ->orderBy('role', 'ASC')
    ->orderBy('nom', 'ASC')
    ->orderBy('prenom', 'ASC');
$results = $query->execute()->fetchAllAssoc('id');
foreach ($results as $row) { some code here }

```

Unfortunately, I can retrieve only the last of each {datedistribution-role-nom}.
For each 'datedistribution', if I have more than one 'role' or 'name', I can get only the last one considering the sort order I put in place.
Strange, no?
Any idea why?

# Answer
> 0 votes
Don't use fetchAllAssoc(). Just $result = $query-\>execute() and then loop over that

---
Tags: 8, database
---


title: Forwarding request to a content page

text:
# Question
Title: Forwarding request to a content page
How can I forward a request from module to a content page?

I have got a module that authenticates users; once authenticated, the module should forward the request to a content page or node (not redirecting).

`public HttpKernel::forward($controller, array $attributes = array(), array $query = array())` allows to forward the request to a controller.

How do I forward the request to, for example, http://localhost:8080/techlab/evaluations, where *evaluations* is a created article?

# Answer
You return a RedirectResponse() with the path. If you're in a controller, you can use the `redirect()` method from ControllerBase.
> 0 votes

# Answer
I developed a class method to perform the forwarding.

```
class HttpUtil {

    /**
     * Use in controller method:
     *  // ....
     *  return HttpUtil::forward('/alias');
     *
     * @param $path
     * @param string $method
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public static function forward($path, $method='GET') {
      $lang = \Drupal::languageManager()->getCurrentLanguage()->getId();

      /** @var \Drupal\Core\Path\AliasStorage $aliasStorage */
      $aliasStorage = \Drupal::service('path.alias_storage');
      $internalUri = $aliasStorage->lookupPathSource($path, $lang);

      /** @var \Symfony\Component\HttpFoundation\Request $request */
      $request = \Drupal::request();

      $subRequest = \Drupal::request()->create(
        $internalUri,
        $method,
        $request->query->all(),
        $request->cookies->all(),
        $request->files->all(),
        $request->server->all()
      );

      /** @var \Symfony\Component\HttpKernel\HttpKernel $kernel */
      $httpKernel = \Drupal::service('http_kernel.basic');

      /** @var \Symfony\Component\HttpFoundation\Response $subResponse */
      $subResponse = $httpKernel->handle($subRequest, HttpKernelInterface::SUB_REQUEST);

      return $subResponse;
    }

    // ...
}

```
> 0 votes

---
Tags: 8, page-controller
---


# Question
Title: Why do I get a syntax error on this query?
I need some help with this query:

```
$result = db_query("SELECT
  UNIX_TIMESTAMP(FROM_UNIXTIME(s.timestamp, '%Y%m%d')) AS date,
  s.nid, COUNT(*) AS all_count,
  COUNT(DISTINCT s.ip_address) AS unique_count
FROM {simpleads_impressions} s
WHERE FROM_UNIXTIME(s.timestamp, '%Y-%m-%d') BETWEEN CURDATE() - INTERVAL 1 DAY AND CURDATE() - INTERVAL 1 SECOND
GROUP BY date, s.nid");

```

The main issue is the `WHERE` clause, and the count/group issue.

```
$query = \Drupal::database()
    ->select('simpleads_impressions', 's')
    ->fields('s', array('nid'));
$query->addExpression("UNIX_TIMESTAMP(FROM_UNIXTIME(timestamp, '%Y%m%d'))", 'date');
$query->addExpression('COUNT(*)', 'all_count');
$query->addExpression('COUNT(DISTINCT ip_address', 'unique_count');
$query->where("FROM_UNIXTIME(timestamp, '%Y-%m-%d') BETWEEN CURDATE() - INTERVAL 1 DAY AND CURDATE() - INTERVAL 1 SECOND");
$query->groupBy('date');
$query->groupBy('nid');
$result = $query->execute()->fetchObject();

```

This is the error message I get:

> Drupal\Core\Database\DatabaseExceptionWrapper: SQLSTATE\[42000\]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'AS unique\_count FROM simpleads\_impressions s WHERE (FROM\_UNIXTIME(timestamp, '' at line 1: SELECT s.nid AS nid, FROM\_UNIXTIME(timestamp, '%Y-%m-%d') AS utime, DATE\_SUB(CURDATE(), INTERVAL 1 DAY) AS startdate, DATE\_SUB(CURDATE(), INTERVAL 1 SECOND) AS enddate, UNIX\_TIMESTAMP(FROM\_UNIXTIME(timestamp, '%Y%m%d')) AS testdate, COUNT(\*) AS all\_count, COUNT(DISTINCT ip\_address AS unique\_count FROM {simpleads\_impressions} s WHERE (FROM\_UNIXTIME(timestamp, '%Y-%m-%d') BETWEEN CURDATE() - INTERVAL 1 DAY AND CURDATE() - INTERVAL 1 SECOND) GROUP BY date, nid; Array ( ) in simpleads\_cron() (line 23 of D:\www\nla-refactor\modules\custom\simpleads\simpleads.module).

What code should I use to fix the error?

# Answer
> 1 votes
I changed the code to the following one, and I don't get the error anymore.

```
$query = \Drupal::database()
    ->select('simpleads_impressions', 's')
    ->fields('s', array('nid'));
$query->addExpression("FROM_UNIXTIME(timestamp, '%Y-%m-%d')", 'utime');
$query->addExpression("UNIX_TIMESTAMP(FROM_UNIXTIME(timestamp, '%Y%m%d'))", 'date');
$query->addExpression('COUNT(*)', 'all_count');
$query->addExpression('COUNT(DISTINCT ip_address)', 'unique_count');
$query->where("FROM_UNIXTIME(timestamp, '%Y-%m-%d') BETWEEN CURDATE() - INTERVAL 1 DAY AND CURDATE() - INTERVAL 1 SECOND");
$query->groupBy('date');
$query->groupBy('nid');
$query->groupBy('timestamp');
$result = $query->execute()->fetchObject();

```

---
Tags: database
---


# Question
Title: HTML E-Mails are being sent out as plaintext
I am using the Swift mailer module to send HTML emails. My actual body in `hook_mail_alter()` is the following.

```
    <p><em><strong>New Enquiry Appear </strong></em></p>

<table border="1" cellpadding="1" cellspacing="1" height="77" width="467">
    <tbody>
        <tr>
            <td style="width: 228px;">お名前</td>
            <td style="width: 258px;">@name</td>
        </tr>
        <tr>
            <td style="width: 228px;"> メールアドレス</td>
            <td style="width: 258px;">@email</td>
        </tr>
        <tr>
            <td style="width: 228px;"> 電話番号</td>
            <td style="width: 258px;">@mobile</td>
        </tr>
        <tr>
            <td style="width: 228px;">題名</td>
            <td style="width: 258px;">@title</td>
        </tr>
        <tr>
            <td style="width: 228px;">メッセージ本文</td>
            <td style="width: 258px;">@message</td>
        </tr>
    </tbody>
</table>

<p> </p>

```

The actual output is something like the following.

```
    /*New Enquiry Appear */

お名前
                        amol

                         メールアドレス
                        testl@gmail.com

                         電話番号
                        99888776655

                        題名
                        challawar
               Html tag are not converted in Bold and Italic.

                        メッセージ本文
                        sssssssssssssssss

```

I want my output to be well formatted as per my HTML markup. (Few HTML tags like `<br />`, `<strong>`, and `<table>` are not working in the above example.)

# Answer
> 0 votes
Did you check the message setting of swiftmailer module? You can change the message format to HTML.

# Answer
> 0 votes
Please check the link module configuration link. It has option of sending email either as Plain Text or HTML. Please re-verify that settings.

# Answer
> 0 votes
In .module file use the following code

```
use Drupal\Core\Render\Markup;

function hook_mail_alter(&$message) {

$message['body'][1] = Markup::create($message['body'][1]);

}

```

---
Tags: 8, emails
---


# Question
Title: Public URLs have web/ prefix while admins do not, how to remove 'web' prefix?
I've setup Drupal 8 using https://www.lullabot.com/articles/goodbye-drush-make-hello-composer, but when I visit the site, all the links begin with web/ which means they break. If I remove web/ then they work. If I login, the links don't have web.

How would I remove web/? Where SHould I look in the source tree for a config file or otherwise to adjust this?

# Answer
This appears to be fixed; the following steps for creating a drupal 8 site don't appear to have the issue: https://www.drupal.org/node/2471553.

(Original issue posted on https://www.drupal.org/node/2673164.)
> 0 votes

---
Tags: 8, uri
---


title: Making a custom form element AJAX aware

text:
# Question
Title: Making a custom form element AJAX aware
How should I go about making my custom Drupal 7 Form element support AJAX events, just like other standard FAPI elements?

For example, with a drop-down list, I would do this:

```
$element['book'] = array(
  '#type' => 'select',
  '#title' => t('Book'),
  '#options' => $books,
  '#default_value' => $default_book,
  '#ajax' => array(
    'wrapper' => 'replace-me',
    'callback' => 'replacement-callback',
    'method' => 'replace',
  ),
);

```

But now that '#type' is my own custom element, the '#ajax' property is ignored. This is what I have implemented thus far:

```
function mymodule_element_info() {
  return array(
    'customelement' => array(
      '#input'          => TRUE,
      '#process'        => array('customelement_process'),
      '#theme'          => array('customelement'),
      '#theme_wrappers' => array('form_element'),
      '#tree'           => TRUE,
    ),
  );
}

function mymodule_theme($existing, $type, $theme, $path) {
  return array(
    'customelement' => array(
      'render element' => 'element',
    ),
  );
}

function theme_customelement($variables) {
  // render some elements
  return $output;
}

function form_type_customelement_value($element, $input = FALSE, &$form_state) {
  // manipulate form values
  return $input
}

function customelement_process($element, &$form_state, $complete_form) {

  // build the compound form array
  $element['#tree'] = TRUE;

  $element['book'] = array(
    '#type' => 'select',
    '#title' => t('Book'),
    '#options' => $books,
    '#required' => true,
  );

  $element['chapter'] = array(
    '#type' => 'textfield',
    '#title' => t('Chapter'),
    '#size' => 3,
    '#maxlength' => 3,
    '#required' => true,
  );

  return $element;

}

```

Using my custom element in a form goes like this:

```
function mymodule_menu() {
  $items = array();

  $items['path/to/page'] = array(
    'title'            => 'Test form',
    'type'             => MENU_LOCAL_TASK,
    'weight'           => 30,
    'page callback'    => 'drupal_get_form',
    'page arguments'   => array('mymodule_callback_testform'),
    'access callback'  => 'user_access',
    'access arguments' => array('mymodule_admin'),
  );

  return $items;
}

function mymodule_callback_testform() {
  $form = array();

  $form['test_element'] = array(
    '#type' => 'customelement',
    '#title' => 'Custom element test',
    '#required' => TRUE,
    '#ajax' => array(
      ... // this has no effect :(
    ),
  );

  return $form;
}

```

But unfortunately it doesn't "magically" support AJAX. I would like to trigger a Drupal AJAX event when any sub-element of my custom element has triggered certain events.

# Answer
The custom element in the example is not a direct form element and act more as a wrapper (like a fieldset or item element) to create a compound form field. It's the same thing as putting an `#ajax` key on a fieldset, which does not make any sense for the form api. So, assuming that the trigger would be the select list, the only thing you need to do for it to work is to transfer the `#ajax` definition to the inside book element in the process function like this :

```
function customelement_process($element, &$form_state, $complete_form) {

  // build the compound form array
  $element['#tree'] = TRUE;

  $element['book'] = array(
    '#type' => 'select',
    '#title' => t('Book'),
    '#options' => array(1 => 1, 2 => 2),
    '#required' => true,
  );

  //If ajax exists, put the definition on the list element
  if(isset($element['#ajax'])) {
    $element['book']['#ajax'] = $element['#ajax'];
    unset($element['#ajax']);
  }

  $element['chapter'] = array(
    '#type' => 'textfield',
    '#title' => t('Chapter'),
    '#size' => 3,
    '#maxlength' => 3,
    '#required' => true,
  );

  return $element;
}

```

And then it will behave as expected. For an element that is not a compound element but totally custom, you have to set the `event` key of the `#ajax` definition inside the process function of your element. You will also have to add the `ajax_process_form` function. Here is an example :

```
function mymodule_element_info() {
  $elements = array();

  $elements['customelement'] = array(
    '#input' => 1,
    //Note the added ajax_process_form
    '#process' => ('customelement_process', 'ajax_process_form'),
    ....
  );

  return $elements;
}

function customelement_process($element) {
  // ... do whatever is needed to build the element

  if(isset($element['#ajax'])) {
    //Set the event to whatever is appropriate for the element
    $element['#ajax']['event'] = 'click';
  }
}

```

It's important to set the `event` key before the `ajax_process_form` because the latter function tries to figure out which event is best suited for the element and if it does not recognize the element it will return it without including the javascript libraries needed to perform the ajax call.
> 1 votes

# Answer
It has no effect because Drupal doesn't know what event to fire on.

If you look at the switch statement in `ajax_pre_render_element()` you can see that it has default events for all core element types. But it it doesn't know about your element type, and no event is provided, so it doesn't know how to continue. It returns the element as-is rather than attempt to make a decision its not qualified to make.

To fix you should just be able to pick an appropriate event for the code to fire on, e.g.

```
$form['test_element'] = array(
  '#type' => 'customelement',
  '#title' => 'Custom element test',
  '#required' => TRUE,
  '#ajax' => array(
    'event' => 'click',
    ...
  ),
);

```
> 1 votes

# Answer
It seemed to work for me to add `'ajax_process_form'` to the #process tag of the element definition. Like this.

```
function mymodule_element_info() {
   return array(
      'customelement' => array(
      '#input'          => TRUE,
      '#process'        => array('customelement_process', 'ajax_process_form'),
      '#theme'          => array('customelement'),
      '#theme_wrappers' => array('form_element'),
      '#tree'           => TRUE,
    ),
  );
}

```
> 0 votes

---
Tags: forms, ajax
---


# Question
Title: how do I determine the field type within a field formatter?
I have a field formatter that I would like to use on either a string or file field type. I have everything working as two separate field formatters, but with so much shared code, I'd like to make it just one. I've been digging in the API and the core sources, but nothing is jumping out at me.

```
/**
 * Plugin implementation of the 'jmol' formatter.
 *
 * @FieldFormatter(
 *   id = "jmol",
 *   label = @Translation("Create a Jmol object"),
 *   field_types = {
 *     "string",
 *     "file"
 *   }
 * )
 */
class SmilesFormatter extends FormatterBase {
public function viewElements(FieldItemListInterface $items, $langcode) {
  foreach ($items as $delta => $item) {
    // Can't figure this next line out
    $type = ($item->type);  // I assume it's something easy
    if ($type == 'string') {
      STUFF
    }
    else if ($type == 'file'){
      STUFF
    }
    COMMON STUFF
  }
}
}

```

# Answer
> 1 votes
The type is in field definition:

```
$type = $items->getFieldDefinition()->getType();

```

# Answer
> 2 votes
Maybe it is better to keep the two formatters separated and just put the shared code into a new formatter. Your two formatters can then extend the new one and just overwride the things specific to them.

---
Tags: 8
---


# Question
Title: Field-images wont be migrated in a migrate-upgrade --- Not sure if it's a bug
I try to Migrate-upgrade a D 7.44 site to D 8.1.3 and all seem to be migrated besides API images (i.e images uploaded in image fields).

Images uploaded in CKeditor with IMCE, on the other hand, appear just fine.

I am not sure if that's a bug because AFAIK, tens if not hundreds of sites were upgraded without that a problem.

---

Details that might help you conclude if this is a bug:

1. The D7 site files folder permissions is 755.
2. The D8 site files folder permissions is 777.
3. The `node__field_image` table in the D8 DB is empty (i.e zero rows).
4. The files path I gave in the Migrate UI module is `/var/www/html/benia.biz/sites/default/files` as in the first image here.
5. The second image describes a warning I saw while migrating and it might be associated to the problem. This warning deals with duplicated image paths, though I have no clue why it would appear.

---

**Image1:**

**Image2:**

# Answer
You've included a critical piece of information here which was not included in https://www.drupal.org/node/2759309:

You specified your file path as `/var/www/html/benia.biz/sites/default/files`.

Actually it should be `/var/www/html/benia.biz/`.

The sites/default/files portion is automatically included in the file paths by the migration process.

* In the correct path note you have an extra slash (one after the benia.biz so it's `benia.biz/`); Missing this slash as well could make the migration process miss the images.
> 1 votes

---
Tags: migrations, upgrading
---


title: Captcha doesn't work for my site

text:
# Question
Title: Captcha doesn't work for my site
I'm using Drupal for my site, and I activated the CAPTCHA image for the login of the administration user. However, it doesn't work.

I don't see the CAPTCHA image, which is replaced by a placeholder.

>

Why does this happen? Do I need to fix something in the settings?

May you tell me how I can, at least, skip this verification to be able to log in, and remove the CAPTCHA for my account?

# Answer
> 0 votes
The issue was because the PHP GD Library was not installed in my machine... So I installed the GD Library using `sudo yum install php56w-gd` and the things working good actually.

Note that to access to admin page (my aim) we can deactivate the captcha module using this command : `drush dis captcha`

---
Tags: captcha
---


# Question
Title: Form ajax add more button added via another ajax callback not working
I have a form button which I want to add another field with another button on that form( I am able to do this) but second button is not clickable. Any idea. Following is my code-

This is my form code-

```
function create_report_form($form, $form_state) {
$form['title'] = array(
    '#type' => 'textfield',
    '#title' => t('Report ttitle'),
    '#value' =>'',
);

$form['actions'] = array(
  '#type' => 'actions',
);

$form['actions']['submit'] = array(
  '#type' => 'submit',
  '#value' => t('Save'),
);
$form['conditions'] = array(
  '#tree' => TRUE,
);
$form['conditions']['report_type'] = array(
  '#title' => t('Report type'),
  '#type' => 'select',
  '#prefix'=> '<div class="conditions-wrapper"></div>',
  '#multiple' => false,
  '#options' => get_report_type()
);

 $form['conditions']['submit'] = array(
   '#type' => 'button',
   '#value' => t('Add condition'),
   //'#name' =>   '_add_another_outcome',
   '#ajax' => array(
      'callback' => 'reports_add_conditions',
      'wrapper' => 'report-form',
      'method' => 'replace',
      'effect' => 'fade',
   ),
  );
   return $form;
}

```

Now, when I click on this button it will call the following function and generate another form element(select list) with another button which will call another ajax function (this is what which is not working).

```
function reports_add_conditions($form, &$form_state){
$values = $form_state['values'];
$form_state['rebuild'] = TRUE;
$type = $values['conditions']['report_type'];
$form['attributes'] = array(
  '#tree' => TRUE,
);
$form['attributes']['submit'] = array(
    '#type' => 'button',
    '#value' => t('Add attribute condition'),
    '#ajax' => array(
      'callback' => 'reports_add_attribute_conditions',
      'wrapper' => 'report-form',
      'method' => 'replace',
      'effect' => 'fade',
    ),
);
$form['attributes']['attribute'] = array(
    '#type' => 'select',
    '#title' => '',
    '#options' => get_options($type),
    '#size' => 22,
);
  return drupal_render($form);
}

```

As you can see from the code I am not able to call "reports\_add\_attribute\_conditions" function for the button.

This is my second call back code-

```
function reports_add_attribute_conditions($form, &$form_state){
$form_state['rebuild'] = TRUE;
$values = $form_state['values'];
$type = $values['conditions']['report_type'];
$form['attribute'] = array(
    '#type' => 'select',
    '#name' => $type,
    '#title' => '',
    '#options' =>  get_options($type),
    '#size' => 22,
);
$form['attributes']['submit'] = array(
    '#type' => 'button',
    '#value' => t('Add attribute condition'),
    '#ajax' => array(
      'callback' => 'reports_add_attribute_conditions',
      'wrapper' => 'report-form',
      'method' => 'replace',
      'effect' => 'fade',
    ),
);

 return drupal_render($form);
}

```

Any idea is greatly appreciable

# Answer
> 1 votes
@NabajitRoy my idea is

1. Never use `drupal_render()` manual calls (return $form array as-is)
2. Move all the form generation code into form constructor( `create_report_form()` ), AJAX callback should not create new elements for form but only `create_report_form()` should
3. AJAX callbacks should only return element form (not generate them) e.g. return `$form['attributes']['submit']` and may be `$form_state['rebuild'] = true;` if needed.
4. To know in `create_report_form()` if it was called by AJAX request button check the `$form_state['triggering_element']` in it.
5. I feel that using `'#type' => 'submit'` instead of `'#type' => 'button'` is better

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

# Answer
> 0 votes
may AJAX request is not send to server at all? Try changin the

```
$form['attributes']['submit'] = array(
'#type' => 'button',

```

to `$form['attributes']['submit'] = array(
 '#type' => 'submit',`

---
Tags: 7, forms, ajax
---


# Question
Title: Drush command to switch to a multi-site child directory?
Is there a Drush command that would `cd` into the directory of a particular multi-site instance, I mean to go to a directory like this one:

`/srv/www/drupal/sites/alpha`

where the parent Drupal resides in:

`/srv/www/drupal`

Thanks.

# Answer
`drush status` produces a **Site Path** in its output which is what you're looking for. With some additional shell commands, you can parse this out.

```
MYPATH=/srv/www/drupal
MYDOMAIN=example.com

SITE_PATH=$(drush status --root=$MYPATH --uri=$MYDOMAIN | grep 'Site path' | cut -d':' -f2 | xargs)
cd "$MYPATH/$SITE_PATH"

```
> 1 votes

---
Tags: drush
---


# Question
Title: How can I load CSS files located outside the web root from within a custom module?
I need to store my css files at a location outside Drupal's path (e.g. /srv/assets/css/my\_site/general.css). I attempt to achieve this using `drupal_add_css` but the browser loads them from:

`http://www.my-site.com/srv/assets/css/my_site/general.css` which results of course in 404 error.

Any idea how to load those *external (file system)* CSS files from within a module? note: I am using Linux.

# Answer
> 0 votes
`drupal_add_css()` expects a path relative to the site root. As such, if you're going to use `drupal_add_css()` you need to add a path within webroot to access the file.

One way to that is to use a symlink. For example

```
ln -s /srv/assets/css/my_site/general.css sites/all/modules/my_module/css/general.css

```

As long as the file is readable by your web server, you can use drupal\_add\_css to reference your symlink path.

```
drupal_add_css(drupal_get_path('module', 'custom') . '/general/custom.css', array('type' => 'file'));

```

---
Tags: 7, theming, files
---


title: Use underscores in menu machine names

text:
# Question
Title: Use underscores in menu machine names
Why cannot I use underscores in menu machine names?
For example menu\_xpto is an illegal machine name for a menu.

What is the problem with using *_* in a machine name?

# Answer
> 2 votes
Menu has an inconsistent pattern for machine names with most other parts of the system, that was simply not unified when converted to use the config system.

There is no reason, but it also can't be changed now as existing menus would then be invalid.

---
Tags: 8
---


# Question
Title: Pager will come by default in blogs template or not?
I am using blogs module in one of the website. I have created a template file for that, I want to add pager if blog items exceeds that 10. So my question is in that template file how can I use pager. It will display by default or is there any other ways to add pager to that template.

# Answer
If you are creating a custom template for the blogs created by the blog module you will have a variable called $pager available to you in that template. Wherever you want it displayed you can just add something like this:

```
 <div id="blog-pager" class="pager"><?php echo $pager ?></div>

```

If you look in blog.pages.inc you'll see that the "pager" is added to the "$build" render array in each of the menu callback functions defined in that file.
> 0 votes

---
Tags: 7, theming, paging, nodes
---


title: Cannot login after moving site

text:
# Question
Title: Cannot login after moving site
I am in the process of recovering from a catastrophic hard disk failure on a completely new machine. I am fortunate to have both a database backup and a backup of the folder with the D7 code that was running on the original machine.

After restoring everything to the original state the site at first appeared to be running well. All nodes that I clicked on worked perfectly and showed the data I expected. **The problems began when I tried to login. It looks as if submitting any form whatsoever (including the login form) does not have any effect**. I couldn't even login until I generated a one time login link with `drush uli`. Using that link I was at last able to login with the admin user, but whenever I try to change something in the admin area I simply can't do it - the page is reloaded after I submit the form and my changes disappear. There are no error messages 1) in the web UI, 2) in the Apache log files, or 3) in the watchdog database table.

Things that I tried without any effect:

* Clean the cache tables. All of them, both with `drush` and with phpMyAdmin
* Set up a completely new site using the same codebase (Drupal 7.14). The new site works perfectly, after the setup I can login and create content without problems. The original site still doesn't work. This shows me that neither the Drupal code I am using is the problem, nor the Apache setup (the vhost for the new site is practically identical to the vhost for the problematic site).
* Upgrade to Drupal 7.44
* Disable all modules (only disable, not uninstall)
* Enable tracing using the xdebug PHP module, but the result gave me information overload. I'm no PHP hacker.

I am now pretty desperate. I must overlook something essential, but for the life of me I can't find what it is. I am aware that this is all pretty vague, but I hope that someone with more experience than me can offer me a hint what I am doing wrong.

Info on my environment

* Server
    + Debian jessie
    + Apache 2.4.10-10+deb8
    + php5 5.6.20+dfsg-0+deb8u1
    + MySQL 5.5.49-0+deb8u1
* Client
    + Mac OS X 10.11.4
    + Firefox 46.0.1 and Safari 9.1 on Mac
* Configuration
    + Drupal 7.14 and 7.44
    + SSL-enabled vhost

# Answer
In your new machine you probably installed Apache and did not enable **a2enmod rewrite**

To enable it, copy and paste the following line to your command line:

```
sudo a2enmod rewrite && sudo service apache2 restart

```

---

Another way to enable it (in case you're on Windows), you could edit `/apache/conf/httpd.conf` and uncomment (remove the #) from `#LoadModule rewrite_module modules/mod_rewrite.so` line and **restart Apache**.
> 1 votes

---
Tags: 7, backups
---


# Question
Title: How to add new content using a content type added after taxonomy access control was installed?
I have added some content types to Drupal to store some custom content. Then I installed the Taxonomy Access Control module to manage the access rights. At this point everything was working perfectly and easily.

Then I added a new content type but when I try to "add a new content", this content type doesn't appear in the list of content types.

Is this because of the Taxonomy Access Control module? Do I have to re install it?

**Note**: I also flushed the cache and performed "rebuild permissions". It appears in the admin/content type filter. but if i add content, no trace of it.

# Answer
> 1 votes
Have a look at the Community documentation of the Taxonomy Access Control module. Especially what it says about the **Global default** (within Global and vocabulary defaults), i.e:

> The **global default**, at the top of the form, determines the grants the role receives for untagged nodes (including nodes with terms that are not in controlled vocabularies). Keep in mind that access is denied by default, so if you want TAC to grant a role access to untagged nodes, set the global default to allow for that grant and role.

See what happens if you adapt this default. If the issue persists, then you may want to perform TAC troubelshooting, possibly even Troubleshooting with Devel.

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


title: Is Settings::set() a valid function?

text:
# Question
Title: Is Settings::set() a valid function?
Can I set value like `Settings::set('some-variable','hello')`?

As if we can get value using `Settings::get('some-variable')` then why the '`set`' method is not working?

# Answer
> 4 votes
No, you can not call Settings::set. You should get an

```
Error: Call to undefined method Drupal\Core\Site\Settings::set() in ...

```

Maybe there's something wrong with your error reporting or you imported any other Settings class (check your namespace). Check your php.ini for this. The Settings Class is for read-only access to the settings in settings.php.

If you need to set some system settings do it like this:

```
// themes
\Drupal::configFactory()->getEditable('system.theme')
->set('admin', 'bartik')
->save();

```

---
Tags: 8, configuration
---


# Question
Title: Three domain names for a multi-site installation
We are currently developing a website on Drupal 8.

This site will be in three versions. The differences between each site is minimal.

1. Different logo
2. Different colors CSS (HTML structure remains the same)
3. Some content is filtered according to the domain name. For this, we created a selection field in the content type to know on which domain name the content appears (*Site A*, *Site B*, *Site C*).

What is the best way to manage this type of project with Drupal 8?

We are aware that this could cause problems with the Drupal cache if we do a simple detection via preprocess to load a particular CSS or content.

# Answer
I am doing something very similar to migrate some D5, D6 and D7 sites to **one** D8 site. Currently I have this solution:

(1) Have one master domain that serves all content (i.e. proreos.de).

(2) Have some paths (routes) that serve special content for different domains (i.e. /asde/\* -\> serve content for anwalt-seiten.de/\*)

(3) Have ThemeNegotiatiors (ThemeNegotiatorInterface) watching for that special routes to set the 'other' theme (like asde-theme).

(4) Have inverse proxies (apache2 mod\_proxy) on the "other" domains that deliver the subcontent from the master domain (i.e. anwalt-seiten.de/index.html -\> proreos.de/asde/index.html)

The advantage I hope to have from this approach:

(a) Have all data in one place (proreos)

(b) Have presentation separated from model (special themes)

(c) Have scalability (by inverse proxies).

But I don't have real experience cause I am still developing. Hope it helps anyway.
> 0 votes

---
Tags: 8, multi-sites
---


# Question
Title: How to calculate user scores based on 3 variables to assign an appropriate text label?
I need to calculate a score for users in D7 based on 3 variables and then assign an appropriate text label and a CSS class.

So, using data from Voting API, time ago joined, and number of nodes published, it needs to select and display one of 15 text labels such as "Promising newcomer, reliable veteran, etc".

Given that I am a site builder with limited PHP skills, where should I start? Should I setup 15 different rules to set a value on a list field?

Before investing time in Computed Field, Display Suite Custom Field or Views PHP, I would love advice from the Drupal community.

Looking for something similar to SE badges.

# Answer
A possible answer is to trigger Rules Actions based on a combination of Rules Events that happen ***asynchronously***, and optionally after they were ***repeated*** multiple times. Which also requires some type of recording of the progress being made. Pretty challenging specs, but there is a solution (module) for it, as further explained below.

# Goals module

You may want to look at the Goals module (disclosure: I'm its maintainer) as a possible alternative. To start using it only requires typical administration tasks (configuration), though it does come with various hooks also for custom module development (if you want to).

Since the Goals module is entity based, it has out-of-the-box integrations with modules such as Views, Rules, Flag, etc.

# Requirements mapping

> I need to calculate a score for users in D7 based on 3 variables and then assign an appropriate text label and a CSS class.

**calculate**: that's what Goals will do for you, by *recording* the progress made on the completion of each *task* required to reach a *goal*.

**3 variables**: that sounds like 3 *tasks* to be completed to achieve 1 *goal*.

**assign an appropriate text label**: you can optionally attach a (custom) image to each goal. The goals completed by a user, can be shown on a Views block included with Goals, with title "Your completed goals".

> So, using data from Voting API, time ago joined, and number of nodes published, it needs to select and display one of 15 text labels such as "Promising newcomer, reliable veteran, etc".

**using data from...**: if you can think of a Rules ***Event*** to discover these events, you use the appropriate Rules ***Action*** (provided by Goals) to record progress on the completion of a *task*. E.g. if 1 such task would be to "create 10 nodes of type XYZ", then each time such nodes are saved (there is a Rules Event for it!), then Goals will *record* so. And if 10 such nodes were recorded, the task is considered completed. And if all tasks of a specific goal or completed, then the goal is reached.

Here is a screenprint of a rule to record a task activity about posting comments:

**15 text labels**: that sounds like 15 *goals* you'd have to configure using the admin interface of the Goals module (no custom coding involved).

# More details

For more details about the Goals module, refer to my answer to "How to implement gamification in a Drupal site and award incentives?".
> 0 votes

---
Tags: 7, views, users, display-suite, entities
---


# Question
Title: Author who is not a user - Does a module exist?
I am about to write a custom module to allow for non-user authors (called Authors for the rest of this question).

Use Case is really the corporate website

* Person publishing content to the website is not the author
* Actual authors are many and potentially multiple on a specific article
* There is no reason to create the authors as users on the CMS

Functional suggestions/ideas

* When editing an article the editor can select one or many "Authors" for the article.
* If none is selected then the creator of the article is displayed as the Author.
* Author would be used in place of User when article displays on the front end.
* If configured Authors would have a block on a node showing Author content fields (image, role ...).
* Users can be associated with an Author through an Entity reference field.
* Re-use profiles on corporate About the Team page

Am I crazy, does a module exist, should I just create them as system users with no privileges and use an existing module? Just seems wrong to give manage users rights to website editor so that they can edit these profiles.

# Answer
> 0 votes
The solution was clearly provided by @Clive in his comment:

> users only make sense in the context of authorisation. Since you don't want/need that, you should just create an 'Author' content type and use that to store your authors and use EntityReference to relate them as Nikhil suggested

If a logged in user needs to be associated with a user in order to pre-fill this author display field you could have an entity reference on the user profile page. If this needs to be a module, use features module to export:

* Author content type
* Author entity reference on users
* Author field base with form field and display handling

I never actually created a module for this.

---
Tags: 7, users
---


# Question
Title: Show all values for a field collection in node.tpl.php
I have a problem with theming field collection. I want to create a loop and I have a field called field\_earth inside field\_helloworld that displays unlimited images. The following code doesn't show any image.

```
<?php
  $counter = 1;
  foreach ($node->field_helloworld['und'] as $key => $value) {
    $field_collection = entity_load('field_collection_item', array($value['value']));
    $idx = $value['value'];
?>
  <p>
    <small><?php print $counter; ?></small>
    <?php print $field_collection[$idx]->field_venus['und'][0]['value'];?>
  </p>
  <div>
    <?php print $field_collection[$idx]->field_earth['und']['0'][value];?>
  </div>
  <?php $counter++; ?>
<?php  } ?>

```

Can anyone show me how to display all images?

# Answer
```
/**
 * @Show all field collection values from node object
 *  Example field collection name: "field_helloworld"
 *  Example fields within a field collection:
 *  - field_title       (string)
 *  - field_image       (image)
 *  - field_description (string)
 */

// get field collections from node
$field_helloworld = field_get_items('node', $node, 'field_helloworld');

// get all fields values if collection exists
if (!empty($field_helloworld)){
    $field = field_view_value('node',$node, 'field_helloworld', $field_helloworld[0]);
    foreach ($field['entity']['field_collection_item'] as $id => $field_collection){

        // load the field collection item entity
        $field_collection_item = field_collection_item_load($id);
        // wrap the entity and make it easier to get the values of fields
        $field_wrapper = entity_metadata_wrapper('field_collection_item', $field_collection_item);

        // all values from a field collection
        $field_title        = $field_wrapper->field_title->value();
        $field_image        = $field_wrapper->field_image->value(); // an array of image data
        $field_description  = $field_wrapper->field_description->value();

        // an example of getting image url from field_image
        $image_url          = $field_image['uri'] ? file_create_url($field_image['uri']) : '';
    }
}

```

Notice that there is no `['und']['0'][value]`.
> 3 votes

# Answer
I have a node with a field collection called "field\_table." I used `field_collection_item_load()` to get all the values inside it. You can get all URIs inside an array, and loop to display the images.

```
 $node = node_load(71); // This is the node containing the field collection.
 $arr = array();

 foreach ($node->field_table['und'] as $oneRow) {
   $row = field_collection_item_load($oneRow['value']);
   $arr[] = array(
     'image' => $row->field_img['und'][0]['uri']
   );
 }

```
> 2 votes

# Answer
The title of this question is *Show all values for a field collection in node.tpl.php*...

Add this to your `node.tpl.php` file to dump all the output:

```
  print '<pre>' . check_plain(print_r($content, 1)) . '</pre>';

```
> 0 votes

# Answer
```
<img src="<?php print image_style_url("thumbnail", $field_collection[$id]->field_image['und'][0]['uri']);?>">

```

Use image\_style\_url and it will work. field\_image is the machine name for image field.
> 0 votes

---
Tags: theming, entities
---


# Question
Title: Split a date field output into two spans
I have a Date field on a content type. I'm trying to render it so that just the Month and Day are visible, but I need each in a separate .

I think the most appropriate place to do this is in the preprocess function for the node theme function. Within that function, here's the date field on the node object:

**What is the appropriate way to convert this to something I can run a custom date formatter on, so I can get the month and the day separately?**

This is my current approach:

```
$date_field = $node->field_event_date_time[$node->language][0];
$date_object = new DateObject($date_field['value'], new DateTimeZone($date_field['timezone_db']));

$variables['event_month'] = date_format_date($date_object, 'custom', 'M');
$variables['event_day'] = date_format_date($date_object, 'custom', 'j');

```

But it does seem a bit messy, and I've noticed is that the field *won't always* have the language array key, so that complicates it a bit further.

# Answer
> 0 votes
If your current approach works, consider sticking with it. Use field\_get\_items() to get past the "field won't always have the language" problem.

To answer the original question, at admin/config/regional/date-time you'll find a tab to create a new format. You can somewhat laboriously create a format based on something like:

```
<\s\p\a\n \c\l\a\s\s="\f\o\o">l F j</\s\p\a\n> - <\s\p\a\n \c\l\a\s\s="\b\a\r">g:i a</\s\p\a\n>

```

All the backslashes may not be necessary, but you have to backslash escape any character that is a special date code.

Then edit a type or make a new one that uses your format with the markup built in.

# Answer
> 0 votes
You can use **theme hooks** to override the format of a specific date format as follows:

```
/**
 * Override theme_date_display_single().
 *
 * @param $variables
 *   An array of variables to pass to the theme template.
 */
function theme_date_display_single($variables) {
  if($variables['dates']['format'] == "d M Y"){
    // In this case i keep only start date. For keep end date use value2.
    $date = $variables['dates']['value']['formatted_iso'];
    $timezone = $variables['timezone'];
    $attributes = $variables['attributes'];
    // Set my vars
    $day = format_date(strtotime($date), 'custom', 'd');
    $month = format_date(strtotime($date), 'custom', 'M');
    $year = format_date(strtotime($date), 'custom', 'Y');

    // Wrap the result with the attributes.
    return '<span class="date-display-single"' . drupal_attributes($attributes) . '>' . '<span class="d">' . $day . '</span>' . '<span class="M">' . $month . '</span>' . '<span class="Y">' . $year . '</span>' . $timezone . '</span>';
  }
}

```

This solution has been posted here: https://www.drupal.org/node/423870#comment-9871591

---
Tags: 7, datetime
---


# Question
Title: How do I forcefully uninstall any module having content?
I want to uninstall the Field module, but this module can not be uninstalled; when I try, I get the following message.

> Field API to add fields to entities like nodes and users. Machine name: field Version: 8.0.6 Required by: TextNodeAdmin ToolbarAdmin Toolbar Extra ToolsFileOptionsAggregator (disabled) ImageAccelerated Mobile Pages (AMP) (disabled)Custom BlockBook (disabled)Text EditorCKEditorCommentInterface TranslationConfiguration Translation (disabled)

How do I forcefully uninstall any module that is having dependency or content inside, for example the Node module, the Views module, or any entity having content in it?

I tried using `\Drupal::service('module_installer')->uninstall(['admin_toolbar']);` but then my site breaks.

# Answer
> For example, I made any custom content entity type and add content into it. Now I can not uninstall my custom module until and unless I delete all content or truncate module specific db table – Sugandh Khanna.

Unfortunately, in Drupal 8 you can't disable a module, like you can in Drupal 7.

In Drupal 7 you need to disable the module first, which means all module related code stays in DB. Then, if you wanted, you Uninstall to remove everything from DB.

In Drupal 8 the only option is to uninstall the module, which means you have to destroy all traces of your module from the Database. You cannot just disable the module anymore.

Also, to uninstall Flag (as in your comment here), you have to uninstall dependencies first, then and only then, it will allow you to uninstall Flag. Because if module X depends on Flag and somehow you removed flag, it will totally screw up module X, X becomes useless, module X is nothing without Flag. Therefore you need to remove module X first, then and only then it will allow you to remove Flag.

For more info: Why can't I uninstall modules in Drupal 8? (Explained)

Issue: Disabled modules are broken beyond repair so the "disable" functionality needs to be removed
> 3 votes

---
Tags: entities, 8, installation
---


# Question
Title: Filter result by using global php value in views
I am appending city code and city value in global php field in views

Now I want to filter the result based on this field value.

For example if a record having city code:NY and city:New York If i search NY-New York then it should filter the results.

Any help plz..

# Answer
Long story short, using views filters change the SQL query, by adding a where clause in the SQL query. The limitation by this is that information needs to be in the database. Since the global PHP field doesn't exist in the database, it's not possible to use views filter on such a value.

You could write some code in a custom module, where you implement the logic and removes all unwanted records, but this wont perform well.

Generally you should avoid the global PHP fields if at all possible.
> 2 votes

---
Tags: 7, views
---


title: Automatic username generation

text:
# Question
Title: Automatic username generation
How do I create a user registration form where username field cannot be modified by the user and is auto-generated on the basis of two other fields in form (dynamically).

I know there are some modules available for the task in Drupal 7, but how do I achieve this in Drupal 8?

# Answer
This is pretty simple. Create your module, then create a form "MyRegForm" where the user can input her email and (if needed) password (twice with the '#type' =\> 'password\_confirm'). Then, in the submit() method create your user like this:

```
\Drupal\user\Entity\User::create([
            'name' => 'hGzfT54re39OpLLLk',
            'pass' => 'hGzfT54re39OpLLLk',
            'mail' => $data->mail,
            'status' => 1,
            'init' => $data->mail,
            'created' => time(),
            'changed' => time(),
            'login' => 0,
            'access' => 0,
        ])->save();

```

The change the username and add whatever roles you need with code like

```
    $tuser = user_load_by_name('hGzfT54re39OpLLLk');
    $tuser->setUsername('My super name logic');
    $tuser->addRole("whatever");
    $tuser->save();
    $rc = $tuser->id();

```

If you don't want to create your own form for registration, go for hook\_form\_alter and set the #access to the "name" field to false and add a #default\_value.
> 1 votes

---
Tags: users, 8
---


# Question
Title: Why am I not able to pass a variable to my JavaScript code?
I'm hoping someone can shed some light on this for me. I've been building my first Drupal 8 custom block via a custom module. It was all going well until I've tried to pass some values into javascript. I'm working on some morris.js graphs, and want to display data from a database.

I've tried numerous variations, but can never get the variable to work. BTW, I'm not great at Javascript, so that might be where the flaw lies.

Here is the library definition:

```
 morris:
  css:
    theme:
      /libraries/morris/morris.css: {}
  js:
    /libraries/morris/morris.min.js: {}
    /libraries/raphael-master/raphael.min.js: {}
    js/custom.js: {}
    dependencies:
    - core/jquery
    - core/drupal.ajax
    - core/drupal
    - core/drupalSettings
    - core/jquery.once

```

Here is the relevant part of the block file:

```
 $build['#attached']['library'][] = 'module_machine_name/morris';
$build['#attached']['drupalSettings']['module_machine_name']['morris']['memGraph'] = $graph_total;

```

And here is the js file:

```
     var infoo;

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

            infoo = drupalSettings.module_machine_name.morris.memGraph;

        Morris.Bar({
      element: 'graph',
      data: [
        {x: '2011 Q1', y: infoo, z: 2, a: 6},
        {x: '2011 Q2', y: 2, z: null, a: 1},
        {x: '2011 Q3', y: 0, z: 2, a: 4},
        {x: '2011 Q4', y: 2, z: 4, a: 3}
      ],
      xkey: 'x',
      ykeys: ['y', 'z', 'a'],
      labels: ['Y', 'Z', 'A']
    }).on('click', function(i, row){
      console.log(i, row);
    });

        }
      };

})(jQuery, Drupal, drupalSettings);

```

Can anybody help? Thanks

# Answer
Have you try changing the order?

First load the drupalSettings attachment and after the library?

```
$build['#attached']['drupalSettings']['module_machine_name']['morris']['memGraph'] = $graph_total;
$build['#attached']['library'][] = 'module_machine_name/morris';

```
> 1 votes

---
Tags: 8, javascript, blocks
---


# Question
Title: Why is my '#id' transformed into 'data-drupal-selector'?
In a custom form I (try to) write, I have this element at the end:

```
$form['referent'] = array(
    '#id' => 'breferentdistrib',
    '#type' => 'hidden',
    '#default_value' => ($bReferentDistrib) ? "Y" : "N"
);

```

'breferentdistrib' being used in javascript this way:
`var breferentdistrib = document.getElementById("breferentdistrib").value;`

Unfortunately, I get this in the rendered HTML: `<input type="hidden" value="N" name="referent" data-drupal-selector="breferentdistrib">`

No 'Id' and 'data-drupal-selector' instead.
Of course, my `getElementById("breferentdistrib")` is not working...
Any idea?

# Answer
It's intentional as @clive says. You can select it using jQuery or CSS of the this way:

```
div[data-drupal-selector=your-selector-id]

```

If you want to use a id you can declare like this:

```
$form['referent']['#attributes']['id'] = 'foo';

```
> 5 votes

---
Tags: forms, 8
---


# Question
Title: How to enable maintenance mode only when there are no active users?
When there are updates available for Drupal, I enable the maintenance mode, update, and disable the maintenance mode again.

As far as I understand it, users that were right in the middle of editing a node or checking out their shopping cart would lose their content/progress because of the maintenance break.

One solution could be to notify all online users that they should save their content, however, this would not work for users that are checking out right now (e.g., filling in the shipping data or being in the payment process).

Ideally, when trying to enable the maintenance mode, **Drupal should warn me that users are currently *active* on the site**.

**Is this possible?** Can Drupal detect that someone (be it a registered or an anonymous user) is "active", even if the user might have been afk/inactive for some time (e.g., searching for the credit card)? Possible indications could be: opened a node edit form but no submission or further request detected; started but not finished the checkout; added products to the cart without checking out; etc.

If yes, **how could I achieve this?** I’m not experienced enough to write this from scratch, so hopefully this doesn’t involve creating a totally new module. Does there exist a module for this purpose?

# Answer
### Solution 1 - Going Down:

Using the Going Down module (credits: J. Reynolds) could be a valid compromise (and maybe help to create a custom work around). Some more details about this module (from its project page):

> ... warns site visitors that the web site will be going down for maintenance at a specified time. The default configuration displays a fixed position red overlay message at the bottom of the browser window with text in the format 'Drupal is going offline for maintenance at Tue Feb 21 14:41:08 2012 -0800'. Module configuration is added to the Site Maintenance administration page (`admin/settings/site-maintenance`).

Here is a screenprint about it (also from its project page):

Only using this module will only reduce the risk of active users when you want to enable maintenance mode (though not completely reduce it).

However, by using that module, you may be able to use the Rules module to build some custom rule(s), in which you add your own custom Rules Conditions to go check if the time left for scheduled maintenance date/time is still sufficient.

Such Rules Condition would be to perform some custom PHP code, to retrieve the date/time set via the Going Down module. And then add this Rules Condition when visiting pages where you want to avoid your issue.

### Solution 2 - Rules (and Message) is your friend:

Use the Rules module to create a custom rule that uses Rules Event "Drupal is initializing". Add whatever Rules Conditions you want, if any (eg: not for users with role admin). And add the appropriate Rules Action(s) to perform some type of special logging, e.g. using the Message module to create custom log data. Such log data should include things like timestamp, user id, current path, etc. If you'd use the Message module, you could create a (rather basic) view (using the Views module) to list the relevant log records that got created by this custom rule.

Enable this custom rule only X minutes (pick whatever value that fits for X) before you plan to enable maintenance mode. From then on just browse the views results to get an idea about how long ago which user/visitor has been visiting which path. For any events (log records) longer then Y minutes ago, just assume that user/session is not really doing anything on the site anymore at the moment you're browsing your Views result.
> 1 votes

# Answer
> Is this possible?

Yes, it's possible. You could check the `timestamp` column in the `sessions` table in the database to see which users are active.

You would need to:
\- Determine criteria for users being 'active'.
\- Ensure anonymous users have a session.
\- Exclude certain users, e.g your own user from the check.

For example, see the 'online' case for the "Who's online" block in `user_block_view`

> How could I acheive this?

You would need to make a custom module to contain your application logic, including for example a `hook_form_alter` to modify the maintenance form to display your warning message.
> 0 votes

---
Tags: 7, users, maintenance-mode
---


# Question
Title: Taxonomy Term description in views when "no results" (Haven't associated nodes)
need help with Taxonomy Term description when no results in views. I'm using Drupal 7.44 / Views 3.14 and render content from node teaser template without using fields, and for showing description used *Header area* / *Global:Text area* / *Php Filter* and this code

`<?php
$view = views_get_current_view();
if (is_numeric($view->args[0])){
$term = taxonomy_term_load($view->args[0]);
return $term->description;
}?>`

But it's work only when term have associated node, but some terms doesn't have nodes and description not showing.

Maybe some one knows how can I fix it?

# Answer
Forgot about "Empty Results". insert code in "Global:Text area" and It's works. Thanks me for helping)))
> 0 votes

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


title: how to retrieve data for apache solr

text:
# Question
Title: how to retrieve data for apache solr
I am using apache solr 3.x . Right now, I mixed the data from my two websites into one solr by mistake. I set one solr on the first website server and set another website's Apache Solr search to link to this server. I don't know they will mess up when I set this. But right now, the first website doesn't add any data into the solr, and all the data from the other website can add the data to the solr.

Is there anyway that I can retrieve each website data to make them show in the correct position?

# Answer
> 0 votes
Use Apache Solr Multisite search https://www.drupal.org/project/apachesolr\_multisitesearch This is the proper way to have multiple sites sharing one index. You can search all sites or single sites.

---
Tags: 7, search
---


# Question
Title: Programically update node when visited by 'editor' role
My goal is to have *promote-node-when-visited-by-editor* feature. This is code from `MYMODULE` using `hook_node_view`:

```
function MYMODULE_node_view($node, $view_mode, $langcode) {
    // 'promote-node-when-visited-by-editor' (roles[6]) feature
    if ($node->type == 'blog') {
        if (empty($node->promote)) {
            if ($view_mode == 'full') {
                global $user;
                if (isset($user->roles[6])) {
                    $node_data = node_load($node->nid);
                    $node_data->promote = '1';
                    node_save($node_data);
                }
            }
        }
    }
}

```

When all IFs are met, I get this error in execution part with hook\_node\_view:

```
Recoverable fatal error: Argument 1 passed to drupal_attributes()
must be of the type array, null given, called in /includes/common.inc
on line 2534 and defined in drupal_attributes() (line 2426
of /includes/common.inc).

```

What's the right hook when I want programically update node when (after, right before...) visited by `editor` role. For example rules have `content is viewed` event.

# Answer
> 0 votes
I have replaced these 3 lines

```
            $node_data = node_load($node->nid);
            $node_data->promote = '1';
            node_save($node_data);

```

with

```
            db_update('node')
                    ->fields(array(
                        'promote' => '1',
                    ))
                    ->condition('nid', $node->nid)
                    ->execute();
            db_update('node_revision')
                    ->fields(array(
                        'promote' => '1',
                    ))
                    ->condition('nid', $node->nid)
                    ->execute();
            db_query('DELETE FROM cache_entity_node WHERE cache_entity_node.cid = :nid', array ( ':nid' => $node->nid));

```

and it seems working :)

---
Tags: 7, hooks
---


title: nodejs server set up

text:
# Question
Title: nodejs server set up
# **UPDATE**:

The node.js server is now running correctly at Openshift. The node.js server and the socket.io script can now be accessed publicly.

Running cron in Drupal, I see that it can also access the node.js server. However, my problem now is this, from the Chrome console:

> GET https://nodejstapchat-breathalert.rhcloud.com:8080/socket.io/?EIO=3&transport=polling&t=LM-NWXx net::ERR\_CONNECTION\_TIMED\_OUT socket.io.js:3511

I think it has to do with that redundant port in the url. Can anyone confirm?

---

## ORIGINAL QUESTION:

Having problems while setting up the drupal nodejs module to use with Chatroom. This is working for me on localhost, so I suspect it has something to do with HTTPS.

The Drupal site is served only via HTTPS, and I just got the nodejs server, running on Modulus.io with HTTPS.

The drupal nodejs module (v7.x-1.13) and nodejs server (v1.0.9) are of compatible versions (based on the doc). Also confirmed the matching config on the Drupal site as well.

Checking the HTML source on one of the chat pages using nodejs, came across this:

```
<script src="https://tapcreativechat-64706.onmodulus.net:8088/socket.io/socket.io.js"></script>

```

But it appears it does not return the socket.io script (also tried port 8080).

Second related problem is the messages in Drupal dblog:

> Error reaching the Node.js server at "nodejs/health/check": \[-110\] Connection timed out.

I am out of ideas why Drupal can't connect to the nodejs server.

My Node.js server config file:

```
//Node.js server
settings = {
scheme: 'https',
port: process.env.PORT || 443,
host: 'localhost',
resource: '/socket.io',
serviceKey: 'key',
//Drupal site
backend: {
    port: 80,
    host: 'tapcreative.services',
    scheme: 'https',
    basePath: '/',
    messagePath: '/nodejs/message'
},
debug: true,
sslKeyPath: '_privatekey.key',
sslCertPath: 'tapcreative_services.crt',
sslCAPath: 'all_certs.crt',
baseAuthPath: '/nodejs/',
extensions: [],
clientsCanWriteToChannels: false,
clientsCanWriteToClients: false,
transports: ['websocket', 'polling'],
jsMinification: true,
jsEtag: true,
logLevel: 1
};

```

Advice is appreciated.

# Answer
> 2 votes
your first `host: '',` (line 4) is empty, should be `host: 'tapcreative.services',`

In addition, you're using the wrong port, port 80 is for HTTP. You need to use the HTTPS port, 443.

Change line 8 from `port: 80,` to `port: 443,`

# Answer
> 0 votes
The first issue is that the script url (https://tapcreativechat-64706.onmodulus.net:8088) does not load in the browser. This url needs to be accessible to the public before you proceed further. Either this url is incorrect, or your application is not set up properly in Modulus.

---
Tags: 7, nodejs
---


title: add base url before field text content

text:
# Question
Title: add base url before field text content
I have a text field used to enter a code (like 1111). This code is linked to a file (image) hosted in another server.

When a user displays this content type, I want to automatically display 3 things :

\*the field content with the code (1111 for exemple) (I know how to do it)

* a picture whose url will always be : www.url.com/FIELD\_CONTENT.jpg (www.url.com/1111.jpg)
* a link to the picture

Is it possible to do that ?

D8 but i can create a D7 website if needed.

# Answer
You can render your image with a render array like this:

```
$a = array('#theme' => 'image',
        '#uri' => 'http://www.url.com/'.FIELD_CONTENT.'.jpg',
        '#alt' => 'Whatever',
    );

```

If you want that to be the content of an A tag (the link to press), render the link like this:

```
Link::createFromRoute($a, routename)->toString()

```

Is this what you need?
> 0 votes

# Answer
Use `<?php print base_path().'yourimage.jpg'; ?>`

https://api.drupal.org/api/drupal/core!includes!common.inc/function/base\_path/8.2.x
> 0 votes

---
Tags: media, navigation
---


# Question
Title: How can I theme the Bootstrap base theme search block?
I've created a sub-theme of the Drupal 8 Bootstrap base theme. My problem is that I'm using a customized version of the Bootstrap CSS Framework that does not include Glyphicons. Instead of Glyphicons, my project is using fontAwesome icons. What I've realized though, is that the Bootstrap theme uses a Glyphicon Search Icon for the Search Form. Since I'm not using glyphicons and the CSS files are not included, I get a search form button that looks like this.

>

It should appear like this.

>

If i inspect the HTML markup using my browser, my theory is correct.

```
<button type="submit" value="Search" class="button js-form-submit form-submit btn-primary btn icon-only" name=""><span class="sr-only">Search</span><span class="icon glyphicon glyphicon-search" aria-hidden="true"></span></button>

```

if I change the following markup, the button shows up correctly because it can find the icon.

```
 <span class="icon glyphicon glypicon-search"></span> to <span class="fa fa-search"></span>

```

What I want to do is to be able to change the icon or the code in the base theme that generates this snippet of code.

```
<span class="icon glyphicon glypicon-search"></span>

```

My assumption is that I should use a preprocess function to alter the form block and output/replace the Glyphicon span with the Fontawesome span.

I believe that the input--button.html.twig in the bootstrap base theme is responsible for outputting the icon classes because of this code.

```
{% block input %}
    {% if icon_only %}
      <button{{ attributes.addClass(classes, 'icon-only') }}>
        <span class="sr-only">{{ label }}</span>
        {{ icon }}
      </button>
    {% else %}
      {% if icon_position == 'after' %}
        <button{{ attributes.addClass(classes) }}>{{ label }}{{ icon }}</button>{{ children }}
      {% else %}
        <button{{ attributes.addClass(classes) }}>{{ icon }}{{ label }}</button>{{ children }}
      {% endif %}
    {% endif %}
    {{ children }}
  {% endblock %}

```

Apparently, it is used to alter the button of many elements instead of only the search form.

# Answer
> 5 votes
Bootstrap theme is deeply bundled with glyphicons .. it guesses the icon from the button text.

You would need to override Bootstrap::**glyphiconFromString**() or Bootstrap::**glyphicons**(). I cannot tell you how to do this in your subtheme ...

If you removed the glyphicons, probably Theme::**hasGlyphicons**() will return `FALSE` and won't show any icon.

## Workaround

You could replace the icon variable in template\_preprocess\_input, like:

```
function MY_TEME_preprocess_input(&$variables) {
  if ($variables['icon']) {
    if (array_key_exists('glyphicon-search', $variables['icon']['#attributes']['class'])) {
     foreach($variables['icon']['#attributes']['class'] as &$sValue)
     {
       if ($sValue == 'glyphicon') {
         $sValue = 'fa';
       }
       if ($sValue == 'glyphicon-search') {
         $sValue = 'fa-search';
       }
     }
    }
  }
}

```

*or*, I guess you have asked this question on do: https://www.drupal.org/node/2757463. There is a suggestion of overwriting the Input element:

Create a file at bootstrapsubtheme/src/Plugin/Preprocess/Input.php and add the following:

```
/**
 * @file
 * Contains \Drupal\bootstrapsubtheme\Plugin\Preprocess\Input.
 */

namespace Drupal\bootstrapsubtheme\Plugin\Preprocess;

use Drupal\bootstrap\Annotation\BootstrapPreprocess;
use Drupal\bootstrap\Utility\Variables;

/**
 * Pre-processes variables for the "input" theme hook.
 *
 * @ingroup theme_preprocess
 *
 * @BootstrapPreprocess("input")
 */
class Input extends \Drupal\bootstrap\Plugin\Preprocess\Input {

  /**
   * {@inheritdoc}
   */
  public function preprocessElement(Variables $variables, $hook, array $info) {
    $element = $variables->element;

    if ($element->icon) {
      $element->icon->replaceClass('glyphicon', 'fa');
      $element->icon->replaceClass('glyphicon-search', 'fa-search');
    }

    // Let bootstrap base theme preprocess the element normally now.
    parent::preprocessElement($variables, $hook, $info);
  }

}

```

# Answer
> 0 votes
Adapted from @remy's Answer. Using $variables\['icon'\] wasn't working so i tried drilling down a little deeper into the variable array and i was able to change the icon to a font-awesome icon. The preprocess function was added to my themes, .theme file.

Let me know if there is a better/ more concise approach. Currently, i only need to change 1 icon, but what if there are 20 icons? (This solution might get pretty busy quickly).

```
  function MYBOOTSTRAPTHEMENAME_preprocess_input(&$variables) {

  $glyphiconclass = $variables['icon']['#attributes']['class'][1];
  $glyphiconname = $variables['icon']['#attributes']['class'][2];

    if (($glyphiconclass == 'glyphicon') and ($glyphiconname == 'glyphicon-search')) {
       $variables['icon']['#attributes']['class'][1] = 'fa';
       $variables['icon']['#attributes']['class'][2] = 'fa-search';
    }

  }

```

# Answer
> 0 votes
It is important that you should BY DEFAULT always have the bootstrap theme enabled, but be working from a subtheme. Look in the templates/bootstrap folder and look for a file named **bootstrap-search-form-wrapper.func.php**. Copy that file to your default theme. and you can then modify it to use Fontawesome rather than the glyphicon.

---
Tags: hooks, theming
---