# Question
Title: How and where to add google analytics tracking code?
Creating a single page responsive site in drupal 7.While trying to enable google analytics module,came through certain doubts. While registering our site with google analytics they gave us a tracking id (a js snippet) Can anyone tell me after enabling module is it necessary to add the snippet ? If its necessary ,then where to add the snippet in which .tpl file in drupal?

# Answer
> 5 votes
Easiest and most admin-friendly way is to use Google Analytics module:

> Adds the Google Analytics web statistics tracking system to your website.

Just install it, turn it on and configure.

<sub>(source: drupal.org)</sub>

---
Tags: google-analytics
---


# Question
Title: How do I customise the header and footer using a page template for a particular content type?
I have a content type.

I want to customise the node pages for this content type, I've used `node--[content-type].tpl.php` but I need to use a page template to customise the header and footer and `page--[content-type].tpl.php` doesn't work.

I've tried `page--node.tpl.php`, but this changes the home page as well, then i created `page--node--[content-type].tpl.php` which is not working.

Please help me.

Thanks

# Answer
> 2 votes
This is explained on this page at Drupal.org.

Below is a more detailed description about how you do this in Drupal 7:

1. Open the `template.php` file in your theme for editing.
2. Look for a function called `THEME_preprocess_page` (replace `THEME` with the theme's name).
3. If this function already exists, you will need to add your code to it inside an if-statement that goes at the end of this function, just before the closing bracket.
4. Otherwise, if it doesn't exist, you'll need to create a new function:

This is how the function should look like:

```
function THEME_preprocess_page(&$vars) {
  // If the function already exists, just leave the code here intact, and add
  // the three lines below to the end.
  if (isset($vars['node']->type)) {
    $vars['theme_hook_suggestions'][] = 'page__' . $vars['node']->type;
  }
}

```

**NOTE:** do *not* string replace any underscores *inside* the content type's machine name if you're using Drupal 7 (I think you had to do that in Drupal 6).

Now, copy the theme's `page.tpl.php` to a file named `page--contenttype.tpl.php` and place it inside the themes `templates/`folder. For `contenttype`, use the *machine name* of the content type. You can inspect the machine name if you navigate to *Administration » Structure » Content types*.

Now, edit `page--contenttype.tpl.php` so that the header and footer is changed the way you want. Do not change the parts you don't want to appear changed.

All nodes with content of that that type will use the new template file.

Provided you're using Drupal 7, observe the following conventions when naming the template override file.

* Use *two* hyphens to separate the elements in the filename.
* If you're overriding a content type, and your content type is two or more words, replace the underscore character (\_) in the machine name with a *single* hyphen (-) in the file name.

For instance, the name of a template override for content type with a machine name `my_machine_name` should be named (in D7): `page--my-machine-name.tpl.php`.

# Answer
> 5 votes
You can have page templates based on a content type, you just have to add some code so Drupal will recognise the template file: This link shows how to do this.

It depends on your Drupal version. You would think this would be default but for some reason, probably performance related, it is not.

For D7 add this to the template.php file in your theme directory.

```
<?php
function themeName_preprocess_page(&$vars) {
  if (isset($vars['node']->type)) {
    // If the content type's machine name is "my_machine_name" the file
    // name will be "page--my-machine-name.tpl.php".
    $vars['theme_hook_suggestions'][] = 'page__' . $vars['node']->type;
  }
}
?>

```

End now you can customize your footer header etc.

---
Tags: nodes, theming, 7
---


# Question
Title: Delete useraccount with rules based on value filled during creation of account
Does someone have a solution/description for my wish to delete (fake) user accounts that almost always fill in the (phone-number) string 12345 or 123456.

I already have a rule that sends me an message when a new account is created, but I cant find the option to delete account when using rules.

PS I already us the module Toboggan.

# Answer
> 1 votes
In Events use "After saving a new user account" event In Conditions use "Data comparison" IN Actions use "Delete entity"

I have not tried it, but hope this will work..!!

Additional rules are available at https://drupal.org/project/rb

# Answer
> 0 votes
You need the Entity Rules module which will add entity related actions: create entity, delete entity, fetch entity by ID, etc.

You are not only limited to users, but to any other entities you have on the site.

# Answer
> 0 votes
Consider using the spamicide module, it essentially does what you are talking about. When you add spamicide to a form, it adds an extra field to the form, and then hides it using CSS. A human would never fill out the form as they cant see it, but Spam Bots loading pages would fill in the form. Every submission with the hidden field filled out is automatically denied.

This wouldn't do anything to accounts that are already signed up, but I use it on some of my bigger sites that were getting 20 to 30 spam sign ups a day, and now there isn't a single one.

---
Tags: users, rules
---


# Question
Title: How to set a new password using a module?
I'm sending out mails to existing users telling them their username and password with tokens.

Because there is no way to access the user's password (fortunately!), I'm simply setting a new password. But It seems not to work at all.

This is what I've tried so far:

```
// Include the password.inc file to use hashing functions
require_once DRUPAL_ROOT . '/' . variable_get('password_inc', 'includes/password.inc');

// This is my user account (dummy function)
$account = get_some_user();

// Generates new random password of length 12
$password = user_password(12);

// Prepares the new user object and hashes the password
$edit = array();
$edit['revision'] = 0;
$edit['pass'] = user_hash_password($password);

// Saves the user object
user_save($account, $edit);

// Do stuff with password...

```

But this does not really work. The password hash gets changed in the `$account[pass]` field, I've checked that, but I can't login using the new password.

What did I miss?

# Answer
> 0 votes
Okay, I was trying to make it more complicated than it is.

The `user_save()` function **already hashes the password**. This works:

```
// Prepares the user object with new password
$edit = array();
$edit['revision'] = 0;
$edit['pass'] = $password;

// Saves the user object
user_save($account, $edit);

```

There is no need to include the `password.inc` and to use `user_hash_password()`.

---
Tags: entities, emails, tokens, users
---


# Question
Title: Drupal - Save for Later using Workbench, conditional required fields
I have a node set up with a few workbench states. The first state, "Draft", should be used to allow someone to save the node without any required fields. The second state, "Submitted", should make the required fields active. Essentially, I'd like to use default required field behavior for all states except the first "Draft". Is this something I can do programmatically with a module?

# Answer
Yes, this should be fairly easy to do with `hook_form_<form-id>_alter()`:

```
<?php

function MODULENAME_form_page_node_form_alter(&$form, &$form_state) {
  $target_field = "FIELDNAME";
  $workbench_state_required = "draft";

  $form[$target_field]['#states'] = array(
    'required' => array(
      ':input[name="workbench_moderation_state_new"]' => array(
        '!value' => $workbench_state_required
      ),
    )
  );
}

```

Just replace `MODULENAME` with the name of your custom module, and `FIELDNAME` with the field in question to toggle required or not (you can print the $form array in this function to work out the exact field name if you like).

For more information on the Form States API, visit: api.drupal.org.
> 0 votes

---
Tags: nodes, workbench
---


title: Why is this db_select not working?

text:
# Question
Title: Why is this db_select not working?
I can't seem to figure out, are you not allowed to chain db\_select methods?

```
$nid = db_select("node", "n")
            ->fields("n", array("nid"))
            ->condition("f.entity_type", "node", "=")
            ->condition("f.deleted", 0, "=")
            ->condition("f.field_products_product_id", $entity->product_id, "=")
            ->addTag("node_access")
            ->join(
                "field_data_field_products",
                "f",
                "f.entity_id = n.nid"
            )
            ->execute();

```

I have the above, and it just won't work it keeps erroring on the join. Basically I want to do

```
SELECT nid FROM node JOIN field_data_field_products ON entity_id = nid WHERE ...

```

# Answer
This is answered in this other question:

How to perform join with multiple columns using db\_select?

> Calls to SelectQuery::join() (like-wise SelectQuery::leftJoin(), SelectQuery::innerJoin(), and SelectQuery::addJoin()) chain-able because those methods don't return a SelectQuery object, but the actual alias used for the join.
> 4 votes

---
Tags: 7, database
---


# Question
Title: Update module issue - version_major in update_calculate_project_update_status()
I am building a site using Drupal 7.26.

I get this notice all the time:

> Notice: Undefined index: version\_major in update\_calculate\_project\_update\_status() (line 628 of /XXX/public\_html/modules/update/update.compare.inc).

Does someone knows what is the problem, and how to solve this?

Thanks!

# Answer
> 4 votes
If you put:

```
if(!isset($release['version_major'])) {
    die('<pre>'.print_r($project, TRUE).'</pre>');
}

```

On line 625 of update.compare.inc then when the version\_major is not set it will print out details of the problem module and die.

Once you know what module is causing the problem then remove this code again as otherwise kittens may die.

When you know what module is causing the issue then you can raise the problem in their issue queue.

---
Tags: updating
---


# Question
Title: How to add a "Last Updated at" field in footer area?
I wanted to add a field in my website (in footer area), which can automatically display the "last updated" date.

I found the same question in SO but it is not working properly. While accessing some pages, I can see this field as blank with follow errors-

```
Notice: Undefined variable: node in include() (line 207 of O:\xampp\htdocs\rutag\sites\all\themes\skeletontheme\templates\page.tpl.php).
Notice: Trying to get property of non-object in include() (line 207 of O:\xampp\htdocs\rutag\sites\all\themes\skeletontheme\templates\page.tpl.php).

```

By saying "Last Updated at", I mean to say that the last date on which admin has updated (published/modified any content) the website.

# Answer
Not all page types have a a `$node` object associated (the user page, for one does not). You can get rid of the error message that says:

```
Notice: Undefined variable: node

```

by wrapping the call to `format_date` in an if-statement like this:

```
<?php
if (isset($node->changed)) {
  print "Last modified date: " . format_date($node->changed);
}
?>

```
> 1 votes

---
Tags: theming, 7
---


title: Importing location data into Drupal 7

text:
# Question
Title: Importing location data into Drupal 7
New to Drupal but am interested in it as an option to transition to from a hand coded site. This site is primarily a location searchable venue index, with venues having various categories.

In Drupal I have set up my content type 'Venue' and have added the location module to store the venue addresses and other contact details.

Now I am wanting to import my existing data which I have ready in a CSV.

To do this I understand I should use the feeds module which I have now installed (along with ctools and job\_scheduler).

Now under Structure-\> Feeds importers -\> Add importer I can create and configure my CSV import - Great!

Unfortunately I can't see any option under Processor to associate my CSV address fields with the location module fields. What am I missing here?

# Answer
A little late but there's this module: https://drupal.org/project/location\_feeds Location Feeds :D

Haven't actually tried it yet but It seems to do exactly what you want.
> 1 votes

# Answer
I can't help you with the feeds module, but i can tell you how we did this. We used the Migrate module to import a large amount of addresses as locations. With migrate we also had the chance to geocode each location on import (with the Google Geocoder). Migrate is a very powerful module which has a lot of possibilities when it comes to importing data to Drupal.
> 0 votes

---
Tags: feeds, importing-exporting, location
---


# Question
Title: My code is making the admin menu disappear
Ok, so any time I try to view a page on my Drupal 7 site while I am using either drupal\_add\_js(drupal\_get\_path('module', 'floormap') . '/includes/javaScript.js'); or drupal\_add\_js('http://code.jquery.com/jquery-1.10.2.js', 'external');

The admin menu is hidden, As soon as I comment them out, it is back.

First, do I need to include code.jquery.com in Drupal, or is it already there?

Next, I went to my jS file, and made it so that on DOMContentLoaded, it checks the page url, if it isnt the url of my module, nothing is executed...I put in an alert(); and it is only alerting on my pages, but somehow the menu is being hidden still. Why is it still happening on other pages if my jS is only being executed on my module's URL? It seems like just having this file included breaks everything.

```
function checkPage() {

    if (window.location.pathname == '/floormap_page'){
        alert(window.location.pathname);
        hideAgentInfo();
    }else if (window.location.pathname == '/floormap_page/setup_floormap') {
        alert(window.location.pathname);
        coordGrabber();
    }
}

function displayAgentInfo(top,left,floormap,uid) {

    var bubble_info = '';
    bubble_info += floormap+','+uid;

    $.ajax({
        type: "POST",
        url: Drupal.settings.basePath + 'floormap_callback',
        data: {'bubble_info':bubble_info},
        success: function(data){
        document.getElementById('agent_info_bubble').innerHTML = data;
        document.getElementById('agent_info_bubble').style.display = "block";
        document.getElementById('agent_info_bubble').style.top = top+'px';
        document.getElementById('agent_info_bubble').style.left = left+'px';
    }
    });

}
function hideAgentInfo() {
    document.getElementById('img').style.height = '550px';
    document.getElementById('img').style.width = 'auto';
    document.getElementById('agent_info_bubble').style.display = "none";
    document.getElementById('agent_info_bubble').innerHTML = '#';

}

document.addEventListener("DOMContentLoaded", checkPage, false);

```

I've noticed that the admin menu is retieved using $.ajax get, I'm using $.ajax post in my jS, could that be causing issues? Again though, the post is only happening on the pages with my module's URL....

Another note, when I look at the page's source code, the div for the admin menu isn't there at all, it isn't just not visible. That is why I'm getting the impression that it's an issue with the GET function. When I'm watching the log with firebug, it show's the GET when everything is commented out. When my files are included, firebug doesn't show the GET.

Here is a link to my javaScript file if there is anything else you need from it. https://gist.github.com/anonymous/9916901

This is what the firebug console gives me if I have ANY drupal\_add\_js() in my module's inc file:

> ReferenceError: jQuery is not defined
>
> jQuery.noConflict();
>
> drupal.js?n3ddny (line 5) ReferenceError: jQuery is not defined
>
> })(jQuery);
>
> contex...s?v=1.0 (line 52) ReferenceError: jQuery is not defined
>
> jQuery(document).ready(function($) {
>
> scripts.js?n3ddny (line 1) ReferenceError: jQuery is not defined
>
> jQuery(document).ready(function() {
>
> scripts.js?n3ddny (line 1) ReferenceError: jQuery is not defined
>
> })(jQuery);
>
> admin\_...?n3ddny (line 397) ReferenceError: jQuery is not defined
>
> })(jQuery);
>
> scripts.js?n3ddny (line 32) ReferenceError: jQuery is not defined
>
> jQuery(document).ready(function() {
>
> main.js?n3ddny (line 1) ReferenceError: jQuery is not defined
>
> ...odules/custom/TLSConnectPackage/TLSApplicationFilter/TLSApplicationFilter.cs...
>
> app.lo...bal.com (line 58)

If I remove drupal\_add\_js() the only thing that shows in the console is the GET for the admin menu.

# Answer
> 1 votes
Drupal comes with jQuery so you don't need to add it. You should use https://drupal.org/project/jquery\_update when trying to use a newer version of jQuery; doing it the way you are currently can cause unknown side effects.

---
Tags: routes, ajax, javascript
---


# Question
Title: How do I change my site time to test my recurring payments?
I am testing the recurring framework in Drupal commerce on my local mamp environment and I want to test the recurring payments. How to I trick my Drupal site into thinking it's a day later so it will trigger the recurring payment?

# Answer
> 3 votes
Change the time of your system/server and run cron manually. PHP reads the time from your system settings and cron is what executes the recurring product functions at the required time.

# Answer
> 3 votes
If you are working with 5.3+ you can do a trick with namespaces: implementing a new time() function inside your current namespace and create a shared resource where you set the return value in your tests.

You can found a complete description in this blog post:

PHP: “Mocking” built-in functions like time() in Unit Tests

# Answer
> 1 votes
i think you can change the PHP time zone to force a time zone then change your local machine to a day later it may help

# Answer
> 0 votes
Using PHP timezone function change the timezone first. See the links for more detail about timezone.

https://php.net/manual/en/timezones.php and https://php.net/manual/en/timezones.africa.php

Calculate day later time using

```
date_default_timezone_set('America/Los_Angeles');
$new_date = date('Y-m-d H:i:s', strtotime('+1 day', $current_date);

```

similar functions. which will help you to test the recurring system by setting manual time to drupal.

Drupal provide default time zone functions just so you can setting timezone and calculate the time in your hook\_cron(). while trigger will get fired Cron processing will work based on your condition.

Hope it will help.

---
Tags: commerce
---


# Question
Title: Sync local dev site to live best practice
What is best practice for syncing a local dev site with a live production site when your live database is constantly changing?

From what I have read there are two possibilities:

1. Replicate changes made in dev manually on your production site. This seems like something you would only want to do with fairly limited changes that I can make while the site is down for maintenance and users are unable to make any changes to the production database. I can imagine that it can make it tough to make more complex updates/changes. I have done this in the past with simple changes/updates to modules and so on.
2. Migrate the test site into production, with the site in maintenance, and synchronize the databases. This option seems more like the way to go for bigger jobs, as long as I can synchronize the databases somehow.

That seems to assume that your production site is basically static and the database will not change much at all when you are making changes on your test site.

However, I am working on a batch of improvements for site that has daily activity (new content, users, transactions, comments etc.). These changes are taking time to set up and test.

I found this comment on Drupal.org https://drupal.org/comment/4511654#comment-4511654

It addresses my situation, but is there any better way to go about this or a more detailed guide/how-to? Or should I be breaking things up into smaller and more manageable chunks -- that way seems time consuming.

# Answer
Here are some good ideas to use:

1.) Backup and Migrate module. Before doing any local changes migrate the production database down to your local environment

2.) Features. Make all your content type into specific features. Include content types, views, context, and any other thing that can be put into features. This will allow you to make content type changes and almost ANYTHING on the site and simply roll it as a feature. When its uploaded to the production environment you simply revert the features, and bam they are there.

