# Question
Title: How to mark a Message as 'viewed' when a user sees it in a View?
I'm displaying a user's Messages (created with the Message module) in a View. I'd like to flag them once they're viewed and thought that a Rule could do this easily. I've set the Rules Event to "A message is viewed" and the Rules Action to "Flag a message", but for some reason *the viewing event is not triggered*. I tried hovering the Message, visiting the referenced node's page and visiting `Content > Messages`, but nothing runs the Rule.

Did anyone experience the same problem before? Maybe this is a bug in the Message module (I've reported it at https://www.drupal.org/node/2291695), but I'd like to know whether you've already found a solution for this.

Ultimately, I'd like the Rule to be activated when a user hovers the Message or clicks it (I've already made sure that he/she will then be redirected to the referenced node/comment).

# Answer
I will go about this differently. Create a non-global flag on the message (ie for each user) and only give flag action (not unflag). Do not auto display this flag.

Then in your view you add the flag action as a field on the row and test whether it works by clicking on it (to test you could give temporary unflag permission). When it works to you satisfaction hide the flag link via css, and add some javascript to click the flag if the row is hovered (or whatever) over. And set the Javascript up so that it can only activate the link once as one can sometimes fire off multiple events when on the border of an element.

And then just add you rule to fire when the message is actually viewed to cover that angle as well as the user may go to that path from somewhere else but your view.

EDIT: jQuery example code:

This code is for a flag called 'test', and a view called 'all', jQuery version 1.7+

```
(function ($, Drupal, window, document, undefined) {
    Drupal.behaviors.MYMODULE = {
        attach: function(context, settings) {
            $('.view-all .views-row').once().on('mouseover', function(){
               // unbind this event handler so it only fires once
                $(this).off('mouseover');
                // get the flag and click it.
                $(this).find('.flag-test a.flag').trigger('click');
            });

            window.alert = function(text) {
            // Prevent unwanted ajax errors when navigation away
            return true;
        };
        }
    };

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

```

One other little issue is that views does not seem to respect the flag unflag permissions per role. I circumvented that by adding a field 'Flags: Flagged (A boolean field to show whether the flag is set or not.) and setting its output to 0/1. I then hid this new field as well as the flag link, and added a Global PHP field with this Output Code, and it worked like a charm:

```
<?php
if (!$row->flagged) print $row->ops;
?>

```

There is a possible patch for this behaviour at Flags: Flag link views field should respect permissions, but I have not tested it.
> 1 votes

# Answer
Have you enabled Message UI module, if not, enable it and add the **view link** in your view. Then clicking the link will take you to the message page and it will trigger the rule event.

Note : make sure you give permission
> 0 votes

# Answer
Based on the comments above:

You would need to create an ajax call built from a custom module. I don't have much experience with ajax in Drupal outside of forms, so I can't provide any code to help, but here's something to start for info - they're not exactly the same but could point you in the right direction:

when mouseover on username display popup views

Failing that (and now that we have determined what the actual question is), I would close this question and ask a new question about modifying values through an ajax call within Views - you might get more relevant answers.
> 0 votes

# Answer
I can see there is a lot of suggestions here - one suggest to trigger it via flag but the trigger will be with the link of the flag... it's sound to much complicated. No need for external module for that.

Some one mentioned here a simple AJAX and he's right about that. What i'm going to give is a mock-up but will explain the process.

First of all we will need a field that will attached to the message and determmine of the message has been watched or any other logic. The secong step is to set up a simple menu callback:

```
/**
 * Implements hook_menu().
 */
function module_menu() {
  $items = array();

  $items['update-message/%message'] = array(
    'page callback' => 'module_set_message_as_watch',
    'page arguments' => array(1),
    // This will set the menu item accessible for any one. You can set your own
    // logic with the 'access arguments' and pass a permission name or use
    // another function name.
    'access callback' => TRUE,
  );

  return $items;
}

/**
 * Menu callback; Set the message as viewed.
 */
function module_set_message_as_watch($message) {
  $wrapper = entity_metadata_wrapper('message', $message);
  $wrapper->field_viwewed->set(1);
  $wrapper->save();
}

```

What i defined here is a menu item that pass him a message ID. When i go to update-message/1 the message 1 will be set as viewed.

You can create in you view a simple HTML output with the link above. A simple jqeury can get in action and do something like:

```
(function ($) {

  Drupal.behaviors.SetMessageAsViwewed = {
    attach: function() {
      $(".set-message-as-viewed").click(function(event) {
        event.preventDefault();

        // Using our own ajax callback.
        $.ajax($(this).attribute('href'))
          .done(function() {
            $(this).text(Drupal.t('The message was viewed.'));
          });
      });
    }
  }

 })(jQuery);

```

The indentation are wrong but this is the big idea. Not something fancy. Simple jQuery and AJAX interaction with Drupal.
> 0 votes

# Answer
I know this question was asked some time ago, but it was one of the top links when I googled for a solution to the same problem as described in the OP.

I believe I have found a solution that doesn't require a custom module, I can't say if this is because the key modules (Views, Rules, Flags and Message) have been updated, or just because no-one else has noticed it before. Anyway, I thought I'd share it so other people that get here from Google can have a go.

My thinking was that the triggering of the Rules event seems to be hardwired somehow to the viewing of the message as a node, and I noticed that on my Message display in Views, there is a "Message: Rendered Message" field. I added this, and on the next screen selected "show complete entity" from the "Display" dropdown menu. I don't think it matters which view mode you select from the next dropdown, and I then removed the label, and excluded the field from being displayed.

This seems to have done the trick for me. I am using an embedded view of a list of messages in the header, and there is a Flag toggle link in that display. I can now, unflag the "seen" flag on a message in the embed, and see that it remains so while I view other messages, and when I view the message again in the main Views display I can see the flag has been changed automatically.

I hope this post is helpful for others with this problem.
> 0 votes

# Answer
> I've set the event to "A message is viewed" and the action to "Flag a message", but for some reason the viewing event is not triggered.

The "clue" about what "Content is viewed" actually means, seems to be like so:

* The event ***Content is viewed*** is what it is: the user has (already) started viewing the content.
* The (system) event ***Drupal is initializing*** is what you should use instead (possible combined with other Events and/or Actions), if you want to trigger some Rules "Action(s)" **BEFORE** the user can start viewing (= looking at) the content.

> Did anyone experience the same problem before? Maybe this is a bug in the Message module ..., but I'd like to know whether you've already found a solution for this.

For a working sample (in Rules 'export format'), refer to How to specify a Rules event like "Content is 'going to be' viewed"?

> Ultimately, I'd like the Rule to be activated when a user hovers the Message or clicks it

A possible implementation which is Rules based (zero custom coding) and close to what you're asking for, is explained in the tutorial "How to allow users to manage their own Message Stack messages?".
> 0 votes

---
Tags: 7, views, message-subscribe
---


# Question
Title: Did anyone have success in configuring Mod security?
I am trying to set up Mod security (the Apache module) for my Drupal site, but it affects basic Drupal functionalities like node submission, module enable/disable and people permission submissions etc.

I am using:

* Drupal 7.56
* Mod Security 2.91
* Owasp crs 3.0
* Apache 2.4

Did anyone have success in configuring Mod security based on Drupal application?

