# Question
Title: Drush runs out of memory, regardless of memory limit (Windows Server 2012)
Drush fails to execute any commands that result in changes. An error on this pattern is returned:

```
PHP Fatal error:  Out of memory (allocated 1223163904) (tried to allocate 130968 bytes) in C:\Users\*[username]*\AppData\Local\Composer\vendor\drush\drush\includes\filesystem.inc on line 361
Drush command terminated abnormally due to an unrecoverable error.                           [error]

Error: Out of memory (allocated 1223163904) (tried to allocate 130968 bytes) in C:\Users\*[username]*\AppData\Local\Composer\vendor\drush\drush\includes\filesystem.inc, line 361

```

Server is running Windows 2012R2, with Apache, PHP & MariaDB. Drush was installed on this server using Composer.

I've been able to adjust the memory allocation by placing the drushrc.php file in the root Drush folder (there's no '.drush' folder in a Composer install on Windows), but it doesn't resolve the issue. When I allocate 128M or 512M, the 'allocated' lines in the error showed all memory allocated; the error you see above, showing 1165M allocated, was returned after I increased the allocation to 2048M. I.e., it will allocate up to 1165M, and still return the error specifying a failure to allocate 130968 bytes (guessing that corresponds to 128M, though it doesn't seem to divide quite right).

So if I'm reading the error correctly, it seems to be telling me that it's already allocated \[512M, 128M, or 1161M, depending\], but is failing to allocate 128M.

512M appears to be the default; it's what's set in my base PHP.ini. Still haven't figured out where that 128M is being specified.

1. Am I reading this error correctly? It's saying that it needs 128M, but it can't allocate it, because it's only got \[some value much greater than 128M\]?
2. if so, what could be going on?
3. has anybody seen this before? I haven't yet found a problem that looks like this. It's obviously not a case of Drush just running out of memory.
4. are there any other places I could be looking for memory limits? I've accounted for the base php.ini, drush.ini, and drushrc.php.

Here's `drush status` output for this site:

```
Drupal version                :  7.37
Site URI                      :  http://default
Database driver               :  mysql
Database hostname             :  localhost
Database port                 :
Database username             :  [db username]
Database name                 :  [db name]
Drupal bootstrap              :  Successful
Drupal user                   :
Default theme                 :  bootstrap_gccverticalr01
Administration theme          :  seven
PHP executable                :  php.exe
PHP configuration             :  E:\php\php.ini
                         C:\Users\[username]\AppData\Local\Composer\vendor\drush\drush\drush.ini
PHP OS                        :  WINNT
Drush script                  :  C:\Users\[username]\AppData\Local\Composer\vendor\drush\drush\drush.php
Drush version                 :  7.0.0
Drush temp directory          :  C:\Users\[username]\AppData\Local\Temp
Drush configuration           :
Drush alias files             :
Install profile               :  standard
Drupal root                   :  E:\htdocs\newsdev
Site path                     :  sites/default
File directory path           :  sites/default/files
Private file directory path   :  sites/default/files/priv
Temporary file directory      :  c:\windows\temp
path

```

Per suggestion from @greg\_t\_anderson, here's a --debug on a module update:

```
E:\htdocs\newsdev>drush up name --debug
Starting Drush preflight. [0.34 sec, 2.41 MB]                                                      [preflight]
Loading drushrc "C:\Users\[username]\AppData\Local\Composer\vendor\drush\drush\drushrc.php" into      [bootstrap]
"drush" scope. [0.34 sec, 2.42 MB]

Cache HIT cid: 7.0.0-commandfiles-0-6fdbceb87a2d9ef0fd59b7f3a6ad6ecd [0.45 sec, 2.48 MB]               [debug]

Bootstrap to phase 0. [0.92 sec, 6.99 MB]                                                          [bootstrap]

Bootstrap to phase 6. [0.93 sec, 7 MB]                                                             [bootstrap]

Drush bootstrap phase : bootstrap_drupal_root() [0.94 sec, 7.37 MB]                                [bootstrap]

Initialized Drupal 7.37 root directory at E:\htdocs\newsdev [1.04 sec, 7.37 MB]                       [notice]

Find command files for phase 1 (max=6) [1.05 sec, 5.25 MB]                                             [debug]

Cache HIT cid: 7.0.0-commandfiles-1-4d4589c654b01ca711dc8471d98c0e08 [1.05 sec, 5.25 MB]               [debug]

Drush bootstrap phase : bootstrap_drupal_site() [1.07 sec, 5.26 MB]                                [bootstrap]

Initialized Drupal site default at sites/default [1.07 sec, 5.26 MB]                                  [notice]

Find command files for phase 2 (max=6) [1.17 sec, 5.26 MB]                                             [debug]

Cache HIT cid: 7.0.0-commandfiles-2-f17fc6bdab2f74278df75194ca483893 [1.17 sec, 5.26 MB]               [debug]

Drush bootstrap phase : bootstrap_drupal_configuration() [1.18 sec, 5.26 MB]                       [bootstrap]

Find command files for phase 3 (max=6) [1.18 sec, 5.27 MB]                                             [debug]

sql-query: SELECT 1; [1.19 sec, 5.39 MB]                                                              [status]

Executing: mysql --defaults-extra-file="C:\\Users\\[username]\\AppData\\Local\\Temp\\druFC47.tmp" --database=gccnewsdev --host=localhost --silent  < "C:\\Users\\[username]\\AppData\\Local\\Temp\\druFC46.tmp"
  1
Drush bootstrap phase : bootstrap_drupal_database() [1.3 sec, 5.39 MB]                             [bootstrap]

Successfully connected to the Drupal database. [1.31 sec, 5.93 MB]                                 [bootstrap]

Find command files for phase 4 (max=6) [1.31 sec, 5.93 MB]                                             [debug]

Drush bootstrap phase : bootstrap_drupal_full() [1.31 sec, 5.93 MB]                                [bootstrap]

Cache HIT cid: 7.0.0-install_profile-66ecfeb9791a023150773849f1550c5d [1.66 sec, 28.68 MB]             [debug]

Find command files for phase 5 (max=6) [1.66 sec, 28.68 MB]                                            [debug]

Cache HIT cid: 7.0.0-install_profile-66ecfeb9791a023150773849f1550c5d [1.66 sec, 28.68 MB]             [debug]

Cache HIT cid: 7.0.0-commandfiles-5-6046ef3049c5fa6ecece7eb50449dd57 [1.66 sec, 28.7 MB]               [debug]

Drush bootstrap phase : bootstrap_drupal_login() [1.69 sec, 29.35 MB]                              [bootstrap]

Find command files for phase 6 (max=6) [1.71 sec, 29.79 MB]                                            [debug]

Found command: pm-update (commandfile=pm) [1.71 sec, 29.79 MB]                                     [bootstrap]

Bootstrap to phase 6. [1.71 sec, 29.79 MB]                                                         [bootstrap]

Calling hook drush_pm_update [1.94 sec, 32.51 MB]                                                      [debug]

Bootstrap to phase 6. [1.94 sec, 32.55 MB]                                                         [bootstrap]

Loading release_info engine. [1.94 sec, 32.56 MB]                                                     [notice]

Loading version_control engine. [1.95 sec, 32.6 MB]                                                   [notice]

Loading package_handler engine. [1.95 sec, 32.62 MB]                                                  [notice]

Executing: wget --version
Loading update_status engine. [2.28 sec, 32.64 MB]                                                    [notice]

Including C:\Users\[username]\AppData\Local\Composer\vendor\drush\drush\commands\pm/updatecode.pm.inc [bootstrap]

[2.29 sec, 32.72 MB]
Calling hook drush_pm_updatecode_validate [2.29 sec, 32.81 MB]                                         [debug]

Returned from hook drush_pm_updatecode_validate [2.29 sec, 32.81 MB]                                   [debug]

Calling hook drush_pm_updatecode [2.29 sec, 32.83 MB]                                                  [debug]

Cache MISS cid: 7.0.0-alias-path--3435207224f9913394154572a229f036 [2.3 sec, 32.86 MB]                 [debug]

Backend invoke: php.exe                                                                              [command]

"C:\\Users\\[username]\\AppData\\Local\\Composer\\vendor\\drush\\drush\\drush.php" --php=php.exe
--backend=2 --verbose --debug --root="E:\\htdocs\\newsdev" --uri=http://default  pm-updatestatus
name 2>&1 [2.32 sec, 32.86 MB]
php.exe "C:\\Users\\[username]\\AppData\\Local\\Composer\\vendor\\drush\\drush\\drush.php"               [notice]

--php=php.exe  --backend=2 --verbose --debug --root="E:\\htdocs\\newsdev" --uri=http://default
pm-updatestatus name 2>&1 [2.32 sec, 32.87 MB]
Obtaining views_bulk_operations project path. [33.21 sec, 35.71 MB]                                    [debug]

Obtaining admin_menu project path. [33.21 sec, 35.72 MB]                                               [debug]

Obtaining advanced_help project path. [33.21 sec, 35.72 MB]                                            [debug]

Obtaining backup_migrate project path. [33.21 sec, 35.72 MB]                                           [debug]

Obtaining block_class project path. [33.21 sec, 35.72 MB]                                              [debug]

Obtaining ctools project path. [33.22 sec, 35.72 MB]                                                   [debug]

Obtaining cas project path. [33.22 sec, 35.73 MB]                                                      [debug]

Obtaining cas_attributes project path. [33.22 sec, 35.73 MB]                                           [debug]

Obtaining ckeditor project path. [33.22 sec, 35.73 MB]                                                 [debug]

Obtaining conditional_styles project path. [33.22 sec, 35.73 MB]                                       [debug]

Obtaining date project path. [33.22 sec, 35.73 MB]                                                     [debug]

Obtaining devel project path. [33.22 sec, 35.74 MB]                                                    [debug]

Obtaining entity project path. [33.23 sec, 35.74 MB]                                                   [debug]

Obtaining features project path. [33.23 sec, 35.74 MB]                                                 [debug]

Obtaining features_override project path. [33.23 sec, 35.74 MB]                                        [debug]

Obtaining feeds project path. [33.23 sec, 35.74 MB]                                                    [debug]

Obtaining feeds_tamper project path. [33.23 sec, 35.75 MB]                                             [debug]

Obtaining field_group project path. [33.28 sec, 35.75 MB]                                              [debug]

Obtaining field_permissions project path. [33.28 sec, 35.75 MB]                                        [debug]

Obtaining file_entity project path. [33.28 sec, 35.75 MB]                                              [debug]

Obtaining flickr project path. [33.28 sec, 35.75 MB]                                                   [debug]

Obtaining gccnews project path. [33.28 sec, 35.76 MB]                                                  [debug]

Obtaining hierarchical_select project path. [33.29 sec, 35.76 MB]                                      [debug]

Obtaining job_scheduler project path. [33.29 sec, 35.76 MB]                                            [debug]

Obtaining jquery_update project path. [33.29 sec, 35.76 MB]                                            [debug]

Obtaining ldap project path. [33.29 sec, 35.77 MB]                                                     [debug]

Obtaining libraries project path. [33.29 sec, 35.77 MB]                                                [debug]

Obtaining logintoboggan project path. [33.29 sec, 35.77 MB]                                            [debug]

Obtaining media project path. [33.29 sec, 35.77 MB]                                                    [debug]

Obtaining media_ckeditor project path. [33.3 sec, 35.77 MB]                                            [debug]

Obtaining media_oembed project path. [33.3 sec, 35.77 MB]                                              [debug]

Obtaining module_filter project path. [33.3 sec, 35.78 MB]                                             [debug]

Obtaining name project path. [33.3 sec, 35.78 MB]                                                      [debug]

Obtaining pathauto project path. [33.3 sec, 35.78 MB]                                                  [debug]

Obtaining pathologic project path. [33.3 sec, 35.78 MB]                                                [debug]

Obtaining redirect project path. [33.3 sec, 35.78 MB]                                                  [debug]

Obtaining respondjs project path. [33.31 sec, 35.79 MB]                                                [debug]

Obtaining rules project path. [33.31 sec, 35.79 MB]                                                    [debug]

Obtaining taxonomy_container project path. [33.31 sec, 35.79 MB]                                       [debug]

Obtaining taxonomy_csv project path. [33.31 sec, 35.79 MB]                                             [debug]

Obtaining taxonomy_manager project path. [33.36 sec, 35.79 MB]                                         [debug]

Obtaining taxonomy_menu_block project path. [33.36 sec, 35.8 MB]                                       [debug]

Obtaining token project path. [33.36 sec, 35.8 MB]                                                     [debug]

Obtaining views project path. [33.36 sec, 35.8 MB]                                                     [debug]

Obtaining workbench project path. [33.36 sec, 35.8 MB]                                                 [debug]

Obtaining workbench_access project path. [33.37 sec, 35.8 MB]                                          [debug]

Obtaining workbench_email project path. [33.37 sec, 35.81 MB]                                          [debug]

Obtaining workbench_media project path. [33.37 sec, 35.81 MB]                                          [debug]

Obtaining workbench_moderation project path. [33.37 sec, 35.81 MB]                                     [debug]

Obtaining bootstrap project path. [33.37 sec, 35.81 MB]                                                [debug]

Update information last refreshed: Sun, 05/10/2015 - 4:13pm
  1
  GNU Wget 1.11.4

  Copyright (C) 2008 Free Software Foundation, Inc.
  License GPLv3+: GNU GPL version 3 or later
  <http://www.gnu.org/licenses/gpl.html>.
  This is free software: you are free to change and redistribute it.
  There is NO WARRANTY, to the extent permitted by law.

  Originally written by Hrvoje Niksic <hniksic@xemacs.org>.
  Currently maintained by Micah Cowan <micah@cowan.name>.
  SYSTEM_WGETRC = c:/progra~1/wget/etc/wgetrc
  syswgetrc = C:\Program Files (x86)\GnuWin32/etc/wgetrc
  SYSTEM_WGETRC = c:/progra~1/wget/etc/wgetrc
  syswgetrc = C:\Program Files (x86)\GnuWin32/etc/wgetrc
  SYSTEM_WGETRC = c:/progra~1/wget/etc/wgetrc
  syswgetrc = C:\Program Files (x86)\GnuWin32/etc/wgetrc
  SYSTEM_WGETRC = c:/progra~1/wget/etc/wgetrc
  syswgetrc = C:\Program Files (x86)\GnuWin32/etc/wgetrc
  SYSTEM_WGETRC = c:/progra~1/wget/etc/wgetrc
  syswgetrc = C:\Program Files (x86)\GnuWin32/etc/wgetrc
  SYSTEM_WGETRC = c:/progra~1/wget/etc/wgetrc
  syswgetrc = C:\Program Files (x86)\GnuWin32/etc/wgetrc
  SYSTEM_WGETRC = c:/progra~1/wget/etc/wgetrc
  syswgetrc = C:\Program Files (x86)\GnuWin32/etc/wgetrc
  SYSTEM_WGETRC = c:/progra~1/wget/etc/wgetrc
  syswgetrc = C:\Program Files (x86)\GnuWin32/etc/wgetrc
  SYSTEM_WGETRC = c:/progra~1/wget/etc/wgetrc
  syswgetrc = C:\Program Files (x86)\GnuWin32/etc/wgetrc
  SYSTEM_WGETRC = c:/progra~1/wget/etc/wgetrc
  syswgetrc = C:\Program Files (x86)\GnuWin32/etc/wgetrc
  SYSTEM_WGETRC = c:/progra~1/wget/etc/wgetrc
  syswgetrc = C:\Program Files (x86)\GnuWin32/etc/wgetrc
  SYSTEM_WGETRC = c:/progra~1/wget/etc/wgetrc
  syswgetrc = C:\Program Files (x86)\GnuWin32/etc/wgetrc
  SYSTEM_WGETRC = c:/progra~1/wget/etc/wgetrc
  syswgetrc = C:\Program Files (x86)\GnuWin32/etc/wgetrc
  SYSTEM_WGETRC = c:/progra~1/wget/etc/wgetrc
  syswgetrc = C:\Program Files (x86)\GnuWin32/etc/wgetrc
  SYSTEM_WGETRC = c:/progra~1/wget/etc/wgetrc
  syswgetrc = C:\Program Files (x86)\GnuWin32/etc/wgetrc
  SYSTEM_WGETRC = c:/progra~1/wget/etc/wgetrc
  syswgetrc = C:\Program Files (x86)\GnuWin32/etc/wgetrc
  SYSTEM_WGETRC = c:/progra~1/wget/etc/wgetrc
  syswgetrc = C:\Program Files (x86)\GnuWin32/etc/wgetrc
  SYSTEM_WGETRC = c:/progra~1/wget/etc/wgetrc
  syswgetrc = C:\Program Files (x86)\GnuWin32/etc/wgetrc
  SYSTEM_WGETRC = c:/progra~1/wget/etc/wgetrc
  syswgetrc = C:\Program Files (x86)\GnuWin32/etc/wgetrc
  SYSTEM_WGETRC = c:/progra~1/wget/etc/wgetrc
  syswgetrc = C:\Program Files (x86)\GnuWin32/etc/wgetrc
  SYSTEM_WGETRC = c:/progra~1/wget/etc/wgetrc
  syswgetrc = C:\Program Files (x86)\GnuWin32/etc/wgetrc
  SYSTEM_WGETRC = c:/progra~1/wget/etc/wgetrc
  syswgetrc = C:\Program Files (x86)\GnuWin32/etc/wgetrc
  SYSTEM_WGETRC = c:/progra~1/wget/etc/wgetrc
  syswgetrc = C:\Program Files (x86)\GnuWin32/etc/wgetrc
  SYSTEM_WGETRC = c:/progra~1/wget/etc/wgetrc
  syswgetrc = C:\Program Files (x86)\GnuWin32/etc/wgetrc
  SYSTEM_WGETRC = c:/progra~1/wget/etc/wgetrc
  syswgetrc = C:\Program Files (x86)\GnuWin32/etc/wgetrc
  SYSTEM_WGETRC = c:/progra~1/wget/etc/wgetrc
  syswgetrc = C:\Program Files (x86)\GnuWin32/etc/wgetrc
  SYSTEM_WGETRC = c:/progra~1/wget/etc/wgetrc
  syswgetrc = C:\Program Files (x86)\GnuWin32/etc/wgetrc
  SYSTEM_WGETRC = c:/progra~1/wget/etc/wgetrc
  syswgetrc = C:\Program Files (x86)\GnuWin32/etc/wgetrc
  SYSTEM_WGETRC = c:/progra~1/wget/etc/wgetrc
  syswgetrc = C:\Program Files (x86)\GnuWin32/etc/wgetrc
  SYSTEM_WGETRC = c:/progra~1/wget/etc/wgetrc
  syswgetrc = C:\Program Files (x86)\GnuWin32/etc/wgetrc
  SYSTEM_WGETRC = c:/progra~1/wget/etc/wgetrc
  syswgetrc = C:\Program Files (x86)\GnuWin32/etc/wgetrc
  SYSTEM_WGETRC = c:/progra~1/wget/etc/wgetrc
  syswgetrc = C:\Program Files (x86)\GnuWin32/etc/wgetrc
 Name               Installed Version  Proposed version  Message
 Name Field (name)  7.x-1.9            7.x-1.10          Update available

Code updates will be made to the following projects: Name Field [name-7.x-1.10]

Note: A backup of your project will be stored to backups directory if it is not managed by a supported version control system.
Note: If you have made any modifications to any file that belongs to one of these projects, you will have to migrate those modifications after updating.
Do you really want to continue with the update process? (y/n): y
Starting to update Name Field code at sites/all/modules/name... [59.32 sec, 34.56 MB]                 [notice]

Verifying signature for svn version control engine. [59.32 sec, 34.58 MB]                              [debug]

Executing: svn info "E:\\htdocs\\newsdev/sites/all/modules/name"
  'svn' is not recognized as an internal or external command,
  operable program or batch file.
Verifying signature for bzr version control engine. [59.44 sec, 34.57 MB]                              [debug]

Executing: bzr root "E:\\htdocs\\newsdev/sites/all/modules/name"
  'bzr' is not recognized as an internal or external command,
  operable program or batch file.
PHP Fatal error:  Allowed memory size of 536870912 bytes exhausted (tried to allocate 130968 bytes) in C:\Users\[username]\AppData\Local\Composer\vendor\drush\drush\includes\filesystem.inc on line 361

```

I also watched the performance monitor while the Drush command was executing. The behavior is very different depending on how much memory is allocated in drushrc.php:

* if memory is set to a moderate fixed amount (for this trace, it was set to 512M), memory usage barely changes, and CPU usage spikes to 100% for several seconds at three points in the process: when the PHP executable is loaded, and at two others later in the process that it was hard to pin down.
* if memory is set to unlimited, memory usage rapidly maxes out (the VM is currently allocated 4GB) and CPU maxes to 100% for the entire processing time, dipping below only when I'm being prompted for input and at a few other points. Eventually the system will either drop the remote desktop connection or spontaneously reboot.

# Answer
> 0 votes
Since I don't have the time or resources to hack or debug Drush, I worked around it by removing and manually re-installing Composer, then installing Drush 8. The problem no longer manifests.

---
Tags: drush
---


# Question
Title: How to add a payment gateway with two different accounts?
I want to add two different accounts for a single gateway . Depending upon `Product_id` or `product_sku` value it should use a corresponding account for payment.

How to do it? I have used the Drupal Commerce module.

# Answer
Use multiple payment method rules for the same payment gateway and add conditions to them that check for the existence of particular products in the order's line items. How you do that is up to you and what your product catalog is like.
> 2 votes

---
Tags: commerce
---


# Question
Title: Expose a view's filters both in a block, and in the actual view
I made a View, and I exposed the filters in a block; then, in the block's administrative screen, I set this block not to appear in the view that belong. In the actual view I don't want to show this block. Instead, I want the filters to appear in the content as they normally would if I didn't expose them in a block.

If that makes any difference, I am using Drupal 7.

# Answer
My understanding is that your view has exposed filters and that *Exposed form in block* is set to Yes.