3.) Stongarm and Diff are additional modules to use with features. They allow to see whats different from the site and the feature, and strongarm allows variable exports into features.

3.) GIT or SVN. Use git or svn to roll to production and keep your code base on track. With major features differences use a branch to complete work and merge it into the trunk. This will allow you to development bigger features, but also give you the ability to make bug fixes that can be sent up in a roll.

4.) RSYNC. Most of the time sites/default/files or CMS uploaded files are not in your repository. Use rsync to sync the production files to your local. Or simply use FTP

5.) Use drush up to update your modules it will keep your subversion or git in tact. It will also attempt to update your database.
> 1 votes

# Answer
Have you worked on deploy module before... really reduce manual process by its smart functionality.

See the below mentioned modules. https://drupal.org/project/deploy\_services\_clienthttps://drupal.org/project/deploy

Read more about deployment configuration https://drupal.org/node/408774

hope it helps
> 0 votes

---
Tags: database, migrations
---


title: Change in URL for social networking

text:
# Question
Title: Change in URL for social networking
I am using Drupal for running a website. I have integrated the "Share bar" module to share the current page in social networking sites. I know from the plugins code of Facebook that the share count of the website is 200+ But the share bar module shows only 20+ count.

I could find out what the problem is, the code for sharebar is:

```
<div id="fb-root"></div> <script>(function(d, s, id) { var js, fjs = d.getElementsByTagName(s)[0]; if (d.getElementById(id)) return; js = d.createElement(s); js.id = id; js.src = "//connect.facebook.net/en_US/all.js#xfbml=1"; fjs.parentNode.insertBefore(js, fjs); }(document, 'script', 'facebook-jssdk'));</script> <html xmlns:fb="http://ogp.me/ns/fb#"> <fb:like href="[url]" send="true" layout="box_count" width="450" show_faces="true"></fb:like>

```

In the code above, \[url\] token actually gives out http://www.indiansnakes.org/frontpage instead of http://www.indiansnakes.org. I think the \[url\] token refers to hyperlink before redirection is completed.

How can I modify the script above so that I get the count for www.indiansnakes.org instead of www.indiansnakes.org/frontpage

# Answer
Looking at the source code on your live site, I see that the code for the fb:like section becomes:

```
<fb:like href="http://indiansnakes.org/frontpage" send="true" layout="box_count" width="450" show_faces="true"></fb:like>

```

...so I assume \[url\] is a token. Assuming that's true, I'd recommend using a more specific URL token.
> 2 votes

# Answer
Create a custom 301 re-direct rule in your .htaccess file.

After the Rewritebase / (line 110) in .htaccess, copy and paste the following...

```
  #custom redirects
RewriteRule ^frontpage$ http://www.indiansnakes.org [R=301,L]
  #end custom redirects

```

This is worth doing whenever you set another node as your default front page to stop any duplicate content issues. Especially when using site map generators that will list both www.indiansnakes.org and www.indiansnakes.org/frontpage automatically in a site map.

Also, try flushing the cache afterwards to make sure ShareBar refreshes.

EDIT:

This re-directed the page correctly, but it didn't update the sharebar app. Looking at source and searching "frontpage" brings up 41 occurrences, and some of them are where the pages canonical url is used. Consider installing the metatag module, and manually setting your front page canonical url as http://www.indiansnakes.org in the metatag module settings for the front page
> 2 votes

# Answer
You can install Global Redirect module, which I would strongly recommend for SEO.

> Once enabled, an alias provides a nice clean URL for a path on a site. However Drupal does not remove the old path (eg node/1234). The problem is that you now have two URLs representing the same content. This is dangerous territory for duplicate pages which can get you sandboxed by the search engines!

This module can also solve your problem with 2 URL's for frontpage: `www.example.com` and `www.example.com/frontpage`

> Checks if the current URL is the same as the site\_frontpage and redirects to the frontpage if there is a match.
> 1 votes

# Answer
I'd assume the ShareBar module isn't very good at resolving Drupal's front page setting, and/or supporting tokens.

In fact, here's an issue for ShareBar dealing with tokens: https://drupal.org/node/2106887 It doesn't appear to have much traction after being posted in late 2013. You might try seeing if you can apply the patch, reviewing it, and/or setting the issue to RTBC.
> 0 votes

