# Question
Title: Programmatically get webform submissions of a specific nodes webform
In Drupal 8 there is no function webform\_get\_submissions() as of this writing.

Webforms can be attached to nodes. How to get all the submissions of a webform that belong to a specific node (e. g. node ID = 15):

webform\_get\_submissions\_by\_node\_id() ... is the wanted function.

There are similar questions here but the PHP code to get only the submissions which where created on one specific node is different. And for this there is still now answer to find.

# Answer
Thank you 4k4. Here is now the correct and full code for use in mytheme.theme file (we need the getData() function:

```
$storage = \Drupal::entityTypeManager()->getStorage('webform_submission');
$webform_submission = $storage->loadByProperties([
  'entity_type' => 'node',
  'entity_id' => $variables['node']->id(),
]);
$submission_data = array();
foreach ($webform_submission as $submission) {
  $submission_data[] = $submission->getData();
}

```
> 8 votes

# Answer
In the Drupal 8 version of Webform submissions are stored in an entity and you can retrieve them like any other entitiy, for example by using `loadByProperties()`:

```
$storage = \Drupal::entityTypeManager()->getStorage('webform_submission');
$submissions = $storage->loadByProperties([
  'entity_type' => 'node',
  'entity_id' => '123',
]);

```
> 4 votes

# Answer
All the current answers are correct but loading submissions by a webform, source entity, and/or account should a little easier, so I created Issue #2954515: Add WebformSubmissionStorage::loadByEntities method which does require you to have the fully loaded entities to load the related submissions.

```
$storage = \Drupal::entityTypeManager()->getStorage('webform_submission');
$webform_submissions = $storage->loadByEntities($webform, $node);

```
> 3 votes

# Answer
You can also make use of Drupal's `entityQuery()` for making advanced filters/conditions:

```
$query = \Drupal::entityQuery('webform_submission')
                ->condition('entity_type', 'node')
                ->condition('entity_id', 123, '='); // optional operator
$results = $query->execute();

```

Note that `$results` will only contains SID (submission id), you may need to load them via its entity loader:

```
\Drupal\webform\Entity\WebformSubmission::loadMultiple($results)

```
> 1 votes

---
Tags: 8, webforms
---


title: Create view without content

text:
# Question
Title: Create view without content
I would like to create a Home view (the principal page of the site) without any type of content like news. The problem is that when I create a view, I don't see any way to hide the content.

I have tried to put the number of items to 0, but this loads all contents. How can I create a home page without any content?

My Drupal version is 7

# Answer
> 0 votes
Instead of dealing with Views just copy the `page.tpl.php` file of your theme to `page--front.tpl.php` and do whatever you want with it. In particular you can comment out the `<?php print render($page['content']); ?>` and replace with any code you need.

---
Tags: 7, views
---


# Question
Title: Export selected view rows and selected columns to excel
I use VBO export module and Views Bulk Operations module to export my view results to CSV. This works fine. The user can also make a selection which rows to export.

Is there a solution to let the user also select which columns (which view fields) will be exported to CSV?

# Answer
To export just a particular column or number of particular columns you would change the view itself. To preserve the original one, just copy the view export only the column(s) you need and delete the temporary view.
> 0 votes

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


# Question
Title: Issue in taxonomy term with hyphen(-) in url drupal7
I have a taxonomy called free-choices.But the contents are not listed when hyphen(-) in the taxonomy name.The pages with taxonomy name without hyphen is listing contents.How to solve this issue?I checked this validation criteria .But this is not working.How to solve this issue?  How to solve this issue in the same views?

# Answer
> 0 votes
If you want a taxonomy term to be recognized wholly, then you definitely do not want to divide it with spaces, so uncheck the `Transform dashes in URL to spaces in term name filter values`.

Also check on the `Use path alias instead of internal path` option and set the correct path component. It shows set to 1, but most probably it's different component in the taxonomy path alias.

Additionally, try to use term ID instead of term name.

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


# Question
Title: what when displaying a variable with kint crashes?
I am trying to find the variable name for the content link in a view.

`{{ kint(content) }}` makes the page crash, probably because the variable is too big.

The same is true for the following code.

```
function my_theme_preprocess_field(&$variables, $hook) {
    var_dump($variables);
}

```

How can I find out what I am looking for?

# Answer
Usually D8 $variables contain way too much data, and browser struggle to render it for you. I strongly suggest to use xdebug or similar debugger, all modern IDEs support it. It makes developer's life much easier. However, there is a workaround without having xdebug configured:

```
function my_theme_preprocess_field(&$variables, $hook) {
    var_dump(array_keys($variables));
    // or better:
    kint(array_keys($variables));
    // or:
    dpm(array_keys($variables));
}

```

This will return you top-level keys, then you can drill down to the next level:

```
dpm(array_keys($variables['some_key']));

```

For objects use type casting:

```
dpm((array) array_keys($object));

```

Set Kint as Variables Dumper on /admin/config/development/devel (with Devel Kint module enabled) and you'll get nicely structured output.

In Twig templates you can use something like this:

```
{% for key, value in content %}
    {{ key }}
{% endfor %}

```

UPD: Valuable comment from Kevin for TWIG:

```
{{ kint(content|keys) }}

```
> 5 votes

---
Tags: 8, theming, debugging
---


# Question
Title: Relation between User field and current user
I have created a view for particular user role (i.e: Agent) that manage some user (for example, users with id: 1, 2, 3).

I've created a custom field for this user for associate this agent with some users.

It's possible create view who allow of this agent view, edit, ecc only content created by users who managed by him?

# Answer
You'd need to add a relationship in views to your custom field you created and then provide a default value of "User ID from logged in user"
> 0 votes

---
Tags: views, entities, users
---


title: What are the available hooks for views

text:
# Question
Title: What are the available hooks for views
I cannot find the list in the api documentation.

https://api.drupal.org/api/drupal/core%21modules%21views%21views.api.php/group/views\_hooks/8.5.x

Nor am I able to enter such functions in a theme when loading a page with a view.

# Answer
They're here

As always, only `*_alter` hooks and `hook_theme` can be implemented in a theme. Any other hook needs to be implemented in a module.
> 2 votes

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


title: Json api create comments

text:
# Question
Title: Json api create comments
I am using the *JSON API* module and I would like to create a comment. I was able to create nodes based on the documentation found here, but I can't figure out how to create comments.

How can I add a comment using that module? I managed to do it through the default REST API module.

# Answer
> 0 votes
It follows the same pattern in the **POST request with relationships** section of the docs you linked to.

* Your endpoint will be `/jsonapi/comment/$MY_COMMENT_TYPE`.
* Your data payload will need to contain both the `data` property (the comment's properties) and `relationships` property (which will contain the comment's author & the entity reference commented on). To get a more concrete example of your data payload, perform a `GET /jsonapi/comment/$MY_COMMENT_TYPE` to see examples of existing comments.

---
Tags: comments, 8
---


# Question
Title: redirect to prod url when creating content
I have a Drupal 7 development site that is a subdomain of the production site, eg. dev.prod.com, for example.

When ever I create a content type, new content, a new user, install a new module, etc on the development site it redirects to the production URL after the form is submitted. I don't have permission on production so I get "access denied". When I go back to the development site and refresh the browser, the content have been created. But this does not work for installing a module. The module is not installed. Obviously, this makes it impossible to work on dev.

I have reviewed .htaccess and settings.php for any rewrite rules that could be causing this but I have not found anything. $base\_url is set to the correct URL for the development server. I have cleared the cache many times.

Any suggestions?

# Answer
Looks like you need to check the value specified for `$base_url`, within the `settings.php` of your dev.prod.com site. Assign a value of (eg) `dev.prod.com` and see what happens then.
> 0 votes

---
Tags: 7, redirection
---


# Question
Title: Configuration variable inside a hook take always the default value in a PHPUnit test
I'm trying to create a Functional test for the dev version of the No Autocomplete module to test that if the configuration is set then an autocomplete attribute=off will be added to the password edit in the user login form.

```
<?php

namespace Drupal\Tests\no_autocomplete\Functional;

use Drupal\Tests\BrowserTestBase;

class FormTest extends BrowserTestBase {

  protected static $modules = ['no_autocomplete'];

  public function testUserLoginForm() {

    $account = $this->drupalCreateUser(['administer no_autocomplete']);
    $this->drupalLogin($account);

    $this->drupalGet('/admin/config/people/no_autocomplete');

    $edit = [
      'no_autocomplete_login_form' => 1,
    ];
    $this->drupalPostForm(NULL, $edit, 'op');

    $this->drupalLogout();
    $this->drupalGet('/user/login');

    $this->assertSession()->elementAttributeContains('css', '#edit-pass', 'autocomplete', 'off');
  }

}

```

So basically I'm trying to test this hook after that the configuration is set:

```
/**
 * Implements hook_form_FORM_ID_alter().
 *
 * Turn off autocomplete on key forms.
 */
function no_autocomplete_form_user_login_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  // Add to the user_login.
  if (\Drupal::service('config.factory')->get('no_autocomplete.settings')->get('no_autocomplete_login_form')) {
    $form['pass']['#attributes']['autocomplete'] = 'off';
  }
}

```

The problem is that the module works as expected, but when I run the test this line inside the hook:

```
\Drupal::service('config.factory')->get('no_autocomplete.settings')->get('no_autocomplete_login_form')

```

Always return FALSE, because this is the default configuration value that comes in the no\_autocomplete.settings file, if I change the value from FALSE to 5, the 5 is returned. But when I check the value of the config in the test it assert correct with TRUE, inside the test the value is TRUE but inside the hook the value is FALSE (or whatever the default value of the variable is) I check the value in the test with the following lines:

```
$config_factory = $this->container->get('config.factory');

$no_autocomplete_login_form = $config_factory->get('no_autocomplete.settings')->get('no_autocomplete_login_form');

$this->assertSession()->assert($no_autocomplete_login_form == TRUE, t('The default configuration value for no_autocomplete_login_form should be TRUE.'));

$this->assertSession()->elementAttributeContains('css', '#edit-pass', 'autocomplete', 'off');
  }

}

```

So, the configuration variable have TRUE as value, but inside the hook the value is always FALSE, so the autocomplete=off attribute is never added to the form element en the test fail.

I'm trying to read in the wrong way the variable inside the hook or I'm missing something here?

***EDIT:*** It seems a cache problem, if I clean the cache inside the hooks the test is OK, but the only problem is that I really don't need to clean the cache for made the module works.

```
/**
 * Implements hook_form_FORM_ID_alter().
 *
 * Turn off autocomplete on key forms.
 */
function no_autocomplete_form_user_login_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  // Add to the user_login.
  drupal_flush_all_caches();
  if (\Drupal::service('config.factory')->get('no_autocomplete.settings')->get('no_autocomplete_login_form')) {
    $form['pass']['#attributes']['autocomplete'] = 'off';
  }
}

```

So I don't know now if this is a Drupal or PHPUnit issue. Any ideas?

# Answer
I found an answer that solve this problem, but I think that maybe there are other answer to this.

After some ideas from @tim.plunkett on slack:

> as i see it: with render caching, changing the config value will not alter the form

and

> the tl;dr is that any conditionals in render-related code need cache contexts

I made the test work with this code:

```
/**
 * Implements hook_form_FORM_ID_alter().
 *
 * Turn off autocomplete on key forms.
 */
function no_autocomplete_form_user_login_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  // Adding cache tags.
  $form['#cache']['tags'] = ['config:no_autocomplete.settings'];

  // Add to the user_login.
  if (\Drupal::service('config.factory')->get('no_autocomplete.settings')->get('no_autocomplete_login_form')) {
    $form['pass']['#attributes']['autocomplete'] = 'off';
  }
}

```

This is the simplest way that I was found because in this case the config object only have one variable and each time that the config is changed is because this variable has changed, so in this case I think that the use of the cache tags is fine.

But I'm still trying to made works the code with a custom cache contexts. But I don't have luck for the moment.
> 0 votes

---
Tags: 8, hooks, testing, configuration
---


# Question
Title: How can I override template_preprocess_file_link function?
I want to print **file size** near file link in file-link.html.twig template. To do so I need something like {{ filesize }} variable avaiable in template.

I tried to override template\_preprocess\_file\_link() with an override function in mytheme.theme like mytheme\_preprocess\_file\_link() but I get this error:

```
The website encountered an unexpected error. Please try again later.
Error: Class 'File' not found in tofacile_preprocess_file_link() (line 12 of themes/custom/mytheme/mytheme.theme)

```

It seems like a class missing... should I add "use Drupal\File\SomethingXXX" declaration??

Thanks

This is my code:

```
<?php

/**
 * @file
 * Functions to support theming in the Tofacile theme.
 */

function tofacile_preprocess_file_link(&$variables){
  $file = $variables['file'];
  $options = [];
  $file_entity = $file instanceof File ? $file : File::load($file->fid);

  // @todo Wrap in file_url_transform_relative(). This is currently
  // impossible. As a work-around, we currently add the 'url.site' cache context
  // to ensure different file URLs are generated for different sites in a
  // multisite setup, including HTTP and HTTPS versions of the same site.
  // Fix in https://www.drupal.org/node/2646744.
  $url = file_create_url($file_entity
    ->getFileUri());
  $variables['#cache']['contexts'][] = 'url.site';
  $mime_type = $file
    ->getMimeType();

  // Set options as per anchor format described at
  // http://microformats.org/wiki/file-format-examples
  $options['attributes']['type'] = $mime_type . '; length=' . $file
      ->getSize();

  // Use the description as the link text if available.
  if (empty($variables['description'])) {
    $link_text = $file_entity
      ->getFilename();
  }
  else {
    $link_text = $variables['description'];
    $options['attributes']['title'] = $file_entity
      ->getFilename();
  }

  // Classes to add to the file field for icons.
  $classes = [
    'file',
    // Add a specific class for each and every mime type.
    'file--mime-' . strtr($mime_type, [
      '/' => '-',
      '.' => '-',
    ]),
    // Add a more general class for groups of well known MIME types.
    'file--' . file_icon_class($mime_type),
  ];

  // Set file classes to the options array.
  $variables['attributes'] = new Attribute($variables['attributes']);
  $variables['attributes']
    ->addClass($classes);
  $variables['link'] = \Drupal::l($link_text, Url::fromUri($url, $options));
}

```

# Answer
Yes, seems you need to add:

```
use Drupal\file\Entity\File;

```

to the begin of your mytheme.theme file. You can also do something like:

```
$file_entity = $file instanceof \Drupal\file\Entity\File ? $file :
\Drupal\file\Entity\File::load($file->fid);

```

And you will have the same problem with `Attribute` and `Url`. You need to import the classes with the complet namespace in your file. https://secure.php.net/manual/en/language.namespaces.importing.php
> 0 votes

---
Tags: theming, files
---


# Question
Title: One exposed filter with different values in one view
I've searched a lot for this one with no luck. My problem is the following:

I have an exposed filter of brands (adidas, nike, etc). It is displayed as a block on the home page. while entering the brand and click apply, it displays a page containing two content types mall and store.

the store content type contains a term reference field brand. As for the mall content type, it contains entity reference stores with term reference field brand in them.

If i add a relationship in the views for the referenced entity and enable the relationship on the exposed filter field brand, it will display the mall content type only. if i remove the relationship it will display the store content type only.

How can I have one exposed filter block to display both the malls and the stores?

I appreciate any help given.

I'm using drupal 7.

# Answer
> 0 votes
you can use views autocomplete filters, add all fields you wish in the view, including the ones with a relationship (can be: contentypes, commerce products and commerce line itmes with propper relationships), then on add an exposed filter choose: **Global: Combine fields filter**, and on filter settings select all fields you wish to filter on, like the image below. This wokrs on D7 & D8. Enjoy.

---
Tags: 7, commerce, views
---


title: Drupal 8 load term by substring

text:
# Question
Title: Drupal 8 load term by substring
Drupal 8 has term method loadproperties which works for custom fields; however, how can I use it (or can I use it) to load by substrings. For example if I have a field: field\_full\_name and I want to load all terms that start with a string "David\*" is this possible ... if not how?

Thanks ~

# Answer
> 1 votes
You can use the SQL operator `LIKE` in an entity query and append the wildcard `%` to the string:

```
$result = \Drupal::entityQuery('taxonomy_term')
  ->condition('name', 'david%', 'LIKE')
  ->condition('vid', 'tags')
  ->execute();

$terms = \Drupal::entityTypeManager()
  ->getStorage('taxonomy_term')
  ->loadMultiple($result);

```

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


title: Menu translation tab how-to?

text:
# Question
Title: Menu translation tab how-to?
I have a menu in the original language English. Spanish is active in admin/config/regional/language . Custom menu link is active in admin/config/regional/content-language . I now have a Translation tab in admin/structure/menu/manage/mymenu/translate. I click Add in the Spanish row, change the label and Description (only Description is sufficient). Then what? How do I add menu items to the now supposedly created Spanish version? I tried several things but could not figure out where this new (empty?) Spanish menu is? It would be logical and consistent when now an "Add link" button would also appear in admin/structure/menu/manage/mymenu/translate/es/edit like in admin/structure/menu/manage/mymenu.

What is missing is some simple help text right in the forms that guide our thoughts in the right direction. For instance what is the purpose of the "Menu language" select box? Is that to change the language of the whole menu? But wasn't the language fixed already at creation (the default language)? I could not find a decent explanation so I resort to the help of somebody who managed to got it working.

# Answer
So far you've translated only the menu configuration consisting of *Label* and *Description*. The menu language select box is for the original language of the menu, in your case English.

The translation of menu links works independently by translating the menu links themselves, which is content translation and works the same as for nodes. You see a *Translate* tab when you click on *Edit* for a menu link in the main screen of the menu (after you've enabled content translation for custom menu links in *admin/config/regional/content-language* as you've already done).

The menu items are the same for all languages. If you want to have a different set of menu links for each language then you have to use separate menus.
> 1 votes

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


# Question
Title: D7 - Commerce Stock - Track products in different unit (e.g. grams?)
I'm using Commerce Stock to track the amount of product stock we're currently carrying. That said, Commerce Stock only seems to let me track product in increments of 1? Is it possible for me to change the unit stock is tracked in? For example, grams? **E.g.** If my user purchases 10 grams, it should subtract 10 from the total 100 grams in stock.

# Answer
One way of achieving this is to let Commerce Stock behave in its usual way, but to override the output on user interface, which should be pretty easy using the right hook. In other words, the custom code could just multiple stock quantity by 10 and, for example, instead of 1 output 10. So total 10 items would become 100 instead, if one item purchased then it would subtract just 1 on backend to output the remaining 9, but your function would just output 90 instead.
> 0 votes

---
Tags: 7, commerce
---


# Question
Title: How do I delete an orphaned paragraph node?
I have a paragraph node which seems to have gone rogue, since it does exist (I found it doing a search using Search API), but it does not appear as content, so I cannot delete it from the user interface.

How can I properly remove it?

# Answer
If you are not afraid to do it programmatically, you could use this code to load and delete the paragraph:

```
$entity = \Drupal::entityTypeManager()->getStorage('paragraph')->load($paragraph_id);
if ($entity) $entity->delete();

```
> 6 votes

# Answer
In Drupal 8, you can still use `entity_delete_multiple()`, but it is marked as deprecated and it is going to be removed from Drupal 9.

It makes easy to remove those entities using Drush, for example, with the following code.

```
drush php-eval 'entity_delete_multiple("paragraph", [$id]);'

```

Even using code that works on Drupal 9, you would delete those entities in a single command line.

```
drush php-eval '$storage_handler = \Drupal::entityTypeManager()->getStorage($entity_type); $entities = $storage_handler->loadMultiple([$id]); $storage_handler->delete($entities);'

```

Replace `$id` with the ID of the entity you are going to delete. You can also delete multiple entities at once replacing `[$id]` with an array of IDs.
> 9 votes

# Answer
This is actually caused by the bug Removed paragraph entities are not deleted from database. When that gets fixed, this problem will stop getting worse (bloating our databases).

To remove all of this no-longer-relevant data in a clean standard way, we need to get a solution to \[META\] Remove obsolete composite entities from existing storage (garbage collection).

Rather than coming up with workarounds as suggested in other answers, patches for either (or both) of these issues would solve the issue permanently.
> 6 votes

---
Tags: 8, paragraphs
---


# Question
Title: How to identify item_selector for Migrate API JSON imports
Trying to import articles from an external JSON feed of "members" with a structure like this:

```
{
   "status":"OK",
   "results":[
      {
         "num_results": 10,
         "offset": 0,
         "articles": [
              {
                 "id": "1",
                 "title": "First article",
...

```

And I haven't been able to isolate the correct values to use for item\_selector to get it to point to the array of "articles":

```
source:
  plugin: url
  data_fetcher_plugin: http
  data_parser_plugin: json
  urls: http://example.com/eample.json
  item_selector: /results/members/

```

The error I continually get in the console is:

> \[error\] Could not retrieve source count from import\_your node: Passed variable is not an array or object

Would be grateful for an explanation of exactly how item\_selector is defined or a pointer to documentation for the same.

# Answer
Think I have a solution, posting here in case it helps others. I tried to find a solution using xpath by using JSON browser like http://jsonpathfinder.com/ which gave me a path like this to find a field:

> results\[0\].members\[0\].id

The source JSON is coming in as an array but it doesn't appear that the way migrate\_plus is handling selectors (splitting on the '/' symbol) is able to handle an xpath array designation, which was flagged in this issue https://www.drupal.org/node/2883803.

To get around this, I thought it would be easier if I could just change the source JSON to fit what migrate\_tools can handle so I setup a simple router on my site:

```
import.my_wrapper:
  path: '/json/wrapper/my.json'
  defaults:
    _controller: '\Drupal\import\Controller\WrapperController::MyWrapper'
  requirements:
    _permission: 'access content'

```

Then built out the controller to use Guzzle to pull down my source URL normally and then flatten it so that migrate\_tools can handle it:

```
  private function PrepJSONData($data) {
    $data_array = json_decode($data);
    $data_array = $data_array->results[0];
    $data = json_encode($data_array, JSON_UNESCAPED_SLASHES);
    return $data;
  }

```

I then updated my fetcher in my migrate yaml files to point to the route I had defined on my local site:

```
  plugin: url
  data_fetcher_plugin: http
  data_parser_plugin: json
  urls: https://example/json/wrapper/my.json

```

Leaving this question open in case anyone else can propose a more efficient approach.
> 0 votes

---
Tags: 8, migrations
---


# Question
Title: SSH authentication failed, please provide another key- Acquia
Team,

I'm trying to Clone my Cloud website and use it in Dev desktop.

I have generated 4096 keygen and add public key in Acquia Cloud.

I am using Latest Acquia Dev Desktop on Windows 10.

I am getting below error-

> Blockquote SSH authentication failed, please provide another key- Acquia Blockquote

Anyone facing similar issue?

Thanks, SS

# Answer
I had this problem too with Dev Desktop 2.
It was my first time trying to pull an Acquia cloud site to local.
I generated a key, added my public key to my Acquia profile, but still kept getting Authentication errors.

What fixed it for me was...
SSH into the server (little square next to the SSH path in dev desktop), then just close it.
I was then able to pull the cloud site to my local machine.
> 4 votes

# Answer
Same issue resolved by using https://docs.acquia.com/dev-desktop/troubleshooting

SSH key error

If, when you synchronize a website between Acquia Dev Desktop and Acquia Cloud, you experience an SSH key error, you may be able to resolve it by doing the following:

* In Acquia Dev Desktop, click Acquia Dev Desktop \> Preferences.
* On the Settings \> General tab, click Remove local websites cloned from Acquia Cloud, and then click OK.
* Click the + button and select Add Acquia Cloud websites.
> 2 votes

---
Tags: acquia-dev-desktop
---


# Question
Title: How to add Open Graph Tags in Custom Module detail page?
For Node I already used https://www.drupal.org/project/metatag

For my custom module's detail page would like to add Open Graph tags for FB share.

So in **my\_test.module**

```
function template_preprocess_my_detail_page(&$variables) {

  $items = $variables['item'];

  $title =  $items->title;

  $og_title = [
        '#tag' => 'meta',
        '#attributes' => [
          'property' => 'og:title',
          'content' => $title,
        ],
      ];

  $variables['page']['#attached']['html_head'][] = [$og_title, 'og_title'];
}

```

Above one suppose to work but **NOT WORKING**.

```
function MY_MODULE_page_attachments_alter(array &$page) {

  $og_title = [
        '#tag' => 'meta',
        '#attributes' => [
          'property' => 'og:title',
          'content' => '',
        ],
      ];

  $page['#attached']['html_head'][] = [$og_title, 'og_title'];
}

```

Above one is working, But I'm not able to get Page Variables. How will I get `$variables` in above function?

This one called in all pages of module, but I want to call only on detail page as mentioned in `proprocess` function

# Answer
> 0 votes
I think that you need this.

```
    /**
 * Alter the metatags for pages that are not of content entities.
 *
 * @param array $metatags
 *   The special metatags to be added to the page.
 * @param array $context
 *   The context, containing the entity used for token replacements.
 */
function hook_metatags_alter(array &$metatags, array $context) {
  // Exclude metatags on frontpage.
  if (\Drupal::service('path.matcher')->isFrontPage()) {
    $metatags = NULL;
  }
}

```

# Answer
> 0 votes
Got the solution

So in **my\_test.module**

```
function template_preprocess_my_detail_page(&$variables) {

  $items = $variables['item'];

  $title =  $items->title;

  $og_title = [
        '#tag' => 'meta',
        '#attributes' => [
          'property' => 'og:title',
          'content' => $title,
        ],
      ];

  $variables['#attached']['html_head'][] = [$og_title, 'og_title'];
}

```

Change from

```
$variables['page']['#attached']['html_head'][] = [$og_title, 'og_title'];

```

to

```
$variables['#attached']['html_head'][] = [$og_title, 'og_title'];

```

---
Tags: 8
---


# Question
Title: Redirect form out of modal window after submit
I have a form within a Colorbox Modal window which successfully submits using the \_submit handler. I then successfully redirect the form to another page (which pre-loads a few fields on another form) using `drupal_goto()`. The problem I am having is that redirect stays in the Colorbox Modal window. I need to somehow close the modal window and transfer the url of the new form to the parent window. I can get this to work with a jquery function of

```
$(#my_form_id).submit(function (){
   parent.window.location="/user/register";
});

```

The problem with this issue is that the function calls when my form is submitted while disregarding anything that happens in the submission handler. So what ends up happening is I get the new page/form without the pre-loaded values until I refresh the page.

Do you have any thought or idea?

# Answer
I would suggest using #ajax to submit the form and then allow the response to close the modal and go somewhere else. For example, here's a submit button that runs a function on click instead of submitting the form and reloading the page:

```
$form['submit'] = array(
  '#prefix' => '<div id="super-cool-wrapper"></div>',
  '#type' => 'button',
  '#value' => 'Submit',
  '#ajax' => array(
    'callback' => 'my_super_cool_ajax_callback',
    'wrapper' => 'super-cool-wrapper',
    'method' => 'replace',
  ),
);

```

And then in your callback function:

```
function my_super_cool_ajax_callback($form, $form_state) {
  // Do what you normally would with the form submission.
  return '<script type="text/javascript">
    parent.window.location="some/where";
  </script>';
}

```

Now you can process the form as needed and return a response that simply redirects the user.
> 1 votes

# Answer
Ctools have nice tools for such thinks, when you read the help file (after installing Advanced help, you can acheive this (and more :) out of the box.

very simple example code for the menu callback that prints the modal :

```
function mymodule_showmodal($js) {
ctools_include('modal');
ctools_include('ajax');

$form_state = array(
    'ajax' => true,
  );
$commands = ctools_modal_form_wrapper('modform',$form_state);
if ($form_state['executed']) {
  $commands = array(ctools_modal_command_dismiss());
}
print ajax_render($commands);
exit();
}

```

dont forget to put \['rebuild'\] = true somewhere ...
> 0 votes

# Answer
Just had the same problem, here's how I got around it.

First I add a trigger in the $GLOBAL array like this:

```
function my_module_node_presave($node){
  if ($node->type == 'product'){
    $GLOBALS['redirect_parent'] = 'product_list';
  }
}

```

Then I add this nice event which gets triggered after the node has been saved

```
function my_module_drupal_goto_alter(){
  if (@$GLOBALS['redirect_parent']!=''){
    die('<script type="text/javascript">parent.window.location="/'.$GLOBALS['redirect_parent'].'";</script>');
    $GLOBALS['redirect_parent']='';
  }
}

```

It's not the most elegant solution, but it works...
> 0 votes

# Answer
I have also similar problem with drual modal form. After user registration and forgot password I have to send it on thanks page. Create tpl file and make registration link using below code.

```
<?php
echo l('Sign up here', 'user/register', array('query'=>array('destination'=>'thanks')));
?>

```

Create tpl file and make forgot password link using below code.

```
<?php
print l('Forgot Your Password?', 'user/password', array('query'=>array('destination'=>'thanks')));
?>

```
> 0 votes

# Answer
for redirecting you can pass inside

```
function() {
  window.location.replace ="url";
}

```
> -1 votes

---
Tags: javascript, forms
---


# Question
Title: Why isn't the image added in the block settings shown in the front end?
When I try to add a background image in *Bootstrap block settings* (the settings added by the BB Animation Module) Drupal uploads it, but the image doesn't appear on the front end.

Any help about this?

# Answer
I applied a patch for this module. This got disturbed due to the media module update.

At line no 300 in bb\_animation.module.I changed the code

from

```
$file = file_load($background_image['fid']);

```

To

```
$background_image_data_type = gettype($background_image);
switch ($background_image_data_type) {
        case 'array':
            $file = file_load($background_image['fid']);
            break;
        case 'string':
            $file = file_load($background_image);
            break;
    }

```
> 0 votes

---
Tags: blocks
---


# Question
Title: Variable passed into a preprocess function has incorrect data or or an unexpected format
I wanted to change some of the forum’s topic's preprocessing. So I copied `template_preprocess_forums()` into a custom module (*myModule*), and renamed the function `myModule_preprocess_forums()`.

I get an error that a method cannot be used on a string, `$topic`. I inspected. When the code is looping through the array `$variables['topics']`, it expects each array item to be an object. However, in `$variables['topics']` there are items that are strings and arrays and no topic objects.

To debug, I inspected `$variables['topics']` in the Forums module, but all the items are objects, as expected.

Why would the values passed to `myModule_preprocess_forums()` differ from what `template_preprocess_forums()` implemented by the Forums module gets?

# Answer
It happens because `template_preprocess_forums()`, which is executed before any `hook_preprocess_forums()` implementation, overrides `$variables['topics']` with the render array for its table.

It would have been better to put the render array in a different array value. As you notice from the function code, starting from Drupal 8.6.x, the original value of `$variables['topics']` is available in `$variables['topics_original']`.

```
  $variables['topics_original'] = $variables['topics'];
  $variables['topics'] = $table;
  $variables['topics_pager'] = [
    '#type' => 'pager',
  ];

```
> 0 votes

---
Tags: theming, hooks
---


# Question
Title: How to debug the evaluate() function of a custom Block Condition Plugin
I'm implementing a custom block visibility condition plugin and am unable to figure out my bugs in the conditional logic, because I can't get a `dpm`, `var_dump`, or `debug` call to work inside the `evaluate()` function.

I've setup a block using the condition plugin, and when i visit any URL, I'm not seeing any debug information. (Obviously, i've cleared caches, and have the relevant and necessary "development" configurations setup in `settings.local.php` to disable caching.

Here is my custom Condition plugin, the relevant part is the `evaluate()` part.

```
<?php

namespace Drupal\mymodule\Plugin\Condition;

use Drupal\Core\Condition\ConditionPluginBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * Provides an 'Entity type' condition.
 *
 * Note that this condition does not work in node_preview and possibly in
 * node_revision contexts without the patch on core issue:
 * https://www.drupal.org/i/2890758
 *
 * @Condition(
 *   id = "entity_type",
 *   label = @Translation("Entity type"),
 * )
 */
class EntityType extends ConditionPluginBase implements ContainerFactoryPluginInterface {

  /**
   * An array of plugin definitions (empty array if no definitions were found). Keys are plugin IDs.
   *
   * @var mixed[]
   */
  protected $entityTypeDefinitions;

  /**
   * Creates a new EntityType instance.
   *
   * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
   *   The entity type manager.
   * @param array $configuration
   *   The plugin configuration, i.e. an array with configuration values keyed
   *   by configuration option name. The special key 'context' may be used to
   *   initialize the defined contexts by setting it to an array of context
   *   values keyed by context names.
   * @param string $plugin_id
   *   The plugin_id for the plugin instance.
   * @param mixed $plugin_definition
   *   The plugin implementation definition.
   */
  public function __construct(EntityTypeManagerInterface $entity_type_manager, array $configuration, $plugin_id, $plugin_definition) {
    parent::__construct($configuration, $plugin_id, $plugin_definition);
    $this->entityTypeDefinitions = $entity_type_manager->getDefinitions();
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
    return new static(
      $container->get('entity_type.manager'),
      $configuration,
      $plugin_id,
      $plugin_definition
    );
  }

  /**
   * {@inheritdoc}
   */
  public function buildConfigurationForm(array $form, FormStateInterface $form_state) {
    foreach ($this->entityTypeDefinitions as $type) {
      $options[$type->id()] = $type->getLabel();
    }

    $form['types'] = [
      '#title' => $this->pluginDefinition['label'],
      '#type' => 'checkboxes',
      '#options' => $options,
      '#default_value' => $this->configuration['types'],
    ];
    return parent::buildConfigurationForm($form, $form_state);
  }

  /**
   * {@inheritdoc}
   */
  public function submitConfigurationForm(array &$form, FormStateInterface $form_state) {
    $this->configuration['types'] = array_filter($form_state->getValue('types'));
    parent::submitConfigurationForm($form, $form_state);
  }

  /**
   * {@inheritdoc}
   */
  public function defaultConfiguration() {
    return ['types' => []] + parent::defaultConfiguration();
  }

  /**
   * {@inheritdoc}
   */
  public function evaluate() {
    if (empty($this->configuration['types']) && !$this->isNegated()) {
      return TRUE;
    }

    foreach ($this->configuration['types'] as $type) {
      if ($entity = $this->getContextValue($type)) {
        var_dump("found $type entity in context");
        return TRUE;
      }
      elseif($entity_id = \Drupal::routeMatch()->getParameter($type)) {
        var_dump("found $type entity in route parameter");
        return TRUE;
      }
      else {
        var_dump("couldn't find $type entity in context or route parameter");
      }
    }
    return FALSE;
  }

  /**
   * {@inheritdoc}
   */
  public function summary() {
    $types = $this->configuration['types'];
    if (empty($types)) {
      return;
    }

    foreach ($this->entityTypeDefinitions as $type) {
      if (in_array($type->id(), $types)) {
        $labels[] = $type->getLabel();
      }
    }

    if (count($labels) > 1) {
      $last = array_pop($labels);
      $labels = implode(', ', $labels);

      if (!empty($this->configuration['negate'])) {
        return $this->t('Entity type is not @types or @last', array('@types' => $labels, '@last' => $last));
      }
      return $this->t('Entity type is @types or @last', array('@types' => $labels, '@last' => $last));
    }
    $label = reset($labels);

    if (!empty($this->configuration['negate'])) {
      return $this->t('Entity type is not @type', array('@type' => $label));
    }
    return $this->t('Entity type is @type', array('@type' => $label));
  }

  /**
   * {@inheritdoc}
   */
  public function getCacheContexts() {
    $contexts = parent::getCacheContexts();
    $contexts[] = 'url';
    return $contexts;
  }

}

```

# Answer
> 1 votes
When you debug this with xdebug you see that the line

```
if ($entity = $this->getContextValue($type)) {

```

throws a `ContextException(sprintf("The %s context is not a valid context.", $name));` and so the code stops before any debug message is printed out.

You don't need to check for a context if you don't indent to implement one for each entity type. A basic version of the plugin should work with a check for the route parameter alone:

```
  public function evaluate() {
    if (empty($this->configuration['types']) && !$this->isNegated()) {
      return TRUE;
    }
    foreach ($this->configuration['types'] as $type) {
      if ($entity_id = \Drupal::routeMatch()->getParameter($type)) {
        return TRUE;
      }
    }
    return FALSE;
  }

```

Because `ContextException` errors thrown in a custom ConditionPluginBase `evaluate()` function are caught upstream, you'd need to add a `try {} catch () {}` clause to properly debug this function.

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


title: Drupal Commerce - Retrieve cart value

text:
# Question
Title: Drupal Commerce - Retrieve cart value
I'm trying to create a popup notification on a route that shows the current cart value (subtotal) and notifies users to add $X.XX to receive free shipping.

I have extended a route to add new functionality but I'm unsure whether a hook or service would be best/appropriate. I can't seem to find any documentation on cart value--I can see some functions for retrieving quantity of items and seemingly could calculate the price by retrieving the prices for each individual item but research isn't bringing up much.

I see information regarding **Order Totals** but one would seemingly have to finish the order process in order to retrieve that data. I'm trying to grab cart value when a user goes to the `/cart` page.

I'm not asking for anything specific, just a pointer in the right direction. Thank you.

# Answer
> 0 votes
If you know the store id and order type then

```
$store_id = 1;
$order_type = 'default';
$cart_manager = \Drupal::service('commerce_cart.cart_manager');
$cart_provider = \Drupal::service('commerce_cart.cart_provider');
$entity_manager = \Drupal::entityManager();
$store = $entity_manager->getStorage('commerce_store')->load($store_id);
$cart = $cart_provider->getCart($order_type, $store);
$cart->get('total_price')->getValue()[0]['number'];

```

---
Tags: commerce
---


# Question
Title: Button that changes form field value based on other field values (D8)
I made a simple form with two input fields and a button. The button is supposed to enter the sum of the two input fields in a third field. I want the value in the third field to be editable by the user. I've tried to change the default\_value with an ajax callback, but that doesn't work. I can change all other field properties though (description, placeholder, title, ...), but not default\_value. I also tried changing the value through form\_state -\> setValue() in a custom validate function that I attached to the button. But form\_state seems to be reset to the initial value upon form rebuild.

This is my code:

```
  class calculatorForm extends FormBase {

  public function getFormId() {
    return 'calculator_example';
  }

  public function buildForm(array $form, FormStateInterface $form_state) {
    $form['#prefix'] = '<div id="calculator-form-wrapper">';
    $form['#suffix'] = '</div>';

    $form['number1'] = array(
      '#type' => 'textfield',
      '#weight' => 0,
      '#title' => $this->t('number 1'),
    );

    $form['number2'] = array(
      '#type' => 'textfield',
      '#weight' => 1,
      '#title' => $this->t('number 2'),
    );

    $form['button_sum'] = array(
      '#type' => 'button',
      '#name' => 'sum',
      '#value' => t('+'),
      '#weight' => 2,
    );

    $form['sum'] = array(
      '#title' => $this->t('sum'),
      '#type' => 'textfield',
      '#weight' => 3,
    );

    // attempt with validation function
    $form['button_sum']['#element_validate'] = array([$this,'calculator_example_custom_validate']);

    // attempt with ajax callback
    $form['button_sum']['#ajax'] = array(
      'callback' => [$this,'sumValues_ajax_callback'], //'sumValues_ajax_callback',
      'event' => 'click',
      'wrapper' => 'calculator-form-wrapper',
      );

    $form['sum']['#description'] = t('calculated sum');
    return $form;
  }

  function sumValues_ajax_callback(array &$form, FormStateInterface $form_state)  {
    $n1 = $form_state->getValue('number1');
    $n2 = $form_state->getValue('number2');
    $sum = $n1 + $n2;
    $form['sum']['#placeholder'] = $sum;
    $form['sum']['#default_value'] = $sum;
    return $form;
  }

  function calculator_example_custom_validate($element, &$form_state, $form) {
    $n1 = $form_state->getValue('number1');
    $n2 = $form_state->getValue('number2');
    $sum = $n1 + $n2;
    $form_state->setValue('sum' , $sum);
    drupal_set_message($this-> t('sum is '). $sum);
    $form_state->setRebuild('true');
  }

  public function validateForm(array &$form, FormStateInterface $form_state) {  }

  public function submitForm(array &$form, FormStateInterface $form_state) {  }

}

```

Does anyone know why $sum doesn't appear as a value in the 'sum' field? What am I doing wrong?

Thanks a lot!!

# Answer
> 1 votes
I found the solution myself. In case someone else stumbles upon this: In the ajax callback you need to change #value instead of #default\_value.

So this callback works:

```
function sumValues_ajax_callback(array &$form, FormStateInterface $form_state)  {
   $n1 = $form_state->getValue('number1');
   $n2 = $form_state->getValue('number2');
   $sum = $n1 + $n2;
   $form['sum']['#placeholder'] = $sum;
   $form['sum']['#value'] = $sum;
   return $form;
}

```

---
Tags: 8, forms, ajax
---


# Question
Title: Is it possible to individually update each module using update.php?
I am trying to update the reCAPTCHA module (which is installed on sites/all/modules) in Drupal 7. I could see other 3 modules which have pending updates. Is it possible to individually update each module using update.php?

# Answer
You can't update single module using "update.php". You can update single module if you installed drush.

List all available modules (except core) with below command.

> drush pm-list --type=module --no-core --status=enabled

Update specified module only.

> drush up 'module-name'

or

> drush pm-update --no-core "module\_name"
> 0 votes

# Answer
Refer https://www.drupal.org/docs/user\_guide/en/security-update-module.html to update single module using Drush and inbuilt functionality.

If you are using composer then run below command.

```
    composer update drupal/<module_name> --with-dependencies

```
> 0 votes

---
Tags: updating
---


# Question
Title: Add custom submission buttons to navigate through different wizard pages
I need to navigate the user through different pages of a multistep webform. I have added additional submit button to the webform using following code.

```
function mymodule_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
if($form_id == 'mywebform_id') {
    $form['actions']['submit_button_step_1'] = array(
      '#type' => 'submit',
      '#value' => t('Go to Step 1'),
      '#submit' => array('custom_navigation'),
    );
    $form['actions']['submit_button_step_2'] = array(
      '#type' => 'submit',
      '#value' => t('Go to Step 2'),
      '#submit' => array('custom_navigation'),
    );
}
}

```

But now How could I navigate the user to the pages based on user clicks on which button?

I found this in community website. But not able to understand where should I put this code in my custom module.

How to programmatically skip pages in wizard forms

# Answer
> 0 votes
I used another more durty way. I just hide pages which must be skipped

```
function my_module_webform_submission_form_alter(array &$form, FormStateInterface $form_state, $form_id)
{
  if (!isset($form['#webform_id']) || $form['#webform_id'] != 'my_form') {
    return;
  }

  $pages = &$form_state->get('pages');

  if (some_statement) {
    $pages['skipped_page_name']['#access'] = FALSE;
  }
}

```

but it works only in forward direction. And if user clicks "previous page" it may cause unexpected behaviour. So you also need "show" pages again on each step:

```
$pages = &$form_state->get('pages');
foreach ($pages as &$page) {
  $page['#access'] = TRUE;
}

```

---
Tags: 8, webforms
---


# Question
Title: Modify Override the Views Filter Criteria Programaticly
I have the following view being called in my code with views\_get\_view() and I then try to modify the filter called **usershare** to admin instead of the default that I have set in my view. But it doesn't seem to override my view output. What am I doing wrong here? I noticed that some examples use **pre\_execute()** and some just use **excute()**. I'm not sure if that has anything to do with it.

```
      $view2 = views_get_view('flag_lists_user_lists_public', FALSE);
      $view2->set_display('default');

$view2->display_handler->display->display_options['filters']['usershare']['value'] = 'admin';

      $view2->pre_execute();
      $output .= $view2->render();

```

# Answer
> 0 votes
You can use hook\_form\_views\_exposed\_form\_alter() :

```
/**
 * Implements hook_form_views_exposed_form_alter().
 */
function MY_MODULE_form_views_exposed_form_alter(&$form, &$form_state) {
  if($form['#id'] == 'flag_lists_user_lists_public') {
    $form['usershare']['#value'] = 'admin';
  }
}

```

---
Tags: 7, views
---


# Question
Title: How can I copy some content from one site to another site?
I have two sites i'm working on (one in D8 8.4.5, the other in 8.5.0).
I'd like to "copy" some elements from one to the other.
For example, some nodes or some menus (with their links, of course) or some users.

How do I do that?

With configuration sync and database tables export/import?

# Answer
> 2 votes
You'll need to use Drupal Core's migration module with Drupal 8 migration (source).

> This is an Migrate source to import Data from a Drupal 8 site.

If you're not familiar with creating custom migrations, you'll need to read up on that. Also read the README file.

---
Tags: 8
---


# Question
Title: Delete all users and there content apart from user 1
I have been asked to help look after a Drupal site that was created by a third party. This site has lots of users (~13,000) and for each user lots of items of content was created.

I want to clean the database from users and content to improve performance. When a user try to log into the site via an ID a user account is created, a web service is called and the correct content is recreated. My next job is to create some cron tasks to keep the data controllable going forward.

I want a way to delete all the users apart from user id 1. I looked at VBO but every now and again it will stop running and I have to start again (it has never completed).

I have created a drush command which calls the following:

```
function delete_users_batch_delete() {
  drush_print('Deleting Users');
  $uids = delete_users_get_uids();
  $count = count($uids);

  $temp = 0;
  foreach ($uids as $uid) {
    $temp++;
    user_delete($uid);
    if ($temp % 25 == 0) {
      drush_print('deleted ' . $temp . ' from ' . $count);
    }
  }
  drush_print('All users deleted');
}

function delete_users_get_uids() {
  $result = db_query('SELECT u.uid FROM {users} u WHERE u.uid > 1');
  $uids = $result->fetchCol();
  return $uids;
}

```

However this is running very slow on my local machine. What would be the best way to delete everything quickly.

If I had started the project myself I would just run my install script which would set up a new instance of the site with it configured correctly. Sadly I don't have this and just one big database dump.

# Answer
> 5 votes
You can use Views Bulk Operations (VBO) module...

Above module allows to execute bulk operations on nodes, users, comments; it also permits to apply the selected operation to all the nodes, users, or comments using the Batch API. The batch API allows forms processing to be spread out over several page requests, thus ensuring that the processing does not get interrupted because of a PHP timeout, while allowing the user to receive feedback on the progress of the ongoing operations.

There is a setting in the View's VBO options to enable a select all button that select all items across all users and unselect admin.

# Answer
> 2 votes
You can do this with Devel's Devel Generate submodule. Go to **Generate users**, set the number of users to generate to 0 and tick the **Delete all users (except user id 1) before generating new users** option, then click on the *Generate* button.

# Answer
> 1 votes
There is user\_delete\_multiple(array $uids) function just for mass deletion. So **do not loop on your own**, let the Drupal do it.

> Delete multiple user accounts.
>
> # Parameters
>
> * $uids: An array of user IDs.

Note that it might not be *much* faster as it still needs to loop for hooks invocation.

Also, array with 13000 entries may be a bit big for `->condition('uid', $uids, 'IN')` call, I would suggest to use some kind of batch processing and split whole list to chunks somewhere between 100 and 1000 users per chunk, depending on your configuration (calculations are hard, easier to test).

# Answer
> 1 votes
With the `devel_generate` module which is a submodule of the great Devel module you could also use Drush to do that.

Please backup your DB in advance ;)

### Delete ALL content.

```
drush genc --kill 0 0

```

### Delete all articles.

```
drush genc --kill --types=article 0 0

```

### Delete all users except uid 1.

```
drush genu --kill 0

```

---

For `genu` with `--kill` that's a hard coded condition in the query: `->condition('uid', 1, '>')` to not delete uid 1.

---
Tags: 7, users, performance
---


title: aegir migration did not update database

text:
# Question
Title: aegir migration did not update database
I am working with aegir 3 (hostmaster-7.x-3.130). After migration of Drupal website from an older platform (drupal version 8.3.7) to a newer version (drupal 8.5.0). Website is sucessfully verified after migration (all drupal modules are updatet as expected). No Error or Warning. Task queue turns green.

However, I figure out that database (as well as drupal entity) updates did not run during the migration, so I have to run "drush updb" and "drush entup" manuelly after the aegir migration.

How can I get aegir-migration automatically updating the database (entity) etc.?

Many thanks and regards

Tom

# Answer
> 0 votes
These operations should be running automatically so there's nothing for you to do; this is clearly a bug. Let's continue the discussion in the bug report at Aegir migration did not update database. Hopefully we can track down the problem over there.

---
Tags: migrations, aegir
---


# Question
Title: How do I share data from a hook to a service/controller?
I'm trying to implement a shopping cart feature that requires retrieving the data (total value of cart) from a Commerce order. The problem is that this is only possible with a hook. But how am I supposed to pass this data from the hook to a service/controller? I can't find any documentation on where the return value is sent from a hook and if it exists, it's certainly not placed in a very easy to access place since I've been searching for a few days now.

Trying to implement this hook:

```
function commerce_cart_order_load($uid = 0) {
  // Retrieve the order ID for the specified user's current shopping cart.
  $order_id = commerce_cart_order_id($uid);

  // If a valid cart order ID exists for the user, return it now.
  if (!empty($order_id)) {
    return commerce_order_load($order_id);
  }

  return FALSE;
}

```

This should give me an assoc array (or some other data object) of the different elements of an order. Not sure how I can pass this around or access it anywhere.

# Answer
For those who may have the same troubles as I do...

I am trying to set a message in Drupal to show on `/cart` the main cart page. The data is seemingly already there but it was a bit trickier to actually pull the data into code compared to the Views module just simply inserting a field.

So I can't say I fully understand how this is working. But my site uses a multi-store model so it's necessary to specify store ID. Here is my code:

This is`CartNotificationController.php` (I changed the route behavior of /cart by setting a default `_controller` method in `RouteSubscriber.php` and copy-pasting the CartController.php class from `commerce_cart/src/Controllers/CartController.php` and making edits. Now the behavior of the route at `/cart` is different.

```
$store = \Drupal::service('commerce_store.current_store')->getStore();
$cart = \Drupal::service('commerce_cart.cart_provider')->getCart('default', $store);
$price = $cart->get('total_price')->getValue()[0]['number'];
drupal_set_message($price); //shows $19.98

```

So it's a rough implementation but I can successfully access the cart value using this. I'll probably make a template or something instead since a drupal\_set\_message is a little bland.

Lots of Google searches will bring up hooks and extending certain hooks but it doesn't seem like you can practically use those within a service/controller.

In other words, I misunderstood what a hook was doing.
> 0 votes

---
Tags: commerce, hooks
---


# Question
Title: How to count the number of calls to a rest service?
I created a rest service which every user on the site calls from a product we are selling.

How do I count the number of calls for every user so I can generate a report of this.

D8

# Answer
> 0 votes
Do your REST service needs authentication?

If yes, you just log each access attempt by users: One attempt per one record per user or one record per user and updating the count column always.

If there is no authentication, you will have harder time to achieve this. It would be also good to know **HOW** they are making this rest calls (eg: clicking on a button which resolves into a rest call?).

You could still try to check session and find out which user made the requeset.

# Answer
> -1 votes
You can create a new *Content Entity*. With this entity you can save all calls on the rest service (p.e. user, url or product, time, ...).

Drupal creates a database table for each entity and with the `ContentEntityBase` it is easy to save new entries, read all entries, read part of the entries, search or whatever you want to do.

There exists a big introduction & documentation

**Addition**

When you save all the calls you can easy read the calls out with the entity. And based on the informations you have saved, you can count the number of calls to your rest service and you can generate the report.

**Code Examples**

1. Create the module-folder `example_module` in `modules/custom`
2. Add the info-file:

*modules/custom/example\_module/example\_module.info.yml*

```
name: EXAMPLE MODULE
description: YOUR DESCRIPTION
package: YOUR PACKAGE

type: module
core: 8.x

```
3. Add the Class to create your entity

*modules/custom/example\_modules/src/Entity/ExampleEntity.php*

```
<?php
namespace Drupal\example_module\Entity;

use Drupal\Core\Field\BaseFieldDefinition;
use Drupal\Core\Entity\ContentEntityBase;
use Drupal\Core\Entity\EntityTypeInterface;

/**
 * Defines the Example Module entity.
 *
 * @ingroup example_module
 *
 * @ContentEntityType(
 *   id = "example_entity_name",
 *   label = @Translation("Example entity"),
 *   base_table = "example_entity_name",
 *   entity_keys = {
 *     "id" = "id",
 *     "user_id" = "user_id",
 *   }
 * )
 */
class ExampleEntity extends ContentEntityBase {

  /**
   * {@inheritdoc}
   *
   * Define the base fields.
   */
  public static function baseFieldDefinitions(EntityTypeInterface $entity_type) {

    // Standard field, used as unique if primary index.
    $fields['id'] = BaseFieldDefinition::create('integer')
      ->setLabel(t('ID'))
      ->setDescription(t('The ID of the entity.'))
      ->setReadOnly(TRUE);

    // Save user_id as a string
    $fields['user_id'] = BaseFieldDefinition::create('string')
      ->setLabel(t('User'))
      ->setDescription(t('The associated user.'))
      ->setSettings([
        'max_length' => 255,
        'text_processing' => 0,
       ]);

    // You can replace the fields or add more. Feel free!

    return $fields;
  }
}

```
4. Enable the module: `$ drush en example_module`
5. Use the entity to save or load content. For example in a Controller of the rest service.

```
// Somewhere above the Controller
use Drupal\example_module\Entity\ExampleEntity;

// Create a new entry
$user_id = Drupal::request()->get('user');
$entityContent = array(
  'user_id' => $user_id,
);
$exampleEntity = ExampleEntity::create($entityContent);
$exampleEntity->save();

// Load entries by user_id
$entityTypeManager = Drupal::entityTypeManager();
$exampleEntityStorage = $entityTypeManager->getStorage('example_entity_name');
$entries = $exampleEntityStorage->loadByProperties($entityContent);
// Now you can count the entries.

```

Be careful, there are different ways to work with Drupal and different ways where to place your own code. Without seeing your code base I can only help with this "default way".

---
Tags: 8
---


title: Search API group by issue with views

text:
# Question
Title: Search API group by issue with views
I have a content type thats is called **course** which has a field that is a reference to a taxonomy called **category**.

My specification tells to build a search where users can search for the course title, category and other fields that the course type has. The search functions like intended and everything works great except the display view. Here is my setup:

* Drupal 8.5
* Search Api with DB / Solr Backend. (tried both)

So to come back: each course can have multiple categorys to be in which means that the view has to be grouped by the category. If I do that my view displays this:

**Category 1 Name**

* Course 1
* Course 2

**Category 1 Name, Category 2 Name**

* Course 3

**Category 2 Name**

* Course 4
* Course 5

**Category 3 Name, Category 2 Name**

* Course 6

**Category 3 Name**

* Course 7
* Course 8
* Course 9

As you can see courses that belong to multiple categorys are not listed underneath the respected category instead they are seperated by a comma. My goal is this:

**Category 1 Name**

* Course 1
* Course 2
* Course 3

**Category 2 Name**

* Course 3
* Course 4
* Course 5
* Course 6

**Category 3 Name**

* Course 6
* Course 7
* Course 8
* Course 9

such behaivor is easy to do if you dont use search api and want just to display a normal view. I have already read this issue but it seems my goal is not possible.

I'm asking now here if something has changed or if its possible to get this done with writing custom code? Maybe tell search api to return every result and display them with custom code grouped by the categorys? Can anyone point me to the right direction?

# Answer
Group by your Category taxonomy and select to `Use rendered output to group rows`, then in your `Filter criteria` for your taxonomy turn on autocomplete of the category terms.

Add View

* View Settings: Show `Content` of type `Course` sorted by `Newest first`
* Page Settings: Create a page `selected`
* Page Display Settings: Display format `Unformatted list` of `fields`

note: you may not want to use the pager.

Edit new View

* Advanced:
    + Relationships: add `Relate nodes to taxonomy terms` with Vocabularies `{Taxonomy}` selected and `Require this relationship` selected
    + Use aggregation: Selected
* Fields: add `content: ID`, `Content: Title`, `Content: {Taxonomy}`
    + `Content: ID`: Exclude from display `selected`, Thousands marker: `-None-`
    + `Content: ID` Aggregation settings: Aggregation type: `Count DISTINCT`
    + `Content: Title`: Formatter `Plain text` and Link to the Content `selected`
    + `Content: {Taxonomy}`: Exclude from display `selected`
* Format:
    + Format settings: Grouping field Nr.1 `Content: {Taxonomy}` and Use rendered output to group rows `selected`
* Filter Criteria: add `Content: Title` and `Content: {taxonomy}`
    + `Content: Title`: Expose this filter to visitors, to allow them to change it `selected` and Operator `Contains`
    + `Content: {Taxonomy}`: Expose this filter to visitors, to allow them to change it `selected` and Operator `Is one of`
    + `Content: {Taxonomy}` settings: Vocabulary `{Taxonomy}` and Selection type `Autocomplete`
* Sort Criteria: `Content: {Taxonomy} (asc)`, `Content: Title (asc)`, `Content: Authored on (desc)`

Note: the preview will not display the Grouping titles, but this dose appear on the page.
> 0 votes

---
Tags: views, 8, search
---


# Question
Title: Override theme function inside module, template_preprocess_field
I'd like to implement `template_preprocess_field` in a module for organizational purposes.

How can I do this?

# Answer
> 1 votes
Hook functions are named like so: MODULENAME\_hook.

In your case that's:

```
function MODULENAME_preprocess_field(&$variables) {

}

```

---
Tags: 8
---


# Question
Title: How to create a rule to email all users with a profile field X with same value as the current-user?
I'm using Drupal 7.57 and I have **2 roles** in my website, **role X** and **role Y**.

I want to **compare a field** (`field_code_postal`) of the **X member profile** of the **current-user**, with the fields (`field_code_postal`) of **all Y members profiles**, and this when X member save a new entityform submission.

**Each time** the field `field_code_postal` is the same, an email should be sent to that Y member.

So if there are **100 Y members** and for **20 of them** the value of the field is equal to the value of it for the current user X, then **20 emails are sent**.

Do I need to use **flags**, or are the **roles** sufficient?

I'm a bit lost, any help?

# Answer
> 2 votes
Import and give a try to the following rule. Note I used `After saving new content` trigger, however you can change to or add another event suitable to your case. For example, you could add `After saving a new comment`.

```
{ "rules_notify_users_with_the_same_postal_code" : {
    "LABEL" : "Notify users with the same postal code",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "node_insert" : [] },
    "IF" : [
      { "NOT data_is_empty" : { "data" : [ "node:author:field-code-postal" ] } }
    ],
    "DO" : [
      { "entity_query" : {
          "USING" : {
            "type" : "user",
            "property" : "field_code_postal",
            "value" : [ "site:current-user:field-code-postal" ],
            "limit" : "100"
          },
          "PROVIDE" : { "entity_fetched" : { "entity_fetched" : "Fetched entity" } }
        }
      },
      { "LOOP" : {
          "USING" : { "list" : [ "entity-fetched" ] },
          "ITEM" : { "list_item" : "Current list item" },
          "DO" : [
            { "mail" : {
                "to" : "list-item:mail",
                "subject" : "A new post #[node:nid] [node:title] has been posted",
                "message" : "A new post #[node:nid] [node:title] has been posted",
                "from" : "[site:mail]",
                "language" : [ "node:language" ]
              }
            }
          ]
        }
      }
    ]
  }
}

```

# Answer
> 2 votes
D7, use rules views module, make a users rules view and load it in rules as a views rules loop, in view settings add a filter criteria Y members = your special field, inside loop, add an action: fetch entity by id: UID from loop, action: send email to fetched UID.

EDIT: because of Pierre comment i'm adding a little more info. Let me first explain something: ID's (uid, nid, tid, etc.) must be passed from rules views to rules as an integer, if you don't, rules will not understand what you are sending in, this is done in rules view settings in "row variable settings" in middle column. So rules inside loop recieves UID as an integer, this means you do not have that user object avilable in rules, that's why you must fetch user by the integer value (UID) passed to rules. Now, you have two objects to work with, inside rule views loop, you have to compare current logged-in user postalcode field value againts the postalcode field of the fetched user, and last, send your email or whatever. you may need also rules conditional module

# Answer
> 1 votes
You may want to give it a try to *process the results of a VBO enabled view via Rules*, whereas your rule performs 2 Rules Actions:

* Load the VBO list that you want to be processed.
* Add a loop to perform a Rules Action, for each row contained in your Views results.

For more details, have a look at the tutorial "How to process the results of a VBO enabled view via Rules?".

To actually trigger such Rules Action, you should be able to use pretty much any Rules Event that fits your needs.

Also, to select only those members (= Y) with the same value of that `field_code_postal` field, it seems you can use either of these techniques:

* Pass it as an argument to the view (so that you only get 1 views result for each member). Refer to the video in the linked tutorial about how to do so.
* Yse an extra Rules Component in which you actually send those eMails, and in which you perform an extra Rules Condition to check that the value for the `field_code_postal` field of member Y is equal to the one for member X (you probably want to pass this value as an extra Rules Component parameter).

---
Tags: 7, users, rules, emails
---


title: Get Authenticated User ID in Hook Cron?

text:
# Question
Title: Get Authenticated User ID in Hook Cron?
I have been trying to get the current authenticated user ID in Hook\_cron() function.

But Its showing only the anonymous user, though the current user is an authenticated user.

How Could I get the current authenticated user in hook\_cron()

# Answer
There's no such thing - cron always runs as the anonymous user.

This is forced by the `drupal_cron_run()` function in Drupal 7:

```
// Force the current user to anonymous to ensure consistent permissions on
// cron runs.
$original_user = $GLOBALS['user'];
$GLOBALS['user'] = drupal_anonymous_user();

```

and `Cron::run` in Drupal 8:

```
// Force the current user to anonymous to ensure consistent permissions on
// cron runs.
$this->accountSwitcher
  ->switchTo(new AnonymousUserSession());

```
> 1 votes

---
Tags: 7, hooks, cron
---


# Question
Title: how to set revision log message programatically in drupal 8
I am trying to set the revision log in a custom module in drupal 8, using $media-\>set("revision\_log","test message")

and it doesnt work. This method is working for all of the other fields. why doesnt it work for the revision\_log?

# Answer
> 1 votes
$media-\>setRevisionLogMessage('foo');

---
Tags: 8, forms
---


# Question
Title: Vocabulary terms deleted but still visible
I work on a D7 website where some taxonomy terms were created and then deleted.

I’ve build a search form with views based on taxonomy terms (filter criterion: Content: Term name (field\_term\_name)) and i see some "deleted" terms in filter exposed to visitor.

I’ve check directly in DB and it appears that these datas (which should be completely deleted) are still in `taxonomy_term_data`.

I do not see these terms in the Drupal admin but I can however still see them in the database, and I can open them directly using the tid in the Drupal interface.

My experience with Drupal let me think that is not a good idea to delete them directly in DB. So how can I proceed ?

# Answer
> 0 votes
`taxonomy_term_data` is the canonical location for term data so it sounds like there might be other issues going on (a broken admin display, caching, DB corruption via orphaned parent/child term, we can only guess).

If you want a safe way to remove taxonomy, invoke the taxonomy API functions (they are the same tools the admin interface is using) via Devel, `drush eval`, or some other dev tool where you can execute arbitrary PHP that uses these functions to remove your desired terms:

For example:

```
$my_bad_tids = [1, 2, 3];
$terms = taxonomy_term_load_multiple($my_bad_tids);
foreach ($terms as $term) {
  taxonomy_term_delete($term->tid);
}

```

---
Tags: taxonomy-terms
---


title: Show New Comment Count in View

text:
# Question
Title: Show New Comment Count in View
If you use the messaging system in Drupal.org, you have noticed that if you go to your messages, there may be a link that says New Message next to the thread.

We have Q&A section where people ask questions and others leave comments.

What is the proper field to add in views that will show "New Message" or "X new messages". The notification will be to the login user only.

# Answer
> 1 votes
You probably want **new comments**

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


# Question
Title: Behat, Selenium and Chromedriver CI errors
I am working on a Behat setup with Selenium and Chromedriver for running Behat tests for a Drupal 7 setup.

I am getting:

> exception ‘WebDriver\Exception\UnknownError’ with message 'Timed out waiting for driver server to start.

Above this error, i am also seeing:

> 21:46:42.198 INFO \[ActiveSessionFactory.apply\] - Capabilities are: Capabilities {browser: firefox, browserName: chrome, ignoreZoomSetting: false, name: Behat feature suite, tags: \[railsonfire\_5e8a4d2e-8ba4-4…, PHP 5.6.34\]} 21:46:42.199 INFO \[ActiveSessionFactory.lambda$apply$11\] - Matched factory org.openqa.selenium.remote.server.ServicedSession$Factory (provider: org.openqa.selenium.chrome.ChromeDriverService) /home/rof/src/bitbucket.org/myorganisation/myproject/chromedriver: 1: /home/rof/src/bitbucket.org/myorganisation/myproject/chromedriver: Syntax error: “(” unexpected 21:47:02.201 ERROR \[OsProcess.checkForError\] - org.apache.commons.exec.ExecuteException: Process exited with an error: 2 (Exit value: 2)

I am running:

```
java -Dwebdriver.chrome.driver=./chromedriver -jar selenium-server-standalone-3.10.0.jar 2>&1 &

```

to start selenium with chromedriver in my pipeline.

I am downloading and unzipping chromedriver like so:

> –2018-03-19 20:39:43-- http://chromedriver.storage.googleapis.com/2.35/chromedriver\_mac64.zip Resolving chromedriver.storage.googleapis.com (chromedriver.storage.googleapis.com)… 172.217.7.176, 2607:f8b0:4004:80c::2010 Connecting to chromedriver.storage.googleapis.com (chromedriver.storage.googleapis.com)|172.217.7.176|:80… connected. HTTP request sent, awaiting response… 200 OK Length: 5508030 (5.3M) \[application/zip\] Saving to: chromedriver\_mac64.zip
>
> 100%\[======================================\>\] 5,508,030 --.-K/s in 0.04s
>
> 2018-03-19 20:39:44 (120 MB/s) - chromedriver\_mac64.zip saved \[5508030/5508030\]
>
> Archive: chromedriver\_mac64.zip inflating: /home/rof/src/bitbucket.org/myorganisation/myproject/chromedriver

My `behat.yml` file used for CI

```
default:
  suites:
    default:
      contexts:
        - FeatureContext
        - Drupal\DrupalExtension\Context\DrupalContext
        - Drupal\DrupalExtension\Context\MinkContext
        - Drupal\DrupalExtension\Context\MessageContext
        - Drupal\DrupalExtension\Context\DrushContext
     filters:
      tags: "~@wip"
  extensions:
    Behat\MinkExtension:
      goutte: ~
      javascript_session: 'selenium2'
      browser_name: 'chrome'
      selenium2:
      wd_host: 'http://127.0.0.1:4444/wd/hub'
    # Should be removed once
    https://github.com/Behat/MinkExtension/pull/311 gets into a release.
      capabilities:
        marionette: null
    # Remove STOP
    base_url: 'http://127.0.0.1:8080'
  Drupal\DrupalExtension:
    blackbox: ~
    api_driver: 'drupal'
    drupal:
      drupal_root: '${project.basedir}'
    text:
      username_field: 'Gebruikersnaam'
      password_field: 'Wachtwoord'
      log_in: 'Log in'
      log_out: 'Uitloggen'

```

Please ignore the `${project.basedir}`, this gets replaced with the phing build target.

Ps: Also note that locally all behat tests run perfectly fine.

All suggestions welcome!

# Answer
> 1 votes
Apparently Codeship, the CI provider that I am using, had a different version of chromedriver that conflicted with my setup. Running chromedriver 2.35 fixed the problem.

Many thanks Aswini K for the effort provided though!

# Answer
> 0 votes
Try with below changes on behat.yml file.

```
 extensions:
        Behat\MinkExtension\Extension:
            default_session: goutte
            javascript_session: selenium2
            goutte:
                guzzle_parameters:
                    ssl.certificate_authority: false
                    curl.options:
                        CURLOPT_SSL_VERIFYPEER: false
                        CURLOPT_CERTINFO: false
                        CURLOPT_TIMEOUT: 120
            selenium2:
              wd_host: "http://localhost:9515/wd/hub"
        Drupal\DrupalExtension\Extension:
            blackbox: ~
            api_driver: 'drupal'

```

---
Tags: 7, testing
---


title: Query based on multiple keywords

text:
# Question
Title: Query based on multiple keywords
I have 5 nodes title with some keywords:

1. this is my node one with some keywords
2. this is my **second title** with some keywords
3. this is my another **title** with **second** keyword
4. this is my another **title second** keyword
5. this was my last node **title**

My search query is: "**second title**"

when i search with only **title** keyword, query return 2,3,4, and 5 well, but when i search **second title**, query return only 2. So, how can i extend my query to return nodes as 2,4,3 and 5 in the last position (since 5 has only one keyword match).

This is my query:

```
$query = db_select('node', 'n')
         ->fields('n')
         ->condition('n.title', '%' . db_like($_GET['Keywords']) . '%', 'LIKE')
         ->execute()
         ->fetchAll();

```

**Updated:** search keywords can more then 2 words, but query should return as much words matches.

please help!

thanks.

# Answer
You want db\_or().

```
$or = db_or()->condition('n.title', '%' . db_like('second') . '%', 'LIKE')->condition('n.title', '%' . db_like('title') . '%', 'LIKE');
$results = db_select('node', 'n')
  ->fields('n')
  ->condition($or)
  ->execute()
  ->fetchAll();

```
> 2 votes

---
Tags: 7, database
---


title: Generate node edit link

text:
# Question
Title: Generate node edit link
I'm attempting to dynamically generate a node edit link. I understand that I can manually create it by using

$editpath = '/node/'.$nid.'/edit';

but I have multiple sites that use subfolders like

> /site1\_subfolder/node/123/edit

and

> /site2\_subfolder/node/123/edit

I looked at the node class and I couldn't see any method that would generate this link for me. I did see that there's a NodeForm class but I didn't see any static methods I could take advantage of either.

Given a node or node id is there a way to generate an admin edit link to its edit form?

NOTE: If that's not possible I would be fine with using a function to get the subfolder names so I could do $editpath = '/'.$subfolder\_name.'/node/'.$nid.'/edit';

But I'm not sure how to do that either.

UPDATE: I suppose I could do a $node-\>toUrl()-\>toString() to get the direct path and add edit at the end but this would only give me the alias, is there a way to not get the alias from this and get the direct link to the node instead?

# Answer
> Given a node or node id is there a way to generate an admin edit link to its edit form?

Absolutely, the `Url` class has a `fromRoute` method:

```
$url = Url::fromRoute('entity.node.edit_form', ['node' => $nid]);
$link = Link::fromTextAndUrl('edit', $url);
$build = [
  ...
  'link' => $link->toRenderable(),
];

```
> 10 votes

# Answer
> Given a node or node id is there a way to generate an admin edit link to its edit form?

If you have the `$node` itself, then you can you can use the `toUrl()` method to get one of the defined links:

```
$url = $node->toUrl('edit-form');
$link = Link::fromTextAndUrl('Title', $url);
$build = [
  //...
  'link' => $link->toRenderable(),
];

```

The various link names for the entity are on the annotation for the Node class:

```
/**
 * Defines the node entity class.
 *
 * @ContentEntityType(
 *   id = "node",
 *   ...
 *   links = {
 *     "canonical" = "/node/{node}",
 *     "delete-form" = "/node/{node}/delete",
 *     "delete-multiple-form" = "/admin/content/node/delete",
 *     "edit-form" = "/node/{node}/edit",
 *     "version-history" = "/node/{node}/revisions",
 *     "revision" = "/node/{node}/revisions/{node_revision}/view",
 *     "create" = "/node",
 *   }
 * )
 */

```
> 9 votes

---
Tags: 8, nodes
---


# Question
Title: Is it possible to get Views data in the views-view.html.twig file?
I see this template just uses

```
{{ rows }}

```

Is it possible to get values from the views fields in this file?

# Answer
> 0 votes
Enable the Devel module and use dpm().

---
Tags: views, theming
---


# Question
Title: Temporarily disable all modules for troubleshooting
I have a bizarre error going on in the Drupal admin and I want to disable all modules to test if any of them are causing the problem. I have dozens of enabled and dozens of disabled modules. I can go through the process of writing down each module and its status, then manually disabling and re-enabling. However, that seems pretty tedious. Is there a better way to temporarily disable all modules without having to manually remember and tick them on/off?

# Answer
> 1 votes
You can collect the machine names of all the enabled modules with the `drush pm-list --type=Module --status=enabled --pipe > enabled.txt` command.

And then iterate through the list do disable:

```
drush -y dis $(<enabled.txt)

```

or enable

```
drush -y en $(<enabled.txt)

```

them.

---
Tags: plugins
---


# Question
Title: Multiple billings for one user in one day for Monthly Recurring (Drupal commerce)
Our Monthly Recurring Billing has been working successfully for more than 1 year. However, there are two customers are charged multiple times on February 28, 2018, once an hour. Other 3 customers (monthly recurring) are charged correctly on the same day.

The cron "commerce\_recurring\_cron" runs every hour, and created a new order of recurring billing for the same user.

```
ORDER NUMBER    UPDATED NAME    USER    TOTAL   ORDER STATUS
8181    February 28, 2018 - 6:43pm  J* C*   j*  $4.99   Completed
8182    February 28, 2018 - 7:09pm  J* C*   j*  $4.99   Completed
8184    February 28, 2018 - 8:09pm  J* C*   j*  $4.99   Completed
8186    February 28, 2018 - 9:11pm  J* C*   j*  $4.99   Completed
8188    February 28, 2018 - 10:11pm J* C*   j*  $4.99   Completed
8190    February 28, 2018 - 11:00pm J* C*   j*  $4.99   Completed
8192    March 1, 2018 - 12:00am J* C*   j*  $4.99   Completed
8183    February 28, 2018 - 8:09pm  L* L*   l*  $4.99   Completed
8185    February 28, 2018 - 9:11pm  L* L*   l*  $4.99   Completed
8187    February 28, 2018 - 10:11pm L* L*   l*  $4.99   Completed
8189    February 28, 2018 - 11:00pm L* L*   l*  $4.99   Completed
8191    March 1, 2018 - 12:00am L* L*   l*  $4.99   Completed

```

All above payments of orders are charge successfully in Authorize.net.

System: Drupal 7.56; Authorize.net Gate Way.
Related modules: commerce 7.x-1.13, commerce\_recurring 7.x-2.x-dev, commerce\_order 7.x-1.11, commerce\_payment 7.x-1.11, commerce\_authnet 7.x-1.4, commerce\_cardonfile 7.x-2.0-beta5+3-dev.

I have spent days on doing research, and debugging the Drupal log and system log. But I can't find any useful info.
I cannot repeat the problem on our DEV site.

I will deeply appreciate it if someone knows some clues about it by chance.

Thank you very much!

# Answer
> 0 votes
There is a fixed issue with Commerce Authorize.Net, discussed on https://www.drupal.org/project/commerce\_authnet/issues/2161989.

If your setup already incorporates that fix, then most probably it is hitting the issue Duplicate queue items should not be created. Apply the patch in #6 and you should be fine.

---
Tags: 7, commerce
---


# Question
Title: How do I add updated timestamp to a file url to ensure people download the latest version?
I'd like to add the last updated timestamp to the uploaded file name e.g. my.pdf?ver=123413414

The file is uploaded on a regular basis and I'd like people to access the latest version.

I can't see a module/formatter to do this.

I can write \- javascript to add the timestamp to the end but the file would never be cached. \- write a file formatter that adds the last updated timestamp to the end of the download link. \- write something that calls "theme\_file\_link"

what is the best approach?

Thanks

# Answer
> 1 votes
The best approach would be to actually rename the file both on the file system and the database and incorporate the upload time in file name.

Appending time after the question mark in URL would have purely informative purpose. And if that's what you want then create a custom module and place the following code in it:

```
function my_custom_module_node_view_alter(&$build) {
  if (isset($build['field_file'])) {
    $time = gmdate("Y-m-d:H:i", $build['field_file'][0]['#file']->timestamp);
    $build['field_file'][0]['#file']->filename = $build['field_file'][0]['#file']->filename.'?'.$time;
  }
}

```

If you have multiple files per node then use the following code instead:

```
function my_custom_module_node_view_alter(&$build) {
 if (isset($build['field_file'])) {
    foreach ($build['field_file'] as $key => $file) {
      if (is_numeric($key)) {
        $time = gmdate("Y-m-d:H:i", $file['#file']->timestamp);
        $build['field_file'][$key]['#file']->filename = $build['field_file'][$key]['#file']->filename.'?'.$time;
      }
    }
  }
}

```

---
Tags: theming, files
---


# Question
Title: Error installing Theme on GoDaddy Drupal 8.4.5
I have goDaddy and installed Drupal 8.4.5, the newest version they have on their Installation. Trying to install the theme Nexus, when I upload the theme from archive (zip file) and click install I get the following error.

> The website encountered an unexpected error. please try again later.

I have tried clearing the cache. I was running Drupal 8.3.2 and it would just go to a blank screen; updating to Drupal 8.4.5 now got me to this error. I have downloaded and tried about 20 different themes. I either get this error or I get that the file is over 2 megabyte and is too big. What am I doing wrong or how do I fix this error?

# Answer
Based on the two errors you noted:

* "The website encountered an unexpected error. please try again later."
* the file is over 2mb

It sounds like your web-hosting provider/CPanel account has a limit on file uploads set, and:

a) your Drupal Core update/upgrade wasn't completed successfully

b) you may not have a temporary directory configured properly for unzipping the theme archive.

---

Recommended course of action would be to:

1. finish your Drupal 8.4.5 upgrade (or perform a fresh install on GoDaddy). If you're drupal core codebase was updated, be sure to go to update.php to ensure all Drupal database updates were applied.
2. Once Drupal Core has been updated and you can navigate the site/add test content successfully, unzip the theme codebase locally and upload the "nexus" folder to your Drupal site's /themes/custom/ folder using either GoDaddy's file manager, ftp, or via version control tools such as *git*.
3. With the theme folder manually installed to the server, flush the cache of your Drupal site; go to Appearance, select and enable the Nexus theme.
> 1 votes

---
Tags: 8
---


# Question
Title: How to get Q & A of a webform submission?
Main goal is to get user filled in form into a pdf. Got my pdf & sending it with email. But I cant figure out how to get Q & A from a submission. I have sid of submission. I tried

```
      $storage = \Drupal::entityTypeManager()->getStorage('webform_submission');
  $webform_submission = $storage->loadByProperties([
    'entity_type' => 'webform',
    'entity_id' => 'questionnaire',
  ]);
  $submission_data = array();
  foreach ($webform_submission as $submission) {
    $submission_data[] = $submission->getData();
  }

```

Webform is not attached to node.

Thanks

# Answer
> 0 votes
For Drupal 8, webform submissions are content entities so you just need to call...

```
\Drupal\webform\Entity\WebformSubmission::load($sid)

```

# Answer
> 0 votes
Try below code:

```
module_load_include('inc','webform','includes/webform.submissions');
$sid = 10; //Replace this value with your dynamic sid value
$submission = webform_get_submissions(array('sid' => $sid));
$nid = $submission[$sid]->nid;

$web_submission = webform_get_submission($nid, $sid);
$node = node_load($nid);
$output = webform_submission_render($node, $web_submission, NULL, 'html');

print $output;

```

# Answer
> 0 votes
Try below code for Drupal 8:

```
 $storage = \Drupal::entityTypeManager()->getStorage('webform_submission');
 $webform_submission = $storage->loadByProperties([
    'entity_type' => 'node', //Entity type = node
    'entity_id' => 1234, // Your Dynamic Node ID
 ]);
 $submission_data = array();
 foreach ($webform_submission as $submission) {
    $submission_data[] = $submission->getData();
 }

```

---
Tags: 8, webforms
---


# Question
Title: Error: Call to undefined function twig_render_template() when accessing website
Error when accessing drupal 8.

```
The website encountered an unexpected error. Please try again later.
Error: Call to undefined function twig_render_template() in Drupal\Core\Theme\ThemeManager->render() (line 384 of core/lib/Drupal/Core/Theme/ThemeManager.php).
Drupal\Core\Theme\ThemeManager->render('views_view', Array) (Line: 437)
Drupal\Core\Render\Renderer->doRender(Array) (Line: 450)
Drupal\Core\Render\Renderer->doRender(Array, ) (Line: 195)
Drupal\Core\Render\Renderer->render(Array, ) (Line: 226)
Drupal\Core\Render\MainContent\HtmlRenderer->Drupal\Core\Render\MainContent\{closure}() (Line: 582)
Drupal\Core\Render\Renderer->executeInRenderContext(Object, Object) (Line: 227)
Drupal\Core\Render\MainContent\HtmlRenderer->prepare(Array, Object, Object) (Line: 117)
Drupal\Core\Render\MainContent\HtmlRenderer->renderResponse(Array, Object, Object) (Line: 90)
Drupal\Core\EventSubscriber\MainContentViewSubscriber->onViewRenderArray(Object, 'kernel.view', Object) (Line: 108)
Drupal\Component\EventDispatcher\ContainerAwareEventDispatcher->dispatch('kernel.view', Object) (Line: 158)
Symfony\Component\HttpKernel\HttpKernel->handleRaw(Object, 1) (Line: 68)
Symfony\Component\HttpKernel\HttpKernel->handle(Object, 1, 1) (Line: 57)
Drupal\Core\StackMiddleware\Session->handle(Object, 1, 1) (Line: 47)
Drupal\Core\StackMiddleware\KernelPreHandle->handle(Object, 1, 1) (Line: 99)
Drupal\page_cache\StackMiddleware\PageCache->pass(Object, 1, 1) (Line: 78)
Drupal\page_cache\StackMiddleware\PageCache->handle(Object, 1, 1) (Line: 47)
Drupal\Core\StackMiddleware\ReverseProxyMiddleware->handle(Object, 1, 1) (Line: 50)
Drupal\Core\StackMiddleware\NegotiationMiddleware->handle(Object, 1, 1) (Line: 23)
Stack\StackedHttpKernel->handle(Object, 1, 1) (Line: 657)
Drupal\Core\DrupalKernel->handle(Object) (Line: 19)

```

Searched for twig\_render\_template function found in core/themes/engines/twig/twig.engine file. I new to drupal 8 so I don't know what I did wrong? It just broke.

Here is the line this error occurs in ThemeManager.php:

```
$output = $render_function($template_file, $variables);

```

and here is $render\_function defined also in ThemeManager.php:

```
$render_function = 'twig_render_template';
      $extension = '.html.twig';

      // The theme engine may use a different extension and a different
      // renderer.
      $theme_engine = $active_theme->getEngine();
      if (isset($theme_engine)) {
        if ($info['type'] != 'module') {
          if (function_exists($theme_engine . '_render_template')) {
            $render_function = $theme_engine . '_render_template';
          }
          $extension_function = $theme_engine . '_extension';
          if (function_exists($extension_function)) {
            $extension = $extension_function();
          }
        }
      }

```

# Answer
> 1 votes
Solved! Apparently core has been damaged, restored core everything is back to normal.

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


# Question
Title: When creating a module, where do I set cookies?
Drupal 7 newb here.

I am creating a simple module. Basically, this has an admin config form with a message text area. On the front end, that message appears or not depending on the state of a cookie.

My question is: where (in what function) should you set the cookie?

My code is:

```
/**
 * Implements hook_block_info().
 */
function message_block_info() {
  return [
    'message_block' => [
      'info' => t('Message'),
      'cache' => DRUPAL_CACHE_GLOBAL,
    ],
  ];
}

/**
 * Implements hook_theme().
 */
function message_theme() {
  return [
    'message_block' => [
      'template' => 'templates/message-block',
      'variables' => [
        'config' => NULL,
      ],
    ],
  ];
}

/**
 * Implements hook_block_view().
 */
function message_block_view($delta = '') {
  if ($delta !== 'message_block') {
    return;
  }

  $config = message_default_settings();
  if (empty($config['alert_message']) || $config['alert_show'] === 0) {
    return;
  }

  $block['content'] = array(
    '#theme' => 'message_block',
    '#config' => array(
      'alert_show' => $config['alert_show'],
      'alert_message' => filter_xss($config['alert_message']),
      'alert_link' => filter_xss($config['alert_link']),
    ),
  );

  return $block;
}

```

# Answer
Here i set the cookie as user login and logged out.

```
/**
 * Implements hook_user_login().
 */
function HOOK_user_login(&$edit, $account) {
  setcookie('user-logged-in', '2', 0, '/');
}

/**
 * Implements hook_user_logout().
 */
function HOOK_user_logout($account) {
  // Set cookie in the past and then remove it.
  setcookie('user-logged-in', '', REQUEST_TIME - 3600, '/');
  unset($_COOKIE['user-logged-in']);
}

```

You can try it will able to create new cookie anywhere i.e Create cookie into hook\_init() https://www.drupal.org/forum/support/theme-development/2009-05-26/setting-custom-cookies#comment-2901778
> 0 votes

---
Tags: 7
---