To put the exposed form where it would appear if it weren't in block, you should be able to place the exposed form block into your *Content* region, above the view itself.

To have the exposed form displayed in both the view and a separate block, leave the form in the view and create a PHP block with the following body:

```
<?php
  if ($block = module_invoke('views', 'block', 'view', '-exp-YOUR_VIEW-YOUR_DISPLAY') ) {
    print $block['content'] ;
  }
?>

```
> 4 votes

# Answer
The accepted answer did not work with Drupal 7 for me. I followed http://www.drup-all.com/blog/exposed-filters-form-your-custom-block-drupal-7 with success. Code below:

```
/** implements hook_block_info() **/
function test_block_info(){
  $blocks = array();
  $blocks['custom_exposed_filter_form'] = array(
    'info' => t('Exposed filter form'),
    'cache' => DRUPAL_NO_CACHE,
  );
  return $blocks;
}

/** implements hook_block_view() **/
function test_block_view($delta = ''){
  $block = array();
  switch($delta){
    case 'custom_exposed_filter_form':
      $block['subject'] = t('Exposed filter form');
      $block['content'] = _test_get_exposed_filter_form();
    break;
  }
  return $block;
}

/** Function to get the Exposed filter form **/
function _test_get_exposed_filter_form(){
  // Get a view from the database or from default views . "test" is the view name.
  $view = views_get_view('test');
  // Set the display as current.
  $view->set_display('page');
  // Acquire and attach all of the handlers to the view.
  $view->init_handlers();
  $exposed_form = $view->display_handler->get_plugin('exposed_form');
  return $exposed_form->render_exposed_form();
}

```
> 7 votes

# Answer
```
$block = block_load('views', '-exp-VIEW_NAME-VIEW_DISPLAY');
$output = drupal_render(_block_get_renderable_array(_block_render_blocks(array($block))));
echo($output);

```
> 1 votes

# Answer
There is a Views UI alternative to the accepted answer, at least with Views 3 / D7:

* configure your view with the view exposed form *you'd like to see on the view page*
* **Clone that view** and for sake of future remembering, call it search block
* In the search block view, in advanced setup, set **Show the exposed form in a block : Yes**
* It 's important that **both views have the same path**
* Display the block where ever you'd like to

It's worth saying that with this method you **can now edit the search block** and remove some filters, add markup... (but no filters that would not be in the mother view I believe).

You can even reproduce steps and have **different custom blocks pointing to the same view.**

I've done that recently and found it very useful
> 1 votes

---
Tags: views
---


# Question
Title: Add CKEditor widget (footnotes) from external addon
I want to add CKEditor footnotes addon to a Drupal 8 toolbar.

The plugin seems to load as I can add the button when configuring the input format and I see `CKEDITOR.plugins.externals.footnotes` is defined and pointing to my plugin file. However the button does not show in the toolbar. No errors or warnings in the console.

This is my `/modules/custom/ckeditorfootnotes/src/Plugin/CKEditorPlugin/CKEditorFootnotes.php`

```
class CKEditorFootnotes extends CKEditorPluginBase implements CKEditorPluginInterface, CKEditorPluginButtonsInterface {

  /**
   * Implements \Drupal\ckeditor\Plugin\CKEditorPluginInterface::getFile().
   */
  function getFile() {
    return drupal_get_path('module', 'ckeditorfootnotes') . '/js/footnotes/plugin.js';
  }

  /**
   * Implements \Drupal\ckeditor\Plugin\CKEditorPluginButtonsInterface::getButtons().
   */
  function getButtons() {
    return array(
      'CKEditorFootnotes' => array(
        'label' => t('Footnotes'),
        'image' => drupal_get_path('module', 'ckeditorfootnotes') . '/js/footnotes/icons/footnotes.png'
      )
    );
  }

```

This is filter.format.basic\_html

```
    uuid: b47ec9da-02dc-420c-8100-c2127d8e5012
    langcode: ca
    status: true
    dependencies:
      module:
        - editor
    name: 'HTML bàsic'
    format: basic_html
    weight: 0
    filters:
      filter_html:
        id: filter_html
        provider: filter
        status: false
        weight: -10
        settings:
          allowed_html: '<a href hreflang target> <em> <strong> <cite> <blockquote cite> <code> <ul type> <ol start type> <li> <dl> <dt> <dd> <h2 id> <h3 id> <h4 id> <h5 id> <h6 id> <p> <br> <span> <img src alt height width data-entity-type data-entity-uuid data-align data-caption> <s> <table> <caption> <tbody> <thead> <tfoot> <th> <td> <tr> <sub> <sup> <section>'
          filter_html_help: false
          filter_html_nofollow: false
      filter_align:
        id: filter_align
        provider: filter
        status: true
        weight: 7
        settings: {  }
      filter_caption:
        id: filter_caption
        provider: filter
        status: true
        weight: 8
        settings: {  }
      filter_html_image_secure:
        id: filter_html_image_secure
        provider: filter
        status: true
        weight: 9
        settings: {  }
      editor_file_reference:
        id: editor_file_reference
        provider: editor
        status: true
        weight: 11
        settings: {  }

```

And finally `editor.editor.basic_html`

```
uuid: 175d53b1-06a9-4aca-9755-85595f23633b
langcode: ca
status: true
dependencies:
  config:
    - filter.format.basic_html
  module:
    - ckeditor
    - editor_file
third_party_settings:
  editor_file:
    status: true
    scheme: public
    directory: inline-files
    extensions: txt
format: basic_html
editor: ckeditor
settings:
  toolbar:
    rows:
      -
        -
          [... several groups ...]
        -
          name: Media
          items:
            - CKEditorFootnotes
            - DrupalFile
            - Blockquote
            - DrupalImage
            - Table
        -
          [... more groups ...]
  plugins:
    stylescombo:
      styles: ''
image_upload:
  status: true
  scheme: public
  directory: inline-images
  max_size: ''
  max_dimensions:
    width: null
    height: null

```

# Answer
It turns out you need to call `editor.ui.addButton()` to get the buttons to show.

It seems to me that it is not usually needed in *vanilla* CKEditor development, because it is not included neither in the tutorials nor in the ckeditorfootnotes plugin. However, most of the current Drupal 8 CKEditor modules do include it in the plugin source.

For the simplebox plugin it would read like this, here `command` is the name of the defined widget.

```
editor.ui.addButton('SimpleBox', {
    label: Drupal.t('SimpleBox'),
    command: 'simplebox',
    icon: this.path + 'icons/simplebox.png'
});

```
> 1 votes

---
Tags: 8, wysiwyg, plugins
---


# Question
Title: Display two products as two radio buttons with a single Add to Cart Form
I am having trouble deciding how to tackle this problem. I have two products (indeed, one *could* be made as an attribute of another, which may help) which are basically two ticket options, only one of which can be purchased by a customer. Therefore I would like to display them as two radio buttons with a single add to cart button (which I would then configure with Rules to send them straight to checkout).

**Right now I have this:**

Again, I would like to basically have two buttons, only one of which can be selected, with a single Add to Cart form.

Any ideas?

# Answer
> 1 votes
Drupal commerce was designed to do exactly this without going through lots of hoops, but it might be a bit tricky to get into.

Instead of making one an argument of another I'd create one product display with two different attached products, for which you can set an attribute field and a price. You can do so by having a node content type to act as a 'product display'. To do so you require inline\_entity\_form and commerce\_product\_reference (part of the commerce package).

* On the product-type add a field the distinguish 'premium' product and make sure to hit the 'Enable this field to function as an attribute' checkbox.
* Add a product reference field to a (new) content type you call 'product display' (or if you plan on selling more different kinds of products you can use a more specific name line 'event ticket' or something).
* For the field widget choose 'inline entity form (multiple)'.
* Create a node of the 'product'-type and add the two different products and their properties; for the 'premium' product make sure to change the price and the attibute field we created earlier.
* Save the node.

If all went well you should end up with a selection box on the 'product display' node, allowing the users to select which version of the product they want to buy.

If you find this too vague, there is a detailed explanation (with pictures) on it here: Product Attributes & Variations. It does not use inline entity form so the 'attach products' involves a drop down on the images, whereas inline entity form will allow you to create and edit the entities directly on the node.

---
Tags: commerce
---


# Question
Title: How do I prevent a product from being added to the cart?
A common question I hear is "How can I prevent a product from being added to the cart?" There are several reasons why you'd want to do this, most end up being related to some logic being required to determine if a product is eligible without actually deactivating the Add to Cart button.

# Answer
While you probably ought to actually disable the Add to Cart button, you'd actually put logic for determining whether or not a product should be added to the cart in a validate handler.

The first step us to add a `form_alter` hook that adds a validation handler to the add to cart forms.

```
/**
 * Implements hook_form_FORM_ID_alter().
 */
function MYMODULE_form_commerce_cart_add_to_cart_form_alter(&$form, &$form_state) {
  // Add a validate hook so that the order can be checked to ensure that the
  // our constraints are met.
  array_unshift($form['#validate'], 'MYMODULE_validate_some_stuff');
}

```

*Note: this works because of `commerce_cart_forms()` which adds the generic form callback instead of requiring us to look for the string in the `$form_id`.*

Now, you just need to implement your logic:

```
/*
 * Check the product/order against my constraints.
 */
function MYMODULE_validate_some_stuff(&$form, &$form_state) {
  $order = commerce_cart_order_load($form_state['values']['uid']);
  $line_item = $form_state['line_item'];

  if (/* your logic here */) {
    form_set_error('product_id', t('Sorry, you can\'t do that!'));
  }
}

```

You'll notice that the `commerce_order` is loaded by the user's UID and you've got access to the `commerce_line_item` that you can then use to grab the product (use `$line_item->commerce_product`). Also, there is no need to return `TRUE` or `FALSE`. Just set an error.
> 5 votes

---
Tags: commerce
---


title: Attaching a JS library to every page

text:
# Question
Title: Attaching a JS library to every page
I'd like to attach a javascript library to every page call. I created a directory for my module called flot\_d8 I created an info file, lot\_d8.info.yml. My understanding is, the libraries section should insert the javascript on every page load:

```
name: FLOT-D8
type: module
description: 'This module provides a wrapper to the javascript FLOT library.'
package: Misc
version: 8.x-1.0
core: 8.x
hidden: false
libraries:
  - flot_d8/flot

```

The library file which describes the flot asset is flot\_d8.libraries.yml. I placed the flot library in drupal/modules/flot\_db/flot:

```
flot:
  version: 1.x
  js:
    flot/jquery.flot.js: {}
  dependencies:
    - core/jquery

```

I enabled my module and fail to see the inclusion of jquery or foot in the header. My next attempt was to make a flot\_d8.module file with a call to hook\_page\_attachment\_alter:

```
<?php
function flot_d8_page_attachments_alter(array &$page) {
  // Attach the flot asset on every page.
  $page['#attached']['library'][] = 'flot_d8/flot';
}

```

Still no dice. Any advice? I'm wanting to begin playing around with getting the flot library working in D8. I'll eventually move the javascript attachment to occur during themeing, but I don't want to attempt that until I can even get the simplest case working.