---
Tags: javascript, uri
---


# Question
Title: Updating of drupal core and modules impossible
I have several different drupal sites (all hosted seperately). Some of them run on 7.22, and some of them run on 7.26.

For some reason the update.php script does not seem to work anymore. I can visit the page and it correctly shows the first step: Verify Requirements is shown in green and I see the Overview step. When I press the Continue button the browser starts loading and never finishes. I have tried this a dozen time, every time with the same result. I tried this on the hosted environment and on my home envirentment (installed a backup of the site).

One site is fairly small so I did a clean install of 7.26, installed all the modules, articles, etc. Same result. I am at a complete loss and now unable to install updates of drupal core and modules. Please help.

BTW 1: I use these modules in all of my sites: ctools, ckeditor, imce, lightbox2, views, metatag token.

BTW 2: nothings strange to be found in Apache error.log and php-errors.log

**EDIT: Just found out that this is a known issue for IE. Tried this in Chrome and it works fine. Hope others with the same problem find this post sooner than I found the anwer**

# Answer
See https://drupal.org/node/2157815. Don't know how else to close this question...
> 0 votes

---
Tags: 7, updating
---


# Question
Title: Entity reference of a menu link gives Restricted access instead of the real data
I am trying to create an entity reference of a "menu link", but instead of having the menu link name I got "- Restricted access -". It seems to be the same problem with wysiwyg profile. I'm using the last version of entity reference (7.x-1.1), event the dev version is the build.

I'm using admin with full right on everything.

Any idea why ?

# Answer
> 0 votes
Here is an issue I found on drupal .org: https://drupal.org/node/2153463

There is a patch inside to fix the issue but it doesn't seem like the final patch, so decide if you want to use it. Your alternative is to use an old version of entity reference which doesn't have this bug.

---
Tags: routes, entities
---


title: How can I merge an image with text

text:
# Question
Title: How can I merge an image with text
I want to create a greeting card and send to the users email. How can I merge text on an image?

Thanks!

# Answer
> 2 votes
Look at Image Cache Actions:

> Effects provided
>
> * Watermarking - a much requested addition that enables you to place any image anywhere over a source picture, with alpha transparency
> * Overlays - Add photo-corners etc to the image
> * Text overlay - add a short copyright notice to your image, using available system fonts
> * Color-shifting - Colorize images. Also invert.
> * Brighten/Darken Alpha blending - turn an image into a transparent mask, and back into a flat image against another color
> * Canvas manipulation - add padding, either onto color or transparent backgrounds \*Background - Place your image onto another source background
> * File Format switcher - If you need tranparency in JPGs : make them PNG. If your PNG thumbnails are 30K each, save them as JPGs. (This is distributed as part of the color-actions submodule)
> * Rounded corners (transparent). With input from canaryMason, we can even set different radius for different corners, and round just one corner etc.
> * Aspect Switcher - lets you perform different actions or use different dimensions based on whether the image is 'landscape' or 'portrait'
> * Custom Actions - Execute your own PHP/GD code in the middle of an imagecache generation process. Requires some familiarity with imageAPI internals.
> * Posterize new as of 7.x-1.4- Reduce the image to a limited number of color levels per channel. This effect can be used to reduce file size on png images.

*How* this module adds text over an image (which is your question) I leave to you to figure out by browsing and deconstructing the module sourcecode.

---
Tags: media
---


title: Proper way to do entity query?

text:
# Question
Title: Proper way to do entity query?
I am wondering if EntityFieldQuery is the proper way to do this

```
SELECT * FROM field_data_field_products JOIN node ON entity_id = nid

```

I'm wondering if there is a better way then my current db\_query way, when dealing with entities.

# Answer
You are not doing the query quite right. There are a few things you are missing.

You need to remember that fields can be on multiple entity types, and that entity IDs are not unique globally. This needs to be part of the `JOIN` clause.

The other is that there is a deleted column, that represents whether the data item has been deleted or not. This also needs to be part of the `JOIN` clause.

You also need to ensure node access rights are maintained for any query against the `{node}` table.

EntityFieldQuery will take care of all of this for you. Otherwise, you should use `db_select()` to build the query, as you can `->addTag('node_access')` the query.

Something like this would be a start for node entities:

```
$query = db_select('node', 'n')
  ->addTag('node_access');

$query->join('field_data_field_products f', 'f.entity_id = n.nid AND f.entity_type = :entity_type AND f.deleted = :deleted', array(
  ':entity_type' => 'node',
  ':deleted', 0,
));

$query->fields('n', array(...))
  ->fields('f', array(...))

```

You would modify this to use different tables and types for different entities. If you aren't querying against the `{node}` table, then you can skip the `->addtag()`;

If you end up using EFQ, remember that it only returns the entity\_ids, so you have to `entity_load()` the results (or use the entity specific version like `node_load()`).

Regarding the query, it is a good habit to put your base table first and then join the secondary tables. This helps with readability. You should also try to explicitly pick the fields you need and avoid `*` results. There is no rule against this, it is just considered best practice by some.
> 4 votes

# Answer
Yes, EFQ will take care of this and you should not touch the field / entity directly with SQL, ever.
> 0 votes

---
Tags: 7, entities
---


title: Drupal Node Id reflection

text:
# Question
Title: Drupal Node Id reflection
What's the preferred way to get the current Node ID while inside a Drupal module function, without passing it in?

Adding more text, because StackOverflow won't post short questions:

Ideally, I'd like some kind of reflection function, where I can simply request the NID of the node being served in the stack trace. Since Drupal revolves around serving nodes, it stands to reason that there should be some kind of reflection function that makes "the node I'm operating on presently, or NULL if I'm not operating on a node", available at all times.

The best discussions I've found pull the NID out of the URL. This strikes me as a backwards way of recovering the NID, and fragile, to put it mildly.

# Answer
> 1 votes
If you would like to get the current viewed nodes id you should be able to do like this:

```
// check so we're really viewing a node
if (arg(0) == 'node') {
  // grab the nid for the node
  $nid = arg(1);
  // you could also try to load the node to make
  // sure the supplied nid is valid
  if (node_load($nid) == FALSE) {
    // failed to load the node
  }
}

```

In the case of an ajax request I guess you really ***should*** supply the `nid` as an argument:

```
function <MODULE>_menu() {
  $items['sample/%1'] = array(
    'page callback' => '<MODULE>_sample',
    'page arguments' => array(1),
    'type' => MENU_CALLBACK,
    'access arguments' => array('access content'),
  };
  return $items;
}

function <MODULE>_sample($nid) {
  // use the supplied nid here
  $node = node_load($nid);
  if ($node) {
    // do something with the loaded node
  }
}

jQuery('#output').load('sample/21');

```

---
Tags: 7
---


# Question
Title: "Access Denied" to the Admin on Old and New Install
There was an access denied issue that I could not get past with my current test drupal install. I installed another drupal instance with a new db and still get this access denied error trying to get into the Admin area. This is not a cpanel, it is a server that is being setup for me.

Does anyone have ideas I can work through to get this resolved?

Does the admin have any special permissions that it needs to "chmod" etc... areas of the drupal site?

Thanks

# Answer
> 1 votes
Are you login as an admin. I mean UID = 1 ? Try to reset the super user password and loggin again.

DRUPAL 6 and below: `UPDATE users SET pass = MD5('givememypasswordback') WHERE uid=1;` DRUPAL 7 - https://drupal.org/node/1023428

Also check error logs if you think its an internal permission issue.

---
Tags: 7, users
---


# Question
Title: how to send a exposed filter when use Service views
I create a exposed filter of field `field_nick_name`.

and I visit this link

```
http://drupal/daxuebao/api/views/user_search_by_nick?filters[field_nick_name]=a

```

and this link

```
http://drupal/daxuebao/api/views/user_search_by_nick?field_nick_name=a

```

this above 2 can not work, is there someone can tell me how to use Service View with exposed filter?

# Answer
I try to find out the views setting that store in database with following code:

```
$db = db_select('views_display', 'v')
    ->condition('v.vid', '30')
    ->fields('v', array('display_options'));

  $res = $db->execute()->fetchAssoc();
  $a = unserialize($res['display_options']);

```

the `$a` contain a `filter` array. The `field_nick_name` actually is `field_nick_name_value`, and `uid` is `uid_raw`
> 0 votes

---
Tags: services
---


title: Where are the term tokens gone?

text:
# Question
Title: Where are the term tokens gone?
I have a hard time setting up URL alias patterns when it comes to taxonomy terms. Especially, I'm stunned that in the Replacement under Content Paths, a term reference field shows just one flat item \[node:field\_term\_name\], rather than an expandable set of taxonomy-related tokens. This is the way it used to be (as in the screenshot here: Pathauto url of term for node?) Have things changed or is it a bug?

# Answer
> 1 votes
Enabling the Entity\_Token sub module does help with this issue, however, you need to add a "Term Reference" type field to any of your content types in order to see your taxonomy vocabulary be listed as one of the replacement tokens. In my case, I had enabled the entity\_tokens module but I was still not able to see my vocabulary as one of the replacement tokens. Then I added a new field to my "basic page" content type. The field type I added was "term reference" and I selected my custom vocabulary as its default vocabulary. This resolved my issue.

# Answer
> 0 votes
After some investigation I found out what was wrong. The key was to enable Entity Token (a submodule of the Entity API package). Following that all the taxonomy reference field's tokens expanded into a subtree and my Pathauto i18n patterns started to work as desired.

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


title: File upload with ajax

text:
# Question
Title: File upload with ajax
Is there any example how to set up form element with type file to upload it via AJAX. I want to be same as field image in node type article.

thx

# Answer
Maybe this will be helpful (in a custom module):

```
function testmodule_forma($form, & $form_state) {
    $form['im-container'] = array(
        '#prefix' => '<div id="im-area">',
        '#suffix' => '</div>',
    );

    $form['image_file'] = array(
        '#type' => 'file',
    );

    $form['upload'] = array(
        '#type' => 'submit',
        '#value' => 'upload',
        '#submit' => array('upload_image'),
        '#ajax' => array(
            'callback' => 'upload_image',
            'wrapper' => 'im-area',
            'method' => 'replace',
            'effect' => 'fade',
        ),
    );
    return $form;
}

function upload_image($form, $form_state) {

    $file = file_save_upload('image_file', array('file_validate_extensions' => array('png gif jpg jpeg')), "public://", FILE_EXISTS_REPLACE);
    if ($file) {
        $file->status = FILE_STATUS_PERMANENT;
        file_save($file);
        $form['im-container'] = array(
            '#title' => t('Preview:'),
            '#prefix' => '<div id="im-area">',
            '#markup' => '<img src="sites/default/files/'.$file - > filename.
            '" height="250" width="250" />',
            '#suffix' => '</div>',
        );
    } else {
        drupal_set_message('No file uploaded.');
    }

    return $form['im-container'];
}

```
> 10 votes

