title: redirect using *

text:
# Question
Title: redirect using *
I have pages in path try/\* and I would like to redirect to node/20. I tried path auto but using * is not allowed, I have to specify one by one.

Is there any module or way to redirect try/\* to node/20

# Answer
Use drupal current\_path() and drupal\_match\_path() api to check the path and redirect to your defined path.

So in your case,

```
if (drupal_match_path(current_path(), 'try/*')) {
  drupal_goto('node/20');
}

```
> 1 votes

# Answer
You could redirect from `.htaccess` directly.

```
RewriteRule ^try/(.*)    node/20   [R=301,L]

```

Place the rule from above in the .htaccess file, the next line after `RewriteEngine on`
> 0 votes

# Answer
Implement the hook hook\_boot in your custom module. This hook gets invoked for every page request. In the hook you may implement the code to match the pattern of the request URI by using preg\_match or by implementing the logic suggested by @manikandan kannan . You can then redirect using the code

```
header('Location: '.$GLOBALS['base_url'].'/node/20');

```
> -1 votes

---
Tags: redirection
---


# Question
Title: The directory sites/default/files does not exist
I received the "The directory sites/default/files does not exist" error on a 7.43 install. In this situation, Drush is not available so I am doing a browser install.

I had this error once before in 2014 according to my notes. I don't know whether it's specific to the server I'm on or a general issue because I've done setups on other servers and don't remember seeing that particular error. In the previous situation, I noted that I changed the permissions on default to 777. I am always loathe to set much of anything to 777 so I am wondering whether it needs to be kept at 777 or is there some point after setting up the site that I can switch it to something more secure.

# Answer
Your perms should (arguably) never be 777 on anything, but your exact situation will dictate that. 755 is often more appropriate for writeable folders, 644 for writeable files, but it depends on how your server is configured, and who owns the files.

You do need to create the sites/default/files folder manually, before the web-based installation can proceed, and your web server user must be able to write to that folder. You also need to create sites/default/settings.php, make it writeable, then remove those write perms once installation has completed. Drupal's status report will tell you about this if you haven't already done it.

There's not a lot more to it, just make sure the perms on all your files and folders are sensible for all the users that can interact with them. Securing file permissions and ownership has the full details, I'd recommended reading and fully understanding that page before going any further.
> 2 votes

---
Tags: 7
---


# Question
Title: How to leave user profiles even when there are several pages?
The profiles of my users have several fields (bio etc.) and several pages which I add with views (following, followers etc.).

I try to leave the profiles of users even when we change page, a little as here :

https://disqus.com/by/iamfrancisyo/ (when you click "followers", the information of the user remain posted at the head of page (avatar etc.)).

Yet, the profile disappears when we change page.

I tried to add the variable $tab to user-profile.tpl.php, but naturally it also disappears during the change of page.

Have you a solution?

# Answer
Easiest way:

For each View (which would have User as base table no doubt and which has uid as contextual filter) you add an attachment View Display and pin it to the top of the main view. In that attachment, under 'Format: Show:' you select to show 'User' instead of 'fields', using the same view mode that is shown for the normal profile.
> 0 votes

---
Tags: 7, views, theming
---


# Question
Title: How does Drupal ensures that the one time unique URL used to reset user password does not get transferred away inside the http_referer header?
For example in case the site relies on and loads some external JS (such as jQuery via CDN). Quite technical but any insights are highly appreciated. Thanks.

# Answer
> 1 votes
At this point in time, it doesn't.

There's an issue to fix this in Drupal 8, after which it will (hopefully) be ported back to 7. Patches are currently awaiting review.

---
Tags: security, users
---


title: Views Different Sort Orders