As background. I've installed the PHP module so I can enter PHP directly into a page. If I insert the scripts and add javascript directly in the page. it works fine. This tells me the files are in the webspace and readable by the outside world:

```
<script src="http://test.mysite.com/core/assets/vendor/jquery/jquery.js"></script>
<script language="javascript" type="text/javascript" src="http://test.mysite.com/modules/flot_d8/flot/jquery.flot.js"></script>
<script language="javascript" type="text/javascript" src="http://test.mysite.com/modules/flot_d8/flot/jquery.flot.pie.js"></script>
<script type='text/javascript'>//<![CDATA[
$(window).load(function(){
  $(function () {
    var d1 = [];
    for (var i = 0; i < 14; i += 0.5)
      d1.push([i, Math.sin(i)]);

    var d2 = [[0, 3], [4, 8], [8, 5], [9, 13]];

    // a null signifies separate line segments
    var d3 = [[0, 12], [7, 12], null, [7, 2.5], [12, 2.5]];

    $.plot($("#placeholder"), [ d1, d2, d3 ]);
  });
});//]]>

</script>
<div id="placeholder" style="width:600px;height:300px;"></div>

```

EDIT: I surrounded the jQuery, and still no go. I tried simplifying the problem to just try to force the inclusion of jQuery on every page load and that does not work either. I changed the module file to be

```
function flot_d8_page_attachments(array &$page) {
  // Attach the flot asset on every page.
  $page['#attached']['library'][] = 'core/jquery';
}

```

and changed the basic page to be

```
<?php
$jquery_already_included = TRUE;
if (!$jquery_already_included) {
  echo '<script src="http://test.mysite.com/core/assets/vendor/jquery/jquery.js"></script>';
}
?>
<script>
(function ($) {
  function myFunction() {
    $("#h01").html("Hello jQuery")
  }
  $(document).ready(myFunction);
})(jQuery)
</script>
<h1 id="h01"></h1>?>

```

and even that does not work.

# Answer
It looks like the javascript file WERE included before, but they were in the footer. When jQuery code is placed in a basic page, that appears to not work. However, forcing the js files in the header allows everything to run.

I changed my module file to be:

```
<?php
function flot_d8_page_attachments(array &$page) {

 $page['#attached']['html_head'][] = [
    // The data.
    [
      // The HTML tag to add, in this case a <script> tag.
      '#tag' => 'script',
      '#attributes' => array(
        'language' => "javascript",
        'type' => "text/javascript",
        'src' => "http://test.mysite.com/core/assets/vendor/jquery/jquery.js",
      ),
      '#value' => '',
    ],
    // A key, to make it possible to recognize this HTML <HEAD> element when altering.
    'jquery-define'
  ];

  // Attach the flot asset on every page.
  $page['#attached']['html_head'][] = [
    // The data.
    [
      // The HTML tag to add, in this case a <script> tag.
      '#tag' => 'script',
      '#attributes' => array(
        'language' => "javascript",
        'type' => "text/javascript",
        'src' => "http://test.mysite.com/modules/flot_d8/flot/jquery.flot.js",
      ),
      '#value' => '',
    ],
    // A key, to make it possible to recognize this HTML <HEAD> element when altering.
    'flot-define'
  ];

}

```

And my Basic-Page javascript now works.
> 0 votes

---
Tags: javascript, 8
---


title: What is the hook_views_data base field?

text:
# Question
Title: What is the hook_views_data base field?
Looking at the documentation for hook\_views\_data(), I see this:

```
$data['example_table']['table']['base'] = array(
  'field' => 'nid', // This is the identifier field for the view.
  ...
);

```

What exactly does identifier field mean? Is it supposed to be the primary key of the table? If so, what if the primary key is composite? Or if not necessarily primary key, why wouldn't it be?

# Answer
> 0 votes
With base you can tell views which table to start from

`base` is a sort of meta data for the views. It describes what would be the primary key of the table, what should be the views title in creating views and some help for the users to use this custom views.

`field` define the primary key of the custom table you want to show in views. `title` is the title that will appear in your `show` dropdown on add view page.

EDIT: field is not a required field but its good to tell your view what is the primary key of your custom table. In case of composite key you can define both your columns in `array(key1,key2)`

---
Tags: views
---


# Question
Title: Add comma in between the Tags Display in Drupal 7
Can any one help me how to add comma inbetween the tags in drupal 7.

I have inspect the code for the following tags

```
Tags: Test bha

```

the code for this is

```
         <DIV class="tagsdisplay" >
             <DIV class="label-inline">Tags: </DIV>
                <A  href="http://localhost/drupal/tags/test" typeof="skos:Concept" property="rdfs:label skos:prefLabel">Test</A>
                <A href="http://localhost/drupal/tags/bha" typeof="skos:Concept" property="rdfs:label skos:prefLabel">bha</A>
              </DIV>
         </DIV>

```

I have used used the following code to add the comma inbetween the tags

```
              function fold__field_tags($variables) {

                   $output = '';

              // Subtract 1 from count to match $delta which starts at 0
               $count = (count($variables['items']) - 1);

              // Render the label, if it's not hidden.
              if (!$variables['label_hidden']) {
             $output .= '<div class="label-inline"' . $variables['title_attributes'] . '>' . $variables['label'] . ': </div>';
                 }

           // Render the items.
          $output .= '<div class="label-inline"' . $variables['content_attributes'] . '>';
          foreach ($variables['items'] as $delta => $item) {
          $classes = 'field-item ' . ($delta % 2 ? 'odd' : 'even');
          $output .= '<div class="' . $classes . '"' . $variables['item_attributes'][$delta] . '>' . drupal_render($item) . '</div>';
         // If this is not the last item, print a comma and space
         if($delta < $count) {
          $output .= ', ';
         }
         }
       $output .= '</div>';

    // Render the top-level DIV.
      $output = '<div class="' . $variables['classes'] . '"' . $variables['attributes'] . '>' . $output . '</div>';

      return $output;

    }

```

Can Anyone help me where i made a mistake.

# Answer
For anyone who needs to do this in the future:

```
div.field-name-field-tags div.field-items div:after {
  content: ", ";
}

div.field-name-field-tags div.field-items div:last-child:after {
  content: "";
}

```
> 3 votes

# Answer
You can also do this with CSS, without modifying templates or adding modules:

```
.field-name-field-tags .field-item:after {
    content: ",";
}
.field-name-field-tags .field-item {
    display: inline;
    margin-right: 0.5em;
}

```

The only drawback is that the last one in the list will also have a comma and a space after. On the other hand, there's no messing around with .php or new modules :)
> 1 votes

# Answer
You might also be interested in the module:

textformatter

> This module provides a field display formatter to **render field values as HTML or comma-separated lists.** This can currently be used on all core field types (text, long text, number, list, and taxonomy reference etc..) and some contributed fields.
> 1 votes

# Answer
I just added the following template to my theme.

```
field--field-titles.tpl.php

<div class="<?php print $classes; ?>"<?php print $attributes; ?>>
  <?php if (!$label_hidden): ?>
    <div class="field-label"<?php print $title_attributes; ?>><?php print $label ?>: </div>
  <?php endif; ?>
  <div class="field-items"<?php print $content_attributes; ?>>
    <?php foreach ($items as $delta => $item) : ?>
      <div style="display:inline;" class="field-item <?php print $delta % 2 ? 'odd' : 'even'; ?>"<?php print $item_attributes[$delta]; ?>>
        <?php
          print render($item);
          // Add comma if not last item
          if ($delta < (count($items) - 1)) {
            print ', ';
          }
        ?>
      </div>
    <?php endforeach; ?>
  </div>
</div>

```
> 1 votes

---
Tags: theming
---


title: Returning HTML from a controller

text:
# Question
Title: Returning HTML from a controller
I have followed the guide at http://befused.com/drupal/first-drupal8-module to create a simple Drupal 8 controller, and it works as described. Instead of printing "Hello World" I would like to create more complex HTML. I found a guide that appears to step through what I need to do at http://jonathanpatrick.me/blog/safe-markup. I added hook\_theme to my flot\_d8.module file:

```
function flot_d8_theme(array $existing, $type, $theme, $path) {
  return array(
    'flot_d8_my_template' => array(
      'template' => 'my-template',
      'variables' => array(
        'variable1' => NULL,
        'variable2' => NULL,
      ),
    ),
  );
}

```

and created the my-template.html.twig file exactly as shown:

```
<div class="my-template">
  This is the first variable: <b>{{ variable1 }}</b>.
  This is the second variable: <i>{{ variable2 }}</i>.
</div>

```

I'm guessing my problem is in the way I try to call the theme. My controller code is:

```
namespace Drupal\flot_d8\Controller;
use Drupal\Core\Controller\ControllerBase;
class Flot_d8 extends ControllerBase {
  public function content() {
    return [
      '#theme' => 'flot_d8_my_template',
      '#variable1' => t("First"),
      '#variable2' => t("Second"),
    ];
  }
}

```

Is this the correct way to print a `<div>` to the screen? Do I need to register the template file in my info file somewhere?

# Answer
> 2 votes
I removed the template line from hook\_theme and renamed the file to flot-d8-my-template. Cleared the cache and it worked.

---
Tags: theming, 8
---


# Question
Title: How do I allow users to rearrange the fields order during content creation?
Assume I have a *content type* with fields `a`, `b`, `c`.

How to allow users to **rearrange fields** (when they create one content) if they want to display fields in another order? Like b,a,c or c,b,a, etc ...

EDIT: Panelizer do the job for my case. There is a bug when trying to save the display. But getting both the Panels and Panelizer modules in latest dev version fixed it.

# Answer
> 1 votes
If you want per-node changing of field display order I recommend looking at Panelizer module. It takes over view modes at the level of entity bundles (content types) and additionally individual entities.

It is not an exact fit of what you describe in that:

* It works on an interface separate from content creation.
* It is view mode specific. So rearranging one view mode (teaser) will not change the full view mode. That might be good or bad depending on what you want.

---
Tags: entities
---


# Question
Title: How to allow special character in username?
Is there any way to allow the special character in username like "#" and "~"?

# Answer
You have to override the defualt user\_validate\_name($name) :

```
Verify the syntax of the given name.

```

To do that, define your username validation code in your custom module

```
function MODULENAME_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'user_register') {
    $form['#validate'] = array();
    $form['#validate'][] = 'registration_username_validate';

  }
}

```

And inside registration\_username\_validate function do your logic to allow your special characters.

Care about **security issues** caused by allowing special chars in username and about display issues not sanitized usernames may cause in themes.
> 11 votes

# Answer
Unfortunately, there is no straight forward way to do this. By default `user_register_form` and `user_profile_form` have `user_account_form_validate` set as their first validator in `$form['#validate']`. `user_account_form_validate()` checks and cleans up the name, email, and signature of an account. As part of checking the name it makes a call to `user_validate_name()`. This is the function we want to override, not `user_account_form_validate`.

One would hope for a helpful hook to override it, but alas. If I didn't care about validation of the email and signature as well the check to see if the name is a duplicate, I could just remove `user_account_form_validate` from `$form['#validate']`. But that's no good. Instead, I add an additional validator that undoes the work of `user_validate_name()` and redoes everything without the special character check.