# Answer
If you are using D7, Why you are writting messy code to achieve this task?

In D7 form API we have type = managed\_file which uploads file using ajax.

Try this example:

```
$form['image'] = array(
            '#type' => 'managed_file',
            '#title' => t('Upload Image'),
            '#default_value' => '',
            '#required' => TRUE,
            '#description' => t("Upload Image description"),
        );

```
> 4 votes

---
Tags: 7, forms, files
---


# Question
Title: How to use jquery accordian in side bar first
I am using facets search filter. I want to use accordion in facest search filter.

# Answer
> 1 votes
As I understood you want to make it Collapsible. If yes try below mentioned module

https://drupal.org/project/facetapi\_collapsible

https://drupal.org/files/project-images/collapsible\_facets\_0.png

---
Tags: search, navigation
---


# Question
Title: Which is the best way to create an entity?
I would like to use entity concept in my next project.So , is it good to use Entity Construction kit for creating entities ? How about Model Entities ? Which is better ?

# Answer
> 1 votes
The Entity Construction Kit (ECK) is a module to assist developers with creating their own entity types. If you want to export your entity types to code for version control and deployment use the Features module. If you don't want to do this (i.e. take the long way) write your entity type code using Model module as an example to follow (essentially the same thing).

---
Tags: entities
---


# Question
Title: Cannot access commerce order relationship in Add relationship form in Drupal 7 Views
I have Drupal commerce installed on a Drupal 7 website. I needed to create a view of users and wanted to display the product type they had purchased along with the user name in the View. However I am unable to create a relationship between the view and commerce order even though the module (commerce) has exposed it via hook\_views\_data

```
'relationship' => array(
  'title' => t('Owner'),
  'help' => t("Relate this order to its owner's user account"),
  'handler' => 'views_handler_relationship',
  'base' => 'users',
  'base field' => 'uid',
  'field' => 'uid',
  'label' => t('Order owner'),
),

```

Can anyone point out what is causing this relationship to not appear in the View add relationship foorm? Is it required to modify any additional configuration settings to bring up this view?

# Answer
This was a false alarm. I was on a different branch with a single module missing. Enabling the module solved the problem.
> 0 votes

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


# Question
Title: Choose Checkbox Insted of radio as a widget in drupal custom content type
While adding field in content type I had chosen **Check boxes/radio buttons** as widget.
By default it takes radio button as a widget.
I want check boxes as a widget instead of Radio Button. What should I do?

# Answer
You need to edit in Field Settings to set Number of Values to Unlimited or more than 1. Then Checkboxes will be used.

Radio buttons are used when user can only select one value.
> 0 votes

---
Tags: nodes
---


# Question
Title: How do I create a link to the author's profile on the node that user created?
I want a create a link on each node page, which redirects to the profile page of the user who created that particular node.

How can I achieve this?

# Answer
> 2 votes
Create a custom block with this:

```
/**
 * Implements hook_block_info().
 */
function mymodule_block_info() {
  $blocks = array();
  $blocks['author'] = array(
    'info' => t('author'),
  );

  return $blocks;
}

/**
 * Implements hook_block_view().
 */
function mymodule_block_view($delta='') {
  $block = array();

  switch($delta) {
    case 'author' :
      $block['title'] = NULL;

      ////////////////////////////////////////////
      $link = NULL;
      if (arg(0) == 'node' && is_numeric(arg(1)) {
        $node = arg(1);
        if (!empty($node->uid)) {
          $link = l('view all work', 'user/' $node->uid);
        }
      }
      //////////////////////////////////////////

      $block['content'] = $link;

      break;
  }

  return $block;
}

```

And set this block to nodes page with context, panels or native drupal blocks page.

# Answer
> 1 votes
This is the default functionality available on Drupal. on detail pages author detail appears.

Just edit your content type display setting and check

> "Display author and date information. Author username and publish date will be displayed."

See the screenshot

After that your can prepare link of author on theme preprocess or hook\_node\_view to make it clickable.

# Answer
> 0 votes
You can use the node--content-type.tpl.php node template file for showing the profile link of the user who created the node. you can use $node-\>uid to find the user id and then use user\_load() function to load the user OR profile2\_load\_by\_user($account, $type\_name = NULL) it will give you the profile url for the user if you are using the profile2 module and the you can create the link using the l() function.

---
Tags: nodes, users, navigation, redirection
---


# Question
Title: How to get a mini-calendar as a block on sidebar?
I am using a Event Calendar module to display the Calendar and it is configured using views and linked with the events and popup the event when clicked.

I want a mini-calendar on front page with same events but like a mini calendar.

I have tried creating block for the view but it didn't work.

Can anyone help me how to do that?

# Answer
> 1 votes
Have a look at Pretty Calendar module.

---
Tags: views, datetime
---


title: Create invoice when registrating

text:
# Question
Title: Create invoice when registrating
I have a register form with some fields like `name shop, btw number, subscription, ...` . I want to create an invoice of the data filled in (do some operations with other variables). I know that there's a drupal module `Invoice` but how can I automatically create one when clicked on register button and send them to the users email? (I'm a drupal beginner)

# Answer
> 2 votes
I can't tell you the exact steps but I can suggest you some workaround for this.

You can use Rules module & create a rule for sending mail after event register.

You can send mail in action. Use Token for mail formatting. Maybe you will need some Mail related modules such as Mime Mail for sending mail.

---
Tags: users, emails, commerce
---


title: simpler theme/view mechanism/function?

text:
# Question
Title: simpler theme/view mechanism/function?
Is there a module that provide a base/framework for simpler/faster rendering of a view(in MVC terms).. a function like

> render\_tpl('path/to/my/tpl/myview.tpl, array('var1'=\>$var1, 'var2'=\>$var2);

? You see something much simpler than having to declare my theme to the theme registry via hook\_theme etc... (sometimes it seems overkill just to render a simple layout)

# Answer
There wasn't enough space in the comment field, so I'll write a full answer :)

As far as I know, there is no way to do that using existing Drupal modules or functions. If you really want to do something alternative, look into guidelines/recipes for creating own functions for simple templating parsing.

> don't you feel that it is sometimes overkill/tedious just to theme something very simple with hook\_theme etc...?

With the same logic, you could argue that you don't need any `hook_menu()` implementations, and that all you could do is have a `.php` file in the root of the site from where you would query the database directly :)

It all boils down to conventions because they imply more efficient/simpler maintenance, security, self-explanatory code for other people working on the same project, etc.

However, if you are the only one who is responsible for the site, you're free to do whatever works.

P. S. Toying around and stripping Drupal/turning it into something else can be very good for learning how things work at the higher level. Few years ago I maintained an in-house stripped version of Drupal 5 and 6 for own purposes, with different folder structure, without many modules/features I did not need and some other tweaks. It was a great learning experience.
> 2 votes

# Answer
If you just need to render a template, without defining any theme function, then you could simply use `theme_render_template()`.

I would rather go with `hook_theme()`, but to just render a template file, that is the simpler code you could use. `theme()` itself uses that function.

```
// Default render function and extension.
$render_function = 'theme_render_template';
$extension = '.tpl.php';

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

// ...

if (!isset($variables['directory'])) {
  $default_template_variables = array();
  template_preprocess($default_template_variables, $hook);
  $variables += $default_template_variables;
}

// Render the output using the template file.
$template_file = $info['template'] . $extension;
if (isset($info['path'])) {
  $template_file = $info['path'] . '/' . $template_file;
}
$output = $render_function($template_file, $variables);

```

You could use similar code for your case, and your code would work even if you change theme engine for the template files you write: instead of the global `$theme_engine`, use another way to set the theme engine to use for those templates.

Keep in mind that code would not work on Drupal 8. Since code for Drupal 8 is going to change, anyway, this is should not be a problem.
> 1 votes

# Answer
Instead of calling views in your system why you are not trying it with angularJS.

Module available in drupal.org https://drupal.org/project/angularjs or you can use it directly with using xml feeds too.

Otherwise use view content cache is a simpler modules to use and load cached views faster https://drupal.org/project/views\_content\_cache

Hope it helps
> 0 votes

---
Tags: views, theming
---


# Question
Title: Submit to external url via Ajax & get return
I need a Drupal form to submit a file to an external server using ajax. I have done the form using Form API and I am able to submit it via Ajax, But the Drupal throbber never stops and I am not able to get the returned value. But in firebug I can see it to be returned.

**My Code:**

```
function upload_video_episode($form, &$form_state){

     $form['files'] = array(
        '#type' => 'file',
        '#title' => t('Video'),
        '#description' => t('Upload a file, allowed extensions: mov, mp4, avi, mkv'),
      );

     $form['submit'] = array(
           '#type' => 'submit',
           '#value' => t('Submit'),
           '#ajax' => array(
           'path' => url('http://web.com/test.php', array('external' => true)),
           'callback' => 'upload_video_test',
           ),
      );

    $form['#action'] = url('http://198.199.95.235:8080/dev/test.php', array('external' => true));
    return $form;
}

function upload_video_test(){
    return "Done!";
}

```

The throbber just keep rotating non-stop.

However, in firebug I can see the form have been submitted and values returned.

Console seems to be showing some error, possibly related to Non-Origin. But in my case the data is already submitted.

```
Error: Permission denied to access property 'document'

```
* Is what I have done so far correct?
* I want to get the returned value and store it in a hidden form field or something.
* Or is Drupal Form API not capable of handling external urls?

Any help would be highly appreciated.

# Answer
Sounds like it's spinning forever because of the js error.

Where is the error occurring? In jQuery library?

If so use an uncompressed version of jQuery and it may be easier to debug.

Maybe even temporarily hack jQuery core to remove error and see if that fixed your problem before spending time figuring out how to fix it properly...
> 1 votes

---
Tags: ajax, forms, external-scripts
---


title: Taxonomy vs Values module in my case

text:
# Question
Title: Taxonomy vs Values module in my case
I'm using the Values module for creating a list of subscriptions the user can choose of when they register (it's a field in the registration form). Now I've seen I can also create a list with the Taxonomy module. I'm just curious what's the best practice for this? Should I use the module already implemented or is Values module better in my case?

# Answer
> 3 votes
The Values module is a *field* for users to enter their own list of values in a key-value format.

Core taxonomy module is used to create lists of terms which can be placed as a *field* on the registration form using a 'term reference'. This would then appear as either a select list, radios or checkboxes (checkboxes if the field is multi select).

The difference is that with Values, users enter their own values and with term reference and Taxonomy, users choose from your list of terms in the taxonomy. Which do you want? I think if you're looking for subscriptions, it's term reference and Taxonomy.

---
Tags: taxonomy-terms, forms, users
---


# Question
Title: How to upload enterprise blog picture programatically in drupal 7
I used "enterprise blog" module for user blog postings. From external php file, I have to upload user picture programatically (i.e., for App). I have configured bootstrap perfectly and user\_load($uid) is working, means drupal functions are working properly, but when I am trying to upload picture programaically "file\_save($file)" is not working. Please check the below code and give me any suggestions to upload enterprise blog picture.

```
 $tmp_photo_realpath = "images/".$userimgname;
      $tmp_photo = "images/".$userimgname;
      $file = new stdClass();
      $file->uid      = $uid;
      $file->status   = 0; // mark the file as temporary
      $file->filename = basename($tmp_photo_realpath);
      $file->uri      = $tmp_photo;
     // $file->filemime = image_type_to_mime_type(exif_imagetype($tmp_photo_realpath));
      $file->filesize = filesize($tmp_photo_realpath);
     $infofile = explode("/",$tmp_photo);
    $infoext = explode(".",end($infofile));
    $imgext = end($infoext);

  // The file should be an image
  $errors = array();
  $errors += file_validate_is_image($file);
  $errors += file_validate_image_resolution($file, variable_get('user_picture_dimensions', '100x100'));
  $errors += file_validate_size($file, variable_get('user_picture_file_size', '30') * 1024);

  // Make sure file extension is a valid image
  if (!in_array(strtolower($imgext), array('jpg', 'png', 'gif'))) {
    $errors[] = ' invalid image file extension.';
  }

  if (count($errors)) {
    drupal_set_message(t('Profile Image Import:') . ' ' . $errors[0], 'warning');
    // Clean up (set fid to avoid error messages)
    $file->fid = 0; file_delete($file);
  }
  else {
    // We'll need a valid file id on the file object; file_save() will give us one
    $file = file_save($file);
    // Update user account (fid is not empty, status is temporary -- image
    // will be moved to proper directory and assigned to the user)
    $fields['field_enterprise_blog_picture'] = $file;
    $account = user_save($account, $fields);
}

```

# Answer
Ok, here is my testing example. I can't say that it works perfectly but in my case it works fine. And, of course, you can modify/customize it by your needs if you want (add validation, check file path, directories, and so on..):

```
function _executeFile($uri, $uid) {

  $file_url = file_create_url($uri);
  $file = system_retrieve_file($file_url, NULL, TRUE, FILE_EXISTS_REPLACE);

  if ($file) {
    $user = user_load($uid);
    $file = file_load($file->fid);
    $file->status = FILE_STATUS_PERMANENT;
    file_save($file);

    // file_usage_add($file, 'MY_MODULE', 'enterprize_picture', $file->fid);

    $file_info = image_get_info($file->uri);

    $user->field_enterprise_blog_picture[LANGUAGE_NONE][0]['fid'] = $file->fid;
    $user->field_enterprise_blog_picture[LANGUAGE_NONE][0]['alt'] = '';
    $user->field_enterprise_blog_picture[LANGUAGE_NONE][0]['title'] = '';
    $user->field_enterprise_blog_picture[LANGUAGE_NONE][0]['width'] = $file_info['width'];
    $user->field_enterprise_blog_picture[LANGUAGE_NONE][0]['height'] = $file_info['height'];
    $user->field_enterprise_blog_picture[LANGUAGE_NONE][0]['uid'] = $file->uid;
    $user->field_enterprise_blog_picture[LANGUAGE_NONE][0]['filename'] = $file->filename;
    $user->field_enterprise_blog_picture[LANGUAGE_NONE][0]['uri'] = $file->uri;
    $user->field_enterprise_blog_picture[LANGUAGE_NONE][0]['filemime'] = $file->filemime;
    $user->field_enterprise_blog_picture[LANGUAGE_NONE][0]['filesize'] = $file->filesize;
    $user->field_enterprise_blog_picture[LANGUAGE_NONE][0]['status'] = '1';
    $user->field_enterprise_blog_picture[LANGUAGE_NONE][0]['timestamp'] = $file->timestamp;
    $user->field_enterprise_blog_picture[LANGUAGE_NONE][0]['rdf_mapping'] = array();

    user_save($user);
  }
  else {
    // SET VALIDATION ERROR
  }
}

```

and call it like this:

```
define('DRUPAL_ROOT', getcwd());
require_once './includes/bootstrap.inc';
require_once './includes/file.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);
_executeFile($uri /* e.g.: 'public://OTHER-OpenSourceSystem_1600x1200.jpg' */, $uid);

```
* First function gets two variables as arguments and loads user object and creates file object from URI, and sets file object properties to user file field and saves it;
* Second piece of code bootstraps system and just calls that function.. You can set your validation rules here
> 0 votes

---
Tags: users, files
---


# Question
Title: How can I add help tips on each page, like a sliding panel?
Is there any module I can use to insert in every page info about the specific page. I could use something like a sliding panel, or a popup. I need the content of that, block or popup or whatever it is, to be translatable. I found this link, but it needs much custom code, which I would like to avoid.

# Answer
We decided to make a custom implementation. In order to answer to @Molot and whomever might find it useful below is a description of our implementation.

1) We already had, for another purpose, an implementation that sets variables (with variable \_set). The valiable name is a label and the variable value is a node id. Also we already had a very simple form which populates the variables. I guess a custom table could also be used. 2) We created nodes(which are translatable) for each help text we wanted to display help info. I added those ids, along with a label to the variables above. 3) In the share tools div of our pages, we added the info image and a div with the help text, which was by default hidden. With javascript, on click the help text is displayed. and Some code:

```
function _share_output() {
  global $theme;
  global $base_root;
  global $base_url;
  global $user;

  $output = '';
  $main_url = $base_root . request_uri();
  $path = $base_url . '/' . drupal_get_path('theme', $theme);
  $output = '<ul id="share" class="share_tools pull-right">';
  $output .= '<li>';
  if ($user->uid == NULL) {
    $title = drupal_get_title();
    $output .= '<a title="' . t('Email this to a friend.') . '" href="mailto:?subject=' . $title . '&body=' . $main_url . '" class="share-email"><img width="24" alt="' . t('Email this to a friend') . '" height="18" src="' . $path . '/images/email.png"/></a>';
    $output .= '  ';
    $output .= '<a title="' . t('Share on Twitter') . '" target="_blank" href="http://twitter.com/share?text=' . $title . '&url=' . $main_url . '" class="twitter-share-button" data-count="none"><img width="24" alt="' . t('Share on Twitter') . '" height="18" src="' . $path . '/images/tweet.png"/></a>';
    $output .= '  ';
    $output .= '<a title="' . t('Share on Facebook') . '" target="_blank" href="https://facebook.com/sharer.php?u=' . $main_url . '" class="facebook-share-button" data-count="none"><img width="24" alt="' . t('Share on Facebook') . '" height="18" src="' . $path . '/images/fb.png"/></a>';
  }
  // THIS is where we display the info image next to the other share images.
  $info_content = mymodule_blocks_info_content();
  if (!drupal_is_front_page() && !empty($info_content)) {
    $output .= '  ';
    $output .= '<a title="' . t('Info') . '" href="#" class="info_toggle"><img width="24" alt="' . t('Help') . '" height="20" src="' . $path . '/images/info.png"/></a>';
  }
  $output .= '</li>';
  // THIS is where we hide the info help text.
  $output .= '<li id="infobox_text" style="display:none">' . $info_content . '</li>';
  $output .= '</ul>';
  return $output;
}

function mymodule_blocks_info_content() {
  $info_content = "";
  $title = drupal_get_title();
  $menu_node = menu_get_object();
  $label = "";
  // Get the label to use, according to which page you are.
  if ($title == 'Search') {
    $label = 'search';
  }
  elseif (isset($menu_node) && is_object($menu_node) && $menu_node->type == 'MY_NODE_TYPE') {
    $label = 'MY_NODE_TYPE';
  }
  //and so on.........
   $info_content = load_info_by_label($label);
   return $info_content;
}

function load_info_by_label($label) {
  global $language;
  $user_language = 'en';
  $content = "";
  // Get the logged in user language.
  if ($language != NULL && !empty($language->language)) {
    $user_language = $language->language;
  };
  //Get the English(default) nid(which is found by the label in the custom table) body content.
  // The function below is a simple function that uses variable_get($label), to get the variable value.
  $content_en_nid = get_system_resource($label);
  if ($content_en_nid != null && !empty($content_en_nid)) {
    $nid = $content_en_nid;
    if ($user_language !== 'en') {
      // Get the tranlations.
      $node_translations = translation_node_get_translations($content_en_nid);
      // If thranslations exist and a translation exist for the user language, get that nid
      if ($node_translations != null && isset($node_translations) && !empty($node_translations) && array_key_exists($user_language, $node_translations)) {
        $nid = $node_translations[$user_language]->nid;
      }
    }
    // LOad te node and get the body value where the help text is stored.
    $node = node_load($nid);
    if ($node && isset($node)) {
      $content = $node->body[LANGUAGE_NONE][0]['value'];
    }
  }
  return $content;
}
//The javasctipt to show hide the help text.
$(".info_toggle").click(function(){
    $("#infobox_text").addClass('pull-right').toggle();
});

//Some CSS
#infobox_text {
    position: relative;
    float: right;
    right: -18px;
    background: #FF6600;
    color: #FFFFFF;
    -moz-border-radius: 6px;
    -webkit-border-radius: 6px;
    -khtml-border-radius: 6px;
    border-radius: 6px;
    width: auto;
    padding: 20px;
    z-index: 999;
    line-height: 20px;
    top: 4px;
}

#infobox_text:after {
    content: '';
    position: absolute;
    border-style: solid;
    border-width: 0 9px 14px;
    border-color: #FF6600 transparent;
    display: block;
    width: 0;
    z-index: 1;
    top: -14px;
    right: 19px;
    top: -11px;
}

.info_toggle {
    position:relative;
}
.info_toggle img {
    border-radius:50%;
    width:18px;
    height:auto;
}

```
> 0 votes

# Answer
It sounds as if https://drupal.org/project/popup may be suitable for for your needs.

You could create a block with various contexts (your translations / page) and then use this module to display the block (using sub module 'Popup Block') on each page when the user requests it, by rollover or click or whatever you choose.

The module is mature, widely used, has a recent version and has documentation provided.
> 0 votes

---
Tags: javascript
---


# Question
Title: How should i get corresponding field value for taxonomy filed attached?
I use drupal 7. I created a content type with these fields:

1. one field to upload a file to private folder
2. a taxonomy field (for that file)

**my problem:** i can save one file with one taxonomy! but how should i get these data again!(is there any API here) I want to know which taxonomy was saved for a certain file(i need to check it inside my custom module). i raised similar question here: so by following code i can get corresponding field:

```
$nids = db_query("SELECT nid FROM node WHERE title LIKE :title", array(':title' => '%'.$title.'%'))->fetchCol();

$nodes = node_load_multiple($nids);

foreach($nodes as $node) {

// using field_get_items here automatically loads the field in the correct language
$field_items = field_get_items('node', $node, 'field_subtitle');
$subtitle = $field_items[0]['safe_value'];
}

```

but it seems it dose not work taxonomy attached field.

**why do i have this question:** i sell some digital files and now i am developing a module for selling my files. *i want to sell them this way:* each file has a certain taxonomy. when my user buys that file he or she gets that taxonomy(and i will keep it in one table). once he clicks on download link i have to check whether that user has that taxonomy already or not! if he has i will let him to download it.

# Answer
You can see the relationship by viewing or editing the node.

If you mean where is this data stored in the DB then if you created a field called file\_type then the tid of the associated taxonomy term would be found in the field\_data\_field\_file\_type table.

The names of the taxonomy terms are stored in the taxonomy\_term\_data table.
> 0 votes

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


# Question
Title: Re-writing SQL statement in Drupal dynamic queries
I have the following SQL query, which I need to re-write using Drupal's dynamic query language. I'm new to Drupal development, could you please give me an example for the following SQL?

```
SELECT
    node.title,
    GROUP_CONCAT(field_data_field_location.field_location_value)
FROM
    node
    INNER JOIN field_data_field_location
        ON node.nid = field_data_field_location.entity_id
    INNER JOIN
        (SELECT DISTINCT
            entity_id
         FROM
            field_data_field_location
         WHERE
            field_location_value IN ('Berlin', 'Stuttgart')) AS IDS
        ON node.nid = IDS.entity_id
GROUP BY
    node.nid

```

---

What I currently have is the following:

```
$query = db_select('node', 'n');
$query->addField('n', 'title', 'title');
$query->groupBy('n.nid');

$subquery = db_select('field_data_field_location', 'loc');
$subquery->distinct();
$subquery->fields('loc.entity_id', array('eid'));
$subquery->condition('loc.field_location_value', $locations, 'IN');

$query->join('field_data_field_location', 'l', 'n.nid = l.entity_id');
$query->addExpression('GROUP_CONCAT(l.field_location_value)', 'locations');
$query->addJoin('INNER', $subquery, 'IDS', 'n.nid = IDS.entity_id');

$result = $query->execute();

return $result->fetchAll();

```

If I execute the code, I just get nothing back from Drupal. I think the problem is the subquery. Do you have any idea how I can solve that?

# Answer
Have you turned down the error\_level? because if you get nothing back from Drupal then this typically means the query executed successfully but that no results were found. Perhaps check the `Reports->Recent log messages` for any SQL errors logged instead. This information should help you troubleshoot future Drupal SQL endeavours.

Anyway, looking over the code, I don't think this is correct:

```
$subquery->fields('loc.entity_id', array('eid'));

```

and should probably be:

```
$subquery->fields('loc', array('entity_id'));

```

or if you want to give the field an alias, use addField:

```
$subquery->addfield('loc', 'entity_id', 'eid');

```

I've just run a similar query on a fresh database (so no custom fields) and set that fields() call correctly, and this seems to get results back:

```
$bundles = array("page", "blog");

$query = db_select('node', 'n');
$query->addField('n', 'title', 'title');
$query->groupBy('n.nid');

$subquery = db_select('field_data_body', 'data');
$subquery->distinct();
$subquery = $subquery->fields('data', array('entity_id'));
$subquery = $subquery->condition('data.bundle', $bundles, 'IN');

$query->join('field_revision_body', 'rev', 'n.nid = rev.entity_id');
$query->addExpression('GROUP_CONCAT(rev.bundle)', 'mybundles');
$query->addJoin('INNER', $subquery, 'IDS', 'n.nid = IDS.entity_id');

$result = $query->execute();

dpq($query); // Let's look at the query
dpm($result->fetchAll()); // Let's see all the results

```

Note, you'll need the devel module installed to use the dpm() and dpq() functions. Hope that can help!
> 0 votes

---
Tags: database
---


# Question
Title: Module has conditional Checkboxes, need to remove value
I am building a module that will have a bunch of checkboxes to enable the addition of metatags like HandheldFriendly, MobileOptimized, etc.

I want to have the first checkbox only displayed. Upon checking that item, other options should appear. (if itemA == checked, then show itemB) I actually have that working. The problem is that if you check itemA and then check itemB and save, but then uncheck itemA, when you return to the configuration page itemB will still have a value.

Here is a simple timeline showing the issue

Snapshot #1: itemA: unchecked itemB: unchecked (invisible)

Snapshot #2: itemA: checked itemB: unchecked (visible)

Snapshot #3: itemA: checked itemB: checked (visible)

Snapshot #4: itemA: unchecked itemB: checked (invisible) // PROBLEM

Between each snapshot, the form was saved. How can I automatically hide AND uncheck the value for itemB when clicking itemA so that when I re-enable itemA, itemB is still unchecked?

If I need to provide further clarification, I can.

module code for poetic\_toolkit.admin.inc file

# Answer
Add a secondary submit handler to run before the main one:

```
array_unshift($form['#submit'], 'poetic_toolkit_admin_submit');

```

Then in that:

```
function poetic_toolkit_admin_submit($form, &$form_state) {

    // check if field A is checked
    if(!$form_state['values']['poetic_toolkit_mobile_viewport_setting']) {
        // if it is not then set field B value to 0
        $form_state['values']['poetic_toolkit_enable_webapp_setting'] = 0;
    }

}

```

Then after this the main submit handler will fire and save our updated values.

This will only update the values once the form is saved.

Additionally, you don't want the `unchecked` condition on the depending item `poetic_toolkit_enable_webapp_setting`, because then it becomes checked whenever the dependent field `poetic_toolkit_mobile_viewport_setting` is checked (double negative). You also want to make sure you have the `#default_value` on the second item set, so that the user see's what is currently set (which will always be unchecked when the first is unchecked but could still be unchecked if the first is checked).

If you want B to become unchecked as soon as A is unchecked then you will need a jQuery solution.
> 0 votes

---
Tags: forms
---


# Question
Title: Use code to automatically fill the form of a content type
I have a content type called Event. I advertise events on my website using this form. I want to advertise automatically using code. I have this code which when I run automatically add content. But at the moment it adds the title and the body.

```
ini_set('display_errors','1');
ini_set('memory_limit', '512M');
define('DRUPAL_ROOT', getcwd());
include_once './includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);
module_load_include('inc', 'node', 'node.pages');
$node = new stdClass();
//print_r($node);
$title          =  "test post 3";// html_entity_decode($_POST['title']);
// $summary     =   "summarry";//$_POST['summary'];
$body           =  "This is testing of Automated Script";// $_POST['body'];
$node->uid      = '0'; //author
$node->type     = 'event';    //content type
// $node->created  = time() - (rand( 1,240) * 60);
$node->created  = strtotime("now");
$node->changed  = strtotime("now");
$node->field_location = 'Oxford';
$node->title    = $title;
$node->status   = 0;
$node->promote  = 0;
$node->sticky   = 0;
$node->language = 'und';
$node->body['und'][0]['value']   = $body;
// $node->body['und'][0]['summary'] = $summary;
$node->body['format']  = 'full_html';
node_submit($node);
node_save($node);
print "ok";

```

How do I add remaining inputs like City, Country, Event Date, Duration, Email Address using code?

# Answer
> 4 votes
You need to do something similar to what you do to set the body of the note for each of your additional field (City, Country, Event Date, Duration, Email Address). The exact data structure for each filed depends on its type.

The general pattern is

```
$node->{$field_machine_name}[$language][0] = array(...);

```

The *hard* part if figuring the content of the `array(...)` which is the value of the field. The value of a field is actually always an associative array. Its keys (also called columns) depend on the type of the field. A text field, for instance, as only one `value` key/column. A taxonomy term reference field has also only one key/column, but named `tid`.

For instance your city and duration field are a simple text fields whose machine names are `field_location` and `field_duration` you can set their values with

```
$node->field_location['und'][0] =  array('value' => 'Oxford');
$node->field_duration['und'][0] =  array('value' => '2');

```

You country field is a Taxonomy Term Reference field, its value can be set with

```
$node->field_country['und'][0] = array('tid' => 1);

```

Where `1` is the ID of a term in the proper taxonomy vocabulary.

If you were using an single address field name `field_location` to store the location, the code should be something like

```
$node->field_location['und'][0] = array(
  'country' => 'GB',
  'locality' =>  'Oxford',
);

```

The structure to set a date field depends on the date format. If the field uses the ISO format, you can set it with something like

```
$node->field_date['und'][0] =  array(
  // The start date.
  'value' => '2014-04-02T10:00:00',
  // The end date.
  'value2' => '2014-04-02T11:00:00',
);

```

To *discover* the structure of a field, I suggest to use the Devel module. It provides a *devel* tab on node that let you explore the structure of the `$node` object for an existing node. You can also check the `hook_field_schema()` implementation of the module defining the field type.

# Answer
> 2 votes
You can use the following code to add custom fields:

```
$node->field_city[$node->language][0]['value'] = 'London';
$node->field_county[$node->language][0]['value'] = 'England';

```

I find the easiest way to make sure you are using the correct structure is to create a node using the back-end UI, and then inspect it with the devel module. This will show you the correct field names to use.

Also not all fields use 'value'.

For example a taxonomy relation field would use:

```
$node->field_taxonomy_reference[$node->language][0]['tid'] = 189;

```

Or an entity reference field would use:

```
$node->field_entity_reference[$node->language][0]['target_id'] = 189;

```

For some other examples see these blog posts How to programmatically create node in drupal 7 or Creating and Updating Nodes Programmatically in Drupal 7.

---
Tags: forms, nodes
---


# Question
Title: Map subset of taxonomy terms to a content type
I have a taxonomy called Writer and I have the terms added to it. I would like to maintain both active and inactive terms in the vocabulary and use only the active terms when mapped to a content type. In other words I would like to soft delete the terms instead of hard-deleting them. For this I added a custom boolean field for Writer vocabulary to indicate if the term is active or not. I am now not sure on how to apply the conditional mapping of taxonomy terms to the content type.

Appreciate help on this.

# Answer
Achieved this using Taxonomy Publisher Filter which is part of Taxonomy Tools module
> 0 votes

---
Tags: taxonomy-terms
---


# Question
Title: Why isn't the page cal back needed in Ajax jQuery?
In the following code, I didn't set any page arguments, but I can still tse the parameter in `example_result()`. Why it works?

```
function example_menu() {
  $items['example-menu'] = array(
    'page callback' => 'example_result',
    'access arguments' => array('access content'),
    'type' => MENU_CALLBACK,
  );

  return $items;
}

function example_result($para) {
  $items = array('a', 'b', 'c');
  return drupal_json(array('values' => $items));
  exit;
}

```

# Answer
> 0 votes
That is explained in the examples shown for `hook_menu()`.

```
 function mymodule_menu() {
    $items['abc/def'] = array(
      'page callback' => 'mymodule_abc_view',
    );
    return $items;
  }

  function mymodule_abc_view($ghi = 0, $jkl = '') {
    // ...
  }

```

Using the code above, and accessing the page as `http://example.com/abc/def`, the page callback would get `0` and `''` as arguments; accessing the page as `http://example.com/abc/def/123/foo`, `$ghi` will be equal to `123`, while `$jkl` will be equal to `'foo'`.

That is the default behavior of Drupal.

You could also use wildcards arguments, but in that case those arguments should be passed in the URL.

---
Tags: 6, routes
---


# Question
Title: SMTP Authentication Support + Unable to send e-mail
I'm working on my localhost with a drupal project. I'd like to be able to send emails so I installed the SMTP Authentication Support module. Now I'm configuring it to send it with my gmail address but the test mail can't be send. I always get this error:

```
Unable to send e-mail. Contact the site administrator if the problem persists.

```

My Settings:

**SMTP Server**: smtp.gmail.com
**SMTP Port**: 465
**Use encrypted protocol**: no
**Username**: myusername@gmail.com (yes, this is correct in my settings)
**Password**: mypassword (yes, this is correct in my settings)
**E-mail from address**: myusername@gmail.com
**E-mail from name**: my username
**E-mail address to send a test e-mail to**: myotheremailaddress@hotmail.com

When I check the Enable Debugging checkbox I get this after trying:

```
SMTP -> FROM SERVER:
SMTP -> FROM SERVER:
SMTP -> ERROR: EHLO not accepted from server:
SMTP -> FROM SERVER:
SMTP -> ERROR: HELO not accepted from server:
SMTP -> ERROR: AUTH not accepted from server:
SMTP -> NOTICE: EOF caught while checking if connectedSMTP Error: Could not authenticate.

```

Am I doing something wrong?

I've also tried it with PHPMailer module with the same settings, same result ..

# Answer
Looks like Gmail needs SSL encryption, so I had to select that in the list of encryption, my bad!
> 1 votes

---
Tags: emails, users
---


title: How to make the pdf files downloadable?

text:
# Question
Title: How to make the pdf files downloadable?
I am able to display file with url: For example

```
echo '<a href="'.$file_url.'" target="_blank">'.$path_parts['basename'].'</a>';

```

How can I make this file downloadable? In case of pdf files, it is not downloading and opening in new tab as i have added target.

# Answer
If you want to Force download PDF files. **if your server is Apache**

put this line in your `.htaccess` file.

```
AddType application/octet-stream .pdf

```

If there is any issues with browser try this

```
SetEnvIf Request_URI "\.pdf$" requested_pdf=pdf
Header add Content-Disposition "attachment" env=requested_pdf

```

**If its NGINX**

```
location ~* /orig/(.+\.jpg)$ {
    internal;
    add_header Content-disposition "attachment; filename=$1";
}

```
> 4 votes

# Answer
In addition to doing it from apache's side via the httpd.conf or .htaccess with above answer ... You can do this with a module as well:

```
<?php
function mymodule_mimetype_override_file_mimetype_mapping_alter(&$mapping) {
  $new_mime_type = 'application/octet-stream'; //already in mimetypes so below array addition wont happen, but put here in case you want to add your own type

  if ( !in_array($new_mime_type, $mapping['mimetypes'])) {
    $mapping['mimetypes'][] = $new_mime_type; //mapping['mimetypes']['octetstream']
  }
  $index = array_search($new_mime_type, $mapping['mimetypes']);
  $mapping['extensions']['pdf'] = 15; //manually setting for now, could have used $index; //15 is octet-stream, 18 is pdf
}

//also added this for my HTTPS site since IE8 couldnt download/display any files if it doesn't have certain cache headers for ssl websites ... heh, booooooo
function mymodule_override_file_download($filepath) {
  header("Cache-Control: private, must-revalidate"); //may have to set Pragma too but not in my case
}

```
> 0 votes

---
Tags: theming, files
---


# Question
Title: How do I setup download links for pdf files directly?
I want to add a pdf file via a file field on a content type, I want to display a download link, and if the user clicks save it to your computer, as in a normal download.

# Answer
> 3 votes
Try the DownloadFile module. In your content type change the field display formatter to download file or whatever suits your need.

# Answer
> 0 votes
If you have access to it, placing the following snippet in your site's .htaccess file will force download in many recent browsers, but Clive is correct: this won't work for everybody (due to user preferences and also not all devices and browsers obey this setting). The following syntax is for apache on LINUX, you may have to tweak it for a windows environment. I wish I knew how to get this to work on iPhones (if anybody knows - do tell!). I'm sure there is a much more elegant way to cover upper and lower case file extensions (hey - I'm making this up as I go along ; )

```
<FilesMatch "\.(mov|mp3|jpg|pdf|MOV|MP3|JPG|PDF)$">
  ForceType application/octet-stream
  Header set Content-Disposition attachment
</FilesMatch>

```

# Answer
> 0 votes
Enable "File" module (it's provided by Drupal distr). Then go to content types (in Structure), add new content type or select on of exists.

After saving content type see "**manage fields**". Add new field (fill label and field name), select Type of this = **File**, click Save. Then in extensions fill PDF, and enter place of storing.

Now try create this content type, PDF file uploading will available and after saving you can see direct link to download it, if you don't see it, visit content type and check "**Manage display**" tab.

Taken from source https://stackoverflow.com/questions/7708452/how-do-i-setup-download-links-for-pdf-files

and also if you want to force the user to download only, then use this module File Force Download

> File Force Download can be used to force the user's web browser to download the file to disk instead of displaying it in the browser window.
>
> Web browsers today are pre-configured to render various types of media directly, such as text files, various image, video and audio formats, PDF documents, and Flash movies. While it is still possible to save such files afterwards by right-clicking on them and selecting "Save As..", it is sometimes desirable to just offer the file for download in the first place. File Force Download solves this issue by supplying a file with certain HTTP headers which instruct the web browser to download the file to the user's disk instead of displaying it in a browser window.

# Answer
> 0 votes
Note: i couldn't use File Force Download module since it only works off of fields... I had files uploaded with IMCE and I had regular links in content Body to those private files... So i had to use setting the header via apache's side via the httpd.conf or .htaccess with above answers ... You can do this with a module as well which is what I ended up going with:

```
<?php
function mymodule_mimetype_override_file_mimetype_mapping_alter(&$mapping) {
  $new_mime_type = 'application/octet-stream'; //already in mimetypes so below array addition wont happen, but put here in case you want to add your own type

  if ( !in_array($new_mime_type, $mapping['mimetypes'])) {
    $mapping['mimetypes'][] = $new_mime_type; //mapping['mimetypes']['octetstream']
  }
  $index = array_search($new_mime_type, $mapping['mimetypes']);
  $mapping['extensions']['pdf'] = 15; //manually setting for now, could have used $index; //15 is octet-stream, 18 is pdf
}

//also added this for my HTTPS site since IE8 couldnt download/display any files if it doesn't have certain cache headers for ssl websites ... heh, booooooo
function mymodule_override_file_download($filepath) {
  header("Cache-Control: private, must-revalidate"); //may have to set Pragma too but not in my case
}

```

---
Tags: navigation, files
---


# Question
Title: hook_install() doesn't seem to work, even though I have disabled and uninstalled module
I'm writing a module that will enable an editor to determine whether a script is available on a specific node, in order to improve page load times.

I need to create a database table to hold an indicator showing, for each node ID, whether the script is available. My code is this.

```
function script_show_schema() {
    $schema['script_show_enabled'] = array(
        'description' => 'Tracks whether Script Show is enabled for a given node',
        'fields' => array(
            'nid' => array(
                'description' => 'The {node}.nid that has Script Show enabled',
                'type' => 'int',
}               'not null' => TRUE,
                'default' => 0,
            ),
        ),
        'primary key' => array('nid'),
    );
    return $schema;
}

```

I've disabled, then uninstalled, then re-enabled my module through the admin UI, (as opposed to using Drush), but I still don't seem to be able to see my database tables.

I know this question has been asked a couple of times before, but usually the solution seems to be the uninstall thing.

Does anyone have any idea on what is going wrong? I wonder if it's a DB permissions thing. But then, I guess Drupal has root access to the DB in order to create its tables in the first place.

Updates:

I am using version 7.23 of the core.

Here's my .info file:

```
; $Id$
name = Script Show
description = "Allows the user to specify that the Maxymiser script will only execute on specific pages"
package = JD Dev Modules
core = 7.x
files[] = script_show.module

flag

```

My entire module is here: github.com/jamesdesq/script\_show.

# Answer
The code in your git repo is *not* the same as the code posted here. Both has syntax errors. See @ARUN's answer for the bug in the code posted here.

As for the code in the git repo, there are two lines of random junk in it (indicated with red striketroughs below), causing Drupal to crash before the table is created in the database.

Remove those two lines and try again.
> 0 votes

# Answer
I tried your code. There is one syntax error at line no:8 (one additional **}**). Remove that and try. It is working.

```
function script_show_schema() {
  $schema['script_show_enabled'] = array(
    'description' => 'Tracks whether Script Show is enabled for a given node',
    'fields' => array(
        'nid' => array(
            'description' => 'The {node}.nid that has Script Show enabled',
            'type' => 'int',
           'not null' => TRUE,
            'default' => 0,
        ),
    ),
    'primary key' => array('nid'),
  );
return $schema;
}

```
> 0 votes

---
Tags: database
---


# Question
Title: Get the value of a field of the taxonomy term referenced with an Entity Reference field
I have a taxonomy vocabulary "Partners", with boolean field `field_1`. When I create a user, I attach to it a term from the vocabulary "Partners" with an Entity Reference field. Is there a way to get the value of the `field_1` field of that term and to bind it to the user?

(In the first case I need this value to limit the access to a page created by Page Manager to the users whose partners has the `field_1` field filled with the value `1`. I suppose I need the field value also for other cases later.)

The relation of the user and the partner could be made in another way, too, if it will be easier, more intuitive or more practical.

# Answer
> 0 votes
The user is already associated with the boolean field via the taxonomy term.

For example, load your user's account:

```
global $user;
$account = user_load($user->uid);

```

Now load your taxonomy term:

```
$partner = taxonomy_term_load($account->taxonomy_field_name[LANGUAGE_NONE][0]['tid']);

```

And then get the boolean value of field\_1:

```
$boolean_value = $partner->field_1[LANGUAGE_NONE][0]['value'];

```

---
Tags: users, entities, chaos-tool-suite
---


# Question
Title: Views: show nodes that share taxonomy term with user
I have a content type `requests` with the taxonomy field `categories`. I have added `categories` to my user's profile as well.

I need to create a view that displays all the requests that have category terms the user has selected in their profile. How do I go about this?

# Answer
> 0 votes
1. Create a view showing requests.
2. Add a contextual filter for Field: Category.
3. When the filter value is NOT in the URL choose "Provide default value" of type PHP.
4. In the "PHP contextual filter code" write:

---

```
global $user;
$account = user_load($user->uid);
return $account->field_category['und'][0]['tid']; // this line may need changing based on your category field name

```

---
Tags: 7, users, views
---


title: entity export not serializing node

text:
# Question
Title: entity export not serializing node
I am trying to use entity export to move existing entitys from a live to dev site. I tried the code below and it returned

```
NULL int(1)
```
However, when I did a dump of the $node object, it did dump the object correctly, so I know that the entity exists
```
$query = new EntityFieldQuery();
$query
  ->entityCondition('entity_type', 'node')
  ->entityCondition('bundle', 'events')
  ->propertyCondition('status', 1)
  ->propertyOrderBy('created', 'DESC');
$result = $query->execute();

$nids = array_keys($result['node']);
//var_dump($nids, 1);
$node = node_load($nids[0]);
var_dump($node,1);

//dpm(entity_get_info());
$entity  = entity_export('node', $node);
var_dump($entity,1);
```

# Answer
The entity\_export function comes with the following caveat:

> Note: Currently, this only works for entity types provided with the entity CRUD API.

This means that if your entity type does not come with this, a call to `entity_export()` will return `NULL`.

This seems to be the case with `node`.

I am not sure, but I *think* the core team never got around to adding CRUD API to core entities.

If you inspect a node entity with `dpm()`, there is nothing. If you do:

```
 debug($node->delete, 'node->delete');

```

it prints NULL.
> 0 votes

---
Tags: entities, importing-exporting
---


# Question
Title: Insert a collapsible fieldset or region in a panels layout
I created a custom layout for a panels display and I would like to have a region or multiple regions in my custom layout be collapsible with javascript/jquery. Ideally the state of the collapible region would also be remembered by a cookie, but first thing is the collapsible functionality. Can anyone help?

```
<fieldset class="collapsible collapsed">
<legend>
Title of fieldset goes here.
</legend>
<p>
Content goes here.
</p>
</fieldset>

```

# Answer
The best I've come up with so far is a custom module's hook\_form\_alter to create a fieldset and move fields in. Note that in order to avoid something like:

```
Notice: Undefined index: field_txt_student_id in ctools_entity_form_field_content_type_render() (line 96 of [...]/sites/all/modules/contrib/ctools/plugins/content_types/form/entity_form_field.inc).

```

because the field is moved and unset(), it is not known by ctools to have been moved (or something). Its render function does basic data sanity checking but then goes with the assumption that this field still exists by name where it was before the alter.

To get around that, instead of unset()'ing the original field, set it to a non-kind-of-field per this thread.

```
//  unset($form[$fieldname]);
$form[$fieldname] = array('#language' => NULL);

```

Would love to hear what other solutions exist! I spilled my "solutions that don't work" in a comment on your original question.
> 0 votes

---
Tags: javascript, display-suite, theming
---


# Question
Title: An AJAX HTTP request terminated abnormally
I am running a large script using `batch api`. I am sending newsletter mails to users. Mail sending is in bulk. I mean the mails is going to 8000 users. For testing I sent it to 1000 users and it worked fine. But for 8000 users it showing me this error :

```
An AJAX HTTP request terminated abnormally. Debugging information follows. Path: /batch?id=34485&op=do StatusText: ResponseText: ReadyState: 4

```

Or is there any other way to do the same? Following my code :

```
<?php
function testingmail() {
    $batch = array(
        'title' => t('Sending Mail...'),
        'operations' => array(),
        'init_message' => t('Connecting'),
        'progress_message' => t('Processed @current out of @total.'),
        'error_message' => t('An error occurred during processing'),
        'finished' => 'skeleton_batch_finished',
        'progressive' => FALSE
    );
    $result = db_select('customsendemail', 'c')->fields('c')->execute();
    $userslist = array();
    while($users = $result->fetchAssoc()) {
        $userslist[] = $users;
    }
    for($i=0;$i<count($userslist);$i++) {
        $userslist[$i]['user'] = explode(",", $userslist[$i]['user']);
    }
    $finallist = array();
    foreach($userslist as $value) {
        foreach($value['user'] as $key => $value2) {
            $finallist[] = array('mail' => $value2, 'subject' => $value['subject'], 'message' => $value['body']);
        }
    }
    foreach ($finallist as $userdetail) {
        $batch['operations'][] = array('skeleton_batch_worker', array($userdetail));
      }
    batch_set($batch);
    batch_process('<front>');
}

function skeleton_batch_worker($userdetail, &$context) {
  if(!isset($context['results']['processed'])) {
    $context['results']['processed'] = 0;
  }
  $context['results']['processed']++;
  $context['message'] = 'Sending Mail to '.$userdetail['mail'].' and subject '.$userdetail['subject'];
  $params['subject'] = $userdetail['subject'];
  $params['body'] = $userdetail['message'];
  drupal_mail('custom', 'mynewsletter', $userdetail['mail'], language_default(), $params, 'my@email.com', TRUE);
}

function skeleton_batch_finished($success, $results, $operations) {
  if ($success) {
    db_delete('customsendemail')->execute();
    $message = format_plural($results['processed'], 'One email sent.', '@count email sent.');
    variable_del("customnewsletter");
    watchdog("Custom Newsletter", "Custom Newsletter end.");
  }
  else {
    $message = 'Somer error in newsletter sending.';
    variable_del("customnewsletter");
    drupal_mail('custom', 'mynewsletter', 'my@email.com', language_default(), array('subject'=>'error in newsletter sending', 'message'=>'sending error'), 'my@email.com', TRUE);
  }
  drupal_set_message($message);
}

```

# Answer
I have setup a cron job that sending mail to 500 users in every half hour.
> 0 votes

# Answer
You are probably exceeding PHP's max\_execution\_time. You can probably change that with ini\_set().
> 0 votes

---
Tags: 7, batch-operations
---


# Question
Title: How and where would I be able to enable/disable gzip compression?
In Drupal 7 where would I be able to enable/disable gzip compression? Is there a module for this functionality?

# Answer
Personally, I do not like the way Drupal handles output compression; I take care of this outside of Drupal.

On the Drupal site, I add

```
$conf['page_compression'] = FALSE;
$conf['css_gzip_compression'] = FALSE;
$conf['js_gzip_compression'] = FALSE;

```

to settings.php, and this to a custom module to show that this is disabled:

```
/**
 * Implements hook_form_FORM_ID_alter().
 */
function MYMODULE_form_system_performance_settings_alter(&$form, $form_state) {
  $form['bandwidth_optimization']['page_compression']['#default_value'] = 0;
  $form['bandwidth_optimization']['page_compression']['#disabled'] = TRUE;
  $form['bandwidth_optimization']['page_compression']['#description'] = t('Handled by Apache.');
}

```

This is to also prevent accidental double output compression, which can be very hard to diagnose if you don't know about the symptoms.

Then, in my Apache config, I do

```
<IfModule mod_deflate.c>

  # Force deflate for mangled headers developer.yahoo.com/blogs/ydn/posts/2010/12/pushing-beyond-gzipping/
  <IfModule mod_setenvif.c>
    <IfModule mod_headers.c>
      SetEnvIfNoCase ^(Accept-EncodXng|X-cept-Encoding|X{15}|~{15}|-{15})$ ^((gzip|deflate)\s*,?\s*)+|[X~-]{4,13}$ HAVE_Accept-Encoding
      RequestHeader append Accept-Encoding "gzip,deflate" env=HAVE_Accept-Encoding
    </IfModule>
  </IfModule>

  # HTML, TXT, CSS, JavaScript, JSON, XML, HTC:
  <IfModule filter_module>
    FilterDeclare   COMPRESS
    FilterProvider  COMPRESS  DEFLATE resp=Content-Type $text/html
    FilterProvider  COMPRESS  DEFLATE resp=Content-Type $text/css
    FilterProvider  COMPRESS  DEFLATE resp=Content-Type $text/plain
    FilterProvider  COMPRESS  DEFLATE resp=Content-Type $text/xml
    FilterProvider  COMPRESS  DEFLATE resp=Content-Type $text/x-component
    FilterProvider  COMPRESS  DEFLATE resp=Content-Type $application/javascript
    FilterProvider  COMPRESS  DEFLATE resp=Content-Type $application/json
    FilterProvider  COMPRESS  DEFLATE resp=Content-Type $application/xml
    FilterProvider  COMPRESS  DEFLATE resp=Content-Type $application/xhtml+xml
    FilterProvider  COMPRESS  DEFLATE resp=Content-Type $application/rss+xml
    FilterProvider  COMPRESS  DEFLATE resp=Content-Type $application/atom+xml
    FilterProvider  COMPRESS  DEFLATE resp=Content-Type $application/vnd.ms-fontobject
    FilterProvider  COMPRESS  DEFLATE resp=Content-Type $image/svg+xml
    FilterProvider  COMPRESS  DEFLATE resp=Content-Type $image/x-icon
    FilterProvider  COMPRESS  DEFLATE resp=Content-Type $application/x-font-ttf
    FilterProvider  COMPRESS  DEFLATE resp=Content-Type $font/opentype
    FilterChain     COMPRESS
    FilterProtocol  COMPRESS  DEFLATE change=yes;byteranges=no
  </IfModule>

  <IfModule !mod_filter.c>
    # Legacy versions of Apache
    AddOutputFilterByType DEFLATE text/html text/plain text/css application/json
    AddOutputFilterByType DEFLATE application/javascript
    AddOutputFilterByType DEFLATE text/xml application/xml text/x-component
    AddOutputFilterByType DEFLATE application/xhtml+xml application/rss+xml application/atom+xml
    AddOutputFilterByType DEFLATE image/x-icon image/svg+xml application/vnd.ms-fontobject application/x-font-ttf font/opentype
  </IfModule>

</IfModule>

```

This lets Apache do the output compression by MIME type, and also make sure all text based output gets compressed. This is adapted from an older version of the HTML5 Boilerplate project's .htaccess file, which now lives in a separate project. I also add in their directives for cache control, and a few other things. I keep all of this in an individual file, that I then `Include` in my virtual hosts.

The downside of this is that the server compresses each request, but it works well for my sites and my clients.
> 11 votes

---
Tags: 7, performance
---


# Question
Title: How to disable Rich Text Editor in image field caption ?
I am using Image Field Caption module. It provide a image caption field but I don't want any rich text editor appearing for the caption field. How to disable that for any specific field?

# Answer
You used to be able to configure CKEditor to appear on a per-textfield basis, but apparently that's no longer possible in the 7.x-1.x versions of the CKEditor module.

The following issue offers a JS workaround:

https://drupal.org/comment/5601364#comment-5601364
> 0 votes

---
Tags: forms, media
---


# Question
Title: Drupal Feature Recreate Module - what next
I am newer to drupal features. I have a site that was built heavily with them.

There is a drupal-feature where I added some fields. After I added and reorganized them I recreated the module.

Do I need to uninstall the current drupal feature module then install the new one? Or can I just add the new module turn it on and go from there?

Thanks for the help!

# Answer
From Modifying, updating and reverting Features:

> The "recreate" button in the web-based administration interface is the equivalent to "update". However, the modified code will be provided for download as a .tar archive, instead of overwriting the existing feature module. It is up to the site builder to manually unzip and re-upload the modified module, replacing the original.
> 0 votes

---
Tags: features
---