title: Scrolling problem

text:
# Question
Title: Scrolling problem
Here I have a challenge. When I am logged in in my Drupal site: NO PROBLEM WITH SCROLLING THE PAGES When I am lopgged out: I can't scrolll the page as normal. This problem **only occurs with Google Chrome**, other pages is no problem. When I clear all cache, log out, then the first time I can scroll the page without problems. Visit the site again, the scrolling problem is there again.

Any suggestions?

The website: www.vankesselnatuursteen.nl

*Ps. With Chrome I have no problem at all at other Drupal sites*

Further information. I moved the site to another domain on my server. There where some problems and a changed some chmod rights of some folders and files.

THANKS IN ADVANCE FOR HELPING

# Answer
There is an error on the page if you scroll before the page is fully loaded:

> Uncaught ReferenceError: init is not defined

line 95 of smoothscroll.js.

**update**
Looks like a bug to me try changing:

```
function ssc_wheel(e) {
    if (!ssc_initdone) {
      init();
    }

```

to:

```
function ssc_wheel(e) {
    if (!ssc_initdone) {
      ssc_init();
    }

```
> 1 votes

---
Tags: javascript
---


# Question
Title: Quick question: horizontal align taxonomy @ node/add?
When adding a node (node/add/article), all the fields are showing up. With module "field group" i can alter the vertical presentation to an editor. In fact, the editor sees (for example) taxonomy-choices as: Taxonomy
\[\] Tag 1
\[\] Tag 2
\[\] Tag 3
\[\] Tag 4
\[\] Tag 5

\[\] Option 1
\[\] Option 2
\[\] Option 3
\[\] Option 4
\[\] Option 5

\[\]Choise a
\[\]Choise b
\[\]Choise c
\[\]Choise d
\[\]Choise e

But how can i present it horizontal, like

Taxonomy-choices (here radiobuttons

+-----------+---------------+--------------+
| \[\] Tag 1 | \[\] Option 1 | \[\]Choise a |
| \[\] Tag 2 | \[\] Option 2 | \[\]Choise b |
| \[\] Tag 3 | \[\] Option 3 | \[\]Choise c |
| \[\] Tag 4 | \[\] Option 4 | \[\]Choise d |
| \[\] Tag 5 | \[\] Option 5 | \[\]Choise e |
+-----------+---------------+---------------+

# Answer
You would do that with pure CSS. In your example you would assign a float:left to your fieldgroups.
> 0 votes

---
Tags: nodes, entities
---


# Question
Title: how to get view_mode from within hook_field_formatter_view
I've created a custom field formatter which works correctly. My problem is that I want to differentiate its output depending on whether it's being used in a `default` or `teaser` view mode.

The hook\_field\_formatter\_view doesn't seem to provide this.

One way I can solve this is by providing a setting on that formatter (hook\_field\_formatter\_settings\_form) with possible values `default` and `teaser`. I'd then have to go to the teaser view mode of all content types and configure this setting on all uses of that formatter. I'd then be able to get the setting using `$display['settings']`. This would work but it's a bad solution since it would be replicating data that is already there and it also requires administrative work.

Is there a cleaner solution to this?

# Answer
Imho a formatter shouldn't be dependent on the view mode. It's the site builder's choice which formatter to use in which view mode, and through that decide how things look. It sounds to me like you'd be better off either having two formatters, or having one formatter which can be configured.

My understanding of the Drupal way here is that you provide the general purpose tools (just like a module typically provides permissions, but not a new role - leaving it to the site builder to aggregate perms into roles appropriate for their particular needs). Every time I create a new view mode I want to have complete power to make it do exactly what I want.
> 1 votes

# Answer
Not sure this can be qualified as "cleaner" code, but looking at field\_default\_view source code, I can get the original view mode by :

```
function my_field_formatter_view($entity_type, $entity, $field, $instance, $langcode, $items, $display) {
  $backtrace = debug_backtrace(TRUE);
  $view_mode = $backtrace[1]['args'][6];

```

You can use Devel to confirm this…
> 0 votes

---
Tags: 7, entities
---


# Question
Title: Simple feedback contact form is shown only in administrator mode
Simple feedback contact form is shown only in administrator mode. How to set it up to make it visible on all pages of my Drupal 7 website? Thank you.

# Answer
> 1 votes
You probably need to give permission to other roles to see or edit simple feedback forms. (**People \> Permissions** in the admin menu.) Administrators are usually able to see and edit all content and interfaces regardless of permissions.

Generally speaking, anytime something is stubbornly not showing up, check for any relevant permissions!

---
Tags: feeds, emails
---


# Question
Title: Is there a D7/Services module for sane field content I/O?
For instance, a GET request to the standard endpoint `node/1.json` returns an object with fields like this:

```
{
   ...

   "field_my_field":{
      "und":[
         {
            "value":"yucky"
         }
      ]
   }

   ...
}

```

To build an easy to use API, we would want to GET and POST objects with fields like this:

```
{
   ...

   "my_field": "clean"

   ...
}

```

It would be easy to implement the vast majority of field types this way. I thought there was a module for this, but I can't find it.

# Answer
> 0 votes
With the Services module, no. However you could build a Page display with Views datasource, that accepts a node id as a contextual filter. The fields you specify in the View can then be configured to "clean up" the property name (or just turn off the label to use the machine name of the field), and then the value will be "flat".

---
Tags: 7, services
---


# Question
Title: How can I override a node's post date theme?
HTML5 provides a **time** element, and a lot of modern sites are using the time element for their content post dates.

How can I override a node's post date theming, so I can change the rendering from a **div** element to a **time** element?

Currently, the markup looks like:

```
<div class="field__item even">2015-01-17</div>

```

I want it to render it as:

```
<time datetime="2015-01-17T12:00">2015-01-17</time>

```

I would like to handle this in my theme, since I have an Omega 4 subtheme I use as a base theme for client sites and want it to handle the functionality.

# Answer
I'm using Display Suite, which takes over the node's created timestamp and turns it into a field named post\_date. Therefore, I overrode the field.tpl.php file and named it field--post-date.tpl.php, and added the **time** element to the markup:

```
<div class="<?php print $classes; ?>"<?php print $attributes; ?>>
  <?php if (!$label_hidden): ?>
    <div class="field-label"<?php print $title_attributes; ?>><?php print $label ?>: </div>
  <?php endif; ?>
  <div class="field-items"<?php print $content_attributes; ?>>
    <?php foreach ($items as $delta => $item): ?>
      <div class="field-item <?php print $delta % 2 ? 'odd' : 'even'; ?>"<?php print $item_attributes[$delta]; ?>><time datetime="<?php print $datetime; ?>"><?php print render($item); ?></time></div>
    <?php endforeach; ?>
  </div>
</div>

```

To get the $datetime variable, I added the following code to theme\_preprocess\_field():

```
function mytheme_preprocess_field(&$vars) {
    // check for Display Suite fields.
    if ($vars['element']['#field_type'] != 'ds') {
        return;
    }
    switch ($vars['element']['#field_name']) {
        case 'post_date':
            if ($vars['element']['#entity_type'] != 'node') {
                break;
            }
            $node = $vars['element']['#object'];
            $vars['datetime'] = date_iso8601($node->created);
        break;
    }
}

```

I'm just handling nodes, and a node always has one created time. The loop in the tpl file can probably be removed, since there will always be one value.
> 1 votes

---
Tags: 7, entities, theming
---


# Question
Title: Periodically set the userpoints for every user
I would like to set the user points of members of my site to an x amount at the start of each month. What would be the best way for this?

The closest I found so far was this: http://drupal.org/node/549640

There are a few issues with this though: 1. It adds 5 points, instead of setting it to 5 universally 2. It uses a while loop which can take long if there are a lot of users

I am thinking of a quick and dirty UPDATE SQL query that does this in one go.

# Answer
> 1 votes
you could extend the userpoints module to have some actions exposed to VBO then execute that periodically with Rules. Depends how much time you have, but it would be a nice addition to that module..

# Answer
> 0 votes
The question has been answered by me in the linked issue at http://drupal.org/node/549640 (comment 5-7). Quoting the answer here so that it can be found easier and the question can be marked as resolved.

> You can't just set the amount of points a user has to a fixed amount. The total is just a summary of all transactions, you do not want to set the amount without a corresponding transaction as this will lead to a very confusing UI as the transactions will list something different than the total a user currently has.
>
> What you need to do for each user is first to query how many points he currently has and then give the missing amount of points.
>
> ```
> <?php
> $points_to_give = 500 - userpoints_get_current_points($uid);
> if ($points_to_give > 0) {
>   // Grant points here.
> }
> ?>
>
> ```
> * Only process a fixed number of users on each cron run and only save the time variable once you processed all users. This means that it could take a few hours until all users have their points, depending on how often you call cron.
> * Not using hook\_crun() but for example create a custom script (e.g. with drush) and then calling it separately. Or a custom page callback that starts a batch process.

The follow-up comments are then about an alternative solution, which is to correct the number of points a user has when he logs in the first time in a new month.

# Answer
> 0 votes
A rules-based solution. Here are the actions:

1. Load points of a user
2. Add a variable: Type: Integer, Value: 750
3. Calculate a value: \[variable-added\] minus \[loaded-points\]
4. Grant points to a user using the calculated value variable

---
Tags: userpoints
---


# Question
Title: putting the most visited content in a block
I need to have the most visited content on a block, I am using view module and I want to know is there any way to do it with view module or I should use an other module

# Answer
> 0 votes
You could use the Drupal Most Popular module

> Showcase the most popular content across your Drupal website and engage your audience. Ready to Use
>
> The module is pre-packaged with several services including:
>
> Drupal - Most Viewed pages (using Statistics module) Drupal - Most Commented pages (from simple database query) Google Analytics - Most Viewed pages AddThis.com - Most Shared pages Disqus.com - Most Commented pages The system defines Drupal hooks to allow new services to be created, which can pull data from third party providers or internally from Drupal. The system also provides an API to help service plugins normalize their results and exclude certain pages, as configured by the administrator.

or another module that you can use and its so easy is Radioactivity and there is a good video tutorial here

# Answer
> 0 votes
If you prefer rolling your own code, the statistics module is a great start.

---
Tags: views, 7, rating
---


# Question
Title: What about Drupal Commons 3 on Drupal 7?
What about Drupal Commons 3 on Drupal7?

Its still in alphas and betas for months. Is it worthwhile waiting till it mature? Or is progress already stalled?

At the time Commons 3 on D7 (1.0) comes out Commons 6 will be at least 2.15 (its already 2.11). Should I go with already matured Commons 2.11 or wait for the delaying Version?

# Answer
> 0 votes
As of today Drupal Commons on Drupal.org, Commons Distribution Projects has reached version 7.x-3.22 from the first full release on February 25, 2013

---
Tags: 7
---


title: Add edit link to a view for admins only

text:
# Question
Title: Add edit link to a view for admins only
I have created a view in Drupal 7 that uses the node's content for display. I would like to add an edit link to this view that only displays if you are an administrator viewing this page. I know how to do this if I am using fields as the display type but not when the display type is set to content. How do I accomplish this?

# Answer
You can implement hook\_field\_attach\_view\_alter to hide the field you've mentioned.

```
my_module_field_attach_view_alter(&$output, $context) {
  global $user;

  // check if the content is what you want to alter
  if ($context['entity_type'] != 'node'] || $content['view_mode']=='my_display') return;

  // only user with 'administrator' role can see
  $output['my_field']['#access'] = in_array('administrator', $user->roles));
}

```

enter link description here
> 0 votes

# Answer
If you use field display to display the EDIT link, the link should actually only be shown to users with the appropriate permission to edit the content type.
> 0 votes

---
Tags: 7, views
---


# Question
Title: How do I bulk switch specific content from one content type to another?
So I get a fair amount of spam on my site that gets a good amount of traffic. But the spam content doesn't fit what my main audience is looking for. So I created a content section called spam and downloaded the Node\_Convert module, which has worked out well. I can easy change content from one type to another individually. But I want to bulk switch specific content from on type to another. I know I can bulk switch a content type using this module, but I don't want to switch a whole content type, just specific articles in one content type to the Spam content type all at once. It would make sense to to this from the admin content dashboard.

# Answer
> I know I can bulk switch a content type using this module, but I don't want to switch a whole content type, just specific articles in one content type to the Spam content type all at once. It would make sense to to this from the admin content dashboard.

Node Convert lets you create a custom action to perform this task. You may cherry-pick any items you want to convert and convert them. You need not convert *all* content from 1 content type.

This feature is in Admin -\> Content.

Be sure you have tried installing the various dependencies. In this case probably Rules and maybe VBO:

> The module integrates with Actions, Rules, Views Bulk Operations and Admin Views nicely. It has support for exporting templates into Features using CTools Exportables.
> 0 votes

---
Tags: nodes
---


# Question
Title: Error 500 when downloading updates for modules
Recently I've transferred several Drupal sites to DigitalOcean.com VPS server (Ubuntu).
Almost all work well.

But when I try to downloading updates for modules I get error:

```
An AJAX HTTP error occurred. HTTP Result Code: 500 Debugging information follows. Path: /batch?render=overlay&id=82&op=do StatusText: Internal Server Error ResponseText

```

I see the error for every Drupal sites at VPS.
I can successfully update modules by drush.
But I want to understand the problem.

There is no error record at error.log (Apache)
And there is following line at access.log:

```
POST /batch?render=overlay&id=83&op=do HTTP/1.1" 500

```

How can I solve the problem?

**UPDATE:**
It seems the problem in PHP.
There is known bug with gzopen() for Ubuntu32.

# Answer
It was PHP bug with Ubuntu 32bit.

I've solved the problem after installation of newer PHP version
> 0 votes

---
Tags: updating
---


title: How to install Drupal 7 on Ubuntu?

text:
# Question
Title: How to install Drupal 7 on Ubuntu?
I'm in the process to move the development on Ubuntu 14.04.

At the beginning everything seemed to work fine but quickly I discovered it was not.

Installing new modules, by UI, Drupal stops without (displaying) any error and shows a blank page. After that, the site works undisturbed. You can go back and continue on other tasks.

After many attempts to log the error without success, I run few test with NetBeans discovering that the code stops, with no reason, in `system.tar.inc`, when preparing to `untar` the package. Really weird.

Tried with fresh install of Drupal 7.28: the same.

Now I don't know how to go on. Main suspect is PHP 5.5.9, but before starting a new adventure with PHP versions, I'd like to hear you. What should I try first?

---

No way. Reinstalled starting from a new VirtualBox, Ubuntu 14.04 and Ubuntu 7.28. Same story, all is working but stops when I try to install a new module (without errors).

I took note of every piece i installed and can't find a reason why.

## apache

```
    apt-get install apache2

```
* in global section of /etc/apache2/apache2.confd:

```
ServerName localhost

```
* replace run user in /etc/apache2/envvars

```
export APACHE_RUN_USER=joe
export APACHE_RUN_GROUP=joe

```
* rewrite mode

```
sudo a2enmod rewrite

```

## MYSQL

```
    apt-get install mysql-server
    apt-get install mysql-client
    apt-get install mysql-workbench
    mysql_secure_installation

```

## PHP5

```
    apt-get install php5
    apt-cache search php
    apt-get install php5-curl php-pear php5-imagick php5-imap
    apt-get install php5-mcrypt libssh2-php php5-dev php5-gd php5-mcrypt

```
* changed values in php.ini

```
realpath_cache_ttl = 36000
max_execution_time = 300
max_input_time = 60
memory_limit = 256M
post_max_size = 128M
upload_max_filesize = 256M
default_socket_timeout = 60

```
* ```
apt-get install phpmyadmin

```
* complete manually some missing conf in: /etc/apache2/apache2.conf

```
include /etc/phpmyadmin/apache.conf

```
* virtual host test-me

```
<VirtualHost *:80>
ServerAdmin webmaster@localhost
ServerName test.me
ServerAlias *.test.me
DocumentRoot /home/joe/Workarea/test-me
<Directory "/home/joe/Workarea/test-me">
Options All
AllowOverride All
Require all granted
 </Directory>
</VirtualHost>

```
* in /etc/hosts

```
127.0.0.1   test.me

```

**DRUPAL**

* created a db test-me with collation `utf8_unicode_ci`
* in: /home/joe/Workarea

```
wget http://ftp.drupal.org/files/projects/drupal-7.28.tar.gz
tar xzvf drupal-7.28
mv drupal-7.28 test-me

```
* in settings.php file:

```
$databases['default']['default'] = array(
  'driver' => 'mysql',
  'database' => 'test-me',
  'username' => 'root',
  'password' => '',
  'host' => 'localhost',
  'prefix' => 'main_',
  'collation' => 'utf8_unicode_ci',
);

```
* Permissions:

```
chmod 644 settings.php
chmod  a+w sites/default

```

# Answer
This could be a bug, see:

As I had the same error and after deep diving I reached to `modules/system/system.tar.inc at line 716` which calls `gzopen()`. Here the errors are suppressed using `@`.

Actually its giving following error on ubuntu 14.04:

```
Fatal error: Call to undefined function gzopen() in /var/www/html/drupcom/modules/system/system.tar.inc on line 718

```

So this is issue with Zlib. I've tried to solve it using these instructions, but no luck. Then I found that it is known bug.
> 1 votes

# Answer
Try enabling error reporting of PHP on your application adding temporally on the index.php:

```
error_reporting(E_ALL);
ini_set('display_errors', TRUE);
ini_set('display_startup_errors', TRUE);

```

You could do the same by editing the same values on the php.ini.

Enable error reporting on Drupal adding on the settings.php:

```
$conf['error_level'] = 2;

```

I had a similar problem with Drupal 6 and PHP 5.4, here is one of the reported issues related to that problem.
> 0 votes

# Answer
I migrated from Ubuntu 12.04 LTS to 14.04 LTS when 14.04.1 was released and 0 issues after examining the Apache configuration changes.

**EDIT:**

from my linked apache 2.4 changes, you're vhost entry **MUST** be named *test-me.conf* btw.
> 0 votes

# Answer
Install the Lazy Dubuntu shell script.

> A shell script that will set-up your Drupal Dev Environment in your Ubuntu OS.

Lazy Dubuntu Project

Github - Lazy Dubuntu
> 0 votes

# Answer
It is PHP bug with Zlib gzopen() function for Ubuntu32.

I've solved the problem after installation of newer PHP version
> 0 votes

---
Tags: 7, installation
---


title: How to showing a view in a marquee?

text:
# Question
Title: How to showing a view in a marquee?
I have a view and I am going to show 5 last contents in a marquee at the top of page, and I want to show it in one line I mean no `<br/>`

How to do it?

# Answer
Don't use the `<marquee>` implement its effect using jQuery, go to this link or this one download the files and it moves the text like marquee.

If your view name is `V1` create a block and replace the text with this command

```
<?php views_embed_view("V1","block");?>

```

also you need to select the last five items in views UI.
> 0 votes

---
Tags: views
---


# Question
Title: Is there any sensitive data in the Configuration Management Export?
I noticed in `default.settings.php` this comment:

> Location of the site configuration files.
>
> The $config\_directories array specifies the location of file system directories used for configuration data. On install, "active" and "staging" directories are created for configuration. The staging directory is used for configuration imports; the active directory is not used by default, since the default storage for active configuration is the database rather than the file system (this can be changed; see "Active configuration settings" below).
>
> The default location for the active and staging directories is inside a randomly-named directory in the public files path; this setting allows you to override these locations. If you use files for the active configuration, you can enhance security by putting the active configuration outside your document root.

And then the example:

```
$config_directories = array(
  CONFIG_ACTIVE_DIRECTORY => '/some/directory/outside/webroot',
  CONFIG_STAGING_DIRECTORY => '/another/directory/outside/webroot',
);

```

I also noticed that when you export to the directory you specify, an .htaccess file is added that denies access to the directory.

I understand that most people will not want their configuration available for anyone to read, but what if your site is in a public repository?

https://github.com/davidbarratt/davidwbarratt/tree/develop/config

Is there anything I should be concerned about? Could this data be used to exploit the site?

# Answer
Well, it contains the complete configuration, like list of modules, views, roles and their permissions.

While those things are not directly sensitive, it would make it easy to check for misconfigurations for example, views that aren't access protected, roles that have administrative permissions and so on.

I'm not sure if core adds anything that is explictly sensitive in there, I don't know any examples.

It does depend on the modules you have installed though. Many sites store API Keys or passwords, when integrating with third party services. Those would also be stored in configuration. For example configuration to send mails through an SMTP server or username/password for a Solr server. And you don't want to have that public.

But you probably also don't want those in git in the first place. You can solve that by setting them through configuration overrides in settings.php.
> 1 votes

---
Tags: 8, security, configuration
---


# Question
Title: Taxonomy terms language depending - why all languages are visible?
What I want to acheive: I have multilingual site (i18n module).

I have vocabulary named "brands" - terms of vocabulary don't need to be translated because they are the same in all languages.

I've also nodes that I can assign to languages and "brands".

In taxonomy - in multilingual options - I set this vocabulary to: `Localize. Terms are common for all languages, but their name and description may be localized.`

Now - the problem is - that when I enter from menu to "brands" and e.g. "volvo" in any language - all nodes (all translations in different languages) are shown.

I'd like to see only the nodes in language that is set.

I have other vocabulary - where terms should be translated also. I have set it to `Translate. Different terms will be allowed for each language and they can be translated.` and there everything works fine - depending on language.

How to acheive that with my first vocabulary?

Thank you for any suggestions.

# Answer
> 0 votes
I have set the vocabulary to `Translate. Different terms will be allowed for each language and they can be translated.` and duplicated each brand for each language and then updated each node - with setting term for particular language.

In my opinion this is workaround, but I couldn't find other solution.

---
Tags: i18n-l10n, taxonomy-terms
---


# Question
Title: Flexslider views messing up my other images styles
Installed flexslider and the flexslider views module. But when in enable them my other image styles don't work no more. In my view everything (image style) is ok. But on my page it doesn't work. www.thewizard.eu Someone advise?

Thanks, Tom

# Answer
> 0 votes
You need to remove a flexslider css style:

```
.flexslider .slides img {
display: block;
width: 100%; }

```

The **width** setting is messing your brands up.

---
Tags: javascript
---


# Question
Title: Configuring Drupal 7 settings.php with both Memcache and Varnish
I am noob to using both Varnish and Memcached. I have been following some copy and paste install guides.

I have both servers installed and running. Memcached seems to be working fine. Varnish is serving pages but there are a lot of cache misses. I am trying to enable the Drupal module to make Varnish aware to cache the pages, the css etc.

However, when I copy the settings.php snippet from the README.txt file in the Varnish module to my own settings.php I get a white page and this message in the Apache error log:

```
PHP Fatal error:  Class 'MemCacheDrupal' not found in /var/www/myhost/includes/cache.inc on line 31

```

Here is the cache section added to my settings.php. The Varnish part is commented out because it causes the above error with MemCached.

```
# Memcache
$conf['cache_backends'][] = 'sites/all/modules/contrib/memcache/memcache.inc';
// The 'cache_form' bin must be assigned no non-volatile storage.
$conf['cache_class_cache_form'] = 'DrupalDatabaseCache';
$conf['cache_default_class'] = 'MemCacheDrupal';
$conf['memcache_key_prefix'] = 'myhost';
# Varnish
// Add Varnish as the page cache handler.
#$conf['cache_backends'][] = array('sites/all/modules/contrib/varnish/varnish.cache.inc');
#$conf['cache_class_cache_page'] = 'VarnishCache';
// Drupal 7 does not cache pages when we invoke hooks during bootstrap.
// This needs to be disabled.
#$conf['page_cache_invoke_hooks'] = FALSE;

```

What is wrong with the Varnish snippet or with my setup in general?

I tried re-ordering to put the Varnish lines before the Memcached lines and I got this error:

```
PHP Fatal error:  require_once(): Failed opening required '/var/www/myhost/Array' (include_path='.:/usr/share/php:/usr/share/pear') in /var/www/myhost/includes/bootstrap.inc on line 2308

```

# Answer
> 3 votes
I got it a little bit later. It was just the array format being different in the two sources I copies and pasted from. The problem line was:

```
#$conf['cache_backends'][] = array('sites/all/modules/contrib/varnish/varnish.cache.inc');

```

It should be:

```
#$conf['cache_backends'][] = 'sites/all/modules/contrib/varnish/varnish.cache.inc';

```

# Answer
> 1 votes
I was in the same issue and my "solution" was to change the order settings without changing the line that was your solution as:

1. Varnish
2. Memcache

My settings (Drupal 7.34, Varnish 3, Memcache 3.8.0):

```
// Varnish
// Add Varnish as a cache bin.
$conf['cache_backends'] = array('sites/all/modules/contrib/varnish/varnish.cache.inc');

//If you plan to use the expire module to be selective with your cache clearing you should add as a new cache bin.

//$conf['cache_class_external_varnish_page'] = 'VarnishCache';

// If you are not going to use the expire module you should replace the default pagecache with varnish.

$conf['cache_class_cache_page'] = 'VarnishCache';

// Memcache
$conf['cache_backends'][] = 'sites/all/modules/contrib/memcache/memcache.inc';
$conf['lock_inc'] = 'sites/all/modules/contrib/memcache/memcache-lock.inc';
$conf['memcache_stampede_protection'] = TRUE;
$conf['cache_default_class'] = 'MemCacheDrupal';

// The 'cache_form' bin must be assigned to non-volatile storage.
$conf['cache_class_cache_form'] = 'DrupalDatabaseCache';

// Don't bootstrap the database when serving pages from the cache.
$conf['page_cache_without_database'] = TRUE;
$conf['page_cache_invoke_hooks'] = FALSE;

//Note that no servers or bins are defined.  The default server and bin
//configuration which is used in this case is equivalant to setting:

$conf['memcache_servers'] = array('localhost:11211' => 'default');

```

---
Tags: proxies, caching
---


# Question
Title: Display comment count of referencing nodes
I have two content types, **Forum** and **Discussion** (urelated to the core forum module). The content type **Discussion** has a node reference to the **Forum** it belongs named field\_forum. I would like to create a views list which show nodes of **Forum** with no. of comments of nodes **Discussion** referencing to it.

Apparently, not a problem:

Just create a view of **Forum** with a reference "Entity Reference: Referencing entity" (A bridge to the Content entity that is referencing Content via field\_forum) and then add a "Content: Comment count" field using this reference, set aggregation to on and set aggregation type for this field as sum.

However, my problem is that, even if I DO NOT check the option "Require this relationship" when I create the relationship, still adding comment count field make forums without any discussion to be excluded from the view, while I want all forum to be there, with or without discussions.

If I remove the "Comment count" field, all forums are visible. Strange enough, using the same techniques for counting the discussions works without problems.

This MAY be related to #1349080 but unfortunately it works with or without the patch in #231 (that solves similar problems in other contests).

# Answer
Solved using the following workaround (patched #231 of #1349080 required): add a second level relation discussion-\>comments and then use the aggregation with count distinct operator over the id field of the comments.
> 1 votes

---
Tags: views, users
---


title: How to integrate outlook 2013 calendar?

text:
# Question
Title: How to integrate outlook 2013 calendar?
I'm working in an organization where we have our own exchange server. I'm developing a performance system to our employees using erpal.

I need an integration between exchange and Drupal that allows the employees to use their outlook calendar and tasks as same as erpal calendar and task (I mean the synchronization).

I found some ways doing it by using import and export but I think these ways are for Individual person. I need an automatic synchronization for all employees who have an email in our exchange server and can login to the system.

Is there any setting or module I have do? Or any steps link I can follow?

# Answer
Have a look for the following modules:

* Click to Schedule

> It has sync capabilities for Outlook, Google calendar or iCal for Mac. Meetings are automatically confirmed, added to your Outlook, Google Calendar, or iCal and confirmation emails are sent to both parties.
* CiviCRM activities iCalendar feed

> Users can access an iCal feed of their upcoming (future) Activities, suitable for subscription via Google Calendar, Microsoft Outlook, and/or similar software.
> 0 votes

---
Tags: 7, datetime
---


# Question
Title: how do i programmatically set the ANONYMOUS USER permissions on a site install profile?
I am having trouble figuring out how to set permissions for users I personally did not programmatically create in my site installation profile. Can someone please help?

I would like to set 'View published content' as true for the ANONYMOUS USER user role in the .install file.

I am using the code below to grant permissions; but I do not know how to access permissions for the ANONYMOUS USER role.

```
       // Create the roles.
$roles['Content editor'] = array(
    'name' => 'Content editor',
    'weight' => $weight++,
    'permissions' => $base_permissions,
);
foreach ($roles as $role) {
    $role_object = new stdClass();
    $role_object->name = $role['name'];
    $role_object->weight = $role['weight'];

    // Save the role.
    user_role_save($role_object);

    // Grant permissions.
    if (!empty($role['permissions'])) {
        user_role_grant_permissions($role_object->rid, $role['permissions']);
    }

```

# Answer
There is a constant for the anonymous RID named `DRUPAL_ANONYMOUS_RID`.

So, you would be able to use something like:

```
user_role_grant_permissions(DRUPAL_ANONYMOUS_RID, array('your permission 1'));

```
> 3 votes

# Answer
@Patrick Ryan's answer is great for individual permissions, but I would also suggest looking at https://www.drupal.org/project/secure\_permissions and https://www.drupal.org/project/profiler\_builder. Those tools are really helpful to export and manage all your permissions.
> 1 votes

---
Tags: users, installation-profiles
---


# Question
Title: how to setup rule events for before/after video is played?
How can I set up a rule events for actions to occur before and after videos are played in a node?

Thank you for any tips/ help you can give!

# Answer
When video start/end it should call js function which trigger ajax call for path you create on drupal (using hook\_menu) the callback of that menu item should call the rule you want using rules invoke function rules\_invoke\_component('rule\_name', $arg);

So the case is how to trigger the ajax call on start/end

if you are using youtube, check this page, you can trigger js function to start the ajax

https://developers.google.com/youtube/iframe\_api\_reference

if you have another player you should look to the api
> 0 votes

# Answer
https://www.drupal.org/project/mediafront\_popcornplayer allows you to configure events that are triggered when a video's playback reaches a specific point in time. This is similar to how the YouTube API works, but abstracted so that it works with any video provider with a Popcorn.js wrapper. That currently includes YouTube, Vimeo, Archive.org and Solidtango. https://www.drupal.org/project/mediafront provides the UI and logic for a site builder to use the Popcorn Player on any Media field on the content type or just in a specific View.

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

Once the Popcorn Player is being used to load the video, the point that the user is at in the timeline is available to you. While there isn't anything specific to integrate this with Rules, you can really do anything you want to alter objects in the DOM like http://popcornjs.org/popcorn-with-youtube. It would be really easy to implement a call back to something like https://www.drupal.org/project/rules\_link with Popcorn.
> 0 votes

---
Tags: rules, files
---


title: Custom pager for View

text:
# Question
Title: Custom pager for View
The client I'm building a site for has a collection of content that they want paged by its ReleaseYear Field. The pager they want should look like:

```
[ < | 2011 | 2012 | 2013 | 2014 | 2015 | > ]

```

How I build a pager like that?

# Answer
As a clue, you should alter the `theme_pager_link` function. copy this function in the `template.php`, if the years are started from 2001, you need to alter the pager so that every link of the pager be summed with 2000, it is the function

```
function THEME_pager_link($variables) {
  $text = $variables['text'];
  $page_new = $variables['page_new'];
  $element = $variables['element'];
  $parameters = $variables['parameters'];
  $attributes = $variables['attributes'];

  $page = isset($_GET['page']) ? $_GET['page'] : '';
  if ($new_page = implode(',', pager_load_array($page_new[$element], $element, explode(',', $page)))) {
    $parameters['page'] = $new_page;
  }

  $query = array();
  if (count($parameters)) {
    $query = drupal_get_query_parameters($parameters, array());
  }
  if ($query_pager = pager_get_query_parameters()) {
    $query = array_merge($query, $query_pager);
  }

  // Set each pager link title
  if (!isset($attributes['title'])) {
    static $titles = NULL;
    if (!isset($titles)) {
      $titles = array(
        t('« first') => t('Go to first page'),
        t('‹ previous') => t('Go to previous page'),
        t('next ›') => t('Go to next page'),
        t('last »') => t('Go to last page'),
      );
    }
    if (isset($titles[$text])) {
      $attributes['title'] = $titles[$text];
    }
    elseif (is_numeric($text)) {
      $text = $text + 2000;  ------>>>>> in this line every number is added with 2000
      $attributes['title'] = t('Go to page @number', array('@number' => $text));
    }
  }

  // @todo l() cannot be used here, since it adds an 'active' class based on the
  //   path only (which is always the current path for pager links). Apparently,
  //   none of the pager links is active at any time - but it should still be
  //   possible to use l() here.
  // @see http://drupal.org/node/1410574
  $attributes['href'] = url($_GET['q'], array('query' => $query));
  return '<a' . drupal_attributes($attributes) . '>' . check_plain($text) . '</a>';
}

```

the indicated line with `------>>>>>` add every number with 2000, the only shortage of this solution is that the current number won't be summed with 2000. A few modification to this code will solve this problem as well. you can also add any css class to `$attributes` variable.
> 1 votes

# Answer
I'd do this the following way :

* ReleaseYear would be a taxonomy.
* Then you'd have it defined in your view an exposed filter.
* And you'd theme your filter to be displayed as links.

Does that make sense to you ?
> 0 votes

---
Tags: views, paging
---


title: Adding an image to the home page

text:
# Question
Title: Adding an image to the home page
I'm using the Zen sub-theme. I don't want all the new stuff on the site showing on the home page so I'm editing page--front.tpl.php. Removed print render($page\['content'\]). But now I want to add some static text and and image to my home page.

How do I go about doing this basic thing?

# Answer
> 1 votes
You can simply create a node, and put this node (eg. node/15) in the admin/config/system/site-information default frontpage field.

Otherwise you can also create a custom page with hook\_menu() like this:

```
$items[path] = array(
    'title callback' => 'page title',
    'page callback' => 'page_callback',
    'access callback' => 'access_callback',
    'type' => MENU_SUGGESTED_ITEM,
);

```

and in page\_callback() you can return your custom theme template/function.

Or simply use some contributed modules like "Empty Page", "Front Page", "Empty Front Page" and others..

---
Tags: media, navigation, theming
---


# Question
Title: How to parse PHP variables in drupal_add_js in template.php
I'm using drupal\_add\_js for some inline jQuery - I need to parse some php variables in the inline jQuery, what is the correct way to do it?

```
drupal_add_js('jQuery(document).ready(function () { alert("Hello!"); });',
  array('type' => 'inline', 'scope' => 'footer', 'weight' => 5)
);

```

I've tried this, and it DOES print the variable, but breaks the JS code in the process (splits the jquery code up and doesnt function) :

```
drupal_add_js('jQuery(document).ready(function () { alert(" '. print $site_name .' "); });',
  array('type' => 'inline', 'scope' => 'footer', 'weight' => 5)
);

```

# Answer
> 1 votes
Just remove the print function from your code:

```
drupal_add_js('jQuery(document).ready(function () { alert(" '. $site_name .' "); });',
  array('type' => 'inline', 'scope' => 'footer', 'weight' => 5)
);

```

Looking at the javascript Window alert() Method it has this syntax:

> alert(message)

And the message parameter has the type **string**

PHP's print function prints to the output buffer and returns an int. It has this definition:

> int print ( string $arg )

So your code prints the variable $site\_name to the output buffer and returns an int, and your string for the alert is then an integer and you have printed to the output buffer which you did not want to do.

---
Tags: theming, javascript
---


# Question
Title: taxonomy term path using two different vocabulary
I have a "destination" vocabulary and a "category" vocabulary. Is there a way to change the taxonomy term path of the "category" terms to include the "destination" terms in front?

i.e. destination\_term/category\_term/term\_title

I tried using tokens but I can't figure out how to add a different vocabulary in front.

UPDATE

Here's the situation:

I have a travel site with a main portal going to 4 different destination pages (all view pages), each set with a term reference from "destination" vocabulary. Then I have a content type for Categories, set with a term reference from "category" vocabulary (restaurant, activities, etc).

I actually have two problems:

* I can't seem to have a "destination" path preceeding the "category", which I need to make blocks appear in the right place. (the only way that I found to do this is by cheating and adding a hidden destination term in my category voc. but that means I would have to copy/repeat the "category" voc. 4 times with a different hidden "destination" term in each. That doesn't make much sense now does it? I'm sure there's a better way. Anyone?
* The other problem is that except for the above part, I am able to make the paths and breadcrumbs appear the way it should (with the help of Pathauto, Taxonomy Menu & Taxonomy Menu Trails modules), but when I get to the actual content, there's nothing in the breadcrumbs anymore (the url path shows up ok though)! Any suggestions?

Any help is greatly appreciated.

# Answer
For your content type, you could set a content path pattern (admin/config/search/path/patterns) that looked something like this:

\[node:field\_destination\]/\[node:field\_category\]/\[node:title\]

This would put the destination term in front of the category term for your content nodes. However, there is no good way for you to put the destination term in the path to the category vocabulary, because there might be zero, one or many content type nodes for any given category, and you have no good way to relate these two terms.
> 1 votes

# Answer
I've had EXACTLY this problem since ever I started to use Drupal (2007), because we both want to have something like: -sevilla/bars -sevilla/hotels -barcelona/bars -barcelona/hotels , right? I came here hoping to find answer, but again, as so often with Drupal: no. However, playing around I just now happened to find an acceptable alternative myself. Instead of using /taxonomy1/taxonomy2/name.htm (being 1 destination and 2 category) you can use \[node:menu-link:parent\]/\[node:field\_location\_type\]/\[node:title\] where you do have to take care that this \[menu-link:parent\] corresponds with the desired destination, not always very handy but it works for me.
> 1 votes

---
Tags: tokens, path-aliases, taxonomy-terms
---


# Question
Title: How to structure repetitive data under an entity type bundle?
I'd like to use Drupal in one of my projects but I'm wondering what's the best way to organize my content.

I have a list of authors. Each author has 3 properties:

* name
* bio
* list of books

On the list of books each book has 6 properties(5 text fields + image).

I was thinking about creating entity type bundle 'Author' and 'Book', then assigning certain books to certain authors and displaying lists of books on author page.

The downside is that on the content list I'll have a list of many different 'pages' of content type 'Book' that can't be easily filtered by author. Also, creating new content type for each author is not a good solution.

1) Is it the best possible solution for Drupal?

2) Would it be possible to create:

a) hierarhical list of author/book\_list posts or

c) content type Author with list of books on it's page(book field with book properties fields)

I'd appreciate your advice :).

# Answer
1.
There is no "best" possible solution for Drupal that can be given here. There are many ways to do it and the best way for one site might not be the best way for another, so it depends on your specific requirements, which we don't know.

Having said that, the way you are planning to do it should work fine. You can create a view with relationships that will allow you to easily filter by author.

From a data point of view it is also good because books and authors could logically be considered different content types.

An alternative solution is the field collection module but it works a little different to your proposed solution so your specific data and requirements will indicate which is the better solution.

If you don't have first hand experience with the different methods the best way forward would be to try any solutions you think may be good and then decide which is the best for you for this project.

2.
a. Yes. Depending on how you end up configuring the content types and your exact listing requirements the solution might be a little different and may require differing amounts of custom themeing or development but it is possible.
b. ?
c. Yes. What I wrote for point a above also applies here however generally speaking I would say this requirement will be easier to satisfy than a.
> 0 votes

# Answer
You could always make another view to supplement or replace your content list. If you're using Entity Reference for the relationship between book and author you *can* create an easily filterable list of books.

Alternatively, 2c is a viable option. You can create a group of fields on `Author` called `book` using field collection and set the group to have unlimited instances.
> 0 votes

---
Tags: entities
---


# Question
Title: How to align three blocks on the front page using CSS
I've got three blocks on my front page and I want them to be centered and aligned.

"About us" block is to be aligned to the left side of the front page what I managed to achieve. The other two blocks are to be aligned to the right side of the front page and one above the other what I managed to achieve as well.

However:

1. Different browsers show different results which is caused by the reference of the language switcher block I guess. It is moving my right hand side set of blocks up and down. IE is showing the result I would like to achieve (the example: test site).
2. I would like to be able to reference language switcher block to the content region which is not the case right now and I am not sure how to do it.

Can someone help or guide me into the propriate direction?

Thanks and regards

# Answer
> 0 votes
Well, after looking at your code I concluded that your css codes are terrible! you may use this code (I didn't test it but it should work or at least a few modifications will make it to perfectly match what you need):

```
<div id="content">
       <div id="blocks-container">
             <div id="left-block">
                    //In here load the slider block and display in here
             </div>
              <div id="right-block">
                     <div>
                    //In here load the top right  block and display in here
                     </div>
                     <div>
                     //In here load the bottom right  block and display in here
                     </div>
             </div>
       </div>
</div>

```

This is CSS

```
#content{
       text-align:center;
       width:100%;
       height:auto;
       display:inline-block;
}
#blocks-container{
       margin:auto;
       width: 975px;
       height:auto;
       display:inline-block;
}
#left-block{
       float:left;
       width: 760px;
}
#right-block{
       float:right;
       width: 215px;
}
#right-block > div{
       clear:both;
       width: 100%;
      float:left;
}

```

Never use margin to align elements to the right, because the margin is calculated based on the parent which in your case is the browser, so If you resize the browser, the browser will try to move the elements to regard the margin.

I recommend you strongly to forget about the `DIV` and `float`, try to learn how to work with flexbox it is very easy to use.

---
Tags: theming, blocks, i18n-l10n
---


title: How to change the local code Link?

text:
# Question
Title: How to change the local code Link?
I am using the Aqcuia Dev Desktop where near to the **local code label** is written the following link: ( `C:\Users\Wessam\DrupalSites\devdesktop\drupal-7.34` )

lets say that i want to move my **drupal localhost site files & folders** to another folder so it will be under the following link: ( `C:\Users\Wessam\AllSites\CompanyName` ) so the **link near to the local code label** should be changed also...

How to do the mentioned above?

# Answer
1)

Follow the Path below:

C:\Program Files (x86)\DevDesktop\AcquiaDevDesktop\datamodel.xml

2)

Open the " datamodel.xml " using the Notepad++ or any other similar programming language editor program

3)

Edit the Link written within:

HERE HERE HERE

HERE HERE HERE

to any link required by you .
> 1 votes

# Answer
Generally there is no problem if you have a good programming! Clearly the url of your local site will be changed but the question is, how did you refer to your site?

I mean if the old url is `localhost/old-version`, Have you ever used this url in your template files or js files? if yes then you should replace them by new url. I recommend you to use

```
<?php
      global $base_url;
?>

```

I have moved my website from a server to another server with new domain and no problem happened (only some trivial changes were needed) because I always use relative paths.
> 0 votes

---
Tags: uri
---


title: Commerce line item views and html mail

text:
# Question
Title: Commerce line item views and html mail
I have a view (commerce line item) with HTML (or unformated) list with several fields.

On each field i unchecked "place a colon after the label" but it does not obey that rule. So i added custom CSS to fields and its working. Each label has "strong" html elemement and that is working fine too.

When the order is complete commerce sends email and results are:

Label: field Label: field

instead of

Label: field

Label: field

html strong tag displays fine.

I have tried with HTMLmail and MimeMail with emogrifier installed.

# Answer
> 0 votes
Was fairly easy to fix the issue.

In styling settings of a field in view i used "SPAN" for field.

---
Tags: views, commerce, emails
---


# Question
Title: why does commerce pricing rule increase price before decreasing price?
I created this simple rule to give authenticated users 50% discount. The individual line items are not being changed as I would expect, only the order total. And before the order total is discounted 50% it's actually doubled in price, so the order total does not actually change from what it would be without the rule.

Subtotal, discount, and total are all double what they should should be. I have no idea why.

Here's there rule:

```
{ "rules_wholesale_discount" : {
    "LABEL" : "Wholesale Discount",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "commerce_line_item", "commerce_product_reference" ],
    "ON" : { "commerce_product_calculate_sell_price" : [] },
    "IF" : [
      { "user_has_role" : {
          "account" : [ "site:current-user" ],
          "roles" : { "value" : { "2" : "2", "3" : "3" } },
          "operation" : "OR"
        }
      }
    ],
    "DO" : [
      { "commerce_line_item_unit_price_multiply" : {
          "commerce_line_item" : [ "commerce-line-item" ],
          "amount" : "0.5",
          "component_name" : "discount",
          "round_mode" : "1"
        }
      }
    ]
  }
}

```

# Answer
> 0 votes
Answer: It doesn't. The checkout page just makes it look like that because all those line items have already had the discount applied to them and the view does not show that.

So my new questions are:

* How to display original price on the product display? (Because only the discounted price is shown to authenticated users)
* How to display the original price in the cart and checkout forms?

But original question answered.

---
Tags: commerce
---


# Question
Title: Writing PHP code to creating menu in block show and alert
I have a menu in a block and this is my code in that block that is in **sidebar second**:

```
<?php
  $url=$base_url.'/drupal';
  echo
  '<ul>
  <li><a href="'.$url.'/article/1">One</a></li>
  <li> <a href="'.$url.'/article/2">Two</a></li>
  </ul>';
?>

```

it is working correctly, but return and red alert:

> Notice: Undefined variable: base\_url in eval() (line 2 of C:\xampp\htdocs\drupal\modules\php\php.module(80) : eval()'d code).

# Answer
> 0 votes
You need to define it as a global variable first:

```
global $base_url;

```

So that your code is now:

```
<?php
global $base_url;
$url=$base_url.'/drupal';
echo
'<ul>
<li><a href="'.$url.'/article/1">One</a></li>
<li> <a href="'.$url.'/article/2">Two</a></li>
</ul>';
?>

```

Then you may don't need drupal in your $url variable. and it would become:

```
$url=$base_url;

```

---
Tags: 7, routes, blocks, navigation
---


# Question
Title: How do I separate multiple values for "print render($content['field']);" with a comma?
So in my node template, I am using the following code:

```
print render($content['field_taxonomy']);

```

Sometimes there is only one result printed, and sometimes there are multiple results printed. How can I separate each result by a comma, but only if there are multiple results printed?

Thank you!

# Answer
For example, I am fetching the texonomy vocabulary terms :

```
$terms = taxonomy_term_load_multiple(array(), array('vid' => '12'));
foreach ($terms as $temsaccess) {
$name[]=$temsaccess->name;
}

<a href="javascript:void(0);" id="<?php echo $term_name; ?>" Click="javascript:showProduct('<?php echo $term_name; ?>', this );"  data-filter="<?php echo $temsaccess; ?>">
<?php echo $temsaccess; ?>
</a>

```

Or refer to this link.
> 0 votes

---
Tags: nodes, theming
---


# Question
Title: How to limit showing of a block just in home page?
I have a library book and in the first page or homepage of my website I want to show just 4 random books in center of my page.

How to set a View block to just show in home page?

# Answer
You can do this by following below way :

1. After creating Views Block.
2. Goto Admin -\> Structure -\> Blocks (Search your block)
3. Configure -\> Your block
4. Goto *Pages* section. Click on *"Only the listed pages"* & write **`<front>`** & Save block.
> 2 votes

---
Tags: 7, views, blocks
---


# Question
Title: Database corrupted getting the site crash
I crashed my website trying to secure it by changing files and folders modifications...After i tried many things (chmod 777 -temporarly- all to take it back, clear the cache, drush rr...) nothing worked yet. So i tried to install a new site, copied all the site file...It was working perfectly.

I tried to link the new site with my old database, and the fatal error get back again...I guess my database might be corrupted...Any idea ?

Thanks for your help

(previous conversation about what i did already here

# Answer
As webdrips has said, your error seems to be with the xmlsitemap module, and considering it is not critical for functionality, you should try disabling it.

Depending on the state of the website, if you are experiencing WSOD, you may need to disable the module through the database using phpmyadmin.

In the system table, find the xmlsitemap module, and edit the row where the column is "status", and set that to 0.
> 0 votes

---
Tags: database, bootstrapping
---


# Question
Title: Drop-down menu only works after clicking into the parent page first
I am using the Venture theme for Drupal 7. I have a 'Products' page listed in the main menu with a drop-down list that is a separate page for each product. However, to get the drop-down list to show up, I first have to click on the 'Products' menu link, which will bring me to an empty page.

I would like the drop-down list to display if I hover over the 'Products' menu item so the user can select a child product page right away instead of having to go into the parent 'Products' page first and then having the option to select from the drop down menu like it is doing now.. Ideally, I would like to not have to display the parent 'Products' page at all, and have it just be in the main menu as a way to access the drop-down list items to other pages.

Any suggestions would be appreciated.

# Answer
> 2 votes
Have you checked the "show as expanded" for the parent menu?

Edit your parent level menu and see if it's checked.

Check it if it's not and check the drop down menu again.

# Answer
> 0 votes
Are you using a specific theme or a custom one?

It seems to be an issue with incorrect classes being applied to the parent list-item element.

While on the main page for my Drupal website, inspecting the list-item element that I know has a dropdown within it shows me:

`<li class="first collapsed">`

The .collapsed class makes sense since I'm not hovering over it, but even hovering over it does not append the .expanded class that I would expect.

When navigating to the parent page that has the dropdown within it and inspecting the same element, I now see:

`<li class="first expanded active-trail">`

And now if I hover over the list-item, the dropdown list appears as expected. Therefore, it's likely that the culprit is either the `.expanded` or `.active-trail` class, or both.

In order to remedy this we could try using a little JavaScript to always give list-items with a `ul` within them the `.expanded` and `.active-trail` classes.

I apologize if this is too technical. I could provide a walkthrough if you'd like. Keep in mind that this is only my best guess based on my own experience with this problem. I haven't yet tried my own solution.

---
Tags: navigation
---


# Question
Title: How can I update file attachment and keep filename?
I understand changes of file attaching in D7, but problem is, if I delete and re-upload changed file, the deleted file is still on server and re-uploaded filename gets changed. If I understand correctly, removed file is deleted by cron, so there is a delay. Is it possible to get file deleted in real time, to avoid renaming of uploaded one?

# Answer
> 0 votes
It is not possible. If files were deleted "in real time", node your readers see would have a link and reference to a file no longer on server's hdd.

If you need to get the same file name, remove file, save node, upload new version, save node. That way you will avoid both broken links and name conflicts.

# Answer
> 0 votes
If you have IMCE installed go to **Home » Administration » Configuration » Media**

and change **IMCE** *common settings*:

**Default behaviour for existing files during file uploads**

* Keep the existing file renaming the new one
* Keep the existing file rejecting the new one
* *Replace the existing file with the new one*

Hope this helps.

---
Tags: 7, files
---


title: Views Page not showing pager

text:
# Question
Title: Views Page not showing pager
I've got a Views Page showing Article teasers. There are lots of Articles in the db and I'm only showing 5 per page in the View, but the Pager is not showing up at all. Here is my Views configuration, am I doing something wrong? Is there a bug?

The preview in the Views screen does not show a Pager at the bottom of the content teaser and it also doesn't show on the real page.

Any ideas?

# Answer
> 16 votes
This can have a whole bunch of reasons. I'm just providing the imho most probable non-obvious one:

Go to "pager settings" (on your screenshot click "Paged, 5 items") and change the "pager id". Docs say this is only needed when there is more than one view on a page, but i saw live examples where this fixed a non-showing pager on a single-view page.

# Answer
> 11 votes
I came across this issue recently since upgrading to views 3.8. for me the issue was caused by views\_php module as discussed here: https://www.drupal.org/node/2276165 there is also a patch available to fix it.

# Answer
> 0 votes
The solution described in the answer from aexl worked for me.

For those who don't understand that answer, maybe this refined version of it helps:

> Go to "pager settings" (on your screenshot click "Paged, 5 items") and change the "pager id" **to something like 5 or any number instead of leaving empty**.

---
Tags: 7, views, paging
---


title: Using a different view mode with a node

text:
# Question
Title: Using a different view mode with a node
I understand using Views you can use a different view mode, e.g. teaser or full content.

Is it possible to view a node using a view mode other than the full content view mode? What I want to achieve is being able to display different fields depending on the user's role.

# Answer
I found a way that works for me, which is to create a new content type, and add a node reference field.
I can then reference the node I want, and using the Node Renderer, display it with the view mode I want.
> 1 votes

# Answer
You can override the page callback used on a node page to use your own function that will select the view mode based on the current user role.

```
/**
 * Implements hook_menu_alter().
 */
function MODULE_menu_alter(&$items) {
   $items['node/%node']['page callback'] = 'MODULE_node_page_view';
}

/**
 * Copy of the original node_page_view to use result from our
 * MODULE_node_show($node) as return value.
 */
function MODULE_node_page_view($node) {
  global $user;
  // If there is a menu link to this node, the link becomes the last part
  // of the active trail, and the link name becomes the page title.
  // Thus, we must explicitly set the page title to be the node title.
  drupal_set_title($node->title);
  $uri = entity_uri('node', $node);
  // Set the node path as the canonical URL to prevent duplicate content.
  drupal_add_html_head_link(array('rel' => 'canonical', 'href' => url($uri['path'], $uri['options'])), TRUE);
  // Set the non-aliased path as a default shortlink.
  drupal_add_html_head_link(array('rel' => 'shortlink', 'href' => url($uri['path'], array_merge($uri['options'], array('alias' => TRUE)))), TRUE);
  return MODULE_node_show($node);
}

/**
 * Copy of the original node_page_view to use result from our
 * MODULE_node_show($node) as return value.
 */
function MODULE_node_show($node, $message = FALSE) {
  if ($message) {
    drupal_set_title(t('Revision of %title from %date', array('%title' => $node->title, '%date' => format_date($node->revision_timestamp))), PASS_THROUGH);
  }

  $view_mode = MODULE_user_node_view_mode($node, $user);

  // For markup consistency with other pages, use node_view_multiple() rather than node_view().
  $nodes = node_view_multiple(array($node->nid => $node), $view_mode);

  // Update the history table, stating that this user viewed this node.
  node_tag_new($node);

  return $nodes;
}

/**
 * Determines the view mode to use for the node page of the given node
 * when viewed by the given user.
 * @param $node
 *  The viewed node object
 * @param $account
 *  The viewing user object
 */
function MODULE_user_node_view_mode($node, $account) {
  // ... Implement your custom view mode selection logic here
}

```

Note: There is probably something that need to be done to ensure the page using a given view mode is not cached and re-used for different user.
> 6 votes

# Answer
For Drupal 6 have a look at Display suite and related modules, it allows you to easily define new build modes you can use in views. There's a similar project called Buildmodes.
> 2 votes

# Answer
For simple node display you can use Display suite to change the teaser and Default view modes as you want: You don't have to create a new one. If you want to create a new view mode in Drupal 7 you can use the Entity view modes module. Then you can change the view mode with Display Suite and use it in Views or in Field Boxes.
> 2 votes

# Answer
contextual\_view\_modes is another option which uses an active context to switch view modes - https://drupal.org/project/contextual\_view\_modes

From project page:

> Ever wanted to change the view mode for a node based off of a context? Now you can. Contextual view modes adds a vertical tab where you can select a context to validate against and display a particular view mode. There is also a global content type option where you can view mode switch by context for every node of that content type.
> 2 votes

# Answer
You can simply use `hook_entity_view_mode_alter()` for that.

> Change the view mode of an entity that is being displayed.

Here I change the view mode depending on a user's role:

```
/**
 * Implements hook_entity_view_mode_alter().
 */
function MYMODULE_entity_view_mode_alter(&$view_mode, $context) {
  if (!user_is_anonymous() && $context['entity_type'] == 'node' && $context['entity']->type == 'MYCONTENTTYPE') {
    $view_mode = 'MYVIEWMODE';
  }
}

```

---

To easily register your own view mode in the same module, simply implement `hook_entity_info_alter`. After that, place your fields and then trigger the switch from the hook above.

```
/**
 * Implements hook_entity_info_alter().
 */
function MYMODULE_entity_info_alter(&$entity_info) {
  $entity_info['node']['view modes']['MYVIEWMODE'] = array(
    'label' => t('My View Mode'),
    'custom settings' => TRUE,
  );
}

```
> 1 votes

# Answer
In all modes you'll have the `$node` object, or at least the node ID that allows you to load the node object.
You can show the node as you want, exactly like you do with node.tpl.php.

Also, Views has its own node-view.tpl.php for each view, so you can show it as you want, on teaser and full mode.

And to answer your question, except if (and I'm not sure) another module add mode, you've only teaser and full mode.
> 0 votes

---
Tags: views, nodes, entities
---


# Question
Title: How to display the same node twice in one teaser?
I added some new fields to **Basic page**:

* teaser image
* teaser title
* teaser subtitle

Now I want to show 2 separate blocks in teaser that point to the same node (basic page). Is it even possible?

# Example of teaser

## Teaser block 1

* title: Buy Acrobat
* subtitle: View our software
* image: acrobat.png

## Teaser block 2

* title: Buy InDesign
* subtitle: Software for low prices
* image: indesign.png

Both teasers should lead to the same basic page "Buy software".

Notice that teasers are displayed on home page (option "promote to front page") and taxonomy (View: Taxonomy).

# Answer
There are a lot of ways you could accomplish that.

One way that seems to match your requirements is using the field collection module.

You could have a multiple value field collection field on your content type and that field collection could have your title, subtitle and image fields.

It depends somewhat on all your requirements though.

For example, this might work very well for your views (like the taxonomy one) if you want both blocks to show one after the other (since you have a view of nodes and these are both on the same node), but maybe it wouldn't be as good a solution if you wanted them spread out (in which case it might be better if they were 2 separate nodes).
> 0 votes

---
Tags: 7, entities, nodes
---


title: PHP Extension gd disabled

text:
# Question
Title: PHP Extension gd disabled
I know this question is floating out there in the forums, but so far all of the answers I've come across over the weekend have been unable to resolve this issue.

I'm working on an Amazon LAMP server (Non-Ubuntu) and have been trying to enable the GD extension so that I may install Drupal 7 on my new AWS site.

The page installation process is producing the following error:

* \[X\] PHP extensions Disabled: Drupal requires you to enable the PHP extensions in the following list (see the system requirements page for more information): gd

Here's what I know from my PHPInfo page: http://ec2-54-173-231-195.compute-1.amazonaws.com/info.php

I've gone ahead and run my scripts to install the gd script which I'm produced with the following result:

* Loaded plugins: priorities, update-motd, upgrade-helper
* amzn-main/latest|2.1 kB 00:00
* amzn-updates/latest | 2.3 kB 00:00
* No package php5-gd available
* Error: Nothing to do

I have also restarted my httpd and mysqld in efforts to restart the system and have my machine honor any restart needed to launch my extension recognition.

Any thoughts are appreciated.

Thanks!

# Answer
> 1 votes
The issue was actually due to I was running php 5.5.\*. The following code resolved my issue for any who come across it themselves.

To discover if you too are running over that version type the following:

```
php -v

```

Once you've determined your running PHP 5.5.\* type the following:

```
sudo yum install php55-gd

sudo service httpd restart
sudo service mysqld restart

```

That should resolve your issue.

---
Tags: 7, installation, files
---


# Question
Title: Drupal7: Rules Module - change the FROM field
I am using the Entityform module with the Rules module.

When the user submit the form, an email notification is sent out. In the email notification, I want the FROM field to be the user's email address as opposed to the '*site-information*' email address.

I couldn't set this with Rules in the Drupal Admin (I can only adjust the 'TO' field) How can I do that by code? or if you have any other idea to have the FROM field varies depending on the user's email address.

Thanks.

Boutros.

# Answer
> 0 votes
I finally figured it out. You can edit the "Send mail" component of the Entityform rules at: */admin/config/workflow/entity\_rules/entityform\_submission/manage/rules\_entityform\_notifications\_email\_send*

Then specify the value of the FROM field from the replacement patterns. Keep in mind, when you build the form, or any new future forms, make sure that you always use the same field for the email and make it required. An empty email will result of the FROM field being sent from the site-wide admin email and not from the user's email. See image, hopefully it helps:

---
Tags: rules, entities
---


# Question
Title: Use computed field to calculate Field collection
I have a field collection named values. It contains the fields:

* Amount
* Price
* Total

The "Total" field calculates the Price\*Amount.

Now I created a new field *outside* the field collection called "Subtotal".

How do I sum all the values of the "Total" field in a node to populate "Subtotal"? I tried a lot of code which I found but none seem to work.

I tried this code but it gives as a warning: undefined index at line 5

```
$field_items = field_get_items($entity_type, $entity, 'field_values');
$total = 0;
foreach ($field_items as $item)
{
  $total += $item['field_total']['und'][0]['value'];
}
$entity_field[0]['value'] = $total;

```

Thank you in advance!

# Answer
> 1 votes
I've got it! After a lot of tries I found a solution: This works for a computed field outside the collection.

```
$sum = 0;
$wrapper = entity_metadata_wrapper($entity_type, $entity);
foreach($wrapper->field_values as $collection) {
   $sum += $collection->field_total->value();
}
$entity_field[0]['value'] = $sum;

```

---
Tags: entities
---


# Question
Title: Trying to change a radio value during form validate
I have a form that includes a set of radio inputs, and other fields that will or will not be relevant, depending on which radio option is selected. I'm using #states for client-side UX sugar.

However there are certain conditions, picked up in the validate function that need to change the value the user entered for the radio, and re-present the form with a different option selected. I'm having problems with this, as the form comes back but the option is not changed. e.g. Submitting this should with 'a' selected should change it to 'b' and re-present.

What happens is that the value is set to b, the form rebuilds, but the browser still shows 'a' selected.

```
<?php
function x_a_form($form, &$form_state) {
  return [
    'switcher' => [
       '#type' => 'radios',
       '#options' => [
           'a' => 'Aye',
           'b' => 'Bee', ],
       '#default_value' => empty($form_state['values']['switcher'])
                           ? 'a'
                           : $form_state['values']['switcher'],
    ],
    'submit' => ['#type' => 'submit', '#value' => 'Go' ],
  ];
}

function x_a_form_validate($form, &$form_state) {
  // silly example of a condition...
  if ($form_state['values']['switcher'] == 'a') {
     // Change the value.
     // Nb. form_set_value() is a very long winded way to do just this:
     $form_state['values']['switcher'] = 'b';
     // We will not be saying anything is invalid, but we don't want
     // the form to submit.
     $form_state['rebuild'] = TRUE;
     return;
  }
  // other validation...
}

```

# Answer
> 1 votes
Did a little more digging. It seems when Drupal (re)builds a form, it sets the element values based on the actual form input ($form\_state\['input'\]) and not the form values ($form\_state\['values'\]). See \_form\_builder\_handle\_input\_element. So form\_set\_value does changes the form value, but it does not update the form input and, therefore, does not get processed how you want it to in this case. While I don't know if this is the "proper" way to do this, but in your form function, you can try throwing in something like:

```
if (!empty($form_state['values']['myelement']) {
  $form_state['input']['myelement'] = $form_state['values']['myelement'];
}

```

I tried this with a textfield element, and the value I set using form\_set\_value was displayed in the textfield when the form was rendered.

---
Tags: 7, forms
---


# Question
Title: Themekey with mobile detect not working properly
I am using themekey module with mobile detect module for switching mobile and desktop version of themes. Some time it works and some time not. On Apple devices it load the mobile version. I'm currently using a Shared Hosting provider and I'm using boost module in order to generated my caching.

# Answer
The mobile detect module had some issue with caching. The Drupal 7 Core caching have been supported since few weeks ago by a sub-module call "Mobile Detect Caching."

However, the developer mention that he boost probably would not work.... Here is what the developer said:

> It will only work with Apache(?). I doubt it will work with Varnish, Boost, or similar. I suspect it will work with {cache\_page} in alternate caches, but I didn't test this.

In the comments you mention that you are using a Shared Hosting and you depend on the boost module and what you should do ?

Well, I would recommend you to follow the issue Drupal Cache + Mobile Detect Conflict where the still discussing this module caching issue. In addition to follow you should ask for boost support or an alternative. They might try to implement this module with the boost module.

In the mean time, I would recommend to used a free CDN called CloudFlare and let them generated the caching instead of the boost Module. However, you probably would not get the same results as the Boost module.
> 0 votes

---
Tags: theme-negotiation
---


title: How to link a view output to its node?

text:
# Question
Title: How to link a view output to its node?
I'm wondering if there is a simple way to link the whole view item output without modifying the template files. It is easy to link some fields to the node but I would like the whole view output to work as a link. Any suggestions?

Thank you very much.

# Answer
> 0 votes
This can be easily done by using the "**Content: Path**" and "**Global: Custom Text**" fields. See the following steps for details.

1. add a "Content: path" field
2. add a "Global: Custom text" field (make sure this is the last field)
3. exclude all fields from display except "Global: Custom Text" field
4. Use "Replacement Patterns" on "Text" inside the "Global: Custom text"
5. In Global: Custom text, check the "Output this field as a link" on rewrite results, and insert "**\[path\]**" on "Link path"

PS: "\[path\]" is link to the node

# Answer
> 0 votes
If yo don't want to modify the template file you may implement it using js, some thing like this,

```
$('.title-class').parent().parent().click(function(){
      var url = $(this).find(".title-class").attr('href');
      windows.location = url;
});

```

BUT YOU MUST BE SURE THAT THE `DIV` DISPLAY MUST BE SET TO `INLINE-BLOCK` IN ORDER TO BE AS LARGE AS ITS CONTENT

---
Tags: views
---


# Question
Title: How to use subquery in views where clause
In my project user can created by profile2 module. When user is created i am assigning some role,initially user is block state. I have another user role ie.user app rover who can approved these user and send activation link for active user.

I am using Mail Logger module for saving sending mail Now i have created a view for user unapprove list

```
    SELECT users.name AS users_name, users.uid AS uid, users.mail AS users_mail,
    profile_users.pid AS profile_users_pid, users.created AS users_created, 'profile2' AS
    field_data_field_cc_first_name_profile2_entity_type, 'profile2' AS
    field_data_field_cc_address_office_profile2_entity_type, 'profile2' AS
    field_data_field_cc_designation_profile2_entity_type
         FROM
         {users} users
         LEFT JOIN {profile} profile_users ON users.uid = profile_users.uid AND
         profile_users.type IN ( 'company', 'goverment_profile' )
         WHERE (( (users.status = '0') AND (users.login = 0) AND (profile_users.type IN
            ('company', 'goverment_profile')) ))
            ORDER BY users_created DESC
            LIMIT 10 OFFSET 0

```

Hear i want to add sub-query in where condition user those already send activation link who will not list in view.

My other table is mail\_logger.

Is there any module by which i can use sub-query in where condition?

# Answer
Just ran into the same question, here is what I found:

You can add a sub query to your view using the `hook_views_query_alter` hook in a custom module (documentation). Inside the module you should add something like the following:

```
function your_module_views_query_alter(&$view, &$query) {
  if ( $view->current_display == '[display in question]'){
    $query->add_where_expression([group], [sub query]);
  }
}

```

documentation for $query-\>add\_where\_expression. You can add whatever where clause you need using this function.

`hook_views_query_alter` should go in your\_module.views.inc. Make sure you declare `hook_views_api` in your\_module.module, otherwise views wont know to look for the file. For example:

```
function your_module_views_api() { // declare your views api # here
  return array(
    'api' => 3,
  );
}

```
> 0 votes

---
Tags: views, users
---


title: Download DB in Admin panel

text:
# Question
Title: Download DB in Admin panel
How to download my drupal site DB in my Drupal 7? I want to know is there any options are there in download db in admin panel.

# Answer
> 2 votes
You can install Backup and Migrate

> Back up and restore your Drupal MySQL database, code, and files or migrate a site between environments. Backup and Migrate supports gzip, bzip and zip compression as well as automatic scheduled backups.
>
> With Backup and Migrate you can dump some or all of your database tables to a file download or save to a file on the server or offsite, and to restore from an uploaded or previously saved database dump. You can choose which tables and what data to backup and cache data is excluded by default.

# Answer
> 1 votes
I would recommend to used something like phpMyAdmin because Backup and Migrate can not be restored from the server level.And you can have some performances issues.

---
Tags: database
---


title: How do I create a Forum topic post?

text:
# Question
Title: How do I create a Forum topic post?
I'd like to be able to create a topic on an existing forum, using the REST API exposed by the Services module. This is drupal7 and services 3.x .

via the REST interface, I can successfully:

* query the index of forums `GET /rest/node?parameters\[type\]=forum`
* retrieve a single forum post. `GET /rest/node/8`
* update forum posts (via PUT) `PUT /rest/node/8 ...`

I have not been able to create a forum post. I tried many different variations of the JSON payload, and have not yet found the secret to success.

Example:

```
curl -i -X POST \
  -H Cookie:SESSe6a353351df0bfa8deadcafe=B0ZkiW3-U2x93yJU-deadbeef \
  -H X-CSRF-Token:PSCd5qIdddax0Mh5gfnOM872hdj893-eeeeffff \
  -H Accept:application/json \
  -H content-type:application/json \
  http://myserver/rest/node \
  -d '{
    "title": "This is a test post",
    "body": {
      "und": [{
        "value" : "This is a test post. Please ignore.",
        "summary": "test1",
        "format": "filtered_html"
      }]
    },
    "type": "forum",
    "language": "und",
    "status": "1",
    "forum_tid": "8"
  }'

```

The error looks like this

```
{
  "form_errors": {
    "taxonomy_forums][und":"An illegal choice has been detected. Please contact the site administrator."
  }
}

```

I have tried many variations of the payload, and always get the same error. I think the error means I need to pass different data. But I don't know which different data. Help?

# Answer
Er, yes, I just succeeded in *creating a Forum topic*, after many trials. This was successful :

```
curl -i -X POST \
  -H Cookie:SESSe6a353351df0bfa8deadcafe=B0ZkiW3-U2x93yJU-deadbeef \
  -H X-CSRF-Token:PSCd5qIdddax0Mh5gfnOM872hdj893-eeeeffff \
  -H Accept:application/json \
  -H content-type:application/json \
  http://myserver/rest/node \
  -d '{
    "type": "forum",
    "title": "test post?",
    "language": "und",
    "taxonomy_forums": {
      "und": "1"
    },
    "body": {
      "und": [{
        "value" : "test post",
        "summary": "this is a test1",
        "format": "full_html"
      }]
    }
  }'

```

The key difference was, I think, adding this to the JSON:

```
    "taxonomy_forums": {
      "und": "1"
    },

```

I guessed this, based on a view of the Firefox firebug Net panel, when using the UI to post a new forum topic. This number specifies the forum to which the new topic should be associated. It is a different matter to get the list of forum topics!

Maybe this will help others.
> 0 votes

---
Tags: 7, services
---


# Question
Title: Image Repo and Uploader for specific role
we'd like our staff to be able to add images to a content type whenever they add a new node to this specific content type. This is easily enough done with the image field. However, this requires a) for all of them to have the same images on their local computers, and b) it uploads multiple versions of the same image over and over again into the files directory. We just want one copy of each image on the site. Ideally, the staff would be able to select an image to use for the node they're creating from a repository somewhere on the drupal site itself (which then only keeps one copy of that image on the server).

It would basically work like a 1:M relationship in a database, with the image being the 1 and the nodes being the many.

Anyone know how this is possible? (preferably not using the IMCE module as that messes up my database configuration for some reason...)

# Answer
> 1 votes
You could use taxonomy easily enough.

1. Create a vocabulary called `Node Images`
2. Add an image field to the taxonomy term
3. Add all your terms (just name and the image)
4. Under manage display (for the term), set it up to only show the image field
5. Under manage display -\> full content (for the node), add the taxonomy reference field and set the format to `Rendered taxonomy term` \<- (requires display suite)

On the content type that your staff uses, add a taxonomy reference field with a dropdown or autocomplete. When they create new content, they would be able to select the correct term/image to attach to the node. You would just need to initially add all the terms/images to the vocabulary.

---
Tags: theming, media, users
---


# Question
Title: Custom migration not appearing in the migration UI
I wrote a custom migration module, and I have enabled it in the Drupal 7 administration pages. I have searched through the web, but nothing shed any light on my issue. I came across this post, but it was not helpful.

I have under sites/all/modules/my\_module the following 4 files:

I apologize, but I really don't know how I could be more specific with my question. Does anyone know what could be wrong?

# Answer
> 3 votes
Is your module enabled? (Seriously, my Drush Make file forgot to enable the module, and I was clueless, yesterday.)

If you use `drush migrate-status` from the command line, is your Migration listed?

# Answer
> 0 votes
If you copied from the examples the info file has hidden = TRUE which makes it a hidden module.

---
Tags: 7, migrations
---


title: How do I retrieve all forums?

text:
# Question
Title: How do I retrieve all forums?
I'm trying to retrieve all Forums on a Drupal 7 site, using the Services module.

I can get a list of all "forum topics" (which I think of as forum *entries* or forum *posts*) this way:

```
curl -i -X GET \
  -H Cookie:SESSedeadbeef=B0ZkiW3-U2x93yJU-jusjw6A-SgeShSNTYEkG \
  -H Accept:application/json \
  'http://myserver.com/rest/node?parameters\[type\]=forum'

```

How can I get a list of all the **Forums**? The parent containers for those posts?

Also, where is the documentation on the Services module? I am having trouble finding anything.

# Answer
ok, I got it to work, I think .

Accomplishing the goal requires two steps. First, find the "taxonomy vocabulary" for forums. Then query the tree for that "taxonomy vocabulary".

Step 1:

```
curl -i -X GET \
 -H Cookie:SESSe6a353351dfbaaadbeef=B0ZkiW3-TNZ34dfe-uywhw3-UIWJJww \
 'http://myserver/rest/taxonomy_vocabulary?parameters\[machine_name\]=forums'

```

Result:

```
[{
  "vid": "1",
  "name": "Forums",
  "machine_name": "forums",
  "description": "Forum navigation vocabulary",
  "hierarchy": "0",
  "module": "forum",
  "weight": "-10",
  "uri": "http://myserver/rest/taxonomy_vocabulary/1"
}]

```

Step 2: Using that vid, Query the tree (via POST!!)

```
curl -i -X POST \
 -H Cookie:SESSe6a353351dfbaaadbeef=B0ZkiW3-TNZ34dfe-uywhw3-UIWJJww \
 -H Accept:application/json \
 -H content-type:application/json \
 'http://myserver/rest/taxonomy_vocabulary/getTree' \
 -d '{ "vid" :"1" }'

```

Result:

```
[{
  "tid": "1",
  "vid": "1",
  "name": "General discussion",
  "description": "",
  "format": null,
  "weight": "0",
  "uuid": "dbf914e7-42c2-45f6-b77a-e66a0da72310",
  "depth": 0,
  "parents": ["0"]
}, {
  "tid": "4",
  "vid": "1",
  "name": "Security and Privacy Issues",
  "description": "",
  "format": null,
  "weight": "1",
  "uuid": "7496bfd7-2cb8-4f87-a1e4-f45b1956a01e",
  "depth": 0,
  "parents": ["0"]
}, {
  "tid": "5",
  "vid": "1",
  "name": "etc....",
  "description": null,
  "format": null,
  "weight": "2",
  "uuid": "9fde5519-16b2-453d-852b-a8c416189e30",
  "depth": 0,
  "parents": ["0"]
}, ...]

```

Or, you can do a parameterized GET:

```
curl -i -X GET \
 -H Cookie:SESSe6a353351dfbaaadbeef=B0ZkiW3-TNZ34dfe-uywhw3-UIWJJww \
 -H Accept:application/json \
 'http://myserver/rest/taxonomy_term?parameters\[vid\]=1'

```

The same data is returned.

My next challenge will be to retrieve the list of posts for each particular forum.

Editorial comment: I saw this documented NO WHERE. I really don't understand how developers who use Drupal manage to use the Services module.
> 0 votes

---
Tags: 7, services
---


# Question
Title: db_query gives PDO Exception "General error: 1366 Incorrect integer value:" when I try to update table
I'm trying to execute the following SQL query

```
$tweet_id_int = intval($tweet->id);
$result = db_query("INSERT INTO tweetsDB (handle,tweet,time_string,tweetid) VALUES     ('%v1','%v2','%v3','%v4')", array('%v1'=>$twitter_handle,'%v2'=>$tweet->text,'%v3'=>$tweet->created_at,'%v4'=> $tweet_id_int));

```

from inside a Drupal module and getting the error

```
    PDOException: SQLSTATE[HY000]: General error: 1366 Incorrect integer value: '%v4' for column 'TweetID' at row 1: INSERT INTO tweetsDB (handle,tweet,time_string,tweetid) VALUES ('%v1','%v2','%v3','%v4'); Array ( [%v1] => davecohen [%v2] => taking it easy - Rosh Hashana [%v3] => Fri Sep 14 08:06:08 +0000 2007 [%v4] => 267918272 )

```

handle, tweet and time\_string are VARCHAR

tweetid is BIGINT

The "TweetID" is the value I received from calling the Twitter API earlier to fetch some tweets. Twitter API returns the Tweet ID as a string, so I called 'intval' before passing it to the SQL query. If I try running the same query into the MySQL database directly via the Sequel Pro console

```
 INSERT INTO tweetsDB (handle,tweet,time_string,tweetid) VALUES ('davecohen','taking it easy - Rosh Hashana','Fri Sep 14 08:06:08 +0000 2007','267918272')

```

Then I get no problems at all.

Any help here would be MUCH appreciated!

# Answer
From the Drupal API on `db_query`:

> Do not use this function for INSERT, UPDATE, or DELETE queries. Those should be handled via db\_insert(), db\_update() and db\_delete() respectively.

The recommended method:

```
// Insert values returned from Twitter API.
$tweetsdb_id = db_insert('tweetsDB')
->fields(array(
  'handle' => $handle,
  'tweet' => $tweet,
  'time_string' =>$time_string,
  'tweetid' => $id,
))
->execute();

```
> 1 votes

---
Tags: database
---


# Question
Title: Adding a page to a menu with query parameters in the URL
I'm trying to add a page generated by CiviCRM to my menu. The pages url is 'civicrm/contribute/transact?reset=1&id=6'. I've added the link to the drupal menu manually, and it goes to the page, but that menu item isn't set to active and the active-trail class is not set to it's parent items.

I tried using the full URL and also tried created a module that added a hook\_menu function to create a url without query parameters. The hook\_menu callback would redirect to the path above.

How can I add that link to my menu, and have the active and active-trail classes set?

# Answer
> 1 votes
Ah yes, this has plagued me for years. I cheat and use "Global Redirect Module" https://www.drupal.org/project/globalredirect

# Answer
> 0 votes
There is a way of making menus do whatever you want, including generating the menu link by php code whenever it is being viewed.

The details you can find in the answer below https://drupal.stackexchange.com/a/53531/12153

---
Tags: 7, routes
---


# Question
Title: How do you functional test your Commerce Kickstart 2.0 projects?
Since Commerce Kickstart 2.0 has its own Drupal installation, I don't see how to use SimpleTest with it. I did find this documentation for the regular Drupal Commerce, not Commerce Kickstart 2 from what I can gather. When I try to find what it alludes to in this documentation (CommerceBaseTestCase ), this does not exist in the Commerce Kickstart install that I can find.

So, how are people testing with Commerce Kickstart 2? Let me be clearer with my question. I have already installed Commerce Kickstart 2 and done some development. I now want to create products and other elements programatically using SimpleTest to do functional testing. However, SimpleTest starts with a clean install of Drupal. This is not possible to use with Commerce Kickstart 2.0 because it has its OWN drupal version, and its not just a set of modules that I could enable programatically.

# Answer
> 0 votes
You can install the Commerce Kickstart 2 on your local environment and it would automatic have some data. If you do not know have a development environment I would recommend you to use Lazy Dubuntu (if you wish to build it on Ubuntu computer) or Acquia Dev Desktop 2 for Mac or Windows.

If you do not want to used your local environment you can use Pantheon to test it out for free.

# Answer
> -1 votes
If you want to playaround:

---
Tags: commerce
---


# Question
Title: Use Google Analytics to Track Home Page Links Differently
We use Google Analytics on our Drupal website. We are re-doing our current homepage and we would like to track the links on our homepage separately from the rest of the tracking. For instance, if you navigate to the "Contact Us" section from anywhere on the website *except* the homepage, it logs it as such. However, if you navigate there directly from the homepage, it notes that the person arrived there from the homepage and there is pretty much a separate statistic for this.

We would like to see where people are drawn to when they land on the homepage, so this is why we would like to implement this.

Alternatively, if Google Analytics can't do this, is there another potential solution?

# Answer
> 0 votes
You can do it in google analytics by creating a segment rule that is based on behavior flow. Google Tags can also do this (recommended) or you can add a custom field using the drupal google analytics module to facilitate tracking.

# Answer
> 0 votes
You actually can see the Landing pages and their behavior flow in your Google Analytics account. Login your Google Analytics account and go to "**Reporting \> Behavior \> Behavior Flow**", and you will see all the landing pages and interaction. The home page should be the "**/**".

---
Tags: 7, google-analytics
---


title: Cannot download generated files

text:
# Question
Title: Cannot download generated files
I have a site (Linux/Drupal/Apache) that generate a .xlsx file from custom code and its saved to files, but after that I cannot download it from drupal, it give permission denied.

```
Forbidden
You don't have permission to access xxxxxxx.xlsx on this server.

```

The upload file is saved with -rw------- or 600 permission, and the user/group from Apache.

If I chmod the file to 644 it works.

How can I made that any file generated in that way, will be -rw-r--r-- or 644 ?

# Answer
A few things to check:

1. make sure there is no .htaccess rule that is preventing the download (it may be inherited).
2. If using file entity check: /admin/config/media/file-settings and make sure .xls is allowed.
3. Could be blocked by server security like modsecurity rules, check the apache logs...
> 0 votes

# Answer
Execute a *drush status-report* and see if you have any problems that Drupal detected.

If not comfortable with drush, navigate to \[yoursitename\]/admin/reports/status and see if you have any action items (highlighted in red)

> How can I made that any file generated in that way, will be -rw-r--r-- or 644 ?

You can check your default perms by executing *umask* (http://en.wikipedia.org/wiki/Umask). It is usually 0022. If it is something like 0077, then you will have to change it, if it isnt then dont worry about it right now.
> 0 votes

---
Tags: files
---


# Question
Title: How to filter content (admin view) based on taxonomy term
I'm looking for a way (I'm happy to write a module if shown the way) to filter content in the admin view based on taxonomy term. I've been using the Administration View modules, but it doesn't provide what I'm looking for. And to be honest, I'd be happy to write a simple module that would do such thing. Can anyone point me in the right direction?

Thanks

# Answer
Using \[Administration Views\] https://www.drupal.org/project/admin\_views you should be able to enable or extend an existing view. I have done it for content but have had trouble with that module and had to revert a few times.
> 1 votes

---
Tags: views
---


title: How to arrange two blocks horizontally?

text:
# Question
Title: How to arrange two blocks horizontally?
I am going to create this, But I really don't know how to do it.

**and I want to create one view with two blocks.**

what Format of view should be? (HTML list, Grid, Table, ...)

I don't know theming, How can I do this and arrange these blocks horizontally beside each other?

# Answer
You can do this by using Panel module.

How can you use so I refer to Link1 & Link2
> 1 votes

# Answer
There are many ways to do this, but the easiest is to use a view format of Grid, with 2 columns and alignment horizontal. Panel Module , Display Suite or perhaps a horizontal slider
> 0 votes

---
Tags: views, theming, blocks
---


# Question
Title: How do I create a link that redirects to a destination after completing an action?
I'm trying to create login/logout options for menus that are parts of groups on my page. The thing is I want each menu to have that login/logout select redirect the user to the group page, not the user profiles. How would I go about setting this up in the path setting of the menu?

# Answer
You can try appending a **?destination=/path/to/destination** in the URL of your menu.

For example when setting up the menu for logout you can type:

> \[yoursitehere\]/user/logout?destination=node/23

Do the same for login menu path.
> 1 votes

# Answer
Have a look at the Login Destination module. From the project page:

> The Login Destination module allows you to customize the destination that a user is redirected to after logging in, registering to the site (7.x), using a one-time login link or logging out (7.x). The destination can be an internal page or an external URL. It is possible to specify certain conditions like referring pages or user roles and make the destination depend upon them. You may use PHP snippets to provide custom conditions and destinations. It is also possible to keep users on the currently visited page after logging in or out.
> 1 votes

# Answer
I would consider using Login Toboggan which among other things allows:

* Optionally redirect the user to a specific page when using the 'immediate login' feature.
* Optionally redirect the user to a specific page upon validation of their e-mail address.

It also has over 80K installs. Great module.
> 0 votes

---
Tags: 7, routes
---