```
<?php
function MODULENAME_form_user_register_form_alter(
  array &$form, array &$form_state, $form_id)
{
  MODULENAME_add_name_validator($form);
}

function MODULENAME_form_user_profile_form_alter(
  array &$form, array &$form_state, $form_id)
{
  MODULENAME_add_name_validator($form);
}

function MODULENAME_add_name_validator(array &$form)
{
  $validate =& $form['#validate'];
  # Since `validate_name()` clears out any errors for the "name" field, we
  # want to put it right after the validator we want to partially override.
  $acct_validate_index = array_search('user_account_form_validate', $validate);
  array_splice($validate, ($acct_validate_index + 1), 0,
    ['MODULENAME_validate_name']
  );
}

function MODULENAME_validate_name(array $form, array &$form_state)
{
  # There is no blessed way of overriding the call to `user_validate_name()` in
  # `user_account_form_validate()`.
  $errors =& drupal_static('form_set_error', []);
    # Yes, this gets the errors. `form_get_error()` uses this method so... yeah.
  if (!isset($errors['name']))
    # `user_validate_name()` is a superset of what is checked here. If the name
    # passed that validation, no need to rerun things.
    return;

  # `form_set_error()` also calls `drupal_set_message()` if it finds an
  # error.
  $msg_index = array_search($errors['name'], $_SESSION['messages']['error']);
  if ($msg_index !== false) {
    unset($_SESSION['messages']['error'][$msg_index]);
    if (empty($_SESSION['messages']['error']))
      unset($_SESSION['messages']['error']);
  }
  unset($errors['name']);

  $name = isset($form_state['values']['name'])
          ? $form_state['values']['name'] : null;

  # These checks are taken from `user_validate_name()`, simply excluding the
  # for characters we don't mind being in the names.
  if (!$name)
    $error = t('You must enter a username.');
  else if (substr($name, 0, 1) == ' ')
    $error = t('The username cannot begin with a space.');
  else if (substr($name, -1) == ' ')
    $error = t('The username cannot end with a space.');
  else if (strpos($name, '  ') !== FALSE)
    $error = t('The username cannot contain multiple spaces in a row.');
  else if (preg_match('/[\x{80}-\x{A0}' .   // Non-printable ISO-8859-1 + NBSP
                      '\x{AD}' .            // Soft-hyphen
                      '\x{2000}-\x{200F}' . // Various space characters
                      '\x{2028}-\x{202F}' . // Bidirectional text overrides
                      '\x{205F}-\x{206F}' . // Various text hinting characters
                      '\x{FEFF}' .          // Byte order mark
                      '\x{FF01}-\x{FF60}' . // Full-width latin
                      '\x{FFF9}-\x{FFFD}' . // Replacement characters
                      '\x{0}-\x{1F}]/u',    // NULL byte and control characters
                      $name))
    $error = t('The username contains an illegal character.');
  else if (drupal_strlen($name) > USERNAME_MAX_LENGTH)
    $error = t('The username %name is too long: it must be %max characters '
              .'or less.'
              ,['%name' => $name, '%max' => USERNAME_MAX_LENGTH]);

  if (isset($error))
    form_set_error('name', $error);
}

```

There is still a special character check, however it only checks for invisible or special use characters.
> 1 votes

---
Tags: 7, users
---


# Question
Title: How do i override a View attachment glossary fields link or url
Is there a way of overriding an `attachment views` field's url link that is in glossary mode?

I've tried altering the url and link property of the field in the pre-render and post render theme functions, and I can alter their values but it never sticks. I've tried the `.tpl.php` file but then the html tags.

I need to make them links to anchor links show.

# Answer
> 0 votes
So i dont have a definitive yes or no, but if i was to wager a bet i would say... No. There is no way of overriding the glossary mode's url link and make it link to content on the current page. I saw someone else ask this question better than I did back in 2012 and no one answered him, which pushed me to do this in the old way, by building a custom html table and doing the leg work there. So the answer is no need to, just do it in the .tpl.php file.

---
Tags: views
---


# Question
Title: Integrating FBA (or Amazon MWS) with Ubercart
I am going to be rebuilding an ecommerce site in Drupal 8 using Ubercart. The site was originally built with Drupal 6 and Ubercart and had Amazon FWS integrated into the store. Is there anything similar I can use for Drupal 8? Basically the client needs FBA (fulfillment by Amazon) integrated into the site.

# Answer
> 0 votes
There's Commerce Amazon fulfillment if you're not wedded to Ubercart, but it needs porting to D8.

---
Tags: 8, ubercart
---


title: Where are fivestar data stored?

text:
# Question
Title: Where are fivestar data stored?
On a D7 site using fivestar , I'd like to extract data from the module but there is not such table or node in the database and looking at the source code, I could not figure out in which table/fields the fivestart data are related/stored.

So appreciate your help about this.

# Answer
The table does not have 'fivestar' in the name - try looking for the content type, or the word 'vote', or the axis name, in table names. For example, I have a (test) content type named 'Review' with three voting axes. The Fivestar fields are as follows:

* field\_data\_field\_review\_votes\_average
* field\_data\_field\_review\_vote\_axis\_one
* field\_data\_field\_review\_vote\_axis\_three
* field\_data\_field\_review\_vote\_axis\_two
> 1 votes

# Answer
Fivestar module defines a field. Add a field to a content type. If fx you add a field named "test" of type fivestar reting to a content type then you can find the table with the name "field\_data\_field\_test".
> 2 votes

---
Tags: rating
---


# Question
Title: Filtering out duplicate dates from different nodes in views
I have a "This day in history" page on my website, which when viewed in a monthly view shows of list of everything that has happened on each day in the month (so, for example January might say January 1: Monkeys learn to motorbike, January 2: Otters invade, etc.)

My issue is we have some new historical dates we want to add, so in this view I'm starting to see duplicate dates that have different content. (i.e, January 10: Yeti discovered, January 10: Moose have picnic with Bears).

The problem is I don't want to have duplicate dates on this view, rather I only want the most recently published/updated node to show up. Is there a way I can order a unique based off of a date field in views?

I'm sure I could probably do this through a views template and just manually remove the duplicate dates, but I would rather just limit the amount of data I'm receiving in the first place.

I'm wondering if this could be done through aggregation? Group my responses together based on their date, and only allow one item per group?

# Answer
> 0 votes
If there was a way to do this purely in views, I haven't discovered it.

What I was able to do though, was to use templates to remove the second item if it had a date that matched another item.

---
Tags: 7, views
---


# Question
Title: Remove login confirmation message programmatically
I have the login form displayed in the CTools modal dialog. When users log in, they see the confirmation message and a Rules action redirect them to the home page. How can I remove the confirmation message without using the disable\_messages module?

# Answer
You can add a custom module hook to alter the login process and unset the messages. If you look at core's user.module you can see the various points where you can hook into the login functions.