text:
# Question
Title: Views Different Sort Orders
I have a content type called events (obviously it keeps a list of events (conferences, meetings, etc).

I have a views-view--events-list.tpl.php file where I render a list of events. All of this is working perfectly.

What I need to do is sort events differently based on the event date. In specific, events that have passed (earlier than today's date), should be sorted descending - that is the most recent past event first and the event that is furthest back in history should be shown last.

For events that are still pending (in the future), the sort order is exactly the opposite - the event that will happen next should be first in the list and the event that is furthest in the future, should be shown last.

For example (assume today is 1/4/2016)

```
event 4: 5 April 2016 (future, the next date we will encounter)
event 6: 15 May 2016
event 5: 25 Dec 2016 (future, the last future event we will encounter)
event 1: 25 Feb 2016 (past, this was the most recent past event)
event 3: 2 Jan 2016
event 2: 24 Dec 2015 (past, this is the furthest past event)

```

I need to do this in one view (I do not want to create two views in code with different date ranges and sort orders; I know how to do that - I am trying to do it using just a clever sort order and the default views-view--events.tpl.php) template file.

My question then - how do I create different sort orders for different nodes (based on a field value such as date) in one view? Is this even possible?

# Answer
I'm pretty sure this can't be done in the standard Views UI.

A **bad** solution would be to use the Views PHP module to programmatically alter the order of the view results, or perhaps the Views Raw SQL module to insert some sorting statements into the SQL, although I haven't ever tried that.

A **good** solution would be to implement hook\_views\_query\_alter() in your own custom module and add your custom sorting order to the SQL query.

Going by this answer I think something like this might work, although I haven't tested it:

```
function mymodule_views_query_alter(&$view, &$query) {
  if ($view->name == 'my_view') {
    $query->orderby = array(
      0 => array(
        'field' => 'my_date_field < CURDATE()',
        'direction' => 'ASC',
      ),
      1 => array(
        'field' => 'greatest(my_date_field, CURDATE())',
        'direction' => 'ASC',
      ),
      2 => array(
        'field' => 'least(my_date_field, CURDATE())',
        'direction' => 'DESC',
      ),
    );
  }
}

```

You would obviously have to substitute in the names of your view and your date field.

Note that this code overwrites any sorting already defined by the view. You could of course add to the `$query->orderby` array rather than replacing it.
> 2 votes

---
Tags: 7, views
---


title: CKEditor widget doesn't work

text:
# Question
Title: CKEditor widget doesn't work
I'm having trouble making my own module to extend and incorporate a button that inserts markup to the ckeditor. I have used the following resources but cannot get it to work.

I managed to get the colorbutton/panelbutton modules to work, but the functionality is completely different to what I want.

I have the following file & folder structure within **modules/grouped\_texts/**

Here is an updated screenshot of the file structure:

The idea as you probably well know is to extend the CKEditor Module to include a custom tool, that on click inserts markup into my custom content editor.

The custom button 'grouped\_texts' appears within the page '/admin/config/content/formats/manage/impact\_editor' as you can see in the screenshot below.

But when I come to edit a page with the editor enabled, the icon does not show. See screenshot below:

As i'm getting familiar with drupal 8 and the limited resources to enable me to debug the extension of this module. Is there something in my code i've done wrong? Can you offer a solution to this problem? Here is the snippets of code i've used:

grouped\_texts.info.yml:

```
name: CKEditor grouped_texts
type: module
description: This plugin adds code tag button.
core: 8.x
package: CKEditor
version: VERSION
dependencies:
  - ckeditor

```

grouped\_texts.php:

```
/**
 * @file
 * Definition of \Drupal\grouped_texts\Plugin\CKEditorPlugin\grouped_texts.
 */

namespace Drupal\grouped_texts\Plugin\CKEditorPlugin;

use Drupal\ckeditor\CKEditorPluginInterface;
use Drupal\ckeditor\CKEditorPluginButtonsInterface;
use Drupal\ckeditor\CKEditorPluginBase;
use Drupal\Component\Plugin\PluginBase;
use Drupal\editor\Entity\Editor;

/**
 * Defines the "grouped_texts" plugin.
 *
 * @CKEditorPlugin(
 *   id = "grouped_texts",
 *   label = @Translation("grouped_texts")
 * )
 */
class grouped_texts extends CKEditorPluginBase implements CKEditorPluginInterface, CKEditorPluginButtonsInterface {

  /**
   * Implements \Drupal\ckeditor\Plugin\CKEditorPluginInterface::getDependencies().
   */
  function getDependencies(Editor $editor) {
    return array();
  }

  /**
   * Implements \Drupal\ckeditor\Plugin\CKEditorPluginInterface::getLibraries().
   */
  function getLibraries(Editor $editor) {
    return array();
  }

  /**
   * Implements \Drupal\ckeditor\Plugin\CKEditorPluginInterface::isInternal().
   */
  function isInternal() {
    return FALSE;
  }

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

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

  /**
   * Implements \Drupal\ckeditor\Plugin\CKEditorPluginInterface::getConfig().
   */
  public function getConfig(Editor $editor) {
    return array();
  }
}

```

plugin.js:

```
(function ($, Drupal, CKEDITOR) {

  Drupal.behaviors.myCkeditor = {
    attach: function (context, settings) {

        CKEDITOR.plugins.add('grouped_texts', {
                requires: 'widget',
                icons: 'grouped_texts',
                init: function(editor){

                    editor.widgets.add('grouped_texts', {
                        allowedContent: true,
                        editables: {
                            mytitle: {
                                selector: '.grouped-texts-title',
                            },
                            mycontent: {
                                selector: '.grouped-texts-content',
                            }
                        },

                        template:
                            '<div class="grouped-texts"><h2 class="grouped-texts-title">[Insert title here]</h2><div class="grouped-texts-content"><p>[Insert sub-elements here]</p></div></div>',

                        upcast: function(element){
                            return element.name == 'div' && element.hasClass('grouped-texts');
                        },
                    });

                    editor.ui.addButton('grouped_texts', {
                        label : 'grouped_texts',
                        command : 'grouped_texts',
                        icons : CKEDITOR.getUrl(this.path + 'icons/grouped_texts.png')
                    });

                    editor.config.contentsCss.push(CKEDITOR.getUrl(this.path + 'css/contents.css'));
                }
            });

    }};

})(jQuery, Drupal, CKEDITOR);

```

Thanks in advance.

# Answer
> 1 votes
You need to change the name of your button in getButtons() from "GroupedTexts" to "grouped\_texts".

Once you do that, you will need to clear the cache, add the button back on the toolbar, and then come back and reload a page with the editor.

See: https://api.drupal.org/api/drupal/core%21modules%21ckeditor%21src%21CKEditorPluginButtonsInterface.php/function/CKEditorPluginButtonsInterface%3A%3AgetButtons/8

"Each button should by **keyed by its CKEditor button name**, and should contain an array of button properties"

---
Tags: 8, wysiwyg
---


# Question
Title: How much time does it take to manage sites within a multisite architecture as compared to multiple single installs?
A service my company offers is similar to managed hosting where we help keep a server, Drupal, related modules, and backups up to date on behalf of clients who can't or don't want to do that in house, and typically this averages out to be about 30 to 90 min of work per site per month.

A client has asked me to manage their entire portfolio of 70 Drupal sites, all of which are part of a multisite architecture with site files on one server and DB on another.

I can't imagine that this is 70 hours of work, but I'm not familiar enough with multisite installs of this size to understand fully what this would entail.

To ensure that I estimate time correctly, what would I need to take into consideration when comparing management solutions for single server / single site installations as compared to the same number of sites in a multisite installation?

# Answer
Short: It really depends.

Long: Each individual multisite installation adds complexity to the whole. If these 70 sites are more ore less the same in terms of individual content but (nearly) same codebase, modules and similar themes (imagine a large organization spread over the world with region specific characteristics), you'll most likely need less time to maintain.

If these are 70 profoundly individual sites, you'll probably end up checking dependencies over dependencies for modules and themes, debugging deadlocks and incompatabilities. Maintaining this can be a real challenge and 70 hours a month are gone faster than you have "drushed and rollbacked" everything to working.

Accurate documentation and a SLA designed fair for both parties should be the key to a successful maintenance.

(I maintain a multisite installation with around 30 instances for a large organization with all the pros described above.)
> 4 votes

# Answer
Maybe you should include Aegir in management. Aegir, along with Drush, can help you a lot to automate some tasks, from backups, verification, enabling / disabling SSL, adding new or removing existing platforms and their multisites.
> 0 votes

# Answer
I can say that you should take into consideration that managing multisite drupal installation usually takes less time then handling same amount of single installations. I will briefly explain how it can be done for drupal 7

1) when you download drupal you can find sites folder in root;

2) You can add as many websites as needed inside sites folder, just create for example "example" folder;

3) In example folder create settings.php file

```
$databases['default']['default'] = array (
  'database' => 'example',
  'username' => 'admin',
  'password' => 'admin123,
  'host' => 'db_host_address',
  'driver' => 'mysql',
);

```

4) create modules, themes, libraries folder for site specific modules, themes and libraries in sites/example folder. All common (used by more then one site or features which potentially can be used in future by multiple sites) modules, themes, libraries can be added into corresponding folders inside sites/all directory.

5) To establish http connection with example website you should create server alias then add sites.php file inside sites folder.

```
$sites['localhost.example'] = 'example';

```

where localhost.example is your server alias and example is your site folder.

you should take into account that in future it will be easier to update drupal core and contributed modules but as cons you should take into account that during each common change all websites which use changed module, theme should be tested well. In case of updating core all sites should go through round of testing.

From my personal experience multisite installation is easier to maintain. I wish you good look with your task!
> -2 votes

---
Tags: multi-sites, configuration
---


title: Proxy problems with Drupal 7.20

text:
# Question
Title: Proxy problems with Drupal 7.20
I have an installation of Drupal 7.20. I've entered the proxy settings in the default.settings.php but it's still unable to check on updates. A simple test with a dummy page which executes

```
http://updates.drupal.org/release-history/drupal/7.x?version=7.20')); ?>

```

Results in the following error message

> object(stdClass)#62 (2) { \["code"\]=\> int(-110) \["error"\]=\> string(20) "Connection timed out" }

Which leads me to believe the proxy settings are not being detected

# Answer
As far as I'm aware, changing default.settings.php won't do anything. This file is only there to be copied into settings.php when the site is first installed - so if you change it after settings.php has been created it will do nothing at all.

You might try this module for proxy settings (though don't believe it when it claims to have a working version for D8)
> 1 votes

---
Tags: proxies
---


# Question
Title: How to submit a field collection from a form into a created node
I would really appreciate if somebody could help me with this :)

I have a field collection called field\_formations. Inside it I have 2 fields:

* field\_technologies - (reference to a taxonomy).
* field\_diploma -(how it's also a field collection which contain 2 other fields:
* field\_name(reference to a taxonomy)
* field\_establishement (text plain) ).
I've created a form with 3 field forms
* technology
* diplome\_name
* establishement

and into the submit form i would like to submit values of this forms into the node created at first.
I tried to setValues like this :

$node-\>field\_formations-\>field\_technologies-\>setValue($values\['technology'\]);
but it dosen't work
Can any body have a suggetion??
PS : I'm using drupal 8

# Answer
You need the id of the field collection item (grand one) which you can find inside the node object. Then you load the field collection by that id as an entity. Edit this field collection and save it as an entity. The point is that you have to load the field collectin entity, make changes and save it.
> 0 votes

---
Tags: nodes
---


title: Comment form doesn't submit

text:
# Question
Title: Comment form doesn't submit
I have inserted comment form to my custom `node.tpl` via `print drupal_render(drupal_get_form("comment_node_{$node->type}_form", (object) array('nid' => $node->nid)));`. It works fine, but form isn't submitted when I click on `Save` button. It submits the data correctly to `comment/reply/<nid>`, but data aren't saved correctly and I'm only redirected back to node page.

I'm using current D7.

# Answer
It was my mistake. I forgot, that I need to enable commenting on individual nodes. Sorry for this stupid mistake. Thanks @rémy
> 0 votes

---
Tags: comments
---


# Question
Title: Multilevel Menu but all in the same drop down?
How would you create a menu in Drupal where you had multiple levels, but they were all displayed in the same dropdown but with the child menu items indented.

e.g.

```
Parent 1
 Child 1
 Child 2
 Child 3
Parent 2
Parent 3

```

# Answer
> 0 votes
Bootstrap has recently removed the sub-menu features from version 3.x, so it won’t support the multi-level menu anymore. But drupal 8 has multi-level menu structure. I am going to show you how to get back the sub menu features in bootstrap and how to render multi-level menu in the drupal 8. Just copy and paste the following css in your custom css, its has been taken from the bootstrap version 2.x with some custom changes, The following article would help to create multi-level menu in drupal 8

---
Tags: navigation
---


title: Delete cookie just before render

text:
# Question
Title: Delete cookie just before render
I am trying to hide the fact that I have a Drupal site (as much as possible).

The idea is that if a would be hacker (I am not talking about some ninja that could break into the pentagon) looks at the site they would not be able to (easily) see it is a Drupal site.

Most of it is done - I just don't know how to delete some cookies set by modules. In specific I want to do this for anonymous traffic (clearly someone that is logged in already knows they are on a Drupal site). The cookies that I want to delete would not affect the site - it is related to two admin modules.

I tried a couple of hooks - the last one was `theme_html_head_alter` \- but nothing works. This is the code I need to insert somewhere - just not sure where?

```
if (!user_is_logged_in()) {
   user_cookie_delete('DrupalModuleFilter');
   user_cookie_delete('Drupal_tableDrag_showWeight');
}

```

# Answer
Did not find the answer (I did try hook\_page\_alter) - but I realised I was not focusing. I want to hide those cookies from anonymous users, but those users will never access the admin section, so the two cookies I am trying to delete, will never be set.
> 0 votes

---
Tags: security, cookies
---


# Question
Title: What's the difference between 'attachment before' and 'block' in views?
Recently I followed a tutorial in views which listed taxonomy and gave me a short list above the view with hyperlinked first characters of taxonomy name. In this case, I created a "block".

In investigating the default Glossary view, I see the same hyperlinked first characters of title created by using "Attachment before".

Are there advantages of using one method over the other?

# Answer
**Block** \- separate views display that can be outputted in any region of the site.
**Attachment** \- views display that can be outputted in addition to another views display, so you can attach this display to output of another views display.

Attachment has some special options like `Inherit contextual filters:Yes`, `Inherit exposed filters:No`, so you could use one exposed filters form for both displays.
> 3 votes

---
Tags: views
---


# Question
Title: Rewrite View Header into first views-row
I need to rewrite/move the header of one View into the first row of that View.

Current View output:

```
<div class="view">
    <div class="view-header">view header text</div>
    <div class="view-content">
        <div class="views-row views-row-1">output</div>
        <div class="views-row views-row-2">output</div>
        <div class="views-row views-row-3">output</div>
        <div class="views-row views-row-4">output</div>
        <div class="views-row views-row-5">output</div>
        <div class="views-row views-row-6">output</div>
    </div>
</div>

```

Desired Output:

```
<div class="view">
    <div class="view-content">
        <div class="views-row views-row-1">view header text</div>
        <div class="views-row views-row-2">output</div>
        <div class="views-row views-row-3">output</div>
        <div class="views-row views-row-4">output</div>
        <div class="views-row views-row-5">output</div>
        <div class="views-row views-row-6">output</div>
        <div class="views-row views-row-7">output</div>
    </div>
</div>

```

How can this be accomplished?

The views-row divs are then displayed inline in a responsive flex grid, so that each views-row div has the same height as its neighbor divs on that same row. Each views-row div is 25% width, so they are displayed in 4 columns (4 divs across the page, with subsequent divs wrapping in 4 additional columns below as needed).

I need the header to be part of that flex grid. I tried applying the flex grid markup to the "view-header" div and the "view-content" div, but it does not provide the desired result.

Thanks!

# Answer
You can use `hook_views_post_execute()` or `hook_views_pre_render()` hooks. Provide you just an example, so you have to add validations and change format of $item variable youself, it depends of your views configuration.

```
/**
 * Implements hook_views_post_execute().
 */
function mymodule_views_post_execute(&$view) {
  $item = (object) array('node_title' => $view->header['area']->options['content']);
  array_unshift($view->result, $item);
}

```
> 1 votes

---
Tags: 7, views, theming
---


# Question
Title: How do I delete all the relations on my site?
I want to remove all the relations (created with the Relation module) on my site because I have replaced them with an entityreference field.

At `/admin/structure/relation`, I can delete the **Relation Types**, but this does not delete the relations belonging to each type.

At `/admin/content/relation`, I can delete the relations individually, but there are 100K relations on this site.

At `/admin/structure/views/view/relations/edit/page`, with the Views Bulk Operations module enabled, I can change the contextual filter **Relation: relation type** to "Display all results for the specified field" for *When the filter value is NOT in the URL* and then add a bulk operation to **delete item** under *Fields*. This allows me to go to `/relations` and trigger a bulk operation to delete all the relations.

Is there a faster way that doesn't involve customizing views?

# Answer
> 1 votes
There are many ways to delete relations on a site. Relations are Entities in Drupal.

1. The Delete All module can help with this process.
2. The Drush Entity command set has a delete function which takes a content type I believe.
3. With care you could by hand TRUNCATE the relation table, and destroy and drupal Fields that use relations. (I've done this on a few sites).

---
Tags: entities
---


# Question
Title: Timeout in sites, perhaps related to cron
I have been struggling with a timeout error in a couple of Drupal 8 sites, which I have not been able to reproduce. When I deploy them into my colleague's production server (a Mac machine), all the Drupal 8 sites are experiencing a page lock up (the browser waits indefinitely). I have not been able to reproduce the error in my machine (running Debian), neither in testing instances in other servers (e.g. a free Pantheon instance). The only clues I have for the moment are:

* The error seems to not occur so often once I disable cron in the Drupal sites. However, if I run cron manually, I have not been able to reproduce it neither.
* This only affects Drupal 8 sites. The rest of the sites (Drupal 7 and many others) are not affected at all.
* The error disappears rebooting Apache. However, only when I do the following combination: "/opt/local/etc/LaunchDaemons/org.macports.apache2/apache2.wrapper stop" & "/opt/local/etc/LaunchDaemons/org.macports.apache2/apache2.wrapper start"
* My colleague suggested me to use "/opt/local/apache2/bin/apachectl graceful" , but in that case, the error does not disappear.

Any ideas on what the issue could be? I am running different versions of Drupal in the sites (8.0.2 and 8.0.5). At https://github.com/CRESS-Surrey/erie\_website\_code/issues/31#issuecomment-172512374 I have attached as well some captures of the http headers in a successful and unsuccessful request . I am trying to document the issues as well (more information) at that issue and https://github.com/drozas/cecan/issues/23 for the other site.

Thanks a lot!

David

# Answer
> 0 votes
Even if you say its not: This issue is most commonly not only Drupal 8 related. You will find issues for Drupal 7 reporting near the same behaviour. It turns out that cron starts after the expired period with first page request. If this happens, the cron seems to take endless time and seems to interfere with the page request in the same moment. Many experienced users run their crons from Drush manually or combine it with server crons. But generally spoken :

There are 3 possible points to look at and to modify (and you already named some of them), which all can interfere each other or can be responsible for it each at their own allone:

1. Take a look at your php and apache settings for memory, cache size and sql query time settings. Cron is a big wave coming. From my experience a smooth Drupal experience can be only granted by increasing it over the given amount suggested.
2. Turn off automatic cron frequence (as you sad, mostly set by 3 hours, set it to -none-) in the admin/config pages, but make sure that you run cron by yourself manually often enough (thats how I generally do it). For some reasons and some unclear circumstances (mostly server related) this is often the only option to prevent this behaviour.
3. Make sure that you have turned off all unneeded modules on production sites. Even if some suggestions say its not related, my experience is, that turning off help, update, dblog (use syslog instead) etc. at production sites makes Drupal faster and prevents such overheats.

---
Tags: 8, cron
---


# Question
Title: Using Context, can I (programiatically) move the page's menu to a different region?
Using Context, can I move a node's menu to a different region?

Or more specifically, from inside `hook_context_page_reaction()`, can I get access to the page's render array to move items between regions?

I'm working with this below.

```
/**
 * Implements hook_context_page_reaction().
 */
function context_movemenu_context_page_reaction()
{

    $node = node_load(menu_get_object()->nid);
    if ($plugin = context_get_plugin('reaction', 'context_movemenu')) {
         $plugin->execute();
    }
}

```

and using this execute() method. I'm just dumping all incoming args to see what I can send over.

```
function execute() {
   dpm(func_get_args());
}

```

Am I approaching this from the wrong location? Ideally, this sites has most of it's configuration in context. The site owner likes that workflow.

# Answer
> 1 votes
You could place ***all*** blocks in template\_preprocess\_page with

```
$variables['page'][$region_key] = array();
$variables['page'][$region_key][]['#markup'] = $region_content;

```

Seeing your edit, you can check for the plugins blocks like this

```
$context_content_bottom = array();
  $blocks_content_bottom = array();

  // Blocks that are assigned to the region using Context
  if ($plugin = context_get_plugin('reaction', 'block')) {
    $context_content_bottom = $plugin->block_get_blocks_by_region('content_bottom');
  }

  // Blocks that are assigned to the region using the blocks interface
  if ($blocks = block_get_blocks_by_region('content_bottom')) {
    $blocks_content_bottom = $blocks;
  }

  // Merge them together
  $vars['region']['content_bottom'] = array_merge($context_content_bottom, $blocks_content_bottom);

```

Taken from here

but why not do it in the UI ?? just place the block several times under opposed conditions

---
Tags: 7
---


# Question
Title: How to export custom entity using Features?
I am trying to export custom entity using Features module but I am not able to see anything under create features.

I have enabled exportable as TRUE in `hook_entity_info`.

I have already added `entity_exportable_schema_fields()` under my custom schema .

# Answer
Follow https://www.drupal.org/node/1021526 for detailed instructions.
> 1 votes

# Answer
You just need to go to "Create Feature" and search under the list "Entity Types" for your entity, that will work
> 1 votes

# Answer
I would recommend you to used the ECK module to generated your custom entities. This would allows you to export them easily with the Features module.
> 0 votes

---
Tags: entities, features
---


# Question
Title: How to give access to inactive user profile?
I guess the title is obvious. I have built a Drupal 7 website showing a view of the previous Users (inactive profiles).

As an admin, I can access these profiles but I need anonymous users to have that permission too (view "previous" or "old" members profiles).

Is there any module to add that kind of permission?

Thanks and sorry for my English ;)

# Answer
The View Profiles Permissions module will work for that purpose: https://www.drupal.org/project/view\_profiles\_perms.

In order for this to work, you will also need to give your blocked users a Role.

It is not the primary function of the View Profiles Permissions module, but there is more information about this specific issue here: https://www.drupal.org/node/2490934

Additionally, You can use the Rules module to automatically assign a role to users when they become blocked.

Steps:

1. Install and Enable the View Profiles Permissions module
2. Create a role called "Blocked"
3. Give permissions to anonymous users to "Access to *Blocked* profiles"
4. Assign the "Blocked" role to all users who are blocked (aka Inactive, Old, Disabled)
5. Extra Credit: Install/Enable the Rules module and a new Rule that automatically assigns the Blocked" role to users when they become blocked.
> 0 votes

---
Tags: users
---


# Question
Title: Taxonomy term page $content is empty but shows up later
I have a taxonomy override page called `taxonomy-term--listing-category.tpl.php`.

As far as I'm aware I'm supposed to (as per documentation) use `<?php render($content); ?>` when the part in my template comes to spill all the items (teasers) associated with the taxonomy term. I'm fine with this.

Except it's empty.

Let me be clear, there are 14 items associated with this term, and they do show up, **after** my template in the HTML structure, as if I *missed* it in my template and Drupal is trying to pick up my slack.

Using Xdebug (hooked into my phpstorm) I have discovered that the `$content` array is `0`, it's empty. None of the node items associated with the taxonomy term is available to display IN my template, they simply don't exist in any registered variable. And as such, shows up AFTER my template.

What gives?

# Answer
> 1 votes
I was stuck on this myself and went hunting for the answer.

From my understanding, taxonomy\_term\_page generates data for a page. Therefore, the $build variable outputs its content to a page template and that's why you see it after the theme template.

The $content variable in the theme template, taxonomy-term.tpl.php, should contain the description or any fields you have created for the term.

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


# Question
Title: How to inject a fake class into container when running WebTestBase tests?
I've got a form class, and I'm injecting my custom functionality class into it via constructor. That class is added to the container via the `services.yml` file defined in my custom module.

I'd like to test that the form is functioning correctly, but for testing purposes I'd like to replace the class that's injected into the form with a fake one.

Both real and fake classes implement the same interface. The form is working with that interface.

My test file:

```
<?php
/**
 * @file
 * Contains \Drupal\my_module\Tests\FormTest.
 */

namespace Drupal\my_module\Tests;

use Drupal\my_module\Tests\Fake\FakeClass;
use Drupal\simpletest\WebTestBase;

class FormTest extends WebTestBase
{

    public static $modules = [
        'my_module',
    ];

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

        $fake = new FakeClass();

        $this->container->set('my_module.real_class', $fake);

        // $this->container->get('my_module.real_class') returns a FakeClass object.
    }

    public function testFormWorks()
    {
        $this->drupalGet('my-form');
        $this->drupalPostForm(NULL, [], 'Submit');
        $this->assertRaw('Form is working.');
    }

}

```

When I'm running the test, the real class is being used, which is not the desired test behaviour.

I can't figure out what I'm doing wrong here. Any help is appreciated.

**Update:** the issue is not specific to forms. Same thing happens in page controllers.

# Answer
Here's the solution.

Let's say your module A defines a new service.

In order to alter that service, you need to create a separate module B and follow the steps outlined in **Overriding the default service class** section on https://api.drupal.org/api/drupal/core%21core.api.php/group/container/8.

Make sure to list module A as a dependency in module B `info.yml` file.

Add both modules to the `$modules` array in your test class, and everything will work. `$this->container->set()` is no longer needed.

That issue on drupal.org: https://www.drupal.org/node/2700739
> 1 votes

---
Tags: 8, testing, dependency-injection
---


# Question
Title: Drop down triggering image_button callback
I have a custom form with 2 dropdowns which trigger an ajax callback on change and change the html inside a wrapper. If I use a submit input with this form which has its own submit callback function, it works fine but if I change the input to image\_button with same callback function, changing the values in dropdown ends up triggering image\_button callback.

```
$form['fieldset1'] = array(
    '#type' => 'fieldset',
    '#title' => t( 'Fieldset Title' ),
    '#title_display' => 'invisible'
);
$form['fieldset1']['select1'] = array(
      '#type' => 'select',
      '#title' => t( 'Select 1' ),
      '#title_display' => 'invisible',
      '#options' => $options,
      '#default_value' => $default_value1,
      '#ajax' => array(
          'event' => 'change',
          'callback' => 'select1_callback',
          'wrapper' => 'my_wrapper_id',
          'method' => 'replace',
          'prevent' => 'click',
          'effect' => 'fade'
      )
  );
$form['fieldset1'] ['select1'] = array(
    '#type' => 'select',
    '#title' => t( 'Select 2' ),
    '#title_display' => 'invisible',
    '#options' => array_combine( range( 1, 10 ), range( 1, 10 ) ),
    '#default_value' => $default_value2,
    '#ajax' => array(
        'event' => 'change',
        'callback' => 'select2_callback',
        'wrapper' => 'my_wrapper_id',
        'method' => 'replace',
        'prevent' => 'click',
        'effect' => 'fade'
    )
);
$form['fieldset1']['to_be_changed'] = array(
    '#type' => 'item',
    '#prefix' => '<div id="my_wrapper_id" >',
    '#suffix' => '</div>',
    '#title' => $to_be_changed_value,
);
//This works.
$form['fieldset1']['submit'] = array(
    '#type' => 'submit',
    '#value' => t( 'Submit Button Value' ),
    '#submit' => array( 'button_callback_function' )
);
//This doesn't work. The button works but dropdown callbacks call button callback
$form['fieldset1']['image_button'] = array(
    '#type' => 'image_button',
    '#name' => 'image_button_name',
    '#value' => t( 'Image Button Value' ),
    '#src' => drupal_get_path( 'module', 'my_module' ) . '/assets/img/image.png',
    '#submit' => array( 'button_callback_function' )
);

```

Not sure what I'm missing over here.

# Answer
Found the problem with the code. Image\_button won't have any #value. It will only have return\_value which in this case can be same as what I was putting in #value.

```
    $form['fieldset1']['image_button'] = array(
    '#type' => 'image_button',
    '#name' => 'image_button_name',
    '#return_value' => t( 'Image Button Value' ),
    '#src' => drupal_get_path( 'module', 'my_module' ) . '/assets/img/image.png',
    '#submit' => array( 'button_callback_function' )
);

```
> 0 votes

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


# Question
Title: Adding a radio button to a Drupal View page
Does anyone know how to 'inject' a radio button onto a Drupal View page?

I have an exposed filter that has nothing to do with a radio button but I want to add a radio button in front of the label in order to apply some additional AJAX to it.

# Answer
Use HTML `<form>`, ex: w3schools.com/html/tryit.asp?filename=tryhtml\_form\_radio

To "inject" your code you could add a header text field to your view OR create a template file for your view.
> 2 votes

---
Tags: views, theming
---


title: Check URL for string in a Twig file

text:
# Question
Title: Check URL for string in a Twig file
I'm new to twig and drupal 8 and finding it hard to access page titles. I want to apply a class to a page title on certain pages, all of which share a sub-directory in the URL path. I'm working with a page-title.html.twig file and want to do something like this:

```
{{ title_prefix }}
{% if title %}
  {% if <url contains "/services/"> %}
    <h1 {{ title_attributes.addClass('services-title') }}>{{ title }}</h1>
  {% else %}
    <h1 {{ title_attributes.addClass('page-title') }}>{{ title }}</h1>
  {% endif %}
{% endif %}
{{ title_suffix }}

```

I'm assuming this is possible, I just can't figure out how to check the URL for the desired string.

# Answer
> 11 votes
Use the "in" operator:

```
{% if '/services/' in url %}

```

More information: http://twig.sensiolabs.org/doc/templates.html#containment-operator

If you didn't do it already, put this preprocess function in the file `mytheme.theme` in your theme directory:

```
function mytheme_preprocess_page_title(&$variables) {
  $variables['url'] = $_SERVER['REQUEST_URI'];
  $variables['#cache']['contexts'][] = 'url.path';
}

```

**Edit:** By moving the code from page inside a block we need to provide a cache context.

---
Tags: theming, 8
---


# Question
Title: How can I change the delete message "This action cannot be undone." in a specific content type?
I have a version drupal 6 and I need to change the next message that is shown when I am going to delete a content:

"This action cannot be undone."

I need to change this message only for some content types, not in all.

Thanks for your help.

# Answer
> 2 votes
Try this code (it works for me - Drupal 6):

```
function module_change_default_messages_form_alter(&$form, $form_state, $form_id) {
if (arg(0) == 'node' && is_numeric(arg(1)) && arg(2) == 'delete') {
      $node = node_load(arg(1));
          if ($form_id == 'node_delete_confirm') {
              if($node->type == 'story'){
                $form['description'] = array('#value' => "here replace to \"this action cannot be undone\"");
              } else if($node->type == 'page'){
                $form['description'] = array('#value' => "this action cannot be undone");
              }
          }
      }
}

```

or you can use the PHP switch statement for more content types.

# Answer
> 1 votes
Here's how to do it in Drupal 6:

http://drupal.org/node/736352

If you have multiple content types you wish to change that message, then I would suggest unifying the code from that link into 1 function, instead of multiple functions per type.

I hope that helps, let me know if you were able to solve it.

# Answer
> 0 votes
You need to:

* Implement `hook_menu_alter()` to alter the menu callback associated with the "node/%node/delete" menu item
* Implement the new menu callback

```
function mymodule_menu_alter(&$items) {
  if (isset($items['node/%node/delete'])) {
    $items['node/%node/delete']['page arguments'] = array('mymodule_node_delete_confirm', 1);
    $items['node/%node/delete']['file path'] = drupal_get_path('module', 'mymodule');
    $items['node/%node/delete']['file'] = 'mymodule.admin.inc';

    // If the function is defined in the module file, you can use the following line instead of the last two lines.
    // unset($items['node/%node/delete']['file']);
  }
}

function mymodule_node_delete_confirm(&$form_state, $node) {
  $form['nid'] = array(
    '#type' => 'value',
    '#value' => $node->nid,
  );

  return confirm_form($form,
    t('Are you sure you want to delete %title?', array('%title' => $node->title)),
    isset($_GET['destination']) ? $_GET['destination'] : 'node/' . $node->nid,
    t('This action cannot be undone.'), // Change this message with the one you prefer.
    t('Delete'),
    t('Cancel')
  );
}

function mymodule_node_delete_confirm_submit($form, &$form_state) {
  if ($form_state['values']['confirm']) {
    node_delete($form_state['values']['nid']);
  }

  $form_state['redirect'] = '<front>';
}

```

As `mymodule_node_delete_confirm()` gets the node object, you can check the content type of that node using `$node->type`; basing on the value of that property, you can change the values for the confirmation form.

# Answer
> 0 votes
In drupal 7, it is easy to override any message. Use following form alter code.

```
function modulename_form_node_delete_confirm_alter(&$form, &$form_state, $form_id) {
  $form['description']['#markup']='Are you sure? Once deleted, the content of this tale cannot be recovered.';
  return $form;
}

```

---
Tags: 6, forms, nodes
---


# Question
Title: How to insert a new column into mysql field data table?
How would I insert a new column into mysql field data table? For example, if I have a field (myfield) with the mysql table field\_data\_field\_myfield having the following columns'entity\_type', 'entity\_id', 'revision\_id', 'bundle', 'delta', 'language', 'myfield\_value' and 'myfield\_format'...how could I add the column mynewcolumn as type varchar?

# Answer
> 1 votes
For adding new column in table, please check this discussion Correct way to add custom column to user table?.

Please check this discussion also https://www.drupal.org/node/2616250

---
Tags: entities, database
---


# Question
Title: Global PHP "sort through" vs other fields
In drupal views, you can create a field called "global php" and insert your own php code. Also as well, it has a sort feature which is handy when your view style is a table.

However, the other fields does not have a "sort" feature on them. Is there a way to add it to them? Or does it just have to come with it, like global php does?

# Answer
It has to be supported by the module supplying the field. In `hook_views_data()`, each defined field has a `'sort'` element that defines the sort handler function for the field.
> 0 votes

---
Tags: 7, entities
---


# Question
Title: What hook do I use to add a field to a content type after it was programmatically created?
I have a module that created a custom content type with some fields.

Now I need to update the content type with a new field and wanted to know what hook do I use? As of now my content type was created via the .install file but need a way to process the changes without uninstalling and re-intsalling the module. My .install file

```
function example_node_install() {
  $t = get_t();

  // Define the node type
  $example_node = array(
   'type' => 'example_node',
   'name' => $t('Node Example'),
   'base' => 'node_content',
   'description' => $t('This is an example node type.'),
   'body_label' => $t('Example Description')
  );

  //Add defualts
  $content_type = node_type_set_defaults($example_node);
  node_add_body_field($content_type);

  // Create the field
  $field = array(
    'field_name' => 'item_description',
    'cardinality' => 1,
    'type' => 'text',
  );
  field_create_field($field);

  // Create the instance map description.
  $instance = array(
    'field_name' => 'item_description',
    'label' => 'The item description.',
    'bundle' => 'example_node',
    'entity_type' => 'node',
    'widget' => array(
      'type' => 'text_textfield',
      'weight'  => 2,
    ),
  );
  field_create_instance($instance);

  //Save Content Type
  node_type_save($content_type);
}

```

Any guidance will be appreciated.

# Answer
> 1 votes
Try the `hook_update_n` function https://api.drupal.org/api/drupal/modules%21system%21system.api.php/function/hook\_update\_N/7

You would define a hook\_update\_n function in your install file in which you place the functionality to add your field to your content type. See for example: http://cgit.drupalcode.org/entity/tree/entity.install#n35

After added this functionality run http://example.com/update.php

A second option would be to use the features module to export your content type to a feature and when you are making changes in the UI to that content type (like adding a field for example) you can export the content type again to the feature and deploy that feature to your other (live) environment and revert the feature (which will bring the new code (the newly added field) into the database.

---
Tags: 7, hooks
---


# Question
Title: One time URL doesn't re-direct the user to change the password
In *Home » Administration » Configuration »* under the email messages section when a user is invited to the site the **\[user:password\]** is not generated and the one-time-login URL doesn't re-direct the user to change the password **(It just logs him in and he doesn't know the password!)**

What can I do to fix this? I have also installed this module

# Answer
That's what's rpt does .. no ??

> (password fields in registration form will be hidden).

So with this module you won't be able to set a password manually i guess.
> 0 votes

# Answer
I am not sure this is help you or not,

Drupal use various function for each and every activity, also for register. After register user **user\_register\_submit** function is called from user module. You can debug/trace the code and see what is going wrong.
For more help for user\_register\_submit function please check https://api.drupal.org/api/drupal/modules%21user%21user.module/function/user\_register\_submit/7

In user\_register\_submit function **\_user\_mail\_notify** function is used to send email, you can trace the php mail here to check which values are become empty.
Details about \_user\_mail\_notify funtion please check https://api.drupal.org/api/drupal/modules%21user%21user.module/function/\_user\_mail\_notify/7
> 0 votes

---
Tags: 7, users, emails, configuration
---


title: fetching user photo or image URL

text:
# Question
Title: fetching user photo or image URL
i am trying to fetch loged in users photo to make a welcome block. i have applied a code which is not working

```
$userphoto = $user->picture;

```

so what to do to fetching user photo or image URL, any idea?

# Answer
The `picture` property of the user entity is the file ID (a reference to the `fid` column in the `file_managed` table).

You can load the file explicitly with `file_load()` like so:

```
$file = file_load($user->picture);

```

And render it to an image using `theme_image()`:

```
$image = theme('image', array(
  'path' => $file->uri,
  'alt' => 'Some alt',
  // etc...
));

```

Alternatively you could dispense with the above and just use the handy `theme_user_picture()` function:

```
$image = theme('user_picture', array('account' => $account));

```
> 5 votes

# Answer
Maybe it is helpful to render with a image styles

image\_style\_url('my\_image\_style',$user-\>picture\['uri'\]);

second param is a drupal's internal file path like 'public://images/myimage.png'
> 1 votes

# Answer
You can try the following:

```
$user = user_load($view->result[$key]->uid);
$filepath = $user->picture->uri;
$picture_url = file_create_url($filepath);

```

This will give you the user's picture url.
> 0 votes

---
Tags: blocks, users, media
---


# Question
Title: How to add a link in a menu with query parameters in paths
I want to add this link : resources?field\_resources\_type\_tid\_i18n\[0\]=130 in the main menu that point to a view with exposed filter. But When I save my link I just find resources without query parameter

# Answer
> 7 votes
There are multiple ways to solve this problem.

1. Use the absolute URL of the page, instead of the Drupal path.
2. Write a module that provides a menu item via hook\_menu(), e.g. for the path `resources/field_resources_type_tid_i18n/130`. The page callback for the menu item would either redirect to `resources?field_resources_type_tid_i18n[0]=130` or serve the desired page directly.
3. Add a rewrite rule to the webserver configuration, the translates `resources/field_resources_type_tid_i18n/130` into `index.php?q=resources&field_resources_type_tid_i18n[0]=130` and add `resources/field_resources_type_tid_i18n/130` to the menu.

Solution 1 is the most simple, but not very flexible. You need to touch the menu links database table if the absolute URL of the site changes. Adapting the link to the currently used scheme (http:// or https://) is not possible.

I prefer Solution 2, but it requires knowledge about Drupal module development.

I do not like to rely on URL rewriting to provide essential functionality, so I do not recommend Solution 3.

# Answer
> 1 votes
Case: you have an existing menu block in your structure. You can add query parameters to existing menu link paths by adding the query option. (see url())

```
function (your_module_name)_block_view_alter(&$data, $block) {
  if ($block->delta == "main-menu") {
    $data['content'][601]['#localized_options']['query'] = array('yourqueryparameter' => 'parameters value');
  }
}

```

For more dynamic code:

```
... if ($block->delta == "main-menu") {
foreach ($data['content'] as $menu_link){
  if (isset($menu_link['#href']) && $menu_link['#href'] == "Link_of_your_menu_item" ){
    $data['content'][$menu_link['#original_link']['mlid']]['#localized_options']['query'] = array('yourqueryparameter' => 'parameters value');
  }
}

```

---
Tags: 7, routes
---


# Question
Title: `drush cc all` command takes too long time, what can I do?
On a site of mine `drush cc all` takes more than 4 mins to run. The site db is a few GBs. However, I cannot see a clear reason as to why it takes too long. What can I do to locate the bottle neck?

# Answer
> 6 votes
The clearing cache it-self doesn't take a long time, since it's just truncating cache tables. What takes time the most is rebuilding the cache registry after that. Usually it's theme registry which scanning for all new hooks and all your Drupal folders for new template files, system which scanning files for the new modules and class files, and similar.

You can always clear specific cache by specifying `drush cc theme-registry` or any other.

It's highly recommended that you use PHP caching mechanism (e.g. OPCache, XCache, etc.) to speed up the processing. And memory-base cache to replace heavy usage on SQL tables (e.g. memcached or redis), so clearing cache would take no time, just by flushing the cache (e.g. `echo flush_all > /dev/tcp/127.0.0.1/11211` in Bash).

Alternatively you can always clear cache manually, e.g. by:

```
echo "SHOW TABLES LIKE 'cache%'" | $(drush sql-connect) | tail -n +2 | xargs -L1 -I% echo "DELETE FROM %;" | $(drush sql-connect) -v

```

---

### Debugging

To check what's taking the most time specifically, you need to debug/profile it (e.g. XDebug, XHProf, phpdbg, dtrace).

On OS X/Unix, this can be achieved by `dtrace` (after running `drush`):

```
sudo dtrace -qn 'php*:::function-entry { printf("%Y: PHP function-entry:\t%s%s%s() in %s:%d\n", walltimestamp, copyinstr(arg3), copyinstr(arg4), copyinstr(arg0), basename(copyinstr(arg1)), (int)arg2); }'

```

On Linux, use `strace`, e.g.

```
strace -e trace=sendto,recvfrom -s1000 -p $(pgrep php)

```

To look for some specific things, try adding e.g.: `strace ... 2>&1 | grep -C5 UPDATE`.

# Answer
> 5 votes
If you have a really large database, and your system is running fine when you are not doing a cache clear, it is likely that you do not have enough memory to fully support your setup.

If your site is running on a Linux box, run 'top' (from your shell) and press shift-M to sort the process list by memory used. Then, run your cache-clear operation from another terminal. You should see mysql and apache rise to the top of the list. You'll be able to see what percentage of total memory each of these processes are using, and how much free RAM is used. If you have a large amount of virtual space, but all of your physical RAM is exhausted, this operation could be causing VM memory to thrash, which can drive your execution time down to a small fraction of what it normally is.

Once, I was running a mid-traffic Drupal site on a box w/out -quite- enough memory to support the setup. When I ran a cache-clear on an unrelated low-traffic site, the cache rebuild pushed the system past its limit, and everything all but locked up. So, the total system behavior is important here; this is why simple tools like 'top' are a handy place to start.

# Answer
> 2 votes
I am going to disagree (somewhat) with @greg\_1\_anderson here.

If the system isn't crashing totally during a `cc all`, then I don't think you have a general memory issue. When a LAMP server runs out of memory, it will hit swap. An active server hitting swap will cause an avalance of badness. httpd processes will start to stack up due to system slowdown (swap makes a system run very slow), which will cause more swap to be used, etc. On sites where I have seen this happen, I would see the process load hit 100, and a ton of active httpd processes.

If your system eventually comes back, then I think you are poorly tuned. `drush cc all` will result in a lot of database accesses, so I think it is showing the problem more. My suggestion would be to run mysqltuner on the site. If you have a multi GB database, my *guess* is that your `innodb_buffer_pool_size` isn't even remotely sized properly, and your MySQL instance is thrashing. I would also investigate an alternate cache backend to try to keep the database footprint smaller.

# Answer
> 1 votes
It could be your web hosting environment. Are you referring to a local setup, or something hosting on shared hosting or a VPS/server?

* **hosting environment** \- if you are on shared web hosting, the amount of memory Drupal/drush can use will be limited see: https://drupal.org/node/207036
* **max execution time** \- needs to be increased

# Answer
> 1 votes
*This is not a complete solution, just one more tool to help identify the source of your delays.*

As well as using `top` to monitor processes, you might find the output of `mytop` informative. (Other answers above presume MySQL but if you're using another DB backend, you'll need to swap mytop for an equivalent tool.)

`mytop` simply executes MySQL `SHOW FULL PROCESSLIST` in a loop, and shows you which queries are being executed (so which take a lot of time). If the cache clear is taking a long time cleaning up this or that table, you'll see exactly what's holding things up here. If you don't have access to install `mytop`, just do a crude version in your shell -

```
while true; do mysql -e 'SHOW FULL PROCESSLIST' && sleep 5 && clear ; done

```

If the delay is not stemming from MySQL queries, then this tool may at least confirm that for you.

# Answer
> 1 votes
I found a blog post entitled Speed Up Cache Clearing on Drupal 7 to be very helpful in narrowing down precisely what portion of the cache clear process was slowing things down. The issues it pinpoints in features module and the entity api module were affecting my site, but the process detailed in the post also helped me track down issues we were encountering in Drupal core and breakpoints module.

It takes some time to work through the process, but it has helped me to reduce cache clears down from multiple minutes to under a minute.

---
Tags: 7, drush, caching
---


# Question
Title: How to stop nodes being automatically added to a simple queue in Nodequeue?
I'm guessing my problem is a configuration error, but every kind of node that is allowed to be added to my (I only have one) simple nodequeue does get added to the nodequeue when a node of an allowed content type is created. I only want specified nodes to be allowed into the queue. Any ideas of where to look?

# Answer
In case someone else runs into this, I finally figured it out.

In the settings (admin/structure/nodequeue/\[NODEQUEUE\_ID\]/edit), there's the list of "Type" checkboxes. When I originally set this up, I assumed that I had to check those content types that I wanted allowed into a queue. Turns out, this actually seems to auto-add new nodes of those content types. I unchecked all of the checkboxes, and now things seem to work as they should.
> 0 votes

---
Tags: nodes
---


# Question
Title: Organic Groups "create post" content link needed with posting content type specific to group
Organic groups 7.x-2.6 Entity reference prepopulate 7.x-1.5

Hello, I am trying to create custom "create posting" link for my organic groups. Each Organic Group has its own content posting content types, so when a user visits the panel page for that group the add posting link should be specific to that group.

I have 2 groups: Amigo group, and Authenticated group I read that target bundles are globally defined for Groups Audience, so I read that you have to add an extra group audience to the Posting content type for your group. You are then supposed to set the target bundle on the 2nd to match the group content type. My problem is that when I try to set the "Content Create Links" section in my panel it wants to only set one group audience field, and I have 2 created, one for each group's posting content type.

I recorded images of each part of this problem for ease of understanding.

Here is my Amigo group's posting content type called "Amigo Group Post". Notice the extra Group's Audience field added to the bottom of the content type. Clicking edit on this allows us to change the settings on this field

Clicking on group audience for Amigo Post takes us to that group audiences configuration page. Here I am choosing to prepopulate the entity reference.

Here is my panel for the Organic Groups group. Lets go to the Content Create Links setting page.

Here you can set ONE of the 2 posting content types to be the content type used for new group postings, but I need it to just choose the posting content type by the type of Organic Group. I chose one because I could only choose one.

Looking at the Amigo group page we can see that the create post section is not even showing up.

This is the Authenticated group page. When viewing this page we do see the create post section, because we had to set one field name for the "content create links" section in the Panel.

Does anyone have any idea how to have the panel choose the content creation link type based on the current group?

# Answer
> 0 votes
I solved this problem. I am not sure if this is the best way. If a better way exists, please do inform me.

To solve this problem I create 2 "Content Create Links" panels within the page. Each added panel references the group audience specific for the Group Posting content type for the group. At first both will probably show up, but you have to go to the global "OG Permissions Overview" and for each group type make sure that create content for that Groups posting content type is checked. For all other type on the page you should not have "Create \____ Content" checked otherwise that content type (a posting type) will also show up as a "Content Create Links" for the wrong posting type for that group.

Do that for each Group type you have created, allowing "Create\__(groups post content type) Content" and not having the "Create\__(other groups post content type)\__ content" for all other group posting content types for the other groups.

Now when I open up "Amigos" groups, I only get "Amigo Group Post" as the posting content type, and NOT "Authenticated Group Post" as well.

If this is too "hacky" I welcome other suggestions on how to configure this properly.

# Answer
> 0 votes
You can also build these custom links yourself, and use an argument, context or php to fill in the group id.

The url would be like `<a href="/node/add/nodetype?og_group_ref={GROUPID}}">Post content of type to group</a>`.

This way you can create those content urls everywhere, in blocks, pages, content, views, etc. If you do not hardcode the groupid, but fetch it from context (which is added to grouppages) you can have those kind of links on all your group subpages.

# Answer
> 0 votes
If you are not using panels module, then install og\_extras since it will create a block with all the correct links for posting content. All you need to then do is also enable the block. To quote from og\_extras module page:

> Extra functions, blocks, and views for Organic Groups 7.2. In particular, this module adds views and blocks needed by sites that are not using Panels, although it also may be useful to sites that do use Panels. This module is for Organic Groups 7.2. It will not work with Organic Groups 7.1.

---
Tags: 7, organic-groups, entities
---


# Question
Title: How do I print core block or views block in node.html.twig?
I'm pretty new to D8, so this might be basic stuff, but I can't find any tutorial how to do it.

In Drupal 7 this is the code that outputs core block in node.tpl.php:

```
<?php $block = module_invoke('block', 'block_view', '10'); print render($block['content']); ?>

```

This works for Views:

```
<?php print views_embed_view('viewname','block_10'); ?>

```

How do I achieve this in Drupal 8?

# Answer
> 11 votes
In Drupal 8, you don't need (and should not) render in PHP. The rendering is done as late as possible in Twig.

So put the build array of your view in a variable.

```
function mytheme_preprocess_node(&$variables) {
  $variables['view1'] = views_embed_view('view1', 'block_news');
}

```

And then render it with `{{ view1 }}`.

Twig will handle the necessary rendering for all kind of render arrays that are possible in Drupal.

You can use the same for a block. (See the comment from Ivan Jaros.)

```
$variables['block1'] = entity_load('block', $id)->getPlugin()->build();

```

The `build()` method gives you the build array of the entity and you can use `{{ block1 }}`.

# Answer
> 1 votes
If you have **multiple blocks** you can make a new region, place them there and use the following code.

```
function THEMENAME_preprocess_node(&$variables){
  $result = array();
  $blocks = \Drupal::entityManager()
            ->getStorage('block')
            ->loadByProperties(array('theme'  => 'THEMENAME',
                                     'region' => 'YOUR_NEW_REGION'));

  foreach ($blocks as $key => $block) {
    if ($block->access('view')) {
      $result[$key] = entity_view($block, 'block');
    }
  }

  $variables['YOUR_NEW_VARIABLE'] = $result;
}

```

Then use `{{ YOUR_NEW_VARIABLE }}` in your template file.

---
Tags: 8, theming
---


# Question
Title: How to choose what tables to skip for drush sql-sync @dev @staging?
Following my previous question How to set Drush sql-sync not to clone users between @dev and @staging? I have manually preselected over 80 tables that should not be automatically synced (content, roles and permissions, users, temporary, cache). I am not fully satisfied with this solution. Why? Because my filter decisions is based on experience, intuition and guess when I would like to use the best practice method.

How to properly choose what tables to skip for `drush sql-sync @dev @tst` and `drush sql-sync @production @staging`?

My setup:

```
git.drupal.org ==> local drupal git repository ==>  @dev -> @tst -> @staging -> @production (configuration, static content, roles and permissions)

@staging <- @production (content, production scenarios to be tested)

```

The Definitive Guide to Drupal 7 by Benjamin Melançon and others says:

> Here is the list of tables that appears in `example.drushrc.php`:
>
> ```
> $options['structure-tables'] = array(  'common' => array('cache',
>   'cache_filter', 'cache_menu', 'cache_page', 'history', 'sessions',
>   'watchdog'),
> );
>
> ```
>
> You may need to add some more tables to this list. A good place to start would be to consider the list of tables that contain `cache` in their name via `drush sql-query 'show tables;' | grep cache`
>
> Remove from this list tables such as `imagecache_action` and so on, and add the remainder to your structure tables list.
>
> After you do an `sql-sync` with skipped tables, you will need to clear the cache on the target site to make sure that things work right.

What are the other tables to consider? Why?

# Answer
> 6 votes
Drush sql-sync does not support shared databases that use prefixes. You might have some luck if you wrote a wrapper script that used `drush sqlq 'show tables;'` to get a list of available tables, filter them manually by prefix, and then pass them back to sql-sync via the --tables-list option.

# Answer
> 5 votes
In Drupal 7 these tables you should consider:

```
'cache', 'cache_field', 'cache_form', 'cache_filter', 'cache_menu', 'cache_page', 'history', 'sessions', 'watchdog'

```

In Drupal 8, these:

```
'cache', 'cache_bootstrap', 'cache_config', 'cache_container', 'cache_data', 'cache_default', 'cache_discovery', 'cache_filter', 'cache_menu', 'cache_page', 'history', 'search_index', 'sessions', 'watchdog'

```

This doesn't include specific tables which are related to Migrate module or any other custom tables which may store some temporary data.

Example drush command to dump and skip these tables (create just a structure without data):

```
drush sql-dump --structure-tables-list=cache,cache_filter,cache_menu,cache_page,history,sessions,watchdog --result-file=dump.sql

```

Hint: Add `--ordered-dump` for nicer human output, but a bit slower on import.

Normally adding `structure-table` option should be enough for local operations (`$options['structure-tables']`), but for `sql-sync`, I think this should be added for specific alias in command-specific section, e.g.

```
$aliases['foo'] = array(
  // These options will only be set if the alias is used with the specified command.
  'command-specific' => array(
    'sql-sync' => array(
      'structure-tables-key' => 'common',
      'skip-tables-key' => 'common',
      'structure-tables' => array(
        // You can add more tables which contain data to be ignored by the database dump
        'common' => array('cache', 'cache_filter', 'cache_menu', 'cache_page', 'history', 'search_index', 'sessions', 'watchdog'),
      ),
      'skip-tables' => array(
        'common' => array('field_deleted_revision_63'),
      ),
    ),
    'sql-dump' => array(
      'ordered-dump' => TRUE,
      'structure-tables-key' => 'common',
      'skip-tables-key' => 'common',
    ),
  ), // end: command-specific
  // Applied only if the alias is used as the source.
  'source-command-specific' => array(
  ),
  // Applied only if the alias is used as the target.
  'target-command-specific' => array(
  ),
);

```

---
Tags: 7, drush
---


title: Drupal single sign on local

text:
# Question
Title: Drupal single sign on local
Is it possible to test signle sign from active directory on locally on your desktop?

Does it work with XAMPP / IIS?

# Answer
Yes, you can test it against any Active Directory you can connect to.

But if you want a local copy of active directory, you can install a local copy of Active Directory Lightweight Directory Services (AD LDS) for Windows7 or equivalent.

Once installed, you will also need to configure to work with drupal's ldap module as normal. Then you will be able to work locally.

I have done this using XAMPP on a windows laptop.
> 1 votes

---
Tags: nodes
---


# Question
Title: How to show a link if the user is member of a specific OG group?
I am not a coder but I'd like to do this line of code:

> **If** the logged in user is a member of the Organic group team1
>
> **Then** show a Link to `node/add/team_1_content` with 'Text' = create node
>
> **Else** show nothing.

# Answer
Create a block that includes that "Link to `node/add/team_1_content` with 'Text' = create node" as in your question.

Then use the Rules block visibility module. Here is a quote from its project page:

> The Rules block visibility module allows Rules components to be used to control block visibility. This provides Drupal administrators and developers extreme flexibility in controlling when blocks should be displayed on their websites, in addition to the default visibility options provided by Drupal.
>
> The general idea is that if you can do it with Rules, you can use it to control block visibility, so the possibilities are limitless:
>
> * Need to show a block only for users registered more than a month ago?
> * Perhaps you have a block that must be shown only between 8am-5pm on weekdays?
> * What about displaying or hiding a block based on current weather conditions?
>
> All of this can be done by using Rules block visibility.

With that, and as per the "*if you can do it with Rules, you can use it to control block visibility*" above, you've reduced your question to making Rules "***check if the logged in user is a member of the Organic group team1***".

For an illustration of how to use this module, refer to my answer to "How to stop a Views block from displaying to admins, such as user/1?".
> 2 votes

# Answer
Another approach is to install og\_extras since it will create a block with all the correct links for posting content for a particular group. All you need to then do is also enable the block, so that it is visible. Links will show automatically if user is a member.

To quote from og\_extras module page:

> Extra functions, blocks, and views for Organic Groups 7.2. In particular, this module adds views and blocks needed by sites that are not using Panels, although it also may be useful to sites that do use Panels. This module is for Organic Groups 7.2. It will not work with Organic Groups 7.1.

You will also need to install eva module. Also make sure organic groups is configured to prepopulate by using entityreference\_prepopulate module
> 1 votes

---
Tags: organic-groups
---


# Question
Title: Use Composer to manage sub-theme Bootstrap LESS dependencies when using LESS starterkit
In Drupal 8 let's say I want to use a Bootstrap subtheme and the LESS starterkit described here: http://drupal-bootstrap.org/api/bootstrap/starterkits!less!README.md/group/subtheme\_less/8

The Instruction there is to:

> Download and extract the latest 3.x.x version of Bootstrap Framework Source Files into your new sub-theme. After it has been extracted, the folder should read ./subtheme/bootstrap.

Unfortunately this puts the Bootstrap source outside the ambit of my composer.json where I am managing my site dependecies and upgrade etc... more on why I want to do this here: https://bojanz.wordpress.com/2015/09/18/d8-composer-definitive-intro/

So how can I include the bootstrap source required by my subtheme in the composer.json?

# Answer
> 2 votes
`composer require twbs/bootstrap ^3.3.6 --prefer-dist -vvv`

Drupal Bootstrap requires 3.x.x the caret will stop us tripping into v4.

We don't want to include any git files so we do --prefer-dist.

This downloads the latest bootstrap source to vendor/twbs.

I can expose this dir to my subtheme by editing:

`/themes/custom/MYSUBTHEME/less/bootstrap.less`

Now when I run `composer update` I will get the latest bootstrap less in my subtheme.

---
Tags: 8, theming, composer
---


# Question
Title: How to check if library is present in vendor folder?
I have a form in which I am providing some options to users. But I want the options to appear in the form on the basis of presence of 3rd party libraries in vendor directory. I want something like this:

`public function buildForm(array $form, FormStateInterface $form_state) {
 $form['settings']['tools'] = array(
 '#type' => 'radios',
 '#title' => $this->t('tools'),
 '#options' => array(),
 '#default_value' => $this->config('module.settings')->get('tools'),
 );
if(check_whether_xyz_library_is present_in_vendor_folder) {
 $form['settings']['tools']['#options'] = array('xyz' => 'xyz');
}`

The vendor folder is present in the module directory itself and I am using composer to download third party dependencies. Since I do not want to check this during installation of module but during form rendering then I suppose hook\_requirements is not option. Any ideas on how to do so?

# Answer
If you are talking about libraries, which are defined in files like \*.libraries.yml, then you can use this:

```
\Drupal::service('library.discovery')->getLibraryByName('MODULE_NAME', 'LIBRARY_NAME')

```

You'll receive an array with all data including paths to check that files are exist.
> 3 votes

# Answer
Since you mention that "the vendor folder is present in the module directory itself", you could check that a vendor file exists within your module:

```
$module_path = drupal_get_path('module', 'MY_MODULE');
if (file_exists($module_path . '/js/MY_FILE.js')) {
  // ...
}

```

Another option would be to store the vendor library in the *libraries* folder, and check if the library exists with `libraries_get_path()`:

```
$name = 'foo';    // your library name here.
if (function_exists('libraries_get_path') && file_exists(libraries_get_path($name))) {
  // ...
}

```
> 1 votes

---
Tags: 8, theming, composer
---


# Question
Title: What could cause uids to not be numbered consecutively?
I just noticed something weird in a site I'm working on. The first account is user/1 as usual. A second account I created two weeks later is user/20, and a third one a couple days later is user/32. Etc. Two accounts I just created right after each other are numbered consecutively as expected.

There are no custom modules modifying the registration process or anything. I wonder what could cause this, and if there's something I need to fix.

# Answer
> 1 votes
So, it turns out this is indeed normal since Drupal 7: the users table is not auto-increment but uids are created with a sequences API that is shared with actions and batch jobs. Uids can therefore be non-consecutive.

Several reasons for changing back from auto-increment table in D6 are pointed out here by chx.

(From reading chx's response to this blog post)

# Answer
> 0 votes
I noticed the same, I had some gaps between new user ids that even reached at some points 1000 because I was relying on the batch API at my site which shared the same incremental ids for its jobs with the user table. Here is a tested solution that ensures that user id's will always increase by one.

```
function MYMODULE_user_presave(&$edit, $account, $category) {
  if (isset($account->is_new) && !empty($account->is_new)) {
   $account->uid = db_query('SELECT MAX(uid) FROM users')->fetchField() + 1;
  }
}

```

---
Tags: users
---


# Question
Title: Getting error "Table 'drupal.watchdog' doesn't exist" during install
I'm a Drupal newbie and haven't been able to find this problem posted elsewhere online, so I'm hopeful someone here can help.

I have just set up php/mysql on a shared hosting environment and copied drupal 8.0.5 over to begin the installation (I changed some file permissions and copied `settings.php` and `.htaccess` over to the correct locations as per the instructions).

The server seems to be running MariaDB 10.0.23-MariaDB~trusty (debian maybe?) and ostensibly php 5.6. However, when I run `php --version` on the server I get `PHP 5.5.32-nfsn1 (cli) (built: Mar 11 2016 21:11:51)`. However, Drupal hasn't complained so it seems to agree that they're running 5.6.

Where I'm getting stuck is during the installation phase, where it breaks about half way through with the following error message:

```
An AJAX HTTP error occurred.
HTTP Result Code: 200
Debugging information follows.
Path: /core/install.php?rewrite=ok&langcode=en&profile=standard&id=1&op=do_nojs&op=do
StatusText: OK
ResponseText: Drupal\Core\Database\DatabaseExceptionWrapper: SQLSTATE[42S02]: Base table or view not found: 1146 Table 'drupal.watchdog' doesn't exist: INSERT INTO {watchdog} (uid, type, message, variables, severity, link, location, referer, hostname, timestamp) VALUES (:db_insert_placeholder_0, :db_insert_placeholder_1, :db_insert_placeholder_2, :db_insert_placeholder_3, :db_insert_placeholder_4, :db_insert_placeholder_5, :db_insert_placeholder_6, :db_insert_placeholder_7, :db_insert_placeholder_8, :db_insert_placeholder_9); Array
(
[:db_insert_placeholder_0] => 0
[:db_insert_placeholder_1] => DrupalKernel
[:db_insert_placeholder_2] => Container cannot be saved to cache.
[:db_insert_placeholder_3] => a:0:{}
[:db_insert_placeholder_4] => 3
[:db_insert_placeholder_5] =>
[:db_insert_placeholder_6] => http://www.mysite.info/core/install.php/?_format=json&id=1&langcode=en&op=do&op=do_nojs&profile=standard&rewrite=ok&rewrite=ok
[:db_insert_placeholder_7] => http://www.mysite.info/core/install.php?rewrite=ok&langcode=en&profile=standard&id=1&op=start
[:db_insert_placeholder_8] => 43.247.118.190
[:db_insert_placeholder_9] => 1459041023
)
in Drupal\dblog\Logger\DbLog->log() (line 84 of /home/public/core/modules/dblog/src/Logger/DbLog.php).

```

clicking the link to the error page takes me to this:

> Catchable fatal error: Argument 1 passed to Drupal\Core\Routing\CurrentRouteMatch::getRouteMatch() must be an instance of Symfony\Component\HttpFoundation\Request, null given, called in /home/public/core/lib/Drupal/Core/Routing/CurrentRouteMatch.php on line 92 and defined in /home/public/core/lib/Drupal/Core/Routing/CurrentRouteMatch.php on line 104

I can't make a lot of sense of this message. A quick google search lead me to a bunch of pages for *similar* errors, but I couldn't find this same issue.

As this is the only database in the mysql instance I have simply given drupal the admin user/password, so I don't see how this could be a permissions issue.

I have not made any modifications to any files, other than copying default.settings.php -\> settings.php.

What am I doing wrong here?

As per another user's request, I tried upgrading to drupal 8.0.6 and am now getting a 500 internal server error, with the following in the logs:

```
[Fri Apr 08 14:11:53.710451 2016] [core:error] [pid 54807:tid 34478458880] [client 172.17.240.6:45115] AH00124: Request exceeded the limit of 10 internal redirects due to probable configuration error. Use 'LimitInternalRecursion' to increase the limit if necessary. Use 'LogLevel debug' to get a backtrace.

```

I've posted another question to resolve this issue: https://drupal.stackexchange.com/questions/197400/500-server-error

# Answer
This is weird, since exactly in 8.0.5 is fixed that kind of error:

#2646410 by claudiu.cristea, dawehner: Container cannot be saved to cache

Can you try Drupal 8.0.6 maybe? Your MariaDB as well as PHP seem to be compatible with D8 requirements (your MariaDB is based on 5.5 plus Mysql 5.6 stuff).
> 1 votes

---
Tags: 8, installation
---


title: Reseed next Drupal User ID (UID)

text:
# Question
Title: Reseed next Drupal User ID (UID)
Is it possible to modify the next User ID when creating new users in a Drupal 7 database?

As an example,

I have a user at UID 100, I then create and immediately two user accounts (101, 102). When I next add a user, I want the UID to revert to 101 rather than default behaviour of 103.

# Answer
In Drupal 7 the `uid` column in the `users` table isn't an autonumber, so there's nothing to reset/reseed.

When you add a user in D7 the `user_save()` function does this:

```
// Allow 'uid' to be set by the caller. There is no danger of writing an
// existing user as drupal_write_record will do an INSERT.
if (empty($account->uid)) {
  $account->uid = db_next_id(db_query('SELECT MAX(uid) FROM {users}')->fetchField());
}

```

So the next user ID is simply the next available free ID (current max + 1) from the `users` table.

If you have a record with a uid of 100, then you add 2 new users (101 and 102), the next available user ID will naturally/logically be 103; which will be returned by the above code in `user_save()`.

If you need that to be 101 again for whatever reason, you need to delete the user you've just created that occupies the 101 ID, and set the uid manually on the new user record that you want to replace it, before you save it (as suggested by the above comments in `user_save()`).
> 4 votes

# Answer
I have recently encountered a similar need at my site and here is the way to achieve the desired behavior:

```
function MYMODULE_user_presave(&$edit, $account, $category) {
  if (isset($account->is_new) && !empty($account->is_new)) {
   $account->uid = db_query('SELECT MAX(uid) FROM users')->fetchField() + 1;
  }
}

```
> 1 votes

---
Tags: users, database
---


# Question
Title: Modifying argument of programmatically called render service. (e.g.: theme to use) = Get object from service container with modified argument
I use the D8 core render service for generating markup that is indexed in an external search service. The indexing is happening on `hook_entity_update`, where I call my indexing service. My custom indexing service is then using the core render service for creating the markup.

Example with static service call:

```
// Get the render array for the teaser.
$viewBuilder = \Drupal::entityTypeManager()
  ->getViewBuilder($entity->getEntityTypeId());
$render_array_teaser = $viewBuilder->view($entity, 'teaser');

// Generate the markup from the render_array.
$renderer = \Drupal::service('renderer');
$rendered_teaser = $renderer->renderPlain($render_array_teaser);
// When called in hook_entity_update $rendered teaser has a crappy
// default markup in it as a 'teaser' view mode and the correct twig
// templates don't exist in the backend theme.

```

This works fine when called from drush. But when called from `hook_entity_update()` the renderer has the wrong theme context. As the node edit form that triggers the update uses the backend theme, the renderer gets also the backend theme as context instead of the default theme.

The renderer gets the current theme injected with the `ThemeManager` object. See core services:

```
renderer:
  class: Drupal\Core\Render\Renderer
  arguments: ['@controller_resolver', '@theme.manager','@plugin.manager.element_info', '@render_placeholder_generator', '@render_cache', '@request_stack', '%renderer.config%']

```

How can I initialize the service but provide my own version of the ThemeManager object?

There is a setter method on the `ThemeManager` object where I could easily set the right theme. But I need to hand this over to the renderer.

e.g.:

```
$my_theme_manager = \Drupal::service('theme.manager');
$my_theme_manager->setActiveTheme('my_frontend_theme');

// How to get the service with this alternative context?
// e.g. something like that.
$service = \Drupal::Service();
$service->setService('renderer');
$service->setArgument(['@theme_manager' => $my_theme_manager]);
$default_theme_renderer = $service->getService();

```

Or is there some way to alter the ThemeManager Object when it is initialized? Before it is injected into the render service? So I can set the correct theme in an event or alter hook?

I know that I can alter the service in general by implementing the `ServiceModifierInterface`but this will modify the container when it gets created as far as I know, and is not a way for manipulation during runtime.

# Answer
> 3 votes
The mailsystem module is doing exactly what you are looking for I think. It has a configuration option to select which theme should be used to render mail templates.

See MailsystemManager::mail()

```
// Switch the theme to the configured mail theme.
$mail_theme = $this->getMailTheme();
$current_active_theme = $this->themeManager->getActiveTheme();
if ($mail_theme && $mail_theme != $current_active_theme->getName()) {
  $this->themeManager->setActiveTheme($this->themeInitialization->initTheme($mail_theme));
}

try {
  $message = parent::mail($module, $key, $to, $langcode, $params, $reply, $send);
}
finally {
  // Revert the active theme, this is done inside a finally block so it is
  // executed even if an exception is thrown during sending a mail.
  if ($mail_theme != $current_active_theme->getName()) {
    $this->themeManager->setActiveTheme($current_active_theme);
  }
}
return $message;

```

}

You can't tell the renderer directly which theme to use. But, you can switch out the active theme before you call it an then switch it back (the try/finally is important, so that you don't end up with the wrong active theme in case of an exception).

The service names for the two used services is `theme.manager` and `theme.initialization`.

---
Tags: theming, 8, dependency-injection
---


# Question
Title: Using video module with ffmpeg to convert; how do I display converted files?
All uploaded videos on our Drupal 7 site need to be in a standard web format: MP4-H.264/AAC to assure play back by all user devices.

ffmpeg is working correctly. Video upload field stores all uploaded files into sites/default/files/videos/originals.

ffmpeg saves converted files into sites/default/files/videos/converted/nnnn which is a directory containing the converted file, and nnnn is a number unique for each file.

On the web page, the original uploaded file is displayed. How can I switch to the converted ("transcoded") file?

Video module supports Rules integration. Is that a good solution?

Production and QA sites are hosted on AWS.

# Answer
Solved this by modifying the custom module. Test if file has been converted, by looking in sites/default/files/videos/converted/nnnn, where nnnn is the File ID of the original file. If not then display the original video file. If conversion completed successfully, then display the converted file from sites/default/files/videos/converted/nnnn. There is only one file in the nnnn directory.
> 0 votes

---
Tags: files
---


title: Integrate SQL Query into views

text:
# Question
Title: Integrate SQL Query into views
I manage a Wordpress site for a football team, and I created therefore a SQL Query to calculate the standings. Now I want to switch over to Drupal and for the calculation of the standings I thought to use the views module. Is it possible to integrate my SQL Query into Views?

Query :

```
$sql="SELECT
  teamname AS Team, Sum(Played) AS Played, Sum(Won) AS Won, Sum(Draw) AS Draw, Sum(Lost) AS Lost,
  SUM(Gfor) as Gfor, SUM(Gagainst) AS Gagainst, SUM(Gdiff) AS Gdiff, SUM(Pts) AS Pts

FROM(
  SELECT
    teamhome Team,
    1 Played,
    IF(homescore > awayscore,1,0) Won,
    IF(homescore = awayscore,1,0) Draw,
    IF(homescore < awayscore,1,0) Lost,
    homescore Gfor,
    awayscore Gagainst,
    homescore-awayscore Gdiff,
    CASE WHEN homescore > awayscore THEN 3 WHEN homescore = awayscore THEN 1 ELSE 0 END Pts
  FROM matches
WHERE homescore IS NOT NULL AND awayscore IS NOT NULL
AND division='1' and season = '2015-2016' AND matchtype='C'
  UNION ALL
  SELECT
    teamaway,
    1,
    IF(homescore < awayscore,1,0),
    IF(homescore = awayscore,1,0),
    IF(homescore > awayscore,1,0),
    awayscore,
    homescore,
    awayscore-homescore Gdiff,
    CASE WHEN homescore < awayscore THEN 3 WHEN homescore = awayscore THEN 1 ELSE 0 END
  FROM matches
  WHERE homescore IS NOT NULL AND awayscore IS NOT NULL
  AND division='1' and season = '2015-2016' AND matchtype='C'
) as tot

JOIN teams t ON tot.Team=t.teamid
GROUP BY Team

ORDER BY SUM(Pts) DESC, Sum(Won) DESC, SUM(Gdiff) DESC";

```

# Answer
> 2 votes
You will need to create a (1) custom table in the drupal database, (2) to adopt that table using the data module and (3) to create a view with that table as base the table of your view.

1) Create your custom table by using pure SQL (the fields order matters)

```
DROP TABLE IF EXISTS my_custom_table;
CREATE TABLE `my_custom_table` (
`node_id` int(10) unsigned NOT NULL DEFAULT '0' COMMENT 'The primary identifier for a node.',
`int_field` int(10) unsigned DEFAULT NULL,
`text_field_1` varchar(255) NOT NULL DEFAULT,
`text_field_2` varchar(255) DEFAULT NULL,
`long_text_field` longtext,
`term_tid_field` int(10) unsigned NOT NULL DEFAULT '0',
`term_field` varchar(255) NOT NULL DEFAULT,
 PRIMARY KEY (`node_id`),
 KEY `text_field_1` (`text_field_1`),
 KEY `text_field_2` (`text_field_2`),
 KEY `long_text_field` (`long_text_field`),
 KEY `term_tid_field` (`term_tid_field`),
 KEY `term_field` (`term_field`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

```

*You can peek at the drupal database for more field types*

1.1) Continue by adding your data into that table by using SQL again:

```
INSERT IGNORE INTO my_custom_table(
SELECT
 int_field,
 text_field_1,
 text_field_2,
 long_text_field,
 term_tid_field,
 term_field
FROM
// Your query
);

```

2) Go to the data module's admin page `admin/structure/data` and adopt your custom table. The module is smart enough and your table will be displayed in the list, simple adopt it.

3) Create a new view `admin/structure/views/add` and if everything went well your table will be in the **Show** list with all other available tables. You should be able to see all the fields (**1:1**) from your table as fields in the view.

A drawback (if it really is) by following that method is that no other fields are available, like node fields, taxonomy, users etc, just yours. The same goes for contextual filters handlers, filters criteria handlers and relationships. That's all.

---
Tags: views, database
---


# Question
Title: Feature creation of Print module for path to print stylesheet
Using the print module, I need to create a Feature to deploy in order to set the path to the .css file to my themes directory on my production site.

In Features, what do I need to check to make sure I get these settings?

When creating the Features, the closest thing I can find is a checkbox under permissions:

Thanks

# Answer
> 2 votes
You also need strongarm enabled to export the path variable. Then it will be available as `print_css` variable.

---
Tags: 7
---


# Question
Title: View of related nodes by continent or country without taxonomy terms
I have a content type called `Packages`.Each content has two fields: `Title` and `Continent`(this field was created using the module Countries).

I have created five contents of content type `Package`:

```
**Title        Continent**
```

```
 London      Europe
```

```
 Madrid      Europe
```

```
 Paris       Europe
```

```
 Brussels    Europe
```

```
 Tokyo       Asia
```

I want to make a block of related nodes by the continent.

For example: if I am viewing the node of London in the block of related nodes show the cities on the same continent in this case: Paris, Madrid and Brussels.

I want to do this without terms of taxonomy, otherwise I'll have to create a vocabulary with more than one hundred fifty terms.

# Answer
There are like mostly in Drupal several possible solutions. One would be to filter Views views for each view and therefore you can filter any field you want the same way, like you do with terms (check the terms view pages as an example, how to build such filtered views).

Another option would be to create node relations like provided with the Relation module or the Entity reference module. The advantage of the relation module is, that the relations are own custom entities which are fieldable again, like term view pages. Thanks to @diqidoq for pointing me to this solution.
> 2 votes

---
Tags: nodes, views
---


# Question
Title: What is the most efficient way to create and manage 500 sales/landing pages
For a domain sales business, what is the best way to create and manage about 500 landing pages, each connected to a top level domain name?

I have worked with the Domain Access module in the past, but that becomes very unpractical with more than 10 domains, it lacks the features to handle large numbers of domains.

I have worked with and Aegir server but don't have experience with using a shared Drupal commerce instance for all the domains.

The domain landing pages can either be one page or multiple pages (sites) as long as it will be easy to apply different themes to them easily, if possible through a centralized management tool.

# Answer
Disclaimer: I'm a maintainer of Aegir.

Aegir is inherently multi-site, you can have many sites on a shared platform, which means you can have many independent sites with the same codebase. This is a lot more efficient resources-wise than having multiple sites without a shared codebase.

If you often need to create new domains, I developed a Software-as-a-Service suite for Aegir: https://www.drupal.org/project/hosting\_saas

Since there is E-Commerce involved, you'll want to have an SSL certificate, with Aegir you can easily use the same wildcard certificate for all the sites if necessary.

If the landing pages don't need to be customized (much), you can even have a single site with 500 aliases in Aegir.

Lastly, one of the main advantages with Aegir is that you can simply clone a site when you need a new instance (which is what we do in Hosting SaaS).
> 0 votes

---
Tags: commerce, domain-access, aegir
---


title: How to execute a VBO using Drush

text:
# Question
Title: How to execute a VBO using Drush
So I want to execute a VBO using drush, taking advantage of `vbo-execute` command to change my workflow state in my views, based on few resources I found this is the command I'm using:

```
drush vbo-execute list_of_node_for_expire  action::workflow_vbo_given_state_action argument:1

```

and I end up with this error:

> in field\_sql\_storage\_field\_storage\_write() (line 514 of /modules/field/modules/field\_sql\_storage/field\_sql\_storage.module). PDOException:
>
> SQLSTATE\[23000\]: Integrity constraint violation: 1048 Column 'field\_workflow\_states\_value' cannot be null: INSERT INTO {field\_data\_field\_workflow\_states} (entity\_type, entity\_id, revision\_id, bundle, delta, language, field\_workflow\_states\_value)
>
> VALUES (:db\_insert\_placeholder\_0, :db\_insert\_placeholder\_1, :db\_insert\_placeholder\_2, :db\_insert\_placeholder\_3, :db\_insert\_placeholder\_4, :db\_insert\_placeholder\_5, :db\_insert\_placeholder\_6); Array ( \[:db\_insert\_placeholder\_0\] =\> node \[:db\_insert\_placeholder\_1\] =\> 34924 \[:db\_insert\_placeholder\_2\] =\> 34924 \[:db\_insert\_placeholder\_3\] =\> listing \[:db\_insert\_placeholder\_4\] =\> 0 \[:db\_insert\_placeholder\_5\] =\> und \[:db\_insert\_placeholder\_6\] =\> )

I have no idea why it's giving me such an error, I'm not even sure if it has something to do with VBO or not, but using Views UI, I can execute my VBO with no errors.

# Answer
> 1 votes
From the looks of the error, it looks like vbo operation or the action is trying to insert a blank value into the `field_data_field_workflow_states` table.

Without actually seeing any code it's a little harder to determine what's going on in the vbo or the action, but check either `list_of_node_for_expire` or `action::workflow_vbo_given_state_action` and make sure you're working with the correct data before it makes the database request.

---
Tags: 7, views, drush, workflows
---


# Question
Title: Taxonomy List in node/add Capitalize all letters in the parent only
I have a strange customer request for a taxonomy list users select from while adding content.

The request from the customer is have the parent vid show up in ALL CAPS and the children to be left alone.

What's the best approach to this? Thanks

# Answer
You can use hook\_form\_alter to alter the node form. This way you don't alter the data in the vocabulary.

```
function modulename_form_alter(&$form, &$form_state, $form_id) {
  // For 'article' content type.
  if ($form_id === 'article_node_form') {
    $lang_code = $form['language']['#value'];
    foreach ($form['field_dd'][$lang_code]['#options'] as $key => $value) {
      // Check if option starts with '-' sign. Only child starts with '-' sign.
      // If yes, then continue.
      if (strpos($value, '-') === 0) {
        continue;
      }
      // Else capitalize all the characters.
      $form['field_dd'][$lang_code]['#options'][$key] = strtoupper($value);
      // $form['field_dd'][$lang_code]['#options'][$key]['#attributes'] = array('class' => array('option-blue'));
    }
  }
}

```

**Note:**

Refer this link for your new use case: https://api.drupal.org/api/drupal/developer!topics!forms\_api\_reference.html/7#attributes
> 1 votes

---
Tags: taxonomy-terms
---