# Answer
Using OWASP CRS v3.0.2 (https://github.com/SpiderLabs/owasp-modsecurity-crs/releases/tag/v3.0.2) you should find no major issues here. Drupal has it's own set of exclusions out of the box because it does things that can be considered bad practice (passing tags via parameters, etc). As outlined in the docs you should uncomment rule 900130 and enable the Drupal exceptions. There is even an example of how to do so.

https://github.com/SpiderLabs/owasp-modsecurity-crs/blob/v3.0/master/crs-setup.conf.example#L302

Enjoy!
> 1 votes

---
Tags: 7
---


# Question
Title: How to serve the same page for all URLs?
I am using Drupal 7 as an API to send JSON data to a Backbone application. It is a single page site with its HTML markup in `html.tpl.php`.

Everything works fine with the Backbone router when I start on the homepage and navigate with internal links but when I refresh a page or type a URL directly I get a Drupal 404 error.

How can I make unknown pages to serve the same page all the time?

The `.htaccess` redirects to `index.php` so it's not a browser 404 but a Drupal 404.

# Answer
> 1 votes
What you could do is stick your webapp in a folder on the root of the site (i.e. `/app`). Then tell `.htaccess` to route all traffic under `/app` to `/app/index.html`. This way, everything `/app` routes to your SPA while everything else is handled by Drupal and you don't mess with Drupal's routing.

Besides, you *really* don't want to route *all* 404 pages to your SPA. For instance, if you delete a piece of content in the site or uninstall a module (that removes its config sections), you will want a Drupal 404 to happen, not your SPA.

# Answer
> 1 votes
In case someone has the same issue, it only happens when connected to Drupal's admin panel. I solved it by disconnecting…

---
Tags: 7
---


# Question
Title: How to create a custom Twig Template for Menu Block
I'm using a menu block to output a section of my main menu into a region so I can have a "In This Section" type of sub menu on every page.

Unfortunately, I can't find a way to pinpoint in menu.html.twig which rendition of "main\_menu" I am working with. (they both have the same "menu\_name") I want to adjust the markup for the menu block, but not for my main menu.

A similar question was asked here: Additional twig suggestions for menus in Drupal 8

I don't quite understand the suggested answer. Is there some way I can extend some class to call a different Twig Template? Is there some hook I'm missing?

# Answer
> 6 votes
Ok, I think I found the answer. Kristian Kaa answers it on his blog here: http://kristiankaa.dk/article/drupal8-region-specific-menu-theme-hook-suggestion

Basically you use 2 preprocess functions like so:

```
/**
 * Implements hook_preprocess_block().
 */
function mymodule_preprocess_block(&$variables) {
  $variables['content']['#attributes']['block'] =    $variables['attributes']['id'];
}

/**
 * Implements hook_theme_suggestions_HOOK_alter().
 */
function mymodule_theme_suggestions_menu_alter(array &$suggestions, array $variables) {
  // Remove the block and replace dashes with underscores in the block ID to
  // use for the hook name.
  if (isset($variables['attributes']['block'])) {
    $hook = str_replace(array('block-', '-'), array('', '_'),    $variables['attributes']['block']);
    $suggestions[] = $variables['theme_hook_original'] . '__' . $hook;
  }
}

```

This will add the block ID as a new theme hook suggestion. Many thanks to Kristian.

# Answer
> 1 votes
FWIW, I ran into an issue while using Greg's answer where I was getting errors about `$variables['attributes']['id']` not having the "id" key. To fix this I added a check to ensure that this key is set.

```
/**
 * Implements hook_preprocess_block().
 * http://kristiankaa.dk/article/drupal8-region-specific-menu-theme-hook-suggestion
 */
function THEMENAME_preprocess_block(&$variables) {
  if(isset($variables['attributes']['id'])) {
    $variables['content']['#attributes']['block'] = $variables['attributes']['id'];
  }
}

```

---
Tags: theming, 8
---


title: How to import nodes in drupal 8?

text:
# Question
Title: How to import nodes in drupal 8?
There are many posts available for migrating the content to D8. But i am not able to understand. I am stopped at some points.

What I have cleared yet?

> Till now there is no UI available node import.
> Feed module not supporting node import.

What I wants to know?

Is it mandatory to create a custom module to achieve this?
Drush is required?

# Answer
Till now there is no UI for importing data included in core. I also didn't find any module which extends the core with that functionality.

I ended up using the migrate\_api which is build in in core and wrote a custom module for my import. Here is a article how you can achieve that https://www.drupal.org/docs/8/upgrade/using-the-migrate-source-csv-plugin

But till now I didn't find any solution how I can import the data without having drush installed.
> 1 votes

# Answer
Try this module to import node data from CSV file. Content Import
> 2 votes

# Answer
I had good success importing nodes from another mysql database using migrate\_plus: https://www.drupal.org/project/migrate\_plus

In there is an example module, migrate\_example, that you can use to base your custom module on.

The imports are run through drush.
> 1 votes

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


# Question
Title: How to unflag all messages when a users visits the Message page?
I am using the Message module in combination with the Flag module in order to build a simple notifications system for my site.

More specifically I have created a page in Views showing all (new) messages for the current user. The page is accessible through a menu link (called "Messages") in the front page. I have also created a message flag so users can flag/unflag there messages as new/old ones.

But instead of forcing the user to manually flag/unflag his messages, **I would like all messages to automatically be unflagged (i.e. become old) when the user visits the messages page** (or a certain context in general).

Any hints on how to achieve this?

# Answer
Although the previous answer seems correct i managed to do this in another way avoiding research, coding and other stuff.

I used Rules, Rules Bonus pack and Panels to do this. Rules bonus pack provides the event "When a page variant is rendered" to trigger actions. So what i did was to create a new page in panels, place my (page) view there and then created a rule that whenever the page is rendered to unflag all the messages.
> 0 votes

# Answer
This sounds like a job for Javascript

Flags has an option to allow the link to use AJAX. So I would dig into the Javascript that the flags modules uses and then create your own script that walks over and triggers each link when the page is loaded.
> 1 votes

# Answer
Below are some details about the steps to be completed, specific to your question here ...

### Step 1:

Create a VBO view of your unread messages, similar to what is described in my answer to "How to allow users to manage their own Message Stack messages?".

### Step 2:

Create a custom Rules Component that will ***execute the VBO list of unread Messages***, and which looks like so:

```
{ "rules_mark_all_unread_messages_read" : {
    "LABEL" : "Mark all unread messages read",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "views_bulk_operations" ],
    "ON" : { "init" : [] },
    "IF" : [
      { "user_has_role" : {
          "account" : [ "site:current-user" ],
          "roles" : { "value" : { "2" : "2" } }
        }
      },
      { "text_matches" : {
          "text" : [ "site:current-page:url" ],
          "match" : "user\/\\d+\/messages\/unread",
          "operation" : "regex"
        }
      }
    ],
    "DO" : [
      { "views_bulk_operations_action_load_list" : {
          "USING" : { "view" : "messages_by_user|page_3" },
          "PROVIDE" : { "entity_list" : { "unread_msgs_list" : "A list of unread messages" } }
        }
      },
      { "LOOP" : {
          "USING" : { "list" : [ "unread-msgs-list" ] },
          "ITEM" : { "current_msg" : "Current message" },
          "DO" : [
            { "component_rules_flag_a_message" : { "message_to_flag" : [ "current-msg" ] } },
            { "drupal_message" : { "message" : "The message with ID [current-msg:mid] (created [current-msg:timestamp]) was marked as read." } }
          ]
        }
      }
    ]
  }
}

```

Some more details about the rule above:

* Rules Event: Drupal is initializing.
* Rules Conditions:

+ only for authenticated users.
    + check if the path being visited is `user/%/messages/unread` (adapt this path if you use another path).
* Rules Actions:

+ Create a list of unflagged messages.
    + Loop over each of the unflagged messages found, and flag those messages.

This rule also performs an extra "set message" action, so that you can see what it does if you want to try it in your own site (it shows a message (oeps!) for each message being flagged). Remove that message after QA-testing if you want.

**That's it, works like a charm!**
> 0 votes

---
Tags: 7, rules, flags, message-subscribe
---


title: Importing data from csv

text:
# Question
Title: Importing data from csv
Is there a way to do a partial data import, essentially updating existing data, without completely re-writing the entire dataset?

# Answer
> 0 votes
For Drupal 7 the Migrate module has an option to `track_changes` in the source content. Which will then perform an update to previously imported content should the source content be modified over time. This is achieved by Migrate creating a hash value across all imported fields and examining that hash value on subsequent imports.

# Answer
> 0 votes
For Drupal 8, import nodes for the content type from CSV file, try this module Content Import

---
Tags: importing-exporting
---


title: Extend the webform submission

text:
# Question
Title: Extend the webform submission
I am building a online purchasing system, and I use a Webform to gather clients' personal information.

A problem rises when I want to append some external data (which is not important enough to be included as a field in my registration form) to the webform *before the submission*.

What should I do? (I used `hook_webform_submission_presave()`, but it seems to me that it can only be used to change data, not adding additional data.)

Here's my presave hook; it works, but it's not serving my purpose.

```
function hook_webform_submission_presave($node, &$submission) {
  // Update some component's value before it is saved.
  if ($node->nid == 0) {
      $component_id = 1;
      $submission->data[$component_id]['value'][0] = 'foo';
  }
}

```

# Answer
You can't create a new value to non-existing field, since the data has no place to save to the database. Ideally you should create a hidden field for your data and modify it in your handler on `presave` event or use `hook_ENTITY_TYPE_presave`. If you have multiple values to add, serialize it or save into JSON and assign to the hidden value.

You can also use *Computed token* field where you can define and place your custom token (with any dynamic data) into value of that computed field which can fetch and store the data dynamically.

Related: Is there a webform way to store additional data on a submit handler?
> 1 votes

---
Tags: 7, webforms
---


# Question
Title: Services Views module no longer maintaines. What are my options?
My site relies heavily on the Services and Services Views modules. The Services Views module is no longer being maintained and it has a security vulnerability in it. Could someone help me either identify what the security vulnerability is. Or point me to a decent alternative module?

# Answer
> 1 votes
The Views Datasource's sub module called Views JSON is what I would recommend: https://www.drupal.org/project/views\_datasource

It's very similar to Services Views, except you just create a "JSON Data Document" Page Display for your View, and specify a Path at which the View can be accessed.

---
Tags: views, services, security
---


# Question
Title: How to assign a link or path to a button in drupalgap?
I put a navbar in the footer and placed some buttons. The display is good, but I cannot find a way to assign the link to a button like usual. The node/123 in the does not work.

```
/**
 * Implements hook_block_info().
 */
function footer_intrfc_block_info() {
  var blocks = {};
  blocks['footer_intrfc_block'] = {
    delta: 'footer_intrfc_block',
    module: 'footer_intrfc'
  };
  return blocks;
}

/**
 * Implements hook_block_view().
 */
function footer_intrfc_block_view(delta, region) {
  //var content = {};
  var content = '<div data-role="navbar">';
  content += '<ul>';
  content += '<li><a href="" data-icon="home">Home</a></li>';
  content += '<li><a href="node/1029" data-icon="action">Saved</a></li>';
  content += '<li><a href="node/969" data-icon="star">Sponsors</a></li>';
  content += '<li><a href="node/1021" data-icon="gear">Setup</a></li>';
  content += '</ul></div>';
  if (delta == 'footer_intrfc_block') {
    content['my_out'] = {
      markup: ''
    };
  }
  return content;
}

```

The link of node will show "Error Loading Page". I wonder where I can set my link by `path: 'node/123'` like in `setting.js`

I also tried:

```
content += '<li><a onclick="javascript:drupalgap_goto("node/1029");" data-icon="action">Saved</a></li>';

```

and

```
content += '<li><a href="javascript:drupalgap_goto("node/1029");" data-icon="action">Saved</a></li>';

```

but they do not work.

# Answer
Try this in your `hook_block_view()`:

```
var content = '<div data-role="navbar">';
content += theme('item_list', {
  items: [
    l('Home', '', { attributes: { 'data-icon': 'home' } }),
    l('Saved', 'node/1029', { attributes: { 'data-icon': 'action' } }),
    l('Sponsors', 'node/969', { attributes: { 'data-icon': 'star' } }),
    l('Setup', 'node/1021', { attributes: { 'data-icon': 'gear' } })
  ]
});
content += '</div>';
return content;

```

Whenever linking in DrupalGap, the key is to use the `l()` or `bl()` functions which will properly assemble a link or button link for you. Here's the docs page with more info: http://docs.drupalgap.org/7/Pages/Navigating\_Pages
> 1 votes

---
Tags: javascript
---


# Question
Title: Testing strategy, stub, mock, prophecy, what?
I have a helper class in my module that facilitates in creating Drupal user accounts *based* on some information returned from an external system.

What I would like to do is add tests for this class.

Here is the class in question:

```
<?php

namespace Drupal\netforum_auth\Netforum;

use Drupal\Core\Logger\LoggerChannelFactoryInterface;
use Drupal\user\UserInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Language\LanguageManagerInterface;
use Drupal\Component\Utility\Unicode;
use Drupal\user\Entity\User;

/**
 * Class NetforumAccountManager.
 *
 * @package Drupal\netforum_auth\Netforum
 */
class NetforumAccountManager implements NetforumAccountManagerInterface {

  /**
   * The entity type manager.
   *
   * @var \Drupal\Core\Language\LanguageManagerInterface
   */
  protected $entityTypeManager;

  /**
   * The language manager.
   *
   * @var \Drupal\Core\Language\LanguageManagerInterface
   */
  protected $languageManager;

  /**
   * The logger.
   *
   * @var \Drupal\Core\Logger\LoggerChannelFactoryInterface
   */
  protected $logger;

  /**
   * The Netforum client.
   *
   * @var \Drupal\netforum_auth\Netforum\NetforumClientInterface
   */
  protected $client;

  /**
   * Class constructor.
   */
  public function __construct(EntityTypeManagerInterface $entity_type_manager, LanguageManagerInterface $language_manager, LoggerChannelFactoryInterface $logger_channel_factory, NetforumClientInterface $client) {
    $this->entityTypeManager = $entity_type_manager;
    $this->languageManager = $language_manager;
    $this->logger = $logger_channel_factory;
    $this->client = $client;
  }

  /**
   * {@inheritdoc}
   */
  public function createUser(\stdClass $netforum_account) : int {
    $user = $this->entityTypeManager->getStorage('user')->create();
    $langcode = $this->languageManager->getCurrentLanguage()->getId();
    $email_address = $netforum_account->result->Customer->cst_eml_address_dn;
    $customer_key = $netforum_account->result->Customer->cst_key;
    $customer_number = $netforum_account->result->Customer->cst_recno;

    $parts = explode('@', $email_address);
    $drupal_username = $parts[0] . $customer_number;
    $password = user_password(15);

    $user->enforceIsNew();
    $user->setUsername($drupal_username);
    $user->setPassword($password);
    $user->setEmail($email_address);
    $user->set("init", $email_address);
    $user->set("langcode", $langcode);
    $user->set("preferred_langcode", $langcode);
    $user->set("preferred_admin_langcode", $langcode);
    $user->set("preferred_admin_langcode", $langcode);
    $user->set("field_netforum_customer_key", $customer_key);
    $user->set("field_netforum_customer_recno", $customer_number);
    $user->activate();
    $user->save();

    // Set the roles.
    $account = User::load($user->id());
    $this->updateUserRoles($account, $netforum_account);

    return $user->id();
  }

  /**
   * {@inheritdoc}
   */
  public function updateUser(UserInterface $account, \stdClass $netforum_account) {
    // @todo: This will be filled in later if they do any profile related stuff.

    // Update the roles.
    $this->updateUserRoles($account, $netforum_account);
  }

  /**
   * Wipe and rebuild a users roles to be in-sync with Netforum memberships.
   */
  public function updateUserRoles(UserInterface $account, $netforum_account) {
    $netforum_role = $netforum_account->result->Individual->ind_int_code;
    $membership_info = $this->getActiveMembershipsForCustomer($netforum_account);
    $member_types = $this->getActiveMemberTypesFromCustomerMembership($membership_info);

    // Remove previous roles, for security reasons.
    $previous_roles = $account->getRoles(TRUE);

    foreach ($previous_roles as $role) {
      // Don't remove Administrator if it was previously set.
      if ($role !== 'administrator') {
        $account->removeRole($role);
      }
    }

    $roles = [];

    // Staff is an actual user role, not a membership type
    if ($netforum_role == 'Staff') {
      $roles[] = 'content_editor';
    }

    foreach ($member_types as $role_name) {
      $roles[] = $this->mapToDrupalRole($role_name);
    }

    // At the least, we should assign a boilerplate role.
    if (empty($roles)) {
      $account->addRole('netforum_member');
    }

    foreach ($roles as $role) {
      $account->addRole($role);
    }

    $account->save();
  }

  /**
   * Maps netforum membership types to local Drupal roles.
   */
  public function mapToDrupalRole(string $membership_type) : string {
    switch (Unicode::strtoupper($membership_type)) {
      case 'CARRIER DIVISION':
        $role = 'carrier_division';
        break;

      case 'RAIL DIVISION':
        $role = 'rail_division';
        break;

      case 'SUPPLIER DIVISION':
        $role = 'supplier_division';
        break;

      case 'ASSOCIATE':
        $role = 'associate';
        break;

      default:
        $role = 'netforum_member';
        break;
    }

    return $role;
  }

  /**
   * Returns all membership information for a given netforum user.
   *
   * I really dislike this call because it returns just a string of XML instead
   * of the responses we are used to receiving. It is a custom SQL call done by
   * using ExecuteMethod, a unique API method in Netforum.
   */
  public function getActiveMembershipsForCustomer(\stdClass $netforum_account) {
    $customer_key = $netforum_account->result->Customer->cst_key;

    $arguments = [
      'serviceName' => 'GetActiveMembershipsForCustomer',
      'methodName' => 'GetActiveMemberships',
      'parameters' => [
        'Parameter' => [
          'Name' => 'cst_key',
          'Value' => $customer_key,
        ],
      ],
    ];

    $response = $this->client->request('ExecuteMethod', [$arguments]);

    $parts = explode('-', $customer_key);
    $last_segment = end($parts);

    if ($response->error) {
      $message = $response->result->Message . ' Customer key ending in: @key.';
      $this->logger->get('netforum_auth')->error($message, ['@key' => $last_segment]);
    }
    elseif (!$response->result) {
      $message = 'Customer key ending in: @key has no membership information.';
      $this->logger->get('netforum_auth')->info($message, ['@key' => $last_segment]);
    }
    else {
      // This entire result is returned as an xml string, convert it.
      $xml = simplexml_load_string($response->result->any);
      $json = json_encode($xml);
      $response->result = json_decode($json, TRUE);
    }

    return $response;
  }

  /**
   * Filters out active roles from the membership information.
   */
  public function getActiveMemberTypesFromCustomerMembership($membership_information) : array {
    $roles = [];

    if ($membership_information->result) {
      foreach ($membership_information->result['Membership'] as $membership) {
        if ($membership['MbrStatus'] == 'Active') {
          $roles[] = $membership['MbrType'];
        }
      }
    }

    return $roles;
  }

}

```

How can I approach testing this class? My first thought was I needed to mock the method that makes an API call and have it return an array like the real call would do (passed to `getActiveMemberTypesFromCustomerMembership`).

I can't quite figure out though how to do this in code. Here is where I started:

```
<?php

namespace Drupal\Tests\netforum_auth\Kernel;

use Drupal\netforum_auth\Netforum\NetforumAccountManager;
use Drupal\Tests\token\Kernel\KernelTestBase;
use org\bovigo\vfs\vfsStream;
use org\bovigo\vfs\visitor\vfsStreamStructureVisitor;

/**
 * Class UserCreateTest
 *
 * @package Drupal\Tests\netforum_auth\Kernel
 * @group netforum_auth
 */
class UserCreateTest extends KernelTestBase {

  /**
   * Modules to enable.
   *
   * @var array
   */
  public static $modules = ['system', 'user', 'netforum_auth'];

  protected function setUp() {
    parent::setUp();

    // create roles
  }

  public function testUserIsCreated() {
    $netforum_wsdl_response = new \stdClass();
    $netforum_wsdl_response->result = new \stdClass();
    $netforum_wsdl_response->result->Customer = new \stdClass();
    $netforum_wsdl_response->result->Customer->cst_eml_address_dn = 'zztesting@example.comzz';
    $netforum_wsdl_response->result->Customer->cst_key = '123-456-789';
    $netforum_wsdl_response->result->Customer->cst_recno = '123456';

    $result = new \stdClass();
    $result->response = [
      'Membership' => [
        0 => [
          'MbrStatus' => 'Active',
          'MbrType' => 'Associate'
        ]
      ]
    ];

    $prophecy = $this->prophesize(NetforumAccountManager::CLASS);
    $prophecy->getActiveMembershipsForCustomer($netforum_wsdl_response)->willReturn($result);
    $netforum_account_manager = $prophecy->reveal();

    $uid = $netforum_account_manager->createUser($netforum_wsdl_response);
    // check $uid is a User
    // check role(s)
  }

}

```

But I get this error:

```
Method call:
  - createUser(stdClass:00000000584be36000000000303910bf Object (
    'result' => stdClass:00000000584be19c00000000303910bf Object (
        'Customer' => stdClass:00000000584be05a00000000303910bf Object (
            'cst_eml_address_dn' => 'zztesting@example.comzz'
            'cst_key' => '123-456-789'
            'cst_recno' => '123456'
        )
    )
))
on Double\Drupal\iana_netforum_auth\Netforum\NetforumAccountManager\P1 was not expected, expected calls were:
  - getActiveMembershipsForCustomer(exact(stdClass:00000000584be36000000000303910bf Object (
    'result' => stdClass:00000000584be19c00000000303910bf Object (
        'Customer' => stdClass:00000000584be05a00000000303910bf Object (
            'cst_eml_address_dn' => 'zztesting@example.comzz'
            'cst_key' => '123-456-789'
            'cst_recno' => '123456'
        )
    )
)))

```

This is the first time I have tried this. Should the two `get` calls be moved out to a new class, and mock the one method? Then test the actual class here?

# Answer
Well, I wound up refactoring the class to decouple the dependency on the `$client` service and moved the API call in this class to an external class. I did not need any mocks and from there just tested my class with dummy data. The class I am testing only assumes now that a Drupal user object or response from a Netforum call is passed in, or both, making it testable (or, more easy to test) than before.

```
<?php

namespace Drupal\Tests\netforum_auth\Kernel;

use Drupal\Tests\token\Kernel\KernelTestBase;
use Drupal\field\Entity\FieldStorageConfig;
use Drupal\field\Entity\FieldConfig;
use Drupal\user\Entity\User;
use Drupal\simpletest\UserCreationTrait;

/**
 * Class NetformAccountManagerTest.
 *
 * @package Drupal\Tests\netforum_auth\Kernel
 * @group netforum_auth
 */
class NetformAccountManagerTest extends KernelTestBase {

  use UserCreationTrait {
    createRole as drupalCreateRole;
  }

  /**
   * Modules to enable.
   *
   * @var array
   */
  public static $modules = ['system', 'user', 'field', 'text', 'netforum_auth'];

  /**
   * The NetforumAccountManager service.
   *
   * @var \Drupal\netforum_auth\Netforum\NetforumAccountManager
   */
  protected $accountManager;

  /**
   * Holds a simluated NetforumClient response about an individual in Netforum.
   *
   * @var \stdClass
   */
  protected $dummy_account;

  /**
   * {@inheritdoc}
   */
  protected function setUp() {
    parent::setUp();

    $this->installSchema('system', 'sequences');
    $this->installEntitySchema('user');

    $this->drupalCreateRole([], 'associate', 'Associate');
    $this->drupalCreateRole([], 'member', 'Member');
    $this->drupalCreateRole([], 'content_editor', 'Content Editor');

    $field = FieldStorageConfig::create(array(
      'field_name' => 'field_netforum_customer_key',
      'entity_type' => 'user',
      'type' => 'text',
    ));

    $field->save();

    $field = FieldStorageConfig::create(array(
      'field_name' => 'field_netforum_customer_recno',
      'entity_type' => 'user',
      'type' => 'text',
    ));

    $field->save();

    FieldConfig::create([
      'field_name' => 'field_netforum_customer_key',
      'entity_type' => 'user',
      'label' => 'Customer Key',
      'bundle' => 'user',
    ])->save();

    FieldConfig::create([
      'field_name' => 'field_netforum_customer_recno',
      'entity_type' => 'user',
      'label' => 'Customer Number',
      'bundle' => 'user',
    ])->save();

    $this->accountManager = $this->container->get('netforum_auth.netforum_account_manager');

    $netforum_wsdl_response = new \stdClass();
    $netforum_wsdl_response->result = new \stdClass();
    $netforum_wsdl_response->result->Customer = new \stdClass();
    $netforum_wsdl_response->result->Individual = new \stdClass();
    $netforum_wsdl_response->result->Individual->ind_int_code = 'Staff';
    $netforum_wsdl_response->result->Customer->cst_eml_address_dn = 'zztesting@example.comzz';
    $netforum_wsdl_response->result->Customer->cst_key = '123-456-789';
    $netforum_wsdl_response->result->Customer->cst_recno = '123456';

    $netforum_wsdl_response->result->Membership = [
      0 => [
        'MbrStatus' => 'Active',
        'MbrType' => 'Associate',
      ],
      1 => [
        'MbrStatus' => 'Inactive',
        'MbrType' => 'At-Large Motor Carrier Division',
      ],
      2 => [
        'MbrStatus' => '',
        'MbrType' => 'At-Large Rail Division',
      ],
      3 => [
        'MbrStatus' => 'Active',
        'MbrType' => 'Member',
      ],
    ];

    $this->dummy_account = $netforum_wsdl_response;
  }

  /**
   * Test that a user is created with the correct roles.
   *
   * @covers \Drupal\netforum_auth\Netforum\NetforumAccountManager::createUser
   */
  public function testUserIsCreated() {
    $uid = $this->accountManager->createUser($this->dummy_account);
    $this->assertNotEquals(0, $uid);

    $account = User::load($uid);
    $roles = $account->getRoles(TRUE);

    // Our Drupal user should have 3 roles, not 2.
    $this->assertContains('associate', $roles);
    $this->assertContains('member', $roles);
    $this->assertContains('content_editor', $roles);
    $this->assertNotContains('administrator', $roles);
  }

  /**
   * Tests the user role mapping method.
   *
   * Unrecognized roles should be set as netforum_member.
   *
   * @covers \Drupal\netforum_auth\Netforum\NetforumAccountManager::mapToDrupalRole
   */
  public function testUserRoleMapping() {
    $role = $this->accountManager->mapToDrupalRole('associate');
    $this->assertEquals('associate', $role);

    $role = $this->accountManager->mapToDrupalRole('MEMBER');
    $this->assertEquals('member', $role);

    $role = $this->accountManager->mapToDrupalRole('AT-LARGE MoToR cARRIER DIVISIOn');
    $this->assertEquals('at_large_motor_division', $role);

    $role = $this->accountManager->mapToDrupalRole('DUMMY TYPE');
    $this->assertEquals('netforum_member', $role);

    $role = $this->accountManager->mapToDrupalRole('Staff');
    $this->assertNotEquals('administrator', $role);
  }

  /**
   * Tests that we get the correct types that we expect.
   *
   * @covers \Drupal\netforum_auth\Netforum\NetforumAccountManager::getMembershipTypes
   */
  public function testMembershipTypeParser() {
    $types = $this->accountManager->getMembershipTypes($this->dummy_account);
    $this->assertEquals($types, ['Associate', 'Member']);
  }

}

```

I'm not sure if this is 100% great approach, but my class and its couple of methods are now covered by tests. To supplement this test, I also want to write a behavior test with Behat to simulate a user actually logging in - the results should be exactly the same.

Would love to know more though about how others are testing their own services or classes.
> 1 votes

---
Tags: 8, testing
---


# Question
Title: Bootstrap Subtheme undefined variable error for custom node type template
I am using the Bootstrap theme, I created a subtheme and duplicated `page.tpl.php` into my subtheme: `/subtheme/templates/system/page.tpl.php`

I then duplicated `page.tpl.php` and renamed to `node--[mytype].tpl.php`. The template is registering but it is filled with "undefined variable" errors. The errors don't happen `/subtheme/templates/system/page.tpl.php` but happen when I add `node--[mytype].tpl.php` despite having the same code.

I've tried putting in `node--[mytype].tpl.php` in different directories including subtheme root and `/templates/` but errors persists.

# Answer
Duplicating node.tpl.php (instead of page.tpl.php) and putting it in /subtheme/templates/node/node--\[type\].tpl.php fixed my undefined variable error.
> 0 votes

---
Tags: 7, theming, bootstrap-theme
---


# Question
Title: How to add a heading at the top of node/add or node/edit?
In my `node/custom_content/edit` and/or `node/add/custom_content` page I want to place a heading at the top of the page as "*Create New My-Content*".

Seems simple enough, but I am unable to do so. How can this be achieved?

# Answer
If you mean to change the title of the page you can do this. This will make all node add form titles "Create new \[content type\]" instead of "Create \[content type\]". It doesn't change the edit form because it doesn't make sense to put "new" in the title there because it is not new content, you are editing existing content.

Create a new custom module that implement this:

```
/**
 * Implements hook_form_BASE_FORM_ID_alter().
 */
function MODULE_NAME_form_node_form_alter(&$form, &$form_state, $form_id) {
  // For the node add form.
  if (!$form['nid']['#value']) {
    // Add "new" to the page title.
    $node_types = node_type_get_names();
    drupal_set_title(t('Create new @type', array('@type' => $node_types[$form['#node']->type])));
  }
}

```
> 2 votes

# Answer
A possible solution to answer this question is to enable the Rules module, and create a custom rule that looks like so:

```
{ "rules_show_new_article_link" : {
    "LABEL" : "Show New Article link",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "node_insert" : [], "node_update" : [] },
    "IF" : [
      { "node_is_of_type" : { "node" : [ "node" ], "type" : { "value" : { "article" : "article" } } } }
    ],
    "DO" : [
      { "drupal_message" : { "message" : "Click \u003Ca href=\u0022[site:url]node\/add\/article\u0022\u003Ethis link\u003C\/a\u003E to add another article ..." } }
    ]
  }
}

```

Some details about this rule:

* **Rules Events**: After saving new content or After updating existing content.
* **Rules Condition**: Content is of type `article`.
* **Rules Action**: Show a message on the site, whereas the actual message content that will be shown is "Click this link to add another article ..." and with 'this link' being rendered as an hyperlink to relative path `node/add/article`.

If you have the Rules UI enabled, you can just import the above rule in your own site. Adapt content type `article` to `custom_content` (or whatever fits your needs).

With that, each time you edit or create a node of article, you'll get such message (with appropriate link) in the Drupal message area. Obviously, you could add any applicable rules logic to further improve this prototype (e.g. to only show this for selected user roles).

PS: this rule is my favorite sample to get started with the Rules module.
> 0 votes

---
Tags: 7, nodes
---


# Question
Title: Error: OAUTH2 SERVER LIBRARY Unavailable
I have a website in drupal version 8.3.3 and since I installed ***oauth2 server module***, I get the below error in *Admin -\> Reports -\> Status Report*

**The OAuth2 server library is required for the OAuth2 module to function. Download the library using composer, downoad it from GitHub or use composer manager.**

So I have added OAuth2 server library by running the below command

```
$ git clone --branch master https://github.com/bshaffer/oauth2-server-php.git

```

This command executed successfully and also the files are created in libraries directory. But still I get the same error

**Note:** I followed the instruction from https://www.drupal.org/node/1938218

# Answer
I encountered the same problem, being new to Drupal 8 development, and this project currently lacking documentation for its use with Drupal 8, probably because it is currently only available through a "dev" edition.

The solution I used was to add the two oauth2-server-php Composer dependencies in the "composer.json" file at the root of the Drupal folder, which are currently:

```
"require": {
    "bshaffer/oauth2-server-php": "~1.7",
    "bshaffer/oauth2-server-httpfoundation-bridge": "~1.1"
}

```

Then install them with Composer by executing "composer install".

You can reach the project issue where I got help there: https://www.drupal.org/node/2897289#comment-12202222
> 0 votes

---
Tags: theming, authentication-authorization
---


title: Inventory or Quantity field

text:
# Question
Title: Inventory or Quantity field
**TL;TR:** Like there is no module like this for D8, how can I create a plugin wich has two fields: one to reference content and onther one to store a number, so I can emulate an inventory.

Hi, I'm using Drupal 8. Is there any module that let me put just a simple number for a node reference? something like an inventory or quantity field.

I've checked for an inventory field on drupal.org but seems to be pretty outdated (drupal 5)

Like an example just image you are going to make an inventory of the animals and plants in a given area; so there is a content type for "animals" and there is a content type for plants (every one with it's own atributes)... and there is a content type "country". So when I'm creating a country I'll like to specify how many dogs, cats, mules, cows, pines, etc does it have. Note that the country has a field that references to the animal or plant node. Using D8, pointing me to an API that let me store and correlate the information can also help me.

# Answer
This solved my question: https://www.lullabot.com/articles/extending-a-field-type-in-drupal-8

It is an example of how to extend the reference field and also associate a quantity with the reference. It was what I was looking for.
> 0 votes

---
Tags: 8, entities, plugins
---


# Question
Title: reCaptcha does not display on modal window(colorbox) webform
I have a webform that I want to add a reCaptcha to. So far I've done everything properly, the webform will display a recaptcha box below the form when viewing the node form. I have a modal window webform (thats similar to an opt-in form), that uses ajax to grab the specific webform and display it as a block in the window. Now the issue is that the reCaptcha does not display below the form.

I've tried replacing the recaptcha with a math challenge captcha, and it would display properly on both the webform and modal window.

The good news is that the ajax webform shows an instance of the captcha when you look at the html.

```
<div class="captcha"><input type="hidden" name="captcha_sid" value="561">
<input type="hidden" name="captcha_token" value="4bbbf337ec22df5fe3befde6f601601d">
<input type="hidden" name="captcha_response" value="Google no captcha">

//g-recaptcha is where the captcha is supposed to be rendered, however it is empty
<div class="g-recaptcha" data-sitekey="6Ld1XSMUAAAAABJRpsnwwzlV7_yceyWERRWnCYgc" data-theme="light" data-type="image"></div></div>

```

I've been stuck on this issue for almost a week. Is there suggestions or approach that I should take?

# Answer
Fixed the issue, there was a patch on issue's forum on the Module page.

# 71 @ https://www.drupal.org/node/2493183
> 0 votes

---
Tags: 7, ajax, webforms, captcha
---


title: Render module block programmatically

text:
# Question
Title: Render module block programmatically
I know I can render my custom block programmatically with

```
$block = \Drupal\block_content\Entity\BlockContent::load(2);
$vars['contact_us_info_block']= \Drupal::entityTypeManager()->getViewBuilder('block_content')->view($block);
$vars['contact_us_info_block'] = drupal_render($vars['contact_us_info_block']);

```

Now I want to render SimpleNewsletter Block programmatically,I tried

```
$block_manager = \Drupal::service('plugin.manager.block');
$config = [];
$plugin_block =  $block_manager->createInstance('simplenewssubscription', $config);
$vars['newsletterblock'] = $plugin_block->build();

```

but faced with following message in output

```
This block is broken or missing. You may be missing content or you might need to enable the original module.

```

SimpleNewsletter module is enabled,**how can I render contributes modules block programmatically?**

# Answer
I render it with following snippets and work correctly

```
$block = \Drupal\block\Entity\Block::load('simplenewssubscription');
$block_content = \Drupal::entityTypeManager()
    ->getViewBuilder('block')
    ->view($block);
$vars['newsletterblock'] = $block_content;

```
> 1 votes

# Answer
Here is the example from Block Token module to render block based on its id:

```
/**
 * Renders the block.
 *
 * @param  string $bid
 *   Block Id.
 *
 * @return string
 *   Rendered block.
 */
function block_token_block_render($bid) {
  $block = \Drupal\block\Entity\Block::load($bid);
  $block_content = \Drupal::entityManager()
    ->getViewBuilder('block')
    ->view($block);
  return \Drupal::service('renderer')->renderRoot($block_content);
}

```
> 0 votes

---
Tags: theming, 8
---


# Question
Title: How to replace drupal-render-placeholder manually?
I've got the element with following plain string (result of some kind of side effect):

> `<drupal-render-placeholder callback="Drupal\block\BlockViewBuilder::lazyBuilder" arguments="0=myform&1=full&2" token="p8BOEzhVedaNVMwuFKbSbXYvHJtJev-99V8a_12Hv4A"></drupal-render-placeholder>`

Which method/function can I call to manually replace this render placeholder with relevant content?

My idea as a workaround is to do this:

```
/**
 * Implements template_preprocess_form_element
 */
function mytheme_preprocess_form_element(&$variables) {
  if ($variables['element']['#title'] == 'Specific Title') {
    $variables['element']['#value'] = REPLACE_PLACEHOLDER($variables['element']['#value']);
  }
}

```

Note that in `$variables['children']`, the placeholder looks in different format for some reason:

> `<input data-drupal-selector="edit-taps" type="hidden" name="myform" value="1:<drupal-render-placeholder callback="Drupal\block\BlockViewBuilder::lazyBuilder" arguments="0=myform&amp;1=full&amp;2" token="p8BOEzhVedaNVMwuFKbSbXYvHJtJev-99V8a_12Hv4A"></drupal-render-placeholder>:2" />`

# Answer
This is the workaround which worked for me:

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

/**
 * Implements template_preprocess_form_element
 */
function mytheme_preprocess_form_element(&$variables) {
  if ($variables['element']['#type'] == 'webform_computed_token') {
    $block = BlockViewBuilder::lazyBuilder('myform', 'full', 2);
    $block_content = render($block);
    $variables['children'] = Markup::create($block_content);
  }
}

```

I've used `$variables['children']`, since the final rendered content was in there (not in `$variables['element']`). Above code has hardcoded `lazyBuilder` method with the arguments based on the data which are included in `<drupal-render-placeholder>`, since reading plain text and parsing the attribute values only to read which callback to call with which arguments would be too complex (as I didn't find any straight functions to read these placeholder tags, however I've posted complete solution below).

The above solution is basically the dirty workaround for the mentioned side effect (currently unknown bug) as normally render placeholders should be part of the `#attached` element (see `createPlaceholder()` in `PlaceholderGenerator.php`).

---

Here is the complete workaround which it did work for me (placed in: `mytheme.theme`):

```
use Drupal\Component\Utility\Html;
use Drupal\Core\Render\Markup;
use Drupal\block\BlockViewBuilder;

/**
 * Implements template_preprocess_form_element
 */
function mytheme_preprocess_form_element(&$variables) {
  if ($variables['element']['#type'] == 'webform_computed_token') {
    // Dirty workaround for this bug: https://www.drupal.org/node/2899439;
    $dom = new DOMDocument();
    libxml_use_internal_errors(true); // Surpress the warnings for HTML load.
    $dom->loadHTML($variables['element']['#value'] ?: (string) $variables['children']);
    $placeholder = $dom->getElementsByTagName('drupal-render-placeholder');
    if (!empty($placeholder[0])) {
      $callback = $placeholder[0]->getAttribute('callback');
      $args = parse_str(Html::decodeEntities($placeholder[0]->getAttribute('arguments')), $args_arr);
      $element = call_user_func_array($callback, $args_arr);
      $content = render($element);
      $variables['children'] = Markup::create($content); // Replace the old markup.
    }
  }
}

```
> 0 votes

# Answer
You can't do this, at least not with the data you've shown in the question.

You need the placeholder attached to `#attached` to execute the replacement. When rendering normally this bubbles up to the page level. But this looks like early rendering in such a way that the metadata is lost, otherwise you wouldn't report the issue.

For a workaround, why you don't replace the value with the render element of the webform you intend to place here:

```
$variables['element']['#value'] = [
  '#type' => 'webform',
  '#webform' => 'myform',
  '#default_data' => [],
];

```

This could be the final solution, if you use a custom token pattern for replacement.
> 1 votes

# Answer
The result of `drupal-render-placeholder` tag inside final output isn't expected and this usually indicates the problem how the content is rendered.

So instead of replacing placeholder manually as in the other answer, rendering method should be fixed by using `renderer` service.

The common mistake is to use ~~`drupal_render($content)`~~ instead of `\Drupal::service('renderer')->renderRoot($block_content)`.

My issue was related to Block Token bug and example fix can be seen in this patch file.
> 0 votes

---
Tags: theming, 8, blocks
---


title: Render login Form

text:
# Question
Title: Render login Form
I would like to call the user login form in my theme but I can't.

In Drupal 7 I did this.

```
$elements = drupal_get_form("user_login");
$form = drupal_render($elements);
echo utf8_decode($form);

```

How I can do this with Drupal 8?

I tried this.

```
Drupal::formBuilder()->getForm(Drupal\user\Form\UserLoginForm::class)

```

How do I render this?

With the following code, I can show the login form, but I can't log in with it. What should I add to make it work?

```
$form = Drupal::formBuilder()->getForm(Drupal\user\Form\UserLoginForm::class) ;
$render = Drupal::service('renderer');
$render->renderPlain($form);

```

# Answer
The code seems to be working fine. If it doesn't work for some reason, make sure that there is nothing else in the theme or modules that might interfere with this.

Here's how to provide a rendered login form through preprocess function. (This code would go to `YOUR_THEME.theme` file.)

```
function YOUR_THEME_preprocess_page(&$variables) {
  // You will most likely want to show and render the form for anonymous users.
  $login_form = FALSE;
  if (\Drupal::currentUser()->isAnonymous()) {
    $login_form = \Drupal::formBuilder()->getForm(Drupal\user\Form\UserLoginForm::class);
  }
  $variables['login_form'] = $login_form;
}

```

Then in the page.html.twig template, you can render it (and use it) with the following code.

```
{{ login_form }}

```
> 9 votes

# Answer
You should use `\Drupal::service('renderer')->renderRoot()` instead of ~~`drupal_render()`~~ which is deprecated in Drupal 8, e.g.

```
$output = \Drupal::service('renderer')->renderRoot($form);

```
> 2 votes

# Answer
In D8 you create render Arrays in Controllers (extends Drupal\Core\Controller\ControllerBase). For your need you could do it like with the following code.

```
$fb = $this->formBuilder();
return $fb->getForm("Drupal\user\Form\UserLoginForm");

```
> 1 votes

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


# Question
Title: Is it possible to create a hierarchical exposed filter in views using the Data module?
I'm using Data module to adopt tables from the same DB as 'native' Drupal tables and Views module to present the data.

I added two dropdown exposed filters with Selective filter module. It takes all values from fields and puts them to the selective list. It works fine.

However I would like to configure my exposed filters the way that the second filter will show values according to the chosen value in the first one. E.g. if you choose a specific academic department in the first filter, the second one will offer you the list of this department's staff members.

Is it possible to achieve such a behavior? If so, do I need any extra modules (taxonomy?) or should I create a module myself?

# Answer
First Install Hierarchical Select Module for display taxonomy of parent/child relations then add that taxonomy as a field to your content type then add this field to your exposed filter. it's working..
> 0 votes

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


# Question
Title: Need clarification for "use this hook and some code" type of answers
Whenever the answer to a Drupal question, either here or on blogs and other articles, is to use a hook and then some example code is provided, what are the assumed steps from beginning to end for implementing this answer? These are likely left out to avoid redundancy but it's difficult to piece together the underlying, assumed foundation and skills.

Where does the given example code from many such answers to questions go? Is this essentially what building a module is? The concept of a hook is easy to understand and explained well here but how to use a specific hook to alter some piece of core to achieve something isn't clear.

For example, if the question is, "how do I change the text of such and such button" and the answer is "use hook `hook_such_and_such_blahdy_blah`" what does this actually mean?

Real world example: This blog about how to theme the comment block is great. But what is the author really saying to do when he says to just override the hook by copying the code from the API page and then alter the hook.

Resources I've checked out but don't mean anything without the missing foundation:

# Answer
> 2 votes
> TL;DR version: Most hooks\_something() go inside your custom module's .module, but not always. You can put alter hooks in your theme's template.php file for D7 or in .theme in D8.

There are several assumptions packed into those answers, and yeah they can be hard for people getting used to Drupal. Here are some assumptions cooked into those answers.

First, they assume you know have the tools and knowledge to write code for your project. Often people give those kinds of answers when asked a question where someone was looking for a module that already does what they are asking. Some of that is the nature of the community, and some of that is the nature of sites like this one.

Second, they assume you have a module or theme for custom code already started (or know how to start one). Lots of Drupal projects will have a module that is just there to provide a few needed hooks to handle an edge case.

Third, they assume you know when to use a module vs a theme for adding the hook. Some hooks really *need* to be in a module, some *should* be in a module, and some *should* be in a theme. But in the end that's is often use case specific (or in the case of agencies done to be consistent with seven sites already supported by the same team). Rarely do people give guidance which is the right choice.

Fourth, for some hooks they are assuming you know how to figure out how to get it called. Some Drupal 7 hooks (e.g. views) have a different pattern where you declare you have the hooks in your main `.module` file and then you define the hooks in their own file.

See also: Is it possible to define hook functions in template.php instead of the module?

---
Tags: hooks
---


# Question
Title: How to print anything in a twig template file
In drupal 7 we were able to resort to simple php functions in tpl.php files to load anything we wanted. Entities, blocks, view etc. This was really powerful for making really customisable blocks. In D7 we can use this php:

```
$block = block_load('views', 'block_name');
$output = drupal_render(_block_get_renderable_array(_block_render_blocks(array($block   ))));

```

When it comes to D8 I have read things about the getParameter but i'm coming up short on how to do it in a twig tpl.

For example, in a custom field in D8 I can get the node by using:

```
$node = \Drupal::routeMatch()->getParameter('node');

```

But how do I do this for a view on a page? And how would I do this in a twig.tpl in which you cannot write php?

I'm interested to see how people are tackling this in D8 or if I have the complete wrong method here.

# Answer
> 0 votes
> better practice is to do that in preprocess functions !

so, fe. in preprocess page, you can access the node (if existing) via the **$variables** array and so on ..., then you add your own variables for the twig template, like:

```
$variables['my_fancy_block'] = \Drupal::service('renderer')->renderRoot($whatever);

```

and access this like:

```
{{ my_fancy_block }}

```

# Answer
> 0 votes
To render a block in Twig template, you can use *Twig tweak* module for that, then you can use the following syntax:

```
  <dd>{{ drupal_block('myblock') }}</dd>

```

Related: How do I programmatically place a block?

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


# Question
Title: drupal_render() and formBuilder's getForm
What exactly is the best way to accomplish this? I can pass the `$form` object returned from `getForm` to `drupal_render()` and get the correct themed output fragment but the API docs say this function will be deprecated in D9 and to use the renderer service instead.

When I use:

```
\Drupal::service('renderer')->render($form)

```

I get

> You have requested a non-existent service "renderer". Did you mean one of these: "render\_html\_renderer", "html\_fragment\_renderer", "html\_page\_renderer"?

When I use:

```
\Drupal::service('render_html_renderer')->render($form)

```

I get a valid object with a protected `content()` method, which contains the string, but I can't seem to find any valid public functions to access this.

I can normally use the route builder to point to a form controller that I've created but, in this instance, I just want to pull an existing form, get the HTML content, and display it - hopefully as a variable in a preprocess function. I don't necessarily want to create a block, since I probably won't be reusing it.

What is the best way to do this? Keep using `drupal_render()` until D9? Can somebody point me in the right direction?

# Answer
> 6 votes
There are almost no reasons to manually call drupal\_render(), you can use/return render arrays almost anywhere, controllers, blocks and also in twig templates.

If you do `$variables['form'] = $your_form;`in preprocess, then `{{ form }}` in your template should just work.

# Answer
> 0 votes
I think should work if you do something like

```
$form = \Drupal::service('render_html_renderer')->render($form);
print $form->__toString();

```

# Answer
> -1 votes
Try using `renderRoot()` instead of `render()`, e.g.

```
\Drupal::service('renderer')->renderRoot($form)

```

> Renders final HTML given a structured array tree.

---
Tags: 8
---


# Question
Title: How many products can Drupal Commerce handle?
Are there any limitations on how many products Drupal Commerce can handle?

# Answer
This question isn't really answerable, since so much depends on how you're using that product data and what your product architecture is. For example, how complex are your product attributes, what is the catalog browsing experience like, etc. You'll do better using a Solr index for your product catalog navigation and search than Views. You may need to consider remote file storage for product images. Things like that can't really be answered in the *abstract*.

When doing load testing at millions of SKUs (yep, we've done that), the biggest limiting factor was throughput for automated updates. At that scale, you aren't going to have people sitting at a desk keeping product data up to date. It's going to come from external systems, and those systems may need to rapidly update broad swathes of the product catalog on a regular basis.

I see in your comments above you're dealing with 10s of thousands of products. You won't have any issues, but I still may look at using something other than Feeds (i.e. Migrate or a bespoke module) to keep your product data up to date.
> 0 votes

# Answer
Interesting question. The major limiting factor for any Drupal Installation is server resources. If you have unlimited budget, it's safe to say you can have unlimited everything. There are upper limits to the architecture, but it's probably a limitation of database structure, that can be avoided by using a different kind of database.

For Drupal Commerce, the biggest limiting factor in Drupal 7 is usually not number of products (one of the companies I've worked with in the past did some tests with millions of products, and it worked just fine), but it is number and frequency of orders. A really busy ecommerce site is dealing with thousands of orders per hour.

I've personally seen tuned Commerce installations that can handle that kind of traffic at peak times and not crash. It takes a very dedicated team to scale any resource like Drupal Commerce to such heights.
> 1 votes

---
Tags: 7, commerce
---


title: HTML output of whole page

text:
# Question
Title: HTML output of whole page
I am trying to generate html output of whole page and then pass it to response array.I am doing something like this:

```
  $page = array(
  '#theme' => 'html',
  '#page_object' => new HtmlPage(render($content)),
   );

```

`$content` is a render array and new HtmlPage creates a HtmlPage object from an existing page. I am passing `render($page)` to the response object, but I am getting error this error:

> LogicException: A stray `drupal_render()` invocation with `$is_root_call = TRUE` is causing bubbling of attached assets to break. in `Drupal\Core\Render\Renderer->doRender()` (line 377 of core\lib\Drupal\Core\Render\Renderer.php).

What should I do to make this correct? Thanks

# Answer
> 1 votes
Try using `renderer` service instead as ~~`rendeer`~~ and ~~`drupal_render()`~~ is deprecated, e.g.

```
\Drupal::service('renderer')->renderRoot($content);

```

> Renders final HTML given a structured array tree.

---
Tags: 8, theming
---


title: Pass raw html to #markup

text:
# Question
Title: Pass raw html to #markup
I have some html content, it comes from a external library so i can not change it, it has many `<span>` and `<div>` tags with attributes like: `<span style="color: #0000ff;">`, but when i use:

```
$render = array(
  '#markup' => $myhtmlcontent,
);

```

In a render array, Drupal strips the attributes, and it keeps just `<span>` without the styles.

So, how can I avoid Drupal changes what I pass as markup, which doesn't need any filter because the library makes it safe, or at last make it allow styles?

# Answer
Use inline template:

```
  return [
    '#type' => 'inline_template',
    '#template' => '{{ somecontent }}',
    '#context' => [
      'somecontent' => $somecontent
    ]
  ];

```

In your case without context, just straight up html.

You can also use the html\_tag element for things like script or link and so on.
> 35 votes

# Answer
In a render array, simply do this:

```
return [
  '#children' => $html,
];

```

EDIT: Alternatively use the method described by @nvahalik in the other answer, in combination with '#markup'. I think this is closer to the intended usage of the render API.

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

[..]
return [
  '#markup' => Markup::create($html),
];

```

E.g. if the `$html` was produced with PHP's `highlight_string()`, it will contain style attributes which would be removed with `#markup`. But `#children` preserves them.

## How to test this?

Go to devel/php (with devel module installed).

```
$elements = [
 ['#markup' => '<div style="font-weight: bold;">markup onionpowder</div>' . "\n"],
 ['#children' => '<div style="font-weight: bold;">children onionpowder</div>' . "\n"],
 ['#markup' => \Drupal\Core\Render\Markup::create('<div style="font-weight: bold;">safe markup onionpowder</div>' . "\n")],
];

var_export(drupal_render($elements)->__toString());

```

I personally get this output:

```
"""
'<div>markup onionpowder</div>\n
<div style="font-weight: bold;">children onionpowder</div>\n
<div style="font-weight: bold;">safe markup onionpowder</div>\n
'
"""

```

(The "onionpowder" allows to set conditional break points in the render functions)

But perhaps it depends on the Drupal version?

Also it can happen that this will be (perhaps unintentionally) processed again in a different point in the pipeline.

## Technical notes

See https://git.drupalcode.org/project/drupal/blob/8.8.x/core/lib/Drupal/Core/Render/Renderer.php#L184

The `'#markup'` is filtered in `->ensureMarkupIsSafe()`, which is called from within `->doRender()`. The same does not apply to `'#children'` in the version of Drupal I was using (It's a local test site, cannot update atm).
> 34 votes

# Answer
As documented in Render API overview, in Drupal 8 a `#markup` value is passed through `\Drupal\Component\Utility\Xss::filterAdmin()`, which strips known XSS vectors while allowing a permissive list of HTML tags that are not XSS vectors. You can use `#allowed_tags` to set the list of allowed tags, but that would not stop Drupal from stripping attributes (for example, the `style` attribute).

```
$output['audio_controller'] = array(
  '#markup' => '<audio src="//www.example.com/resources/sample.mp3" controls><p>Your browser does not support HTML5 audio tags.</p></audio>',
  '#allowed_tags' => ['audio'],
);

```

Since in your case you are passing complex HTML markup, you should use `#type` or `#theme`. In this case, `#type` seems a better solution.

You could also implement a new type, with a render element plugin, but if that is the only case where you need it, then implementing a render element plugin is probably excessive.
> 29 votes

# Answer
If you want to add plain Markup to render arrays, you can create it using \Drupal\Core\Render\Markup. This will allow you to put raw HTML into something. For instance, here's how it's used in the Permission Report module to put HTML into tables:

```
$rows[] = [
  [
    'data' => $this->l($meta['title'], new Url('permission_report.permission', ['user_permission' => $perm], $options)),
  ],
  ['data' => $users_having_role],
  ['data' => Markup::create(implode(', ', $display_roles))],
];

```
> 14 votes

---
Tags: theming, 8
---


title: Token get node NID

text:
# Question
Title: Token get node NID
Can anyone please tell me how to get the NID of a node from the 7.x-1.7 version of the Token module?

I haven't used Token in a long while until now when I'm simply trying to include the NID in the file directory path of an image field.

As the following screen shot shows, I have no token representing the NID (there used to be quite a lot of current node tokens):

Help, please!

# Answer
`[current-page:url:unaliased:args:value:1]` is the way to get the node ID from the URL with the token module. Source.

<sup>Glad it helped you out sisko. Cheers! Thank you. </sup>
> 6 votes

---
Tags: tokens
---


# Question
Title: Should a cache tag only render array for an otherwise empty block work?
I have a custom blocks that displays results based on an entity query. For some pages the correct result is blank, and I want to hide the block.

When a return an empty array from the block's `build()` method it appears to cache more or less forever.

If I return a render array that just contains `#cache` values will that get honored, or will the lack of content invalidate those tags some place another the way?

```
if (empty($relatedContent)) {
  return [
    '#cache' => [
      'contexts' => ['url'],
      'tags' => ['node_list'],
    ],
  ];
}

```

For what it's worth, I've been testing the idea and I'm running into issues, but it's not clear yet if that's related to this or some other problem.

# Answer
You are right about this, you need content (in form of a render element) for the cache metadata to be recognized. But you don't need to worry about this, because `BlockViewBuilder` detects an empty block and adds a markup render element with an empty string:

```
public static function preRender($build) {
    ...
    if ($content !== NULL && !Element::isEmpty($content)) {
      ...
    }
    else {
      // Abort rendering: render as the empty string and ensure this block is
      // render cached, so we can avoid the work of having to repeatedly
      // determine whether the block is empty. For instance, modifying or adding
      // entities could cause the block to no longer be empty.
      $build = [
        '#markup' => '',
        '#cache' => $build['#cache'],
      ];
      ...

```
> 1 votes

---
Tags: 8, blocks, caching
---


# Question
Title: Is there any procedure to exclude taxonomy vocabulary terms from views display
I am using **drupal7**. I created a view with nodes under **category(Taxonomy) Vehicle.**

It looks fine, I am able to output a good looking page with set of images, title,desc etc along with **tags(I mean vocabulary == Vehicle)..** Can any one guide me how to **exclude taxonomy name from displaying in view**.

Please help..

Thank you.

# Answer
you can use exclude display from view
> 1 votes

# Answer
I'm not totally clear on what you want to do, if you're excluding a whole set of tags, or just individual ones.

If you're excluding individual ones, you can add a filter for "Term Name" and choose "Is not" or "Does not contain" and put the text of the name you want to exclude.
> 0 votes

# Answer
If you are listing full node in view then you can use 'view mode'. For D7, you can try this contrib module. https://www.drupal.org/project/ds
> 0 votes

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


# Question
Title: Passive / light-weight / serializable translatables?
So.. in Drupal 8 we have several classes that implement `\Drupal\Core\TypedData\TranslatableInterface`, and we have `Drupal\Core\StringTranslation\TranslatableMarkup`.

Each of these classes contain references to services that will actually do the translation, making them heavy on e.g. `var_export()` or `serialize()`.

Is there a class to store an untranslated string plus replacements plus options, that does not contain these dependencies?

Maybe `\Drupal\Core\Annotation\Translation` does get close, but I think it is only meant for annotations.

# Answer
See https://www.drupal.org/node/2893029.

Ther isn't really a workaround until that is fixed.
> 1 votes

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


# Question
Title: Programmically create a content type with publishing options
I've been able to successfully create a content type on the install of my module by following Creating a custom content type in Drupal 8 in the drupal.org documentation, but I can't find a way to add the publishing options.

>

How should I add the publishing options when creating a content type?

# Answer
> 3 votes
You have to add a base field override to change the default value of `status`, `promote` and `sticky` for newly created nodes. For the first and second option the default value is predefined as TRUE and for the third option as FALSE in the base field definition of the entity type. See this example for `promote`:

*Drupal\node\Entity\Node::baseFieldDefinitions*

```
$fields['promote'] = BaseFieldDefinition::create('boolean')
  ->setLabel(t('Promoted to front page'))
  ->setRevisionable(TRUE)
  ->setTranslatable(TRUE)
  ->setDefaultValue(TRUE)
  ->setDisplayOptions('form', [
    'type' => 'boolean_checkbox',
    'settings' => [
      'display_label' => TRUE,
    ],
    'weight' => 15,
  ])
  ->setDisplayConfigurable('form', TRUE);

```

The base field override needs only to be present if you want to change this preset for a specific content type.

Example for the `status` field:

**foobar/config/install/core.base\_field\_override.node.car\_brand.status.yml**

```
# core.base_field_override.node.car_brand.status.yml
langcode: en
status: true
dependencies:
  config:
    - node.type.car_brand
id: node.car_brand.status
field_name: status
entity_type: node
bundle: car_brand
label: 'Publishing status'
description: 'A boolean indicating the published state.'
required: false
translatable: true
default_value:
  -
    value: 0
default_value_callback: ''
settings:
  on_label: 'On'
  off_label: 'Off'
field_type: boolean

```

You can override the fields `promote` and `sticky` the same way.

---

The same task in PHP:

```
$fields = \Drupal::service('entity_field.manager')->getFieldDefinitions('node', 'car_brand');
$fields['status']->getConfig('car_brand')
  ->setDefaultValue(FALSE)
  ->save();

```

The method BaseFieldDefinition::getConfig loads an existing base field override or creates one if none exists from the base field definition in the entity type.

Using the PHP code in an install hook is IMHO the better solution, because you only need to change the default value and don't need to repeat all other values.

---
Tags: 8, entities
---


# Question
Title: how to solve Notice: Undefined offset: 1?
I used the following function to alter menu (`hook_menu_alter()`)

```
function _term_account(){
  global $base_url;
  global $user;
  $account_id = custom_get_user_account_id();
  $tesr = explode('_', arg(3));
  if($tesr[1] == $account_id){
    return true;
 } else {
    return false;
 }
}

function custom_menu_alter(&$items) {
  // Works fine.. So every user has he's own and only vocabulary return true..
  $items['admin/structure/taxonomy/%taxonomy_vocabulary_machine_name/list']['access callback'] = '_term_account';
  }

```

In `/reports/dblog` I noticed that there's these repeated error

> Notice: Undefined offset: 1 in \_term\_account() (line 277 of ../public\_html/sites/all/modules/custom/custom.module).

# Answer
This line of code will split `arg(3)` into an array of strings using `_` as the delimiter.

```
  $tesr = explode('_', arg(3));

```

Assuming that in this case `arg(3)` is never empty, it is still possible that there are no underscores in `arg(3)`, in which case you will have an array of 1 item.

Since arrays are zero based, this will give you something like

```
Array
(
    [0] => 'somestring'
)

```

In that case, your next piece of code

```
  if ($tesr[1] == $account_id) {

```

will throw the `Undefined offset: 1` notice because there is no array element with the key `1`.

If you want to safely use $tesr\[1\] you have to do something like

```
  if (isset($tesr[1]) && $tesr[1] == $account_id) {

```

**Additional unsolicited feedback:**

* Don't name your module 'custom'. Name it something more descriptive of its purpose. If it has many distinct purposes split it into multiple modules. It will be easier to maintain in future if you can easily tell what different modules do.
* Always prefix your function names with the name of the module. `_term_account()` might clash with another module's function. Prefixing with your module's name helps avoid that.
* You have `global $base_url;` and `global $user;` but then you never use them.
* Consider using a variable name that is more descriptive than `$tesr`, so you can easily tell what it means if you come back to the code in future.
* Code is easier to work on if it uses consistent formatting standards. Check out Drupal's at https://www.drupal.org/docs/develop/standards
> 0 votes

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


# Question
Title: Rules not marking all registrations to complete when commerce order is complete
I am using the RedHen raiser profile which comes with Drupal Commerce and entity registration set up and ready to go. In my set up users can 'register for an race/run event' The process is they choose the number of 'tickets' they want. Based on this number entity registration shows that number of registration forms. User completes the registration forms, then hits the checkout process which tallies up the number of registrations for the order.

A single order can have multiple registrations.

I have a rule to mark all registrations to 'Complete' when the order is finished.

When I use the 'When an order is first paid in full' event only one registration from the order gets marked as complete.

When I use the 'Completing the checkout process' event all registrations are marked as complete.

From what I understand using 'Completing the checkout process' isn't safe because technically a user could get a failed credit card transaction and the completing the checkout process would return as true.

Below is the export of my rule using the completing the checkout process.

```
{ "commerce_registration_complete_upon_full_payment" : {
"LABEL" : "Set Registrations to Complete upon Full Payment",
"PLUGIN" : "reaction rule",
"OWNER" : "rules",
"TAGS" : [ "Commerce Registration" ],
"REQUIRES" : [ "commerce_registration", "commerce_checkout" ],
"ON" : { "commerce_checkout_complete" : [] },
"DO" : [
  { "commerce_registration_set_state" : {
      "commerce_order" : [ "commerce-order" ],
      "registration_state" : { "value" : { "complete" : "complete" } }
    }
  }
]}}

```

My question is: How can I mark all registrations in the order to complete when the order is truly complete?

# Answer
Have you experienced the issue with the failed card? I run an event website with entity registration and commerce and we process an average of 20 registrations a day and haven't had that problem yet.

But if you want to be certain you could utilize hook\_commerce\_checkout\_complete, look at the order payment details and check that the order has been marked paid successfully. If so, invoke the rule or use entity query to lookup all registrations related to the order\_id and mark them complete.
> 0 votes

---
Tags: commerce, rules
---


title: Database connection onto an module

text:
# Question
Title: Database connection onto an module
I created a module and I want to add a database connection for my module. In looking for an answer, I noticed the `getConnection()` method of the `Database` class.

I tried this code in a controller.

```
$connection = \Drupal\Core\Database\Database::getConnection('moduleunicef','password');

```

I added the following code in the setting.php file.

```
$databases['default']['default'] = array(
  'driver' => 'mysql',
  'database' => 'moduleunicef',
  'username' => 'theuser',
  'password' => 'password',
  'host' => 'localhost',
  'prefix' => '',
);

```

I get the following error message.

> Drupal\Core\Database\ConnectionNotDefinedException: The specified database connection is not defined: root in Drupal\Core\Database\Database::openConnection() (line 366 of core/lib/Drupal/Core/Database/Database.php).
>
> Drupal\Core\Database\Database::getConnection('moduleunicef', 'password')
> Drupal\unicef42\Controller\PbRouteController-\>index()
> call\_user\_func\_array(Array, Array)
> Drupal\Core\EventSubscriber\EarlyRenderingControllerWrapperSubscriber-\>Drupal\Core\EventSubscriber{closure}()
> Drupal\Core\Render\Renderer-\>executeInRenderContext(Object, Object)
> Drupal\Core\EventSubscriber\EarlyRenderingControllerWrapperSubscriber-\>wrapControllerExecutionInRenderContext(Array, Array)
> Drupal\Core\EventSubscriber\EarlyRenderingControllerWrapperSubscriber-\>Drupal\Core\EventSubscriber{closure}()
> call\_user\_func\_array(Object, Array)
> Symfony\Component\HttpKernel\HttpKernel-\>handleRaw(Object, 1)
> Symfony\Component\HttpKernel\HttpKernel-\>handle(Object, 1, 1)
> Drupal\Core\StackMiddleware\Session-\>handle(Object, 1, 1)
> Drupal\Core\StackMiddleware\KernelPreHandle-\>handle(Object, 1, 1)
> Drupal\page\_cache\StackMiddleware\PageCache-\>pass(Object, 1, 1)
> Drupal\page\_cache\StackMiddleware\PageCache-\>handle(Object, 1, 1)
> Drupal\Core\StackMiddleware\ReverseProxyMiddleware-\>handle(Object, 1, 1)
> Drupal\Core\StackMiddleware\NegotiationMiddleware-\>handle(Object, 1, 1)
> Stack\StackedHttpKernel-\>handle(Object, 1, 1)
> Drupal\Core\DrupalKernel-\>handle(Object)

I tried the following code and it works.

```
$connection = \Drupal::database();

```

What parameters do I need to pass to `Database::getConnection()`?

# Answer
> 1 votes
You can do something like this:

```
    $database_info = array(
        'host' => $host,
        'port' => $port,
        'database' => $dbname,
        'username' => $dbuser,
        'password' => $dbpass,
        'driver' => 'mysql'
    );

// Add connection info
    Database::addConnectionInfo('externaldb', 'default', $database_info);

// Test connection
    try {
        $connection = Database::getConnection('default', 'externaldb');
        $caught     = false;
        return array($caught, $connection);
    }
    catch (PDOException $e) {
        // Ups connection failed
        $connection = NULL;
        form_set_error('syncsae_config_host', t('Connection failed.'));

        $errornumber  = $e->getCode();
        $errormessage = $e->getMessage();

        drupal_set_message(t('Error: @errornum.', array(
            '@errornum' => $errornumber
        )), 'error');
        drupal_set_message(t('Error description: @errormes.', array(
            '@errormes' => $errormessage
        )), 'error');

        $caught = true;
        return array($caught, $connection);
    }

```

# Answer
> 2 votes
I'm using this code to change connection and query a database table.

In the settings.php file, add the following code.

```
databases['customer_db']['default'] = [
  'driver' => 'pgsql',
  'database' => 'drupal',
  'username' => 'drupal',
  'password' => 'drupal',
  'host' => 'xx.xx.xx.xx',
  'port' => '5432',
  'prefix' => '',
  'namespace' => 'Drupal\\Core\\Database\\Driver\\pgsql',
];

```

To query the database, use the following code.

```
$db = \Drupal\Core\Database\Database::getConnection('default', 'customer_db');
print_r($db->databaseType());
$query = $db->query("SELECT * FROM customer");

```

---
Tags: database
---


# Question
Title: Why is only one field saved when I use entity_metadata_wrapper()?
I'm using `entity_metadata_wrapper()` to access entityform fields in my module's form, including a field collection I will need to save to.

However, for some reasons, I can't fathom why only the last element in the field collection in my entityform is actually saved. I'm collecting the form data fine, and setting it fine (as reported back by `dsm()`), but the wrapper saves only the last value.

This is the code I am using.

```
function investment_lineitems_form_submit($form, &$form_state) {
  // The entityform ID is passed as URL argument.
  $entityform = array_pop(arg());
  // Fetch the specific entityform.
  $wrapper = entity_metadata_wrapper('entityform', $entityform);
  // Use this counter to read back the numbered fields in form.
  $collection_count = 0;

  foreach ($wrapper->field_inv_account_details as $field_collection_wrapper) {
    // Cycle through each line in the field collection.
    // Increment the counter on each loop; the first one is 1.
    $collection_count++;
    // Grab the value from the form field.
    $collection_item_value = $form_state['input']['edit_your_percent_amount_' . $collection_count];
    // Check we're getting the correct value. (We are.)
    dsm("collection item value: ". $collection_count ." = " . $collection_item_value);
    // Set the new value in the field collection field.
    $field_collection_wrapper->field_inv_your_percent_split_a->set($collection_item_value);
    // Check we've set the correct value. (We have.)
    dsm($field_collection_wrapper->field_inv_your_percent_split_a->value());
  }

  // The following should save all items in the field collection.
  // This should save the field collection, but only the last field
  // collection item is being written to the database.
  $field_collection_wrapper->save();

  drupal_set_message(t('The form has been submitted.'));
}

```

Why is only one field saved?

# Answer
The `$field_collection_wrapper->save();` command shouldn't be outside the `foreach` loop. That's why it's only catching the last item processed. Moving it inside the loop should solve the problem.
> 0 votes

---
Tags: entities
---


title: Product display on Commerce Kickstart 2

text:
# Question
Title: Product display on Commerce Kickstart 2
Trying to set up Kickstart2. On the Product display grid the word **From** appears before the price. I need to remove this but as yet can't find where it is in the code. Its in a span class of price\_prefix. Having searched the code I have found two files where it does appear but changing these and clearing the cache does not remove it. The files tried so far are commerce\_kickstart\_product.features.field\_instance.inc and commerce\_kickstart\_lite\_product.features.field\_instance.inc What I would like to happen is for my term reference used for that product to be shown after the price, so how do I then set term ref field\_weight to show up

# Answer
> 0 votes
Generally speaking, you can't just change code in random files and expect it to reflect in changes on the front end. It's not recommended from a maintenance standpoint assuredly, as you will lose your customizations on the next module or distribution upgrade anyways.

In this case, the "From" prefix is coming from the field display settings on the product variation types defined by Commerce Kickstart 2.x. For the "Node: Product List" view mode, Kickstart 2.x is using the "Price with Prefix / Suffix" display formatter provided by the Commerce Extra Price Formatters module. You can view the configuration in a Kickstart 2.x install using demo content at the following path:

> /admin/commerce/config/product-variation-types/bags-cases/display/node\_product\_list

To get rid of the prefix, you can either edit the settings for the display formatter there or change it completely to use the "Formatted amount" display formatter. That's the default display formatter in Drupal Commerce, and it will not have a prefix or suffix.

Once you make the change, though, keep in mind that the Commerce Kickstart Product feature is now overridden. If your deployment process includes a step that reverts all features, you will lose this configuration change. Saving your features updates is a topic for another thread, but it's going to be complicated by the fact that you'll need to override a feature defined by a distribution. If I were you, rather than depend on the default features modules provided by Kickstart 2.x, I'd learn how the distribution built things and build them yourself from scratch. If you can't do that, then just ensure that you avoid reverting features from here on out.

---
Tags: commerce
---


# Question
Title: How can I count visitor's views of specific block?
I know I can use Statistics module to get total views for specific node.

**But how can I count visitor's views of specific block?**

The block is not connected to some fixed path (or node) and the block can be displayed in any place of site.
I could not find any module for the task.
What hook would be better to use to count visitor's views of the block?

# Answer
> 0 votes
```
function mymodule_entity_view($entity, $type, $view_mode, $langcode) {

    if ($type == 'node' &&  $entity->nid == 17457) {
        $entity->field_counter['und']['0')]['value']++;
        node_save($entity);
    }

}

```

---
Tags: 7
---


title: REST access denied to vote

text:
# Question
Title: REST access denied to vote
I have enabled the following modules on the site: VotingApi, Like&DisLike, Rest, RestUI and other depending modules

I use POSTMAN as my client and write my GET and POST request from it.

I have Resource "Content" and "Vote" enabled with all methods, auth and format.

I have created a REST Export view of the content and vote.

When I try to GET and/or POST to create a content I was able to do it successfully.

But when I use POST to vote on the content, I get a 403 response. I have provided a correct credentials on it, with header same as content has.

In Drupal browser logs, it says:

```
Type    access denied
Date    Friday, June 30, 2017 - 07:12
User    Anonymous (not verified)
Location    http://example.com/entity/vote
Referrer
Message /entity/vote
Severity    Warning
Hostname    172.17.0.1

```

Here is my POST request:

```
{
    "type": [
        {
            "target_id": "like"
        }
    ],
    "entity_id": [
        {
            "target_id": 2
        }
    ],
    "value": [
        {
            "value": 1
        }
    ],
    "value_type": [
        {
            "value": "points"
        }
    ],
    "user_id": [
        {
            "target_id": 1
        }
    ]
}

```

# Answer
You probally haven't added permissions for anonymous user to do a GET/POST request to the given endpoint. Go to permissions, search for rest and enable "Access GET on \[rest resource\]" (Access GET on Node rest resource resource)
> 0 votes

---
Tags: users, rating
---


# Question
Title: My website's http header has weird information
So I have a Drupal website. Today I checked the http headers on its homepage and found the following value:

EXPIRES Sun, 19 Nov 1978 05:00:00 GMT

I did some google research and found it's the Drupal's founder's date or something. How does it effect my site if any and how do I change this or remove it if needed? Does it effect SEO ranking as well?

Thanks!

# Answer
It means you have no additional caching mechanism and the default Drupal caching will be used, several of my sites also return this header without any problem.

On other sites I use different mechanisms to control the caches, Memcache or Redis in addition with Authcache gives you quite a lot of additional control over the caches, but you'll need access to additional resources on the server.

Another aspect I've heard about is Varnish but I have no knowledge of using this myself.
> 1 votes

---
Tags: caching
---