This is one option (I think there are several and you may need to adjust based on your site's settings) You should be able to do something along these lines:

```
function YOURMODULE_user_login(&$edit, $account) {
  if ($account->uid) {
     if (isset($_SESSION['messages']['status'])) {
       unset($_SESSION['messages']['status']);
     }
  }
}

```
> 0 votes

---
Tags: 7, forms, rules, users
---


# Question
Title: How do I declare my custom entities as non-multilingual?
I have written a custom module providing two custom config entities holding data, that is not language-specific. But I can't seem to find a way to tell Drupal, that there is no need to "translate" these entities - in fact, I get this action offered on every entity listing.

Even all core entities I found so far implement translation, but some provide their own translation handler. (Is this maybe a way to do it? Implementing a custom translation handler that tells Drupal not to translate anything? But how?)

Is someone out there who can point me in the right direction please?

My actual annotation look like this (please notice the "translatable" option, which is not working):

```
@ConfigEntityType(
  id = "ad_tag",
  label = @Translation("Advertisement tag"),
  module = "field_vimeo",
  config_prefix = "field_vimeo.ad_tag",
  admin_permission = "administer site configuration",
  translatable = FALSE,
  handlers = {
    "storage" = "Drupal\field_vimeo\AdTagStorage",
    "list_builder" = "Drupal\field_vimeo\AdTagListBuilder",
    "form" = {
      "default" = "Drupal\field_vimeo\Form\AdTagForm",
      "delete" = "Drupal\field_vimeo\Form\AdTagDeleteForm"
    }
  },
  links = {
    "edit-form" = "/admin/structure/field_vimeo/ad_tags/manage/{ad_tag}",
    "delete-form" = "/admin/structure/field_vimeo/ad_tags/manage/{ad_tag}/delete"
  },
  entity_keys = {
    "id" = "id",
    "type" = "type",
    "label" = "label"
  },
  config_export = {
    "id" = "id",
    "type" = "type",
    "label" = "label",
    "data" = "data"
  }
)

```

# Answer
Translatability for config and content entities is different. Translation handler is a content entity thing. Storage for translations needs to be explicitly enabled by adding a data table.

For config entities, it's different. Translatability works automatically there through config overrides. There's nothing that you need to do to opt-in to being translatable, but you also can't prevent it. What you can is control which properties are translatable through the config schema. Like the label,which is, technically, a translatable, user-provided string.

If you don't need it translated, just don't create any translations for it or if you don't need any configuration translations, don't enable the config translation module.
> 3 votes

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


# Question
Title: Invalid form POST data - ajax for Authenticated users
I have a Drupal form using ajax. When I submit the form I am getting the following being displayed:

When I check the Drupal log I have the following entry.

I have Googled the error and found this post but it applies to anonymous users. I am only using this with authenticated users.

Searching for the error in the code returns the `ajax_get_form()` function in `ajax.inc`

```
 $form_state = form_state_defaults();

  $form_build_id = $_POST['form_build_id'];

  // Get the form from the cache.
  $form = form_get_cache($form_build_id, $form_state);
  if (!$form) {
    // If $form cannot be loaded from the cache, the form_build_id in $_POST
    // must be invalid, which means that someone performed a POST request onto
    // system/ajax without actually viewing the concerned form in the browser.
    // This is likely a hacking attempt as it never happens under normal
    // circumstances, so we just do nothing.
    watchdog('ajax', 'Invalid form POST data.', array(), WATCHDOG_WARNING);
    drupal_exit();
  }

```

`$form` is not an object. I am not sure why.

In the `ajax_get_form()` function I am doing ado a `dd()` of `$form_build_id`. This returns me something like `form-ymw-BN0Zhp9j2CZf82mZzslbUBiLo8kZbreXhB1y8kE`.

If I perform the following SQL in the database I get a result.

```
select *  from cache_form where cid like '%form-ymw-BN0Zhp9j2CZf82mZzslbUBiLo8kZbreXhB1y8kE%';

```

The `cid` in this instance is `form_state_form-ymw-BN0Zhp9j2CZf82mZzslbUBiLo8kZbreXhB1y8kE`.

In form\_get\_cache() the code is as follows:

```
function form_get_cache($form_build_id, &$form_state) {
  if ($cached = cache_get('form_' . $form_build_id, 'cache_form')) {
     //code missing
  }
}

```

From `cache_get()` we are looking for `form_form-ymw-BN0Zhp9j2CZf82mZzslbUBiLo8kZbreXhB1y8kE`but what we have stored in the database is `form_state_form-ymw-BN0Zhp9j2CZf82mZzslbUBiLo8kZbreXhB1y8kE`. Of course we do not match so nothing is returned.

I am unsure why this is happening.

My form code is as follows

```
  $form['welcome'] = array(
    '#markup' => //some html markup,
  );

  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Test'),
    '#ajax' => array(
      'callback' => 'myform_js',
      'wrapper' => 'message_container',
      'method' => 'replace',
      'effect' => 'fade',
      'event' => 'click',
    ),
  );

  $form['result'] = array(
    '#prefix' => '<div id="message_container">',
    '#suffix' => '</div>',
    '#type' => 'fieldset',
  );

```

The function `myform_js()` is not being hit as when dd() is added to the top it is not called. I can't see anything obviously wrong with this so not sure if there are any environmental issues that could cause the issue.

I have also tried changing the type of `$form['submit']` to `button`.

It looks that the part that is failing is the call to `cache_set()`. I am unsure as why at the moment.

# Answer
OK think I have it.

As `form_form-ymw-BN0Zhp9j2CZf82mZzslbUBiLo8kZbreXhB1y8kE` was not being set I looked at `form_set_cache()`.

```
/**
 * Stores a form in the cache.
 */
function form_set_cache($form_build_id, $form, $form_state) {
  // 6 hours cache life time for forms should be plenty.
  $expire = 21600;

  // Cache form structure.
  if (isset($form)) {
    if ($GLOBALS['user']->uid) {
      $form['#cache_token'] = drupal_get_token();
    }
    cache_set('form_' . $form_build_id, $form, 'cache_form', REQUEST_TIME + $expire);
  }

  // Cache form state.
  if ($data = array_diff_key($form_state, array_flip(form_state_keys_no_cache()))) {
    cache_set('form_state_' . $form_build_id, $data, 'cache_form', REQUEST_TIME + $expire);
  }
}

```

I dug into `cache_set()`

```
function cache_set($cid, $data, $bin = 'cache', $expire = CACHE_PERMANENT) {
  return _cache_get_object($bin)->set($cid, $data, $expire);
}

```

I then looked into `set()`

```
  /**
   * Implements DrupalCacheInterface::set().
   */
  function set($cid, $data, $expire = CACHE_PERMANENT) {
    $fields = array(
      'serialized' => 0,
      'created' => REQUEST_TIME,
      'expire' => $expire,
    );
    if (!is_string($data)) {
      $fields['data'] = serialize($data);
      $fields['serialized'] = 1;
    }
    else {
      $fields['data'] = $data;
      $fields['serialized'] = 0;
    }

    try {
      db_merge($this->bin)
        ->key(array('cid' => $cid))
        ->fields($fields)
        ->execute();
    }
    catch (Exception $e) {
      // The database may not be available, so we'll ignore cache_set requests.
    }
  }

```

Here an exception is caught and not reported. I added a `dd()` into catch. Looking in drupal\_debug.txt

```
[message:protected] => SQLSTATE[08S01]: Communication link failure: 1153 Got a packet bigger than 'max_allowed_packet' bytes

```

I have now increased the value of `max_allowed_packet` in MySQL. It has fixed things.

With this information I did some more googling and found this post. They have had the same problem that I had.
> 9 votes

# Answer
After the "Invalid form POST data" watchdog message, notice that the **ajax\_get\_form()** function calls **drupal\_exit()**.

Your custom module can take advantage of this by hooking into **hook\_exit()**... from there you can rebuild the expired/uncached form and attempt to resubmit form using Drupal's ajax\_commands framework.

The following is an example of how I resolved this problem for an "AJAX-ified" user-login form.

```
/**
 * Implements hook_exit().
 */
function example_exit($destination = NULL) {
  if (arg(0) == 'system' && arg(1) == 'ajax') {
    $is_user_login_form_submission = isset($_POST) && isset($_POST['name']) && isset($_POST['pass']) && isset($_POST['form_build_id']);

    if ($is_user_login_form_submission) {
      watchdog(__FUNCTION__, 'User login AJAX form submission failed. Trying again...', array(), WATCHDOG_WARNING);

      $form_build_id = $_POST['form_build_id'];
      $form_state = form_state_defaults();
      $form_state['values'] = $_POST; // Important!
      $form = drupal_rebuild_form('user_login', $form_state);
      $form['#build_id_old'] = $form['#build_id']; // Important!

      // Try form submission again after it is rebuilt above
      $commands[] = ajax_command_update_build_id($form);
      $commands[] = ajax_command_invoke('form#user-login', 'trigger', array('submit'));

      print ajax_render($commands);
    }
  }
}

```
> 2 votes

# Answer
I know this question has been solved, but I encountered "Invalid form POST data" and the cause was different, so I'll throw it out there for people who come across this.

Basically, my culprit was a cron job that was especially zealous, clearing cache every 5 minutes. The issue wasn't with memory limits or writing to the database, but rather that fairly often the form would get cached, the cache would get cleared, and then attempting to get the form from cache would fail. Switching the cron job to hourly fixed it.
> 1 votes

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


# Question
Title: Adaptive theme css which stylesheet to use?
In the adaptive theme in the sass folder and it has following files, I understand about some stylesheets and for what purpose they are. But I am confuse about `global.base.scss`, `global.style.scss`, `responsive.desktop.scss`, `responsive.custom.scss` and `print.scss`. Now which one shall I use specific purpose.

e.g. `global.base.scss` and `global.style.scss`, both has `html` and `body` now if we want to use `font-size: 62.5%` in `root` for using `rem` as `unit` so in which `html` shall I have to put?

# Answer
The AdaptiveTheme site has a lot of great documentation to help explain this.

In general, you should use `global.styles.scss` to style elements that will look the same across all devices, and the individual responsive stylesheets (e.g. `responsive.desktop.scss`) for device-specific styles. If you want to override something in `global.base.scss`, you're probably best off doing it in `global.styles.scss`, depending on how fundamental the change is.
> 1 votes

---
Tags: theming
---


title: Using 'AddThis' to add a 'more' button

text:
# Question
Title: Using 'AddThis' to add a 'more' button
I'm using AddThis to add sharing functionality for my nodes. I setup the tool in 'config' and selected the options I wanted...and it shows up ok. However, I can't figure out how to add the orange 'more' button with the white + sign...see here for an example of what I mean by the orange button with the plus sign (it's their favico and also displays on their vertical addthis sharing bar on the left).

I tried finding it here but searching for 'more' doesn't find it. So I don't know what it's called. I also tried just adding a bunch more services but that just adds a long horizontal list of buttons.

This more button is great because not only does it allow people to use other services to share things, other than the most common services, but it also shows the number of times the page has been shared!

Anyone know how to add this more button?

# Answer
> 0 votes
Ok, so it turns out you add the orange 'more' services button (with the white plus icon) by using 'compact' as the name of the service in the services list when configuring the display for the AddThis field in your content type.

---
Tags: 7
---


# Question
Title: How to show the number of times a page has been shared by all services total?
Is it possible to show a small block (using code or a module or something) that shows how many times the page a user is on has been shared using ANY of the available sharing methods?

For example, I'm trying to use the social sharing module AddThis and I'm showing the Facebook, Twitter, and Pinterest, and Email icons (although I also want to use the 'more' icon to show all the others).

And I want a little box to the right of those that just shows how many times the page has been shared. Is this even possible?

# Answer
All of these are great answers. It turns out the AddThis module includes something you can use right out of the box to do this counting. Just add the 'bubble\_style' option to your toolbox when configuring the display for the field in your content types and this automatically counts all the shares using the other services you've loaded for the module.
> 1 votes

# Answer
you could use:

### Social Share Counter Module

> This module is clearly inspired by the share buttons used by Mashable.
>
> This module gives the share counts for only Facebook,Twitter and more which has some excellent features in more elegant manner. If you have a website, then you definitely need this module.

### If you still want to use AddThis, then use Social Stats Module

> This is a statistics module. It provides data from various social media sites. The data which is saved per node. It includes data from:
>
> Facebook : likes count, shares count, comments count & total count.
>
> Twitter : tweets count.
>
> LinkedIn : share count.
>
> Google Plus : plus one
>
> count, share count & total count Total Share Count : total across all available social networks Note: This module is intended to collect the statistics per node from the networks mentioned above.
>
> **It does not actually provide sharing widgets for the social networking sites. They have to added manually, or using other modules. List of the modules recommended to use alongwith Social Stats are:**
>
> * Service links
> * **AddThis**
> 5 votes

# Answer
The Social Share Statistics is better than other modules listed in other answer.

**Social Share Statistics:**

> This module is developed to track the share statistics of social media clicks. So when a registered drupal user shares any content to social media, this module saves the uid, nid and the share count for `FB/twitter/GPlus` in the database for the record.
>
> There is a 'Shares' tab on the user profile page where the user can get the list of content shared on different social networks `(facebook, twitter)`.
>
> This module only tracks shares that are made using the share buttons that the module provides. If you share the nodes with some other mechanism `(say directly copy paste the link to Facebook, Twitter, etc. or use some other module)`, those actions / shares do not count.
>
> Please read the `readme.txt` file for detailed instructions on configuration steps.

**Reason Why it is better than other module:**

> The reason why this module is different from the rest of the modules available on d.org is it tracks which user shared which node. This we didn't find in any other module. For example - Social Stats just shows number of shares per node but which registered user shared which node is not available with Social Stats module and even the way the count is fetched is different in both the modules.
> 5 votes

# Answer
# Get Rules involved

Have a look at my answer to "How to post the node link in social networking if node is published?", which explains how the Rules module can be used as an engine to post to various social networks, such as Facebook and Twitter.

# Let Rules track your social networking services

By using Rules as your "Social Network Dispatcher" (or whatever you'd call it), you can have the Rules module ALSO take care of keeping track of "*how many times the page a user is on has been shared using ANY of the available sharing methods*". Here are the highlights of what you'd need to get that to work:

* Add a field (say with machine name `field_sharing_counter`), to any of your relevant content types for which you want to implement the below logic. That field (initial value = 0) will be used as your "counter" (= "*how many times a page is shared*").
* Expand the rules used for posting to social networks, with basically only these enhancements:

+ Add a **Rules Condition** like "*entity has field*" (related to your `field_sharing_counter` field). That way you know it's a page you want to monitor.
    + Add a **Rules Action** which simply increments the `field_sharing_counter` field.
* To make the above Rules expansions AbitMORE modular, I'd recommend to move this logic into a **Rules Component** (so that the modifications of the relevant rules are limited to just adding 1 rules action (= trigger that Rules component). The extra advantage you have that it's a peace of cake to maintain this extra logic (just adapt the single Rules component to have it apply for all Rules that use it).

Once you have this `field_sharing_counter` in place (and updated via Rules), it's straight forward to build a Views block with the specs matching your "small block" (it'd get boring to also provide the details for such view here, right?).

The above approach should work for at least Facebook and Twitter (more homework needed to find out how Rules can "talk" to Pinterest, though Googme+ might be tough ..).

### Variations:

* By using a separated field for each social network, you can even make it like X times 'Facebook', Y times 'Twitter', and Z times 'others'.
* If you'd create like a special "Thank you for sharing on ABC" node (1 for each social network), you could have the Rules module perform a Rules action to redirect to that special node after sharing (and use a destination parameter to return to the page that was shared). And the number of page visits for each of these special nodes would be the "counter" that obsoletes the `field_sharing_counter` field entirely.
> 3 votes

---
Tags: 7
---


# Question
Title: Conditionally require user to complete a content type based on answers from other content types?
I'm working on a drupal project that collects information about a business and then offers advice based on the information submitted.

Following the initial sign up process, a user can add a new business profile content type. This will be the entity referenced by all other nodes related to this entity aka the "business profile". Based on the answers provided within this initial questionnaire, I want to require the user to complete other supplemental questionnaires (basically other content types with entity reference to the main business profile content type) before submitting a finalized business profile.

For example, in the initial business profile there may be the question "Do you have any foreign operations?", if the user answer yes, I would want to make them complete the "foreign operations" content type questionnaire with many fields that relate to foreign operations. Further, if the user answers no to a question such as "do you have any employees?" I don't want to make the user complete an extended questionnaire (aka an employee related content type) regarding employees. In addition to simple yes/no answers, if a user selected a certain business industry SIC code from a select list, I would want to require specific content types to be completed with questions related to this industry. In my mind, I could have 50 content types with questions, but for each business's unique operations, they may only need to complete 5 of those content types. Finally, I would need a dashboard to keep track of what content types are required, pending and have been completed - then once all of the required supplemental content type questionnaires are verified completed, allow the user to submit a finalized profile.

I would say my level of drupal is intermediate as I understand the basics of entity referencing, structure and views; however, admittedly my experience in rules is limited. I'm using drupal 7.x.

I'm hoping someone can help to offer me a rough step by step of how best to accomplish this. (i.e. use this module, within rules conditions add blah, etc. etc.) Is my approach the correct one or is there a better solution such as webform, etc.?

Any help or guidance is appreciated.

# Answer
> 2 votes
Interesting question (challenge), with quite some background info (so well documented question). It seems that at its core, this is the key challenge you need to address:

> Finally, I would need a dashboard to keep track of what content types are required, pending and have been completed - then once all of the required supplemental content type questionnaires are verified completed, allow the user to submit a finalized profile.

Here is a "rough step by step" answer you asked for:

* Use the Flag module to introduce a set of flags related to your business content type. That set consist of 1 flag for each extra questionnaire (content type) that might possibly be needed. E.g. 1 flag related to "foreign operations" and another flag related to "employees".
* Use the Rules module to automatically set the appropriate flags to indicate that some related content type is required, but still missing (or not fully completed yet).
* Whenever such related content type gets completed, you "unset" (automatically, via Rules) its corresponding flag.
* Should you want to implement some review process (as per your "review completed" you mentioned), you may want to add the Workbench module to the mix (maybe some of its related modules also?), so that the "unset" of these flags only happens after the "status" of some related content type became something like "approved".
* As soon as a business profile no longer has any of such flags set, your business content type can be considered as a "finalized" profile.
* Possibly you may want to add the Content Access module to the mix, to implement some additional features that you may want to use.
* To implement your "dashboard", you just have to build a few (rather basic) reports using the Views module, with appropriate fields, filters, etc related to the various flags.

If you're not familiar (enough/yet) with Rules, checkout the 32 (!!!) great, and free, video tutorials Learn the Rules framework. Possibly also the similar set of 8 video tutorials about the Flag module.

# Answer
> 0 votes
If it's questionnaire, try using Entityform instead of content type.

Then investigate Rules Forms which extends Rules with triggers/actions specially designed for forms (which can invoke on form validation, build, submit, etc.).

# Answer
> 0 votes
I wanted to elaborate on how I used @Pierre.Vriens answer to accomplish a “proof of concept” for my question using rules and his suggestions. At this point, I only used rules as it seems to work for what I’m trying to accomplish. I didn’t see the need to use flags; instead, I’m going to create another Boolean field for the question content types and set it to TRUE if required based on the client content type answers.

Primary modules used:

* Rules
* Entity Views Attach
* Conditional Rules.

Content types for my project:

* Clients – contains the Boolean field “do you have employees, yes/no” and a term reference field “SIC Codes”
* Report – the node that we will add the required questions to. This entity references Clients.
* Employee Questions – one of the question content types. This specific set of questions contains the additional questions related to employees.

Basic concept: Once a new client is created, I add a report node referencing that client. Then depending on the client questions, I add other question content types referencing the report node.

## Rule

Event: After saving new content of type Clients

Condition: Entity has field Parameter: Entity: \[node\], Field: field\_clients\_termref\_sic\_codes

Actions Create a new entity Parameter: Entity type: Node, Content type: Reports, Title: First Report, Author: \[site:current-user\] Provides variables: Created entity Reports (entity\_created\_report)

Save entity Parameter: Entity: \[entity-created-report\], Force saving immediately: true

Set a data value Parameter: Data: \[entity-created-report:field\_report\_entityref\_clients, Value: \[node\]

Show a message on the site Parameter: Message: We created the first report for this client!

Conditional

If: Data comparison Parameter: Data to compare: \[node:field-client-has-employees\], Data value: Yes, we have employees Provides variables: Created entity Employee Questions (entity\_created\_employeeq)

Create a new entity Parameter: Entity type: Node, Content type: Employee Questions, Title: New Employee Questions, Author: \[site:current-user\] Provides variables: Created entity Employee Questions (entity\_created\_employeeq)

Save entity Parameter: Entity: \[entity-created-employeeq\], Force saving immediately: true

Set a data value Parameter: Data: \[entity-created-employeeq:field\_employeequestion\_entityRef\_reports, Value: \[entity-created-report\]

Show a message on the site Parameter: Message: We created the Employee questions!

---

…I then created additional conditional actions within this rule for each of the other answers provided in the initial clients page. Using Entity Views Attached I will then list all the referenced questions (all the question content types) to the Reports node for the user to complete one by one.

Eventually I plan to have a button at the bottom of my Reports display page allowing the user to submit a final report. I plan to use rules to validate if they’ve completed all the required fields for each content type, and I’ll change the status of all the required question content types to “submitted” and disable any further editing. (That’s my plan at least, I haven’t gotten that far.)

I hope this helps someone else.

---
Tags: rules, entities
---


# Question
Title: How do I create a role programmatically?
How do I create a role programmatically?

What am I doing wrong here?

```
$role = \Drupal\user\Entity\Role::create(['id' => 'client', 'name' => 'Client']);
$role->save();

```

# Answer
The problem is in the data array change *name* by *label*:

```
$role = \Drupal\user\Entity\Role::create(array('id' => 'client', 'label' => 'Client'));
$role->save();

```

Or you can use:

```
//your data array
$data = array('id' => 'client', 'label' => 'Client');
//creating your role
$role = \Drupal\user\Entity\Role::create($data);
//saving your role
$role->save();

```
> 19 votes

---
Tags: 8, users, installation
---


# Question
Title: Postpaid license billing type does not work with Commerce Stripe
This has been placed on https://www.drupal.org/node/2634778, but since there is no any reaction there yet I thought I'd have better chances here on Drupal Questions.

This has been tested well on a clean Drupal Commerce setup:

If a product configured with **prepaid** license billing type (see different billing types on https://www.drupal.org/node/2127603) is checked out, then everything works well - Drupal Commerce creates two orders: one already processed and one for the next billing period with the "Recurring: Open" status.

However, if a product with **postpaid** license billing type is checked out, then Drupal Commerce creates only one initial order that never recurs. What is interesting, if a postpaid product is checked out together with a prepaid product in a single order (just to get an order with "Recurring: Open" status created) and then if prepaid product gets cancelled, then the postpaid one keeps recurring successfully.

At the same time, if "Example payment" is used instead of "Commerce Stripe" as the payment method, then both pre and postpaid products recur without problems. Which makes me to believe that something in Commerce Stripe is not triggered when postpaid product is ordered.

# Answer
> 1 votes
This is just to let every one interested know, that Aviindub was kind enough to reply to my post on https://www.drupal.org/node/2634778#comment-10669204, after which I have re-installed everything from scratch once again, but in little bit different order, and postpaid orders started to recur too.

---
Tags: commerce
---


title: Error while accessing admin section

text:
# Question
Title: Error while accessing admin section
I am facing the following error while trying to access Admin section in Drupal 8 (WAMP Server). I tried to install the `Update manager module` and from then I am facing this error. I am unable to access any Admin section of the website. But, I am able to login and access the User account section `(Ex: http/test.com/user/1)`.

> The website encountered an unexpected error. Please try again later.
>
> Symfony\Component\Routing\Exception\RouteNotFoundException: Route "update.report\_update" does not exist. in `Drupal\Core\Routing\RouteProvider->getRouteByName()` (line 191 of core\lib\Drupal\Core\Routing\RouteProvider.php).

Any suggestion please?

# Answer
Its problem with my custom module. Wherever I am installing that module, it is creating a mess. I am trying to sort out the issue with my module.

This is due to the menu routing problem in my custom module. Please see the below link: https://www.drupal.org/node/2635308
> 0 votes

---
Tags: 8, updating
---


# Question
Title: Useability of the user registration workflow
When you want to create an account on a drupal7 page, you have to click very often to create the account finaly.

1. Go on user/register
2. Click on one time login link
3. Open the one time login page and click an login
4. Change password
5. Now your done

Are there any approaches to modify the registration process without loosing the email verification? There so many Websites doing it better. Is there a Drupal way?

# Answer
Use https://www.drupal.org/project/logintoboggan to allow users to login immediately and assign them a "not verified" role. Once they use the verification link they will become authenticated users.

Enjoy.
> 2 votes

# Answer
Use Logintoboggan module, it help you change the registration steps and flow.

Some of this module features :

> The LoginToboggan module offers several modifications of the Drupal login system in an external module by offering the following features and usability improvements:
>
> * Allow users to login using either their username OR their e-mail address.
> * Allow users to login immediately.
> * Provide a login form on Access Denied pages for non-logged-in (anonymous) users.
> * The module provides two login block options: One uses JavaScript to display the form within the block immediately upon clicking "log in". The other brings the user to a separate page, but returns the user to their original page upon login.
> * Customize the registration form with two e-mail fields to ensure accuracy.
> * Optionally redirect the user to a specific page when using the 'immediate login' feature.
> * Optionally redirect the user to a specific page upon validation of their e-mail address.
> * Optionally display a user message indicating a successful login.
> * Optionally combine both the login and registration form on one page.
>
> + Optionally have unvalidated users purged from the system at a pre-defined interval (please read the CAVEATS section of INSTALL.txt for important information on configuring this feature!).
> * Integrates with Rules module to do various tasks when a user validates via email validation process (see http://drupal.org/node/880904 for an example)
> 1 votes

---
Tags: 7, ajax, users
---


# Question
Title: Drupal custom coding checkout redirect not working
I have used custom coding to add a product into a cart.

```

 $items['buynow/%'] = array(
    'title' => t('buynow'),
    'page callback' => 'drupal_get_form',
    'page arguments' => array('custom_module_my_form3',1),
    'access arguments' => array('access content'),
    'type' => MENU_CALLBACK,
  );
function custom_module_my_form3($form, &$form_state,$id) {
global $user;
$product_id=$id;
$product = commerce_product_load($product_id);
$quantity=1;
$line_item = commerce_product_line_item_new($product, $quantity);
$line_item_added = commerce_cart_product_add($user->uid, $line_item);
$order_id=$line_item_added->order_id;
drupal_goto('checkout/'.$order_id);
}

```

Product added succesfully in the cart but redirecting into checkout page doesn't work.It redirecting into home page.

I have created link for each product like `buynow/product_id`. I have also created a custom menu path like `buynow/%`.

After that put the above code in the callback by passing argument.

# Answer
> 1 votes
Your fault is want using `drupal_goto` in form builder!!!

Change your code to this

```
 $items['buynow/%'] = array(
    'title' => t('buynow'),
    'page callback' => 'custom_module_my_form3',
    'page arguments' => array(1),
    'access arguments' => array('access content'),
    'type' => MENU_CALLBACK,
  );

function custom_module_my_form3() {
   global $user;
   $id=arg(1);
   $product_id=$id;
   $product = commerce_product_load($product_id);
   $quantity=1;
   $line_item = commerce_product_line_item_new($product, $quantity);
   $line_item_added = commerce_cart_product_add($user->uid, $line_item);
   $order_id=$line_item_added->order_id;
   drupal_goto('checkout/'.$order_id);
}

```

---
Tags: commerce
---


# Question
Title: How to add CSS classes to a an image which belongs to a content type?
I have a content type with an image field; I would like to add CSS classes to those images.

I have looked at the values of the `$content` variable in node.tpl.php via the `dpm()`, but I couldn't see any properties/keys related to classes or attributes. Maybe I just couldn't see them, or I didn't know where to look.

I would like to print something like `<img src="path-to-image" class="my-classes">` by using `print render($content['myimage_field'])` in node.tpl.php.

I do not want to use external modules to accomplish this. Is there any theme functions I can override? How do I override them?

# Answer
> 3 votes
You can use **hook\_node\_preprocess** in your themes *template.php* file to add to the 'attributes' array for the node before the variables are sent to your node template. when your field gets built up into html it will then have your class.

If you enable the devel module you can add the following to *template.php* to see what this 'build array' which is used to render the node looks like.

```
function twt_preprocess_node(&$vars) {

    dpm($vars);

}

```

To alter the classes added to your field use something like the following (though look to the above to find out if you are putting your class in the right place).

```
function twt_preprocess_node(&$vars) {

    $vars['field_myimagefield']['#attributes']['class'][] = 'myclass';

}

```

Some useful reading:

# Answer
> 3 votes
There is no such method available to apply classes directly from node.tpl.php You can achieve it by using theme function theme\_image\_style

e.g, in template.php

```
/**
 * Theme override
 *
 * Add custom class to image styles
 */
function MY_THEME_image_style($variables) {
  // Determine the dimensions of the styled image.
  $dimensions = array(
    'width' => $variables['width'],
    'height' => $variables['height'],
  );

  image_style_transform_dimensions($variables['style_name'], $dimensions);

  $variables['width'] = $dimensions['width'];
  $variables['height'] = $dimensions['height'];

  // Determine the URL for the styled image.
  $variables['path'] = image_style_url($variables['style_name'], $variables['path']);

  /* Begin custom snippet */
  // Add or append custom classes, to avoid clobbering existing
  if (isset($variables['attributes']['class'])) {
    $variables['attributes']['class'] += array('my-class', $variables['style_name']);
  }else{
    $variables['attributes']['class'] = array('my-class', $variables['style_name']);
  }
  /* End custom snippet */
  return theme('image', $variables);
}

```

Note: This is just a clone of theme\_image\_style with the custom classes added at the end.

You can add some conditional logic based on style\_name for specific classes, and also do a similar thing with theme\_image if needed.

---
Tags: theming, media
---


title: How to use the OR operator in Views?

text:
# Question
Title: How to use the OR operator in Views?
How do I create a view that will display all content of type '**Accountancy**' and also all content with a taxonomy term '**Accountancy**' (of any content type)?

I am trying this with a filter of `Type: Accountancy` OR `Taxonomy: Accountancy` but this is only showing the taxonomy nodes. The only filter that would work was the Delta.

Thanks Елин Й & morbiD - You both suggest the same answer, however, this does not work, please see screen shot below. (N.B. all this content is not published and only used these views)

# Answer
* Add a *Relationship* **Content: Taxonomy terms on node** under **Advanced** section:
* Select the vocabulary:
* Add the filter **Taxonomy term: Name**.
* Enter **Value** *Accountancy*.
* Click "And/Or, Rearrange" for the **Filter Criteria** and make it read like:

> **Content: Published Yes** AND (**Content: Type = Accountancy** OR **(term) Taxonomy term: Name = Accountancy**)
> 3 votes

# Answer
Please add another filter there of taxonomy field as **OR** condition and for can **Empty** condition. It will load all the content content of type '**Accountancy**' which not have the taxonomy term assigned.

Remember this will be a new filter with OR condition.
> 1 votes

# Answer
Add the following relationship:

* Content: \<your taxonomy field name\>

Then add your filters:

* Content: Type (= Accountancy) **OR**
* Taxonomy term: Term (= Accountancy)

where the taxonomy term filter uses the relationship you added.

Note: Views seems a bit flaky about letting you choose the taxonomy term you want to filter so you might have to save your view after you add the filter and then edit it again in order select a term.

Update: Given that your nodes are unpublished, this only seems to work properly by using a "Content: \<taxonomy field name\>" relationship. For example, if my non-accountancy content types have a taxonomy field called "Tags" then the following works:
> 1 votes

---
Tags: views
---


# Question
Title: Why isn't ['field_name'][0]['#markup'] work for getting taxonomy of this node?
I have two content types: Case and News.
In node--case.tpl.php, I'm using `echo $content['field_case_category'][0]['#markup'];` in order to print the taxonomy term for the page and that works fine. In node--news.tpl.php, I can't use `echo $content['field_news_category'][0]['#markup'];`; in fact, #markup is not even present in this array at all.

1. Why doesn't this method work in the second case? What can I do to solve it?
2. Is there a better/right way to print taxonomy terms in nodes?

The error I get is the following:

> Notice: Undefined index: #markup in include()

# Answer
> 1 votes
Please don't print some result directly. You should print the content of field like below.

```
print drupal_render($content['field_case_category']);

```

Hope this solves your problem. Also please check whether your node contains the value for the field\_case\_category field.

# Answer
> 1 votes
The correct way to render a field API field is using `render()` (`print render($content['field_case_category'])` or `print render($content['field_news_category'])`) that, through `drupal_render()`, is able to correctly handle all the cases, including the case #markup is not set because the field is empty.

Notice that you don't normally need to explicitly print node fields, if not in the case you hide them before calling `render($content)`, and then you need to render them separately. The default node.tpl.php file used from the Node module, or any theme that comes with Drupal.

```
// node/node.tpl.php
<div id="node-<?php print $node->nid; ?>" class="<?php print $classes; ?> clearfix"<?php print $attributes; ?>>

  <?php print $user_picture; ?>

  <?php print render($title_prefix); ?>
  <?php if (!$page): ?>
    <h2<?php print $title_attributes; ?>><a href="<?php print $node_url; ?>"><?php print $title; ?></a></h2>
  <?php endif; ?>
  <?php print render($title_suffix); ?>

  <?php if ($display_submitted): ?>
    <div class="submitted">
      <?php print $submitted; ?>
    </div>
  <?php endif; ?>

  <div class="content"<?php print $content_attributes; ?>>
    <?php
      // We hide the comments and links now so that we can render them later.
      hide($content['comments']);
      hide($content['links']);
      print render($content);
    ?>
  </div>

  <?php print render($content['links']); ?>

  <?php print render($content['comments']); ?>

</div>

```

```
//bartik/templates/node.tpl.php
<div id="node-<?php print $node->nid; ?>" class="<?php print $classes; ?> clearfix"<?php print $attributes; ?>>

  <?php print render($title_prefix); ?>
  <?php if (!$page): ?>
    <h2<?php print $title_attributes; ?>>
      <a href="<?php print $node_url; ?>"><?php print $title; ?></a>
    </h2>
  <?php endif; ?>
  <?php print render($title_suffix); ?>

  <?php if ($display_submitted): ?>
    <div class="meta submitted">
      <?php print $user_picture; ?>
      <?php print $submitted; ?>
    </div>
  <?php endif; ?>

  <div class="content clearfix"<?php print $content_attributes; ?>>
    <?php
      // We hide the comments and links now so that we can render them later.
      hide($content['comments']);
      hide($content['links']);
      print render($content);
    ?>
  </div>

  <?php
    // Remove the "Add new comment" link on the teaser page or if the comment
    // form is being displayed on the same page.
    if ($teaser || !empty($content['comments']['comment_form'])) {
      unset($content['links']['comment']['#links']['comment-add']);
    }
    // Only display the wrapper div if there are links.
    $links = render($content['links']);
    if ($links):
  ?>
    <div class="link-wrapper">
      <?php print $links; ?>
    </div>
  <?php endif; ?>

  <?php print render($content['comments']); ?>

</div>

```

If your template is already using `render($content)`, and you are not seeing the taxonomy terms, then you need to check the field has not been hidden in the display setting, or a module is hiding it.

---
Tags: nodes, entities, taxonomy-terms
---


# Question
Title: Services 3 File upload, create/return image styles
Ahoy all!

So, long story short, I'm uploading files to drupal through services from an angular app, and getting a response/url/etc no problem. **My question is, how do I enable image styles to be created on REST upload from services?** I'm receiving an empty response in the image\_styles array. I am assuming it likely isn't something I need to add into the POST request, but happy to add POST request code if needed.

I am coming up a little short on my google-fu on this one, and any help appreciated!

# Answer
the image created with the style when you request a page displaying that image\_style So you have to call it in code.

The default generation method only creates images when they are requested by a user's browser.

**image\_style\_url** Returns the URL for an image derivative given a style and image path

code sample :

```
// $file object from file_load($fid)
image_style_url('style name', $file->uri)

```
> 0 votes

---
Tags: services, media
---


# Question
Title: How to designate a region for regional shipping charges by weight with drupal commerce?
My commerce shop needs ***different shipping charges by weight to different regions*** in the U.S.; the east coast, the mid-west, and the west-coast.

Such that *a 6oz package would have three different shipping charges depending on where it was going.*

I would imagine this need ***three different weight-based rules*** for shipping, I am specifically wondering about how to implements the conditional statements for these. I would imagine one way to implement this would be a series or AND/OR statements in the conditional, but for a case like the US, thus means sometimes 20+ AND-OR conditions on a state by state basis.

***Is there an easier way to designate a geographic region as a collection of states? Or is this the best and only way to implement this?***

# Answer
> 1 votes
You can try out Commerce Shipping Postal Code Weight, which sounds like it might solve your problem.

---
Tags: location, commerce
---