# Question
Title: Conditional class on <html> element a la boilerplate
This might be a totally mundane question, but I hope not.

I want to add conditional classes onto the `<html>` element of my theme like boilerplate. I'd like to keep things neat and not complicate my page.tpl.php.

```
<?php
  $htmlvar = 'xmlns="http://www.w3.org/1999/xhtml" xml:lang="' .
    $language->language . '" lang="' .
    $language->language . '" dir="'. $language->dir .'"';
?>

<!--[if lt IE 7 ]> <html class="ie6" <?php print $htmlvar ?>> <![endif]-->
<!--[if IE 7 ]>    <html class="ie7" <?php print $htmlvar ?>> <![endif]-->
<!--[if IE 8 ]>    <html class="ie8" <?php print $htmlvar ?>> <![endif]-->
<!--[if (gte IE 9)|!(IE)]><!--> <html <?php print $htmlvar ?>> <!--<![endif]-->

```

Reactions? Suggestions? Taunts?

# Answer
There isn't really a great way to do this: Drupal 7 modified `drupal_add_css()` to make adding conditional CSS possible outside the template file, but not for arbitrary HTML. Drupal 6 doesn't have anything.

In Drupal 6, and for arbitrary conditional HTML, you either need to add the markup directly to `page.tpl.php`, or you could create a variable in your theme's implementation of `template_preprocess_page()` that contains the relevant markup as a string:

### Drupal 7

```
function foo_preprocess_html(&$variables) {
  $htmlvar = 'xmlns="http://www.w3.org/1999/xhtml" xml:lang="' .
    $variables['language']->language . '" lang="' .
    $variables['language']->language . '" dir="'. $language->dir .'"';

  $variables['conditional_html'] = '<!--[if lt IE 7 ]> <html class="ie6"' . $htmlvar . '> <![endif]-->';
  // Concactenate the rest of the conditional HTML here
}

```

Then add `$condtional_html` to the appropriate place in `html.tpl.php`.

### Drupal 6

```
function foo_preprocess_page(&$variables) {
  $htmlvar = 'xmlns="http://www.w3.org/1999/xhtml" xml:lang="' .
    $variables['language']->language . '" lang="' .
    $variables['language']->language . '" dir="'. $language->dir .'"';

  $variables['conditional_html'] = '<!--[if lt IE 7 ]> <html class="ie6"' . $htmlvar . '> <![endif]-->';
  // Concactenate the rest of the conditional HTML here
}

```

Then add `$condtional_html` to the appropriate place in `page.tpl.php`.

---

If you're interested in Drupal 7's conditional CSS handling, you can see Bartik's implementation of `template_preprocess_html()` for an example:

```
function bartik_preprocess_html(&$variables) {
  // ...

  // Add conditional stylesheets for IE
  drupal_add_css(path_to_theme() . '/css/ie.css', array('group' => CSS_THEME, 'browsers' => array('IE' => 'lte IE 7', '!IE' => FALSE), 'preprocess' => FALSE));
  drupal_add_css(path_to_theme() . '/css/ie6.css', array('group' => CSS_THEME, 'browsers' => array('IE' => 'IE 6', '!IE' => FALSE), 'preprocess' => FALSE));
}

```
> 2 votes

# Answer
Drupal 7's Zentropy base theme does this, here is a live demo: http://d7.webdrop.net.br/

That said, and since I'm the theme's lone maintainer, I wouldn't use it as all development efforts have gone towards a Drupal 6 backport, available on here on github. And also, this functionality was eventually removed from the D6 backport.
> 2 votes

# Answer
Browser class module is the way to go here:

http://drupal.org/project/browserclass

Example :

```
<body class="... chrome chrome11 mac desktop">
...
</body>

```

### Supported browsers

ie, opera, safari, chrome, netscape, ff, konqueror, dillo, chimera, beonex, aweb, amaya, icab, lynx, galeon, operamini

### Browser version checking

The module creates version classes.

ie\[version\], opera\[version\], chrome\[version\], safari\[version\], netscape\[version\], ff\[version\], konqueror\[version\], operamini\[version\]

### Supported platforms

win, ipad, ipod, iphone, mac, android, linux, nokia, blackberry, NetBSD, FreeBSD, OpenBSD

### Mobile detecting

The module checks if the device is mobile and adds "mobile" or "desktop" class.
> 1 votes

---
Tags: theming
---


# Question
Title: Redirect users on first time login to a particular page
In my drupal 7 website when a user registers, an email is sent to them. And when they click on the verification link in the email they are redirected to "SITENAME/user" page. I wanna change that. I want the user to be redirected to another page say "SITENAME/upload" page. I have used the user registration password module. The email sent to the user is

```
[user:name],

Thank you for registering at [site:name]. You may now log in and verify your account by clicking this link or copying and pasting it to your browser:

[user:registrationpassword-url]

This link can only be used once. You will be able to log in at [site:login-url] in the future using:

username: [user:name]
password: Your password

--  [site:name] team

```

I think I have to change the \[user:registrationpassword-url\] part. But Im not sure what to change that to.

Thanks

# Answer
> 1 votes
you don't need to change the url in the email, becase user need to click it to visit the page, but You can use the Rules module to do that "https://www.drupal.org/project/rules". after verifying the user redirect them to the Upload page. Also here is a great video tutorial : https://drupalize.me/videos/overview-actions-conditions-and-events?p=1157 for how to use Rules module if you didn't use it before.

# Answer
> 1 votes
This is actually very simple in D7 using the Rules module. All you have to do is see if the value of the user's Last Access field is empty. When an account is created, the initial value of the Last Access is empty.

The value of this field is not set until sometime AFTER the rules have been run. So, all you have to do is setup a conditions in rules that check:

```
Data value is empty
site:current-user:last-access

```

Here is an export of my rule and it has been working fine. If anyone finds any issues, please let me know. You should be able to import this rule into your site.

{ "rules\_first\_time\_login" : {
"LABEL" : "first time login",
"PLUGIN" : "reaction rule",
"WEIGHT" : "1",
"OWNER" : "rules",
"REQUIRES" : \[ "rules" \],
"ON" : { "user\_login" : \[\] },
"IF" : \[
{ "data\_is\_empty" : { "data" : \[ "site:current-user:last-access" \] } },
{ "user\_has\_role" : { "account" : \[ "account" \], "roles" : { "value" : { "16" : "16" } } } }
\],
"DO" : \[
{ "drupal\_message" : { "message" : "Welcome to Drupal Camp Florida. Please submit your session proposal below." } },
{ "redirect" : { "url" : "node/add/sess?destination=/admin/dashboard" } }
\]
}
}

The role with a value of "16" is a role of "Speaker".

# Answer
> 0 votes
A quick google search offered these modules:
Login Destination
Login Redirect

---
Tags: emails, redirection, users
---


# Question
Title: How to create a select list of which the selected item is used as parameter in VBO rules component?
It's a common scenario, but I couldn't find a solution yet:

I have a view (a list of tasks) with checkboxes (views bulk operations)

I want: 1) a dropdown select list of taxonomy terms 'Priority' above the view. 2) a rules component that uses the selected taxonomy term, as parameter for applying the priority to the selected tasks.

# Answer
VBO uses the core 'actions'. You can create new actions with hook\_action\_info.

The https://www.drupal.org/project/examples module has a good action example.
> 0 votes

# Answer
You could probably do this without creating a custom module if you were willing to choose the taxonomy on a second screen.

The Rules module allows you to create custom Actions in `admin/config/workflow/rules/components`.

Click 'create new component', give it a useful, descriptive name and continue. Under actions click 'new action' and choose 'set a data value'. Choose the relevant field, and click save and continue until you are back at the main components screen.

You can now use your new component with VBO in your view.
> 0 votes

---
Tags: rules, views
---


title: How does Drupal Cron effect Page Cache?

text:
# Question
Title: How does Drupal Cron effect Page Cache?
I'm trying to figure out how Drupal's cron effects the page cache of my site. It would be nice to store as many pages in the cache table as possible so that when requests are made they are being served from the page cache!

However I am getting conflicting answers on the effect of Drupal's cron job on the cache!

This link says that "each cron run clears the cache for all pages":

http://tomroelandts.com/articles/how-to-ensure-that-visitors-always-see-cached-pages-in-drupal-7

as well as -\> drupal.org/node/1576686

But this guy, says it only clears caches that can be expired:

https://www.drupal.org/node/1691116#comment-6352756

Would love to get a definitive answer on this!

# Answer
System module's system\_cron() clears **expirable** entries from cache tables. An expirable cache entry is one that is beyond its "can expire" date, or it's an entry that was initially saved with the CACHE\_TEMPORARY flag.

Assuming you're using the default database cache, you can see which entries are expirable by looking in a cache table. The "expire" column contains the timestamp at which an entry becomes expirable. If the value is "-1", it's CACHE\_TEMPORARY and always expirable.

As far as Drupal's default database page cache goes, the "expire" column won't tell you much, since the minimum cache lifetime is not applied to the expire value. Instead, Drupal keeps track of the last time the entire cache was flushed, and will not flush the page cache again until at least "minimum cache lifetime" seconds have passed.
> 6 votes

# Answer
The page cache is cleared on cron every time if the minimum cache lifetime is set at the default of none. If the minimum cache lifetime is set, cron deletes all cache entries no more than once per the minimum cache lifetime setting.

Inside of drupal\_page\_set\_cache() you can see that `'expire' => CACHE_TEMPORARY,`.

With the core database cache, it ignores the minimum cache lifetime on clears. When you look at the code in DrupalDatabaseCache::clear; there is zero code in there that has to do with when the cache was created; thus the minimum cache lifetime is not enforced. Inside of system\_cron one of the caches that gets cleared is cache\_page.

If you wish to change this you can change how often system\_cron runs; elysia cron is a good way to do this. But be aware that any node save from the GUI will also clear the page cache as well; see node\_form\_submit, at the bottom it will clear the page cache. Same is true for any comments saved, see comment\_form\_submit().

The best solution is to change how the page cache works. Have it respect the minimum cache lifetime. There are 2 modules that enforce this:
https://www.drupal.org/project/apdqc Asynchronous Prefetch Database Query Cache
https://www.drupal.org/project/adbc Alternative Database Cache
ADBC was created to make the minimum cache lifetime more useable & is database agnostic. APDQC has all of ADBC in it but it also gets rid of deadlock and metadata lock issues when using MySQL as well as speeding up cache get and set calls; only works with MySQL. If you're using MySQL I would recommend using APDQC; if you're using a different database then ADBC is the way to go.

Once the minimum is enforced you do need a way to update that cached page if it was actually updated. The Cache Expiration module can do this for you.

D7 issue: https://www.drupal.org/node/891600
> 5 votes

---
Tags: caching, 7, cron
---


# Question
Title: Creating comments and nodes with Services 3.x and JSON
I'm having trouble getting services to recognize a POST to /comment.json. I have a similar issue with creating nodes as well.

The following is the error I get: HTTP/1.1 406 Not Acceptable: Missing required argument comment

This message comes from the file: /services/server/rest\_server/includes/RESTServer.inc Specifically, the lines:

```
  elseif (!isset($info['optional']) || !$info['optional']) {
    return services_error(t('Missing required argument !arg', array(
      '!arg' => $info['name'],
    )), 406);
  }

```

basically, it seems to think the "comment" argument is missing (and it's not optional).

This is one of many bits of JSON I've given it (posting a comment to node 8801)

```
{name:"test",language:"und",cid:"0",pid:"0",uid:"17593",nid:"8801",
comment:{subject:"Subject of the comment, if not entered it will be auto-generated",
comment_body:
{und:[
[{value:"value of the field comment in the comment, remember that in D7 we can create fields for comments too", format: "full_html"}]
]}}}

```

It's perfectly valid (based on other online JSON checks). It also matches what I see in the services test examples at /services/test/functional/ServivesResourceCommentTests.test

however, I always get the same error message. This seems similar to: Drupal 7 services json node object

which is also unresolved. Can someone help me with the proper JSON formatting? Really, all I want to do is pass it something like:

```
{ nid : 8081 , uid : 17593 ,comment:{comment_body:"test",subject:"test"}}

```

my http headers seem ok and user/login worked fine.

# Answer
The following JSON appears to be the minimum you need to post a comment:

```
{
  "nid":"1",
  "subject":"Comment Subject Text",
  "comment_body":{
    "und":[{
      "value":"Comment body text"
    }]
  }
}

```

Since there is no user, commenting on this "example.com/node/1" needs to be turned on and permissions for anonymous users to post comments need to be set.
> 5 votes

# Answer
Turns out I was trying to create nodes/comments without authentication, and the site didn't allow anonymous users to create nodes/comments. Once I turned on session auth, logged in properly, things worked fine.
> 2 votes

# Answer
Can you tell me to what URL you would post this json string. I've been looking all over the web for some documentation how to create a comment on a node using services 3. The documentation on this module is completely lacking. I've tried posting to:

example.com/api/node/{nid}/comments.json

example.com/api/comment.json

example.com/api/comment/create.json

Nothing seems to work. I always get "404 Not Found : Could not find controller"

**EDIT:** as soon as I posted this I got it to work. If it will help anyone else you post your json string to:

**example.com/api/comment.json**

If you're using Poster to test be sure to set the content type to application/json. When using jquery make sure you set dataType: 'json'.
> 2 votes

# Answer
Here are some examples to create and update nodes and comments in the following format:

* HTTP method
* ContentType
* URL Path
* Data to Send

# Node Create

* **POST**
* ContentType: *application/json*
* **?q=endpoint/node.json**

{"type":"article","title":"t8yZUfX2it","language":"und"}

# Node Update

* **PUT**
* ContentType: *application/json*
* **?q=endpoint/node/123.json**

{"node":{"nid":"123","title":"9AjrXJhWMI","language":"und"}}

# Comment Create

* **POST**
* ContentType: *application/json*
* **?q=endpoint/comment.json**

{"subject":"liJmJfpqMX", "comment\_body":{"und":\[{"value":"9DyaNZi3lA"}\]}, "nid":"18"}

# Comment Update

* **PUT**
* ContentType: *application/x-www-form-urlencoded*
* **?q=endpoint/comment/456.json**

{ cid: 456, "subject":"hzU27R6daE", "comment\_body":{"und":\[{"value":"BqZU5DwArD"}\]}, "nid":"18"}
> 2 votes

# Answer
I was getting similar problems even when just testing with the firefox plugin poster. It turns out that it was quite simply the extra whitespaces and some other simple formatting (such as escapes) that was doing it. Here is a list of what works in my own tests for what I needed:

CREATE USER WORKS = endpoint/user

```
{"name":"myusername","pass":"12345678","mail":"myemail@example.com","status":"1"}

```

LOGIN WORKS = endpoint/user/login

```
{"username":"admin","password":"admin"}

```

CREATE FILE WORKS = endpoint/file

```
{"uid":"1","filesize":"99999","filename":"whatever.bin","file":"BASE64_ENCODED_DATA"}

```

CREATE NODE WORKS = endpoint/node

```
{"title":"testrest1","type":"dl","field_dl_file":{"und":[{"fid":582}]},"uid":"1","language":"und"}

```
> 1 votes

---
Tags: 7, services
---


title: Google docs style drupal site

text:
# Question
Title: Google docs style drupal site
Ive been searching around drupal and google to find some awnsers but get lost and fustrated and came here for some help.

What i want to do is have a drupal site which is not public, and has the functionality of google docs, calendar and drive...yes i know i could just use what google have already made but im a little paranoid in this world and would like to have TOTAL control over my documents as this will also be on a dedicated server.

So are there modules/ways out there where i can upload/download + edit text documents and spreadsheets? I know i could use a WYSIWYG but could i then download the page/node as a .doc file for example?

Sorry if it doesnt make much sense, Many Thanks in Advance Russel

# Answer
An all in one solution I think is hard to find/make for drupal.
There's a module, where you can import and edit spreadsheets. I've testet it briefly for a project, that never go further than prototyping, but the module simply worked: http://drupal.org/project/sheetnode

There might be similar projects for word processors. Or you might have it made :)

For a Google drive alternative, where you are in control, have a look at http://owncloud.org. They have calendar, contacts, and many other things, but I don't think they have editors.
> 2 votes

# Answer
Original .doc specification is proprietary, so you need to be big enough company if you want to deal with Microsoft about it. To my best knowledge there are no free, drupal-based clones of Google Docs, Open Office or any other office suite. OpenOffice's source code is about 250MB compressed. Drupal's is around 3.5MB compressed... That should show amount of work ratio nicely.
> 1 votes

# Answer
Not sure if you found a solution. You might be interested in depdocs.com. It's a document management Drupal system that does what you are looking for. It's not as flexible as Google docs but it will get you a long way.
> 1 votes

# Answer
For online document editing, you could integrate Firepad into Drupal. That won't give you the full Office-style document suite, however, and it stores data using firebase.com - paid service, now free for small traffic but this may change in future.

Alfresco appears to offer something more like what you are after as an addon but of course Alfresco isn't Drupal.
> 0 votes

---
Tags: 7
---


# Question
Title: Is it possible to exclude module settings when migrating database?
Our dev server is on an internal network that is not connected to the WWW. As such, I have the Google Analytics module turned off on the dev server, because it really slows down page loads when enabled, since it can't reach the Google servers. Occasionally, when I migrate site changes up to the production server, I will forget to enable the module on the live site. It gets disabled because it's disabled on dev. Is there a way to exclude module settings from a database backup? (We're using the Backup and Migrate module.)

# Answer
> 0 votes
It probably is possible, but not with Backup and Migrate. BaM only enables you to exclude whole tables, and enabled / disabled status is a row.

Worse, your devel environment contains different set of scripts than production one. This may have various side effects, bugs you will only see after migrating your changes to production. That's exactly what you want to *avoid*, so consider other options:

1. Test site in environment that can connect to WWW, either by switching your dev server, or by creating dev/staging machine connected to www-enabled testers' workstations. In this latter case, you will catch if you forgot to enable something.
2. Store GA JavaScripts on some local place, and use hosts file or local DNS to fake traffic. It would be pretty safe to just make needed JS files available, I nothing changed recently you don't need to care about actually doing anything with data GA is trying to send to Google.

# Answer
> 0 votes
Good question. Have a look at the \[environment project. It's drush with a php snippet that provides actions based on environment.

---
Tags: 7, backups
---


# Question
Title: How to drop tables shown as Missing in Schema Report
During development/testing after using Backup and Migrate Restore in conjuction with Schema, Schema will show Extra tables no longer referenced in the database, used by modulesetc, and no longer required.

How can these tables be removed with a module or within drupal with api/php? Can a form be created to specify select tables to drop?

# Answer
> 1 votes
Check out the db\_drop\_table function.

You could use it on the `mysite.com/devel/php` page which runs arbitrary php for you, but be ultra careful with it and always have backups, because if you get it wrong you could completely kill your site.

---
Tags: debugging, database
---


# Question
Title: Taxonomy term not localized correctly in multilingual site in Drupal 7
I am having multilingual site in drupal 7. I have a content type that should be translated in 2 languages, I am using **term reference** field in it, with display type **select list**

First I tested
**Localize. Terms are common for all languages, but their name and description may be localized.** and
**Translate. Different terms will be allowed for each language and they can be translated**
But in any language, all terms from all languages are shown in the select list,
Then I decided to use
**Fixed Language. Terms will have a global language and they will only show up for pages in that language.**
and use separate vocabulary per language but when I want add a node in second language or translate english nodes in second language(persian) show the first language (english) terms only.
How can I achieve this job ? I want to show terms only from current language.

**Edit** again I came back to using one vocabulary and I have this problem
and my vocab and translations

and when I am in english site show perisan terms :(

**why does this happen? and what is the solution ?**

# Answer
> 2 votes
I had the same problem. I enabled 'Synchronize translations' (i18n\_sync) module. This solved it. It is bundled with i18n module.

https://www.drupal.org/project/i18n

# Answer
> 0 votes
If I understand you correctly - 1. Multilingual site (3 languages) 2. Taxononomy Goal - when in language 1, show taxonomy terms in language 1. When in language 2, show taxonomy terms in language 2.

I think it is Check Translate. Different terms.... When you enter a new taxonomy term, you will need to put it in three times using the translate button that appears next to edit when you display the taxonomy term.

When the user chooses a language, then the correct taxonomy terms should appear.

I hope this step-by-step helps you see the structure.

# Answer
> 0 votes
A bit old question but i just came across because i had the same problem. Selecting "Translate. Different terms will be allowed for each language and they can be translated." when you create your vocabulary seems the right option BUT IS NOT!

You have to select "Localize. Terms are common for all languages, but their name and description may be localized." to your vocabulary settings. Then when you add a new term (e.g. in English) you have to select "Save and Translate" at the end of the form.

That worked for me :)

# Answer
> 0 votes
You can try using the Entity translation module with the Title module instead of taxonomy translation (i18n\_taxonomy).

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


title: Select All checkbox and sub fieldgroups

text:
# Question
Title: Select All checkbox and sub fieldgroups
I am looking for a way to present the following to users. This will be a list of checkboxes:

\[ \] Region 1 A
\[ \] Region 1 B
\[ \] Region 1 C
\[ \] Region 1 D
\[ \] Region 1 E
\[ \] All of Region 1
\[ \] Area 2
\[ \] Area 3
\[ \] Area 4

This would all be stored in the same field.

So there are two main things I want to be able to do:

1) When entering the data, the admin/user should be able to choose any of the options, but if the select "All of Region 1", it automatically selects all of the Region 1 choices along with the "All of Region 1" choice.

2) When site visitors are searching this field (through an exposed Views filter), if they choose to filter for "All of Region 1" they should get anyone who chose any one of the Region 1 areas as well as anyone who chose "All of Region 1".

One solution would be to just remove the "All of Region 1" option from the exposed filter.

Or have the "All of Region 1" option in the exposed filter also check all the region 1 options automatically.

Is this necessarily a hook\_form\_alter solution?

# Answer
This is a possible solution using javascript that shows how to select the child checkboxes with JQuery.
> 0 votes

---
Tags: views, forms
---


# Question
Title: bulk importing data in articles node catagory based
Hello how to bulk Import XML feeds -Content from xml systems category base to drupal

Hello I have custom CMS we are moving to Drupal.Our custom CMS has bulk post system via XML feed. We post 1000 articles/News via xml per hour on our CMS.

We need to know how to import bulk xml as Categories (Taxonomy) base.

Here is our xml file below

`Sports
 Title
 Image Location

 Bulgaria votes in parliamentary poll
 Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Nam liber tempor cum soluta nobis eleifend option congue nihil imperdiet doming id quod mazim placerat facer possim assum. Lorem ipsum dolor sit amet, consectetur adipisici elit, sed eiusmod tempor incidunt ut labore et dolore magna aliqua. Lorem ipsum dolor sit amet. Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi.Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. At vero eos et accusam et justo duo dolores et ea rebum. Sanctus sea sed takimata ut vero voluptua. Consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat.
 tag1,tag2,tag3
 2/15/2015 8:26:01 AM

 Sports
 Youssou Ndour awarded Polar Prize
 At vero eos et accusam et justo duo dolores et ea rebum. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. Excepteur sint obcaecat cupiditat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Sanctus sea sed takimata ut vero voluptua.Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Nam liber tempor cum soluta nobis eleifend option congue nihil imperdiet doming id quod mazim placerat facer possim assum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi.
 tag1,tag2,tag3
 2/15/2015 8:26:01 AM`

# Answer
> 0 votes
Using Feeds and Feeds XPath Parser will do the trick. I would also take a look at Feeds Tamper. I have used it myself in the past and it works very wel!

Here is also a basic tutorial to get you started.

Good luck!

---
Tags: nodes
---


# Question
Title: Saving form data and running custom queries in mysql
I'm new to drupal and although I've researched and asked some questions I'm still stuck on how I can achieve my end result. I have built a php/html/mysql website (www.gbpokerclub.co.uk) but I now want to create it in drupal, mainly so I can easily give different users their own permission levels, and also so I can have my admins do some of the content editing.

Most of that I've worked out but the bit I'm stuck on both practically and conceptually is how I can record data into custom tables and retrieve that into leaderboards and results tables.

At present an admin logs poker game results via a form, this records the venue id, player id, finishing position etc into a mysql table. I have other tables that record venue details, player details, agent details etc. I then have some complex mysql queries that take data from results, player and venue tables, performs some calculations on it and spits out a leaderboard showing who has the most points.

This is currently done using forms to input the data, and mysql queries and php include files to drop the data back into a presentable format on the webpage.

My big question is ..

> **How can I emulate this process in Drupal?**

the feedback I've had so far suggests I could use content nodes with specialised types, or custom DB tables and views to present it back, or coding a custom module, but I've also been warned against using SQL and to use the database.api instead.

To be honest there seems to be many solutions to the achieve what I need, but I'm ideally looking for someone to tell me exactly which method I should go with and how I should go about implementing the solution.

I hope that all makes sense! Thanks

# Answer
Short simple answer is Views to display output of Entity Form inputs.
> 0 votes

---
Tags: 7, blocks, database
---


# Question
Title: multiple views want single search field is it possible in drupal?
I have developed Multiple views with multiple nodes.like(View1 , View2,View 3).

* In these three views Name field is same.
* so is that based on Name filed search feature is possible or not.
* I have tried with views default search criteria,but its working for only particular views only.

any suggestions please?

# Answer
You can't use a single exposed filter for multiple views. There is a workaround though:

* Make a new view that displays the three types of nodes you declared before.
* Make sure you use "display: content" in your view
* Choose a view mode
* Expose the name field that is used on the different content types

So it all comes down to using 1 view
> 1 votes

---
Tags: views
---


# Question
Title: I can't get my drupal_http_request to go to the correct function
I am working with Drupal 7, I have a hook\_services\_resources() set up:

```
function Api_services_resources() {
  $api = array(
    'applicant' => array(
      'operations' => array(
        'retrieve' => array(
          'help' => 'Updates applicants',
          'callback' => '_Api_retrieve',
          'access callback' => 'user_access',
          'access arguments' => array('access content'),
          'access arguments append' => FALSE,
          'args' => array(
            array(
              'name' => 'gwf',
              'type' => 'text',
              'description' => 'GWF Number',
              'source' => array('path' => 0),
              'optional' => TRUE,
              'default' => '0',
            ),
          ),
        ),
        'create' => array(
          'help' => 'Creates applicants',
          'callback' => '_Api_create',
          'access callback' => 'user_access',
          'access arguments' => array('access content'),
          'access arguments append' => FALSE,
          'args' => array(
            array(
              'name' => 'data',
              'type' => 'array',
              'description' => 'User Account Info',
              'source' => 'data',
              'optional' => FALSE,
              'default' => '0',
            ),
          ),
        ),
        'test' => array(
          'help' => 'Tests API Connection',
          'callback' => '_Api_test',
          'access callback' => 'user_access',
          'access arguments' => array('access content'),
          'access arguments append' => FALSE,
          'args' => array(
            array(
              'name' => 'timestamp',
              'type' => 'text',
              'description' => 'Timestamp',
              'source' => array('path' => 0),
              'optional' => TRUE,
              'default' => '0',
            ),
          ),
        ),
      ),
    ),
  );

  return $api;
}

```

And am trying to post to it using:

```
$create_website_applicant_path = 'http://' . $website_url . '/api/applicant/create/';

      $applicant = array(

        'mail' => $user['applicant_email'],
        'pass' => user_password(8),
        'status' =>  1,
        'roles' =>  array(2 => 1, 3 => 0, 8 => 0, 7 => 0, 6 => 0, 9 => 0),
        'notify' => 0,
        'timezone' => drupal_get_user_timezone(),
        'field_given_name' => array('und' => array('0' => array('value' => $user['first_name']))),
        'field_family_name' => array('und' => array('0' => array('value' => $user['last_name']))),
        'field_gwf' => array('und' => array('0' => array('value' => $user['gwf']))),
        'field_vac_ip' => array('und' => array('0' => array('value' => $_SERVER['REMOTE_ADDR']))),
        'submit' => 'Create new account',
        'ldap_user_create_ldap_acct' => 0,
        'op' => 'Create new account',
        'signature_format' => 'filtered_html',
      );

      $create_website_applicant_params = array(
        'method' => 'POST',
        'data' => drupal_http_build_query($applicant),
        'timeout' => 15,
      );
      $create_website_applicant_result = drupal_http_request($create_website_applicant_path, $create_website_applicant_params);
      echo $create_website_applicant_path;
      print_r($create_website_applicant_result);

```

The only problem is that when I try to use POST I get an error saying 404:Not found: Could not find the controller. I know the page is there, I can go to it in my browser. If I try to use GET the function being called for /api/applicant/create is actually \_Apt\_retrieve(). I'm not sure why this is and can't get it to point to the other function.

# Answer
The path that you are passing in drupal\_http\_request is incorrect. It should be `$create_website_applicant_path = 'http://' . $website_url . '/api/applicant/';`
> 0 votes

---
Tags: hooks, services
---


title: How to include an external PHP script?

text:
# Question
Title: How to include an external PHP script?
I have PHP file and I need to include that PHP file in static page. Where is best place to store that PHP file so I can include it in a static page.

# Answer
If that's your code, transform it into Drupal custom module. If you want use PHP API delivered by external service - transform it into library (move code into sites/all/libraries/yourLibrary) and write custom module which loads files on demand (with Libraries API).
> 1 votes

---
Tags: external-scripts
---


title: Updating few thousand nodes in one time

text:
# Question
Title: Updating few thousand nodes in one time
I have script which updating 2000-5000 nodes in loop and performance is poor. At the moment the code looks like:

```
foreach($nids as $nid) {
  $node = node_load($nid);
  // updating $node fields
  node_save($node);
}

```

It's possible optimize it? I don't need revisions, call node\_\* hooks, just update data.

# Answer
There's a module called Views Bulk Operations.

This will update more than thousand node at a time without memory limit exception.
> 1 votes

---
Tags: nodes, performance
---


title: Drush 6 on Windows not doing anything

text:
# Question
Title: Drush 6 on Windows not doing anything
I've installed Drush 6 on Windows using this installation package and have ensured that the following is in my PATH variable:

> C:\ProgramData\Drush\\;C:\Program Files (x86)\Drush\GnuWin32\bin;C:\Program Files (x86)\Drush\Php

When I open the Drush Command Prompt and type "drush status", nothing happens. The cursor moves a line down and blinks as if it's working on executing the command, but nothing is shown, and the process never ends. I have to Cntl+C to get out of it.

The same thing happens in Git Bash. No error messages, nothing. Just the ever blinking cursor. Any idea what's happening or how to fix it? Thanks in advance!

# Answer
> 1 votes
Figured it out. It was a problem with the reverse-proxy we're using. I installed a different version of drush in cygwin and tried to run it. Here it paused like I described above, but after a minute showed me this error:

> Drush needs a copy of the PEAR Console\_Table library in order to function, and the attempt to download this file automatically failed. To continue you will need to download the 1.1.3 package from http://pear.php.net/package/Console\_Table, extract it into C:\cygwin64\usr\local\src\drush/lib directory, such that Table.php exists at C:\cygwin64\usr\local\src\drush/lib/Console\_Table-1.1.3/Table.php.

I installed this package manually and now things are working. I just didn't realize Drush was trying to download extra content.

---
Tags: installation, drush
---


# Question
Title: how to add username and password field in commerce order
I am new with Drupal and I am willing to learn more.

now, I am creating a project and I am using the drupal commerce.

In the check-out process, In default, for unregistered users, it has the `email field` and others field. I just want to add `username`, `password` and `password confirm` fields so that the anonymous user will register then he can pay for the item he cheked-out.

but the problem is I don't know how to add those fields.

I have also checked the `Checkout Rules (Create a new account for an anonymous order)`, I think the process of creating the user is done here, but I don't know how.

Does anyone can help me in my case? any help will be appreciated...

thanks in advance ...

# Answer
> 1 votes
This is currently being handled via the Rules module. The rule that is enabled by default creates the user via the "Create a new account for an anonymous order" rule. There is no way to insert a password in here but is up to the user to open the link in their email and set their password manually.

# Answer
> 1 votes
I did it with below solution but I want to create a module for do this is future( If I will hav time :) )

first in my custom module add password field to checkout process

```
        function yourmodule_form_alter(&$form, &$form_state, $form_id) {
        if ($form['#form_id'] == 'commerce_checkout_form_checkout') {
            global $user;
          if($user->uid==0)  {
          $form['account']['login']['pass'] = array(
          '#type' => 'password_confirm',
          '#title' => t('Password'),
          '#required' => TRUE,
          '#size' => 30,
        );
          $form['buttons']['continue']['#submit'][]='_myfunction_user_register_incheckout_submit';
        }
        }
        }

```

then save password in session with

```
        function _myfunction_user_register_incheckout_submit($form,$form_state){
            $s_name='pass-'.$form_state['values']['account']['login']['mail'];
        //    $pass=user_hash_password($form_state['values']['account']['login']['pass']);
        // it's better hash it later , for more security
            $pass=$form_state['values']['account']['login']['pass'];
            _ym_session($s_name,$pass);
        }

        function _ym_session($key, $value = NULL) {
          drupal_session_start();
          static $storage;
          if ($value) {
            $storage[$key] = $value ;
            $_SESSION['ym'][$key] = $value ;   // I use 'lists' in case some other module uses 'type' in $_SESSION
          }
          else if (empty($storage[$key]) && isset($_SESSION['ym'][$key])) {
            $storage[$key] = $_SESSION['ym'][$key]?$_SESSION['ym'][$key]:false;
          }
          return $storage[$key];
        }

        function _myfunction_user_register_incheckout($user_account){
            $s_name='pass-'.$user_account->mail;
            if(_ym_session($s_name)){
            $pass=_ym_session($s_name);
            user_save($user_account,array('pass'=>$pass));
        //    ym(user_load($user_account->uid),'message');
        //    ym(user_load($user_account->uid));
            }
        }

```

after it in `commerce_checkout_new_account` rules in `/admin/config/workflow/rules/reaction/manage/commerce_checkout_new_account` add a php action in **PHP CODE** section add

\_myfunction\_user\_register\_incheckout($account\_created);

save it then put it after `Fetch entity by property` and before 'LOOP' and save rule,

Then test and enjoy it :D

---
Tags: entities, commerce, users
---


# Question
Title: How to retrieve files from url when they have whitespace into filename?
I need to import a lot of images/pdf from urls, and then save them to a file/image field into nodes.

To achieve that, I am using this script (example with images):

```
if($image!='\N'){

    $image_url = 'http://www.example.com/images/news/'.$image;
    $managed = TRUE; // Whether or not to create a Drupal file record
    $path = system_retrieve_file($image_url, 'public://news/', $managed, $replace = FILE_EXISTS_REPLACE);
    $fid = $path->fid;
    $node->field_image['und'][0]['fid'] =$fid;

}

```

This is working so well in almost every case. Only files containing whitespaces in filename are not retrived as expected. Example:

```
2009 juin texte TVA vote final.pdf
Geoffrey Schinder Award.jpg

```

/\**** EDIT \****/

Regarding Molot comment I changed my code including urlencode(), this way:

```
if($image!='\N'){
    $image_url = urlencode('www.example.com/images/news/'.$image);
    $managed = TRUE; // Whether or not to create a Drupal file record
    $path = system_retrieve_file($image_url, 'public://news/', $managed, $replace = FILE_EXISTS_REPLACE);
    $fid = $path->fid;
    $node->field_image['und'][0]['fid'] =$fid;
}

```

But it's even worse, I can not retrieve any file this way. Here is my filename after urlencode():

```
http%3A%2F%2Fwww.example.com%2Fimages%2Fnews%2F2009+juin+texte+TVA+vote+final.pdf
http%3A%2F%2Fwww.example.com%2Fimages%2Fnews%2FGeoffrey+Schinder+Award.jpg

```

And before:

```
http://www.example.com/images/news/2009 juin texte TVA vote final.pdf
http://www.example.com/images/news/Geoffrey Schinder Award.jpg

```

/\**** EDIT 2 \****/

Here is the kind of errors I am getting when file has white spaces:

```
HTTP error 404 occurred when trying to fetch http://www.example.com/images/photos/Geoffrey Schinder Award.jpg

```

This is so strange because I can reach all these images from browser, for example typing http://www.example.com/images/photos/Geoffrey Schinder Award.jpg in url bar will display the image correctly. But system\_retrieve\_file() isnt' able to reach it.

```
$path = system_retrieve_file($image_url, 'public://news/', $managed, $replace = FILE_EXISTS_REPLACE);

```

# Answer
> 3 votes
I managed to solve the issue by adding this command:

```
$image= str_replace(' ', '%20', $image);

```

I juste replaced all whitespaces with html whitespace characters..

# Answer
> 0 votes
First I recommend using https://www.drupal.org/project/transliteration in drupal, so that all imported files will get lower letters and "\_" instead of blancs.

For similar file imports from url to entity fields I already used feeds with feeds tamper successfully. As long as your url fit (you can see them in browser) that would be no problem. Hope I understood your issue right and this helps.

---
Tags: files
---


title: Plupload widget type not appearing

text:
# Question
Title: Plupload widget type not appearing
This is what I've done so far:

1. Installed & enabled the Plupload integration module in my drupal website (version 7.x-1.7)
2. Added Plupload library to my libraries directory (version 1.5.8)

In my status report I see that he can find the plupload library:

Now when I want to add an **Image** I only get the `widget type` Image and **not** the Pupload option. What could be the problem of this?

# Answer
> 4 votes
You need a combination of modules:

1. https://www.drupal.org/project/filefield\_sources\_plupload
2. https://www.drupal.org/project/filefield\_sources
3. https://www.drupal.org/project/plupload

I have intentionally left these as URLs as these module are often confused between each other.

In the content type which you wish to use the plupload widget: manage fields \> images \> edit. Scroll down until you see "File Sources", expand and select "Advanced Upload Widget (Plupload).

These basic steps should give you the option to use plupload when uploading images. You can further change the setting to allow a specific number of images etc.

---
Tags: 7, entities, files, media
---


# Question
Title: apache solr result logged users node should appear on top and then other user's node
I am using apache solr modules. My requirement was if I hit the search logged in user node should appear on top and then other user's node. How to achieve this requirement. Any help will be greatly appreciated.

# Answer
I strongly recommend using the Apache Solr View module, with this module installed it is only a matter of indexing the correct data and building the view with the correct sorting.
> 0 votes

---
Tags: search
---


# Question
Title: Get value of field attached to the file entity in a view
I extended the file entity of type video, which ships with the media/file\_entity module, with an extra field "tags". How can i get the values of this attached field in views?

# Answer
> 1 votes
You should just need to add a relationship with your file field, then the fields on your file entity should be available when adding fields to your view.

---
Tags: views, entities
---


# Question
Title: How to make a checkbox field required when a radio button is selected.
I need to show a validation error message when a radio button is clicked but none of the checkbox is checked. The checkbox field is optional in content type. Should be required when radio button is clicked. How can it implement this programaticaly. Not interested to add conditional field module for a single requirement.

# Answer
> 1 votes
Have you try the field API hook\_field\_validate?

# Answer
> 1 votes
In form alter use this code

```
function my_module_form_alter(&$form, &$form_state, $form_id) {
      $radio = $form['#node']->field_radio['und'][0]['value'];

      if($radio == 1){//if
         $form['field_checkbox']['und']['0']['value']['#required'] = TRUE;
         //OR
         $form['field_checkbox']['und']['0']['#required'] = TRUE;
      }
}

```

---
Tags: forms
---


title: How to remove all users from a role?

text:
# Question
Title: How to remove all users from a role?
How to remove all users and their content from a specific role programmatically ?

# Answer
> 2 votes
Here are some quick code examples that I have used to add or remove user roles in Drupal 6. This can be very helpful if you are building a module for a specific site that has to manipulate user roles. Using this technique is not the most flexible solution as it limits itself to the roles configured on a specific site (based on role id and role name). However, you could easily add a database table and an administration section and make this more flexible if needed.

**Here is an easy way to add a role:**

//you will need to enter the uid of the user here, I am just using user 1

```
$user = user_load(1);

```

//first we check if the user has the role in question (using the rid of the role)

```
if (!isset($user->roles[7])) {
    //if not we add the role and set the role name based on what is entered
    //in the drupal role administration section
    $user->roles[7] = 'role name seven';
}

```

**Here is an easy way to remove a role:**

//you will need to enter the uid of the user here, I am just using user 1

```
$user = user_load(1);

```

//first we check if the user has the first role in question

```
if (isset($user->roles[8])) {

  //if so, we unset the role
  unset($user->roles[8]);

  $edit = array('roles' => $user->roles);
  user_save($user, $edit);
}

```

**Here is an easy way to do a role swap:**

//you will need to enter the uid of the user here, I am just using user 1

```
$user = user_load(1);

```

//**first we check if the user has the first role in question**

```
if (isset($user->roles[8])) {

  //if so, we unset the role
  unset($user->roles[8]);

  //now we check to see if they have the role we want to swap for
  if (!isset($user->roles[7])) {

    //if not we add this role
    $user->roles[7] = 'role name seven';
  }

  $edit = array('roles' => $user->roles);
  user_save($user, $edit);
}

```

check this link for more info my post How to remove all roles from a user?

# Answer
> 0 votes
You need three things:

* All users with a certain role
* Call user\_delete\_multiple on an user list (form the previous step)
* Use batch API or Drupal Queue API to do the work and avoid PHP execution time exceed errors. If the total user number is very low you may skip this step, but this means less than 100 users. If this is a task that is going to be done just once in the website lifetime you may call directly, but limit the user list form step 1 to 40 or 50 users, the repeat until are users are deleted.

For the first step you can check this question: Get all users with specific roles using EntityFieldQuery

For the third step you can check the Examples for Developers module, Bastch API submodule: https://api.drupal.org/api/examples/batch\_example!batch\_example.module/group/batch\_example/7

---
Tags: users
---


title: Module installation via web browser

text:
# Question
Title: Module installation via web browser
I've a question regarding the installation of modules via the web browser. At the moment, I can easily upload both themes and modules to my Drupal site via sftp, but when I attempt to do the same using the module 'Update Manager' (i.e., through the web server itself, to avoid the hassle of adding the theme/module manually) I get an error that reads "Your server does not support installing modules and themes from this interface..." How does one enable the fix? I've read through some documentation regarding module installation but the comments seem contradictory, with some users suggesting a chown prompt and others saying such a solution is a breach of site security and thus to be avoided. Is there any consensus on what to do in this situation? Any help would be appreciated.

# Answer
You need to install the `php5-ftp` package and reload your webserver to load this extension.
> 1 votes

# Answer
For installing module has many way:

* Install by browser: in module page in drupal installing ftp by ftp url. This link is module page in drupal
* Install by drush with drush en module\_name
* Install with ftp. With ftp software upload module files in sites/all/modules and go to module page in drupal and install this.
> 0 votes

---
Tags: 7, installation
---


# Question
Title: Views: Can I create views based on taxonomies that link to other, context-specific taxonomy-based views?
I need to keep things in taxonomies so that I can retain the faceting behaviour in search, but I would also like to set up a more conventional way of drilling down through pages (and I'm hoping Views will let me do this). I'm wondering if I can have a Views page that lists all the items in one taxonomy package, but when a user clicks on one of those items, they are taken to another set of taxonomies. When they select something from that page, they are given only the list of nodes that have both taxonomies applied to them.

It will probably be too confusing to explain exactly what I'm working with, so let's say I was creating a page that collects government documents. Every node corresponds to one document, but every document will have a taxonomy for region (i.e., California, Texas, etc.) and department (i.e., Transportation, Education, etc.). So the first View would show all the states, and when they click on a state, they're taken to a list of departments. When they click on a department, they're shown a View that lists all the documents for that state.

I realize this is just faceting behaviour, but I've been requested to build something like this anyway.

# Answer
> 0 votes
One solution is to create a view showing taxonomy terms.

## Display 1

Create a page display with a path "documents"

Add a relationship "Taxonomy term: Content using `<state vocab>`." Require this relationship.

Under Other \> Query Settings select Distinct

Add fields

* Taxonomy term: Term ID
* Taxonomy term: Name

Exclude term ID from display

Rewrite the results of Name \> Rewrite the output of this field: `<a href="/documents/[tid]">[name]</a>`

Add a filter Content: Type (= `<your document content type>`)

## Display 2

Create a new page display with a path "documents/%"

Remove the Relationship for the state for "This page (override)" and add a relationship for your Department taxonomy. Require this relationship.

Add a contextual filter for `Content: <state field>` and display contents of "No results found" when filter value is not in the URL.

Edit the rewrite value of your name field, make sure to select "This page (override)": `<a href="/documents/!1/[tid]">[name]</a>`

## Display 3

Create a third page display with a path "documents/%/%"

Keep the state relationship from the view's defaults, but add a relationship using "This page (override)" for your Department taxonomy. Require this relationship.

Add a contextual filter, override for this display, for Content: State and then add one for Content: Department.

Override your fields for this display, removing the Term ID and Term Name, and add a field for Content: Title.

If I have explained this well enough, display 1 should give you a list of states that link to display 2 using the contextual filter to give a list of departments from that state, linking to display 3 showing a list of your document node titles from that state department.

---
Tags: views, taxonomy-terms, search
---


title: Automatic filter by user country ip

text:
# Question
Title: Automatic filter by user country ip
I want filter products views by user country ip. Can i use maybe rules for automatic sort, or some module? If this is not possible, as it may be possible to automatically filter on the field by the country?

# Answer
yes you can do this by using some of the contributed modules example is shown down https://www.drupal.org/node/522240

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

http://www.appnovation.com/blog/proximity-search-using-views-drupal

read this this will help you to find out
> 1 votes

---
Tags: views
---


# Question
Title: Best way to add a wrapper <div> to selected fields in a content type
I have a content type called resources which has a bunch of fields including a screenshot image field. When I order the items the screenshot shows at the bottom (or at whatever weight I set it). But what I want is for the screenshot to appear to the RIGHT of the text in the other fields (basically like a float:right with css). But although I have the class of the item using Firebug and have styled it float:right accordingly it still doesn't go next to the other fields, it gets placed below them...to the right.

I think what I need to do is find a way to add a wrapper to the other fields so I can float that left and my screenshot field right...but I don't know how to add a wrapper to fields in a content type.

Anyone know of a good way to do this?

# Answer
If you want to take a theme based approach you can provide a theme function in `template.php` or a template file. You can see the details here: https://api.drupal.org/api/drupal/modules!field!field.module/function/theme\_field/7

I'd put a specific theme function in the template file based on the link above and alter it for my own needs.

```
    function MY_THEME_field_field_SCREENSHOT($variables) {
      $output = '';

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

      // Render the items.
      $output .= '<div class="field-items"' . $variables['content_attributes'] . '>';
      foreach ($variables['items'] as $delta => $item) {
        $classes = 'field-item ' . ($delta % 2 ? 'odd' : 'even');
        $output .= '<div class="' . $classes . '"' . $variables['item_attributes'][$delta] . '>' . drupal_render($item) . '</div>';
      }
      $output .= '</div>';

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

      return $output;
    }

```

I'd do that rather than add a module because it seems more efficient to me, but your use case may be different.
> 1 votes

# Answer
Maybe the Field Group module is what you are looking for? According to the documentation, it provides many kind of wrappers.

Hope that helps,
> 2 votes

# Answer
You can use Field Formatter Class Module

> Allows site administrators to add classes to the outer HTML wrapper for any field display, so that CSS and Javascript can target them.

OR

You can use the hook\_form\_alter and can add your wrapper div as a prefix and suffix to the fields, in your custom module eg: `$form['title']['#prefix'] = '<div class="form-box">';`
> 0 votes

# Answer
It might be overkill for this issue, but what I would do is copy node.tpl.php to node--resources.tpl.php and put the wrapper in this template file.
> 0 votes

# Answer
If you are familiar with Views, there is "Style settings: customize field and label wrapper"(see screenshot) option per field. Then, set the path per content type with "%"(whildcard).
PS: They even have the "Global: Custom text" field in Views, so you have the full control with "Replacement Patterns".
> 0 votes

---
Tags: entities, nodes, theming
---


# Question
Title: hook_menu parameter can contain a forward slash
I've built a custom module to get cloudinary images and it works great. However, a bug has cropped up. You can navigate to /cloudinary/resource/public\_id and it gets the image with public\_id. On cloudinary there is now the ability to specify folders, so a public id could be something like "unitedstates/public\_id". This is wrecking my hook\_menu:

```
function cloudinary_menu() {

    ...

    $items['cloudinary/resource/%'] = array(
        'access callback' => TRUE,
        'page callback'  => 'get_resource',
        'page arguments' => array(2)
    );
...

```

Is there any way to specify that anything after /% should be passed?

# Answer
I don't think so, but you can kludge something together pretty easily:

```
function get_resource() {
  $resource_path = implode('/', func_get_args());
}

```

Results:

* cloudinary/resource/unitedstates/public\_id =\> unitedstates/public\_id
* cloudinary/resource/unitedstates/foo/bar/public\_id =\> unitedstates/foo/bar/public\_id

And so on
> 2 votes

# Answer
Additional arguments are still sent to page callback functions.

You might try doing a check for additional arguments:

```
function get_resource($id) {
  $args = func_get_args();
  if (count($args) > 1) {
    $id = end($args);
  }
  /** rest of your code **/
}

```

This way if the public id was "unitedstates/public\_id", func\_get\_args() would return two items, the second one being "public\_id" which would be set as the $id if there is more than one argument. Note this will always set the last argument as $id if there is more than one.
> 2 votes

---
Tags: 7, hooks, routes
---


# Question
Title: Why are URLs with non-existing subdomains not triggering an error 404?
One of my websites ignores random subdomains. The site doesn't have any subdomains but it will happily accept URLs such as fjiddifjdskdjf.example.com or dsfkljsdflsdjfds.example.com.
In both cases, it will display the home page. Similarly, I can log in at sfkjsdidisfdj.example.com/user.

At first, I suspected the problem was with a .htaccess file I put in the root directory. The file is used to redirect URLs that changed when I redesigned the website. It's got entries like this.

```
RedirectMatch 301 ^/2012/06/$ /blog/201206

```

However, after renaming the file, it's still accepting these odd, random subdomains.

I've also checked another Drupal site I maintain. On that site, entering a non-existent subdomain results in an 404 error. I've compared both sites' standard .htaccess files and they're identical. Both sites use the same (shared) hosting package, which should rule out differences in how the server has been configured.

Why URLs with non-existing subdomains don't trigger an error? How can I correct this behaviour?

# Answer
While you have stated that hosting is the same for both your sites it is most probably that this is either a server configuration issue or a DNS configuration issue rather than a Drupal setting issue. **In .htaccess the following catches 'wildcard' subdomains**

```
RewriteCond %{HTTP_HOST} ^[^.]+\.example\.com$ [NC]
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule ^ https://example.com%{REQUEST_URI} [L,R=301]

```

**In Apache configuration the following catches 'wildcard' subdomains**

```
<VirtualHost *:80>
        ServerAlias *.example.com
        Redirect 301 / http://www.example.com
</VirtualHost>

```

**In Nginx confiuration the following catches 'wildcard' subdomains** (as you are using .htaccess you are obviously not using Nginx but for completeness..)

```
server {
  server_name *.example.com;
  return 301 $scheme://example.com$request_uri;
}

server {
  server_name www.example.com;

  #add in further directives to serve your content
}

```

These are the most common configurations that will catch wildcard sub-domains on the server.

It is possible to do redirects in settings.php also but not for wildcard.

**The other possibility is that the issue is at the DNS entry. You may have set up a wildcard sub-domain which may also be known as a catch-all-subdomain.**

The layout of this will be determined by your DNS provider. This Drupal guide illustrates how it would be acheived on cPanel: https://www.drupal.org/node/1068894
> 4 votes

---
Tags: .htaccess, subsites
---


# Question
Title: How to set Permission based on roles for Views Data Export
Using views data export module, I set the permission for different roles in the **Data Export** in Views like:

But I can still see the Export button for all users in front page. However if the role doesn't have permission to export then after clicking it they are redirected to ***Access Denied Page***

Is there any way I can ***hide*** the export button from all the user roles except the ones that have permission to export?

If it was a link defined in **\*.tpl.php** then I could have done something like

```
<?php if (in_array('myRole', $user->roles)): ?>
// The export button
<?php endif; ?>

```

But I couldn't figure out how to do it with Views Data Export *(without hacking the module)*

# Answer
This issue has been fixed in the 7.x-3.0-beta8 version. See the issue thread here.
> 0 votes

# Answer
Add a template for the view. Then by using css, hide the default export button coming with view. Then print the export link manually based on user role.
> -1 votes

---
Tags: 7, views, users, importing-exporting
---


# Question
Title: Can I create a keyword filter on emails sent from an email form with Rules?
Can I make a Rule that will check content of an email sent from a contact form and block the send if a condition is met?

I was hoping I could set up a Rule to react on event Before Email Send, or something of that kind and then check the content, but that event doesn't exist: could I create it? Or is there a better way?

Context: I have a content type where each node is an advert for a local attraction. I have an email field which is set to display as an email contact form which can be submitted by anonymous users. I am using Mail System and Mandrill to send the emails.

Although I have Spamicide module and Captcha already installed, the odd spam email is creeping through the form. The spams are usually highly obvious and would be simple to eliminate if I could set up a keyword blacklist, but I am not sure how best to create one.

# Answer
Using hook\_mail\_alter https://api.drupal.org/api/drupal/modules!system!system.api.php/function/hook\_mail\_alter/7 you can check/change all mails before they are being sent.

Setting $message-\>send = FALSE; will stop the mail system from sending out the mail.
> 0 votes

---
Tags: rules, emails, advertising
---


# Question
Title: How do I use AND condition in Rules to add shipping to sales tax?
The default sales tax Component Rule calculates sales tax on all line items... so it was (for us) correctly adding sales tax to products and shipping line items. We started using Userpoints\_Discount and I created a new Product Type 'Points' to allow users to purchase Userpoints. I then edited the Component Rule as below. So now, it calculates Sales Tax on the product which are NOT 'Points' (good) but it has stopped calculating sales tax on shipping (bad).

Can someone look at this Component Rule and explain why the Shipping Line Item is no longer having sales tax calculated?

The logic should be:

```
IF Commerce Line Item IS IN bundle Products OR bundle Shipping
  AND Commerce Line Item Product Type IS NOT 'Points'

```

I am using Commerce Kickstart 2.

```
{ "commerce_tax_rate_state_of_washington" : {
    "LABEL" : "Calculate State Of Washington 9.5%",
    "PLUGIN" : "rule",
    "OWNER" : "rules",
    "TAGS" : [ "Commerce Tax", "sales_tax" ],
    "REQUIRES" : [ "rules", "inline_conditions", "commerce_tax" ],
    "USES VARIABLES" : { "commerce_line_item" : { "label" : "Line item", "type" : "commerce_line_item" } },
    "IF" : [
      { "AND" : [
          { "entity_is_of_bundle" : {
              "entity" : [ "commerce-line-item" ],
              "type" : "commerce_line_item",
              "bundle" : { "value" : { "product" : "product", "shipping" : "shipping" } }
            }
          },
          { "NOT commerce_product_has_type" : { "commerce_line_item" : [ "commerce_line_item" ], "type" : "points" } }
        ]
      }
    ],
    "DO" : [
      { "commerce_tax_rate_apply" : {
          "USING" : {
            "commerce_line_item" : [ "commerce-line-item" ],
            "tax_rate_name" : "state_of_washington"
          },
          "PROVIDE" : { "applied_tax" : { "applied_tax" : "Applied tax" } }
        }
      }
    ]
  }
}

```

# Answer
> 1 votes
NB: As so often happens with Drupal, apparently I was asking the wrong question. IMO this is such a -basic- part of any eCommerce system used in USA/Canada, but the answer is buried in a support request on Drupal.org. This is -terrible- documentation and I hope the Commerce Guys are duly ashamed. Doesn't matter how cool the code is if one can't easily figure it out.

Apparently what one has to do is add the rule into

Admin -\> Store Settings -\> Shipping (Calculation Rules) -\> Configure Component

Please see here (#29) https://www.drupal.org/node/1243218#comment-6732098

...and also (#42).

What one does is add a new Rule to Shipping Event: Calculate Shipping Condition: Order Address Component Comparison Actions: (Your Salestax Component Rule goes here)

For the Action you simply use the same sales tax component rule you used for

Admin -\> Taxes -\> Configure Component

...in my case 'Sales Tax WA'

So I suppose if you live in a jurisdiction with many possible taxes, you'd create a separate component rule for each under shipping, using exactly the same Order Address Comparison and Action Rule you used for the Taxes section.

What confused -me- was that I thought one could use use the IF/AND/OR under Taxes to differentiate between Shipping and Product line items. Apparently this does not work. That would be a MUCH better solution (reduce duplication of effort, cut down on errors.) If someone knows how to do this, PLEASE post here!

So, in one sentence, you have to apply all the same sales tax component rules in two places: in Taxes (for product line items) and then in Shipping under Calculate Rules to apply tax to the freight.

And here is the exported rule:

```
{ "rules_apply_taxes_to_shipping" : {
"LABEL" : "Apply Taxes to Shipping",
"PLUGIN" : "reaction rule",
"OWNER" : "rules",
"REQUIRES" : [ "commerce_order", "rules", "commerce_shipping" ],
"ON" : { "commerce_shipping_calculate_rate" : [] },
"IF" : [
  { "commerce_order_compare_address" : {
      "commerce_order" : [ "commerce-line-item:order" ],
      "address_field" : "commerce_customer_billing|commerce_customer_address",
      "address_component" : "administrative_area",
      "value" : "WA"
     }
   }
 ],
 "DO" : [
   { "component_commerce_tax_rate_state_of_washington" : { "commerce_line_item" :
     [  "commerce-line-item" ] } }
       ]
   }
}

```

---
Tags: rules, commerce
---


# Question
Title: How can I implement a non-CRUD function in hook_service_resources()?
This question is similar to this question but I don't understand how the URLs are modified enough for the answer there to make sense to me.

The module adds **retrieve** and **index** operations by default. I am attempting to extend privatemsg\_services\_resources with an additional option, **unread**.

I have added **unread** to the function as shown below, but I cannot figure out how to access it via URL.

```
function privatemsg_services_services_resources() {
  return array(
    'privatemsg' => array(
      'operations' => array(
        'index'    => array(
          'callback'        => '_privatemsg_services_get',
          'access callback' => 'user_is_logged_in',
          'args'            => array(),
        ),
        'unread'    => array(
          'callback'        => '_privatemsg_services_unread_count',
          'access callback' => 'user_is_logged_in',
            'args' => array(
              array(
                'name'        => 'uid',
                'type'        => 'int',
                'description' => t('UID of the user to check the number of unread messages for.'),
                'source'      => array(
                  'path' => 0,
                ),
              ),
            ),
          ),
        'retrieve' => array(
          'callback' => '_privatemsg_services_get_thread',
          'access arguments' => array(
            'get private messages from remote',
          ),
          'args' => array(
            array(
              'name'        => 'thread_id',
              'type'        => 'int',
              'description' => t('ID of the thread to be retrieved.'),
              'source'      => array(
                'path' => 0,
              ),
            ),
          ),
        ),
      ),
    ),
  );
}

```

When I go to **www.myexample.com/drupalgap/privatemsg**, I get the value for **index**.

When I go to **www.myexample.com/drupalgap/privatemsg/THREAD\_ID**, I get the **retrieve** value for THREAD\_ID.

When I go to **www.myexample.com/drupalgap/privatemsg/unread/UID** or **www.myexample.com/drupalgap/privatemsg/unread**, I get the message `["Invalid parameters passed."]`.

However, if I comment out the function for **retrieve** and then rename **unread** to **retrieve** (to test my code for **unread**), after clearing the caches, going to **www.myexample.com/drupalgap/privatemsg/UID** gives me the number of unread messages. So the code is OK, I'm just setting up the resource the wrong way.

How can I call both **retrieve** and **unread** from the URL?

# Answer
> 2 votes
The key is to use the `actions` array instead of the `operations` array when creating non-CRUD resources.

Here's an example for DrupalGap: http://drupalgap.org/node/187

FYI, all calls must use `POST` when using `actions`.

When using `operations`, the calls are directed based on the HTTP method (GET, POST, PUT, DELETE).

Don't forget to attach the `X-CSRF-Token` header to your `POST` calls. Its value can be retrieved here: `?q=services/session/token`

Since this is for DrupalGap, and you're passing along an argument to your service resource, I'd recommend following these instructions, that way jDrupal can be utilized and your function(s) can easily be re-used:

http://drupalgap.org/node/203

---
Tags: services, 8
---


# Question
Title: Duplicate breadcrumbs but they're not in the $breadcrumb variable?
I'm trying to remove this duplicate breadcrumb but I don't see what's generating it. Any ideas?

# Answer
This was an easy one: turn off custom breadcrumb modules...
> 0 votes

---
Tags: breadcrumbs
---


# Question
Title: How can I filter a view by date ranges from another content type?
I am building a site in Drupal 7 that has a list of events. I would like to be able to filter these events by specific date ranges from another content type.

I have successfully been able to set up a view that enables users to filter the list of events by a number of criteria including an arbitrary date range. That much is fine.

However, I would like to allow users to filter the events into date ranges that come from another content type. In this particular case I want the site to show events that occur within the term of office of UK prime ministers. I have set up a content type that has the start and end dates of the term of office of the prime ministers but I can't see how to use this to filter the events.

Ideally I would like a drop down list that allows the user to select a prime minister and this will show a list of events that occur during that prime minister's term of office.

How would you suggest that I do this?

Thank you in advance for your help.

# Answer
It's not a dropdown list, but if you don't want to write code, consider the following.

Create a view of all UK PM's in a view. Rewrite the results to output links in the format: events/*start\_date*/*end\_date*.

On your events view (with 'events' path). Add contextual filters catching start\_date and end\_date.

You could make the first view a jump menu and show it as a block above your events view. This will have the same effect as exposed filters, but will be harder to combine with actual exposed filters.
> 1 votes

---
Tags: 7, views
---


title: How to get batch ID?

text:
# Question
Title: How to get batch ID?
I'm running some really long batch process. So in case user navigates away from the batch progress page, I'd like to be able to give him a link that leads back to that page. How can I get the batch ID needed for the batch processing page?

Knowing that batch processing url is something like `http://example.com/batch?op=start&id=183` so in theory I could look for the `$_GET['id']` inside my batch process function and store that in a session variable but it seems really ugly. Yet I didn't find any way to get the id of the batch that I just started.

It would be really nice if `batch_set()` would return batch id or would just add it to the batch definition array.

# Answer
After batch\_set(). Use

```
$batch =& batch_get();

```

This contains the information you need.

But I'm not sure you will be able to resume.
> 3 votes

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


# Question
Title: geofield and leaflet maps: how to show proximity-originator on map?
**My Goal:**
Show a hotel on a map, together with nearby restaurants.

Currently, i have only a table, based on a view with the hotel's node-id as contextual filter. Now i'd like to put all that in a map.

I think with OpenLayers i could show the hotel in one layer, and the restaurants in another. But i'd prefer leaflet for it's size, so i did not try Openlayers yet.

Using geofield, i saw there is a proximity-filed in views. With that, i can show the restaurants and have the proximity in the tooltip, but i can't show the Hotel. My case would be an "abuse" of the proximity field, but i guess there would be more reasonable use-cases, which could use such a feature.

I also thought about how to do a view that contains hotel x and all all referenced restaurants, but i did not find a way yet. Restaurants and Hotels are nodes, with hotels having a multivalue entity-reference field pointing to the recommended restaurants.

# Answer
If you are using geofields you can set up a proximity filter, and in your view filters, add the geofield proximity. In the settings 'source of origin input' try 'other geofield'? Ty mapping the hotels and restaurants using two separate geofields, one for hotels, one for restaurants. Then map the restaurant distance from the hotels as origin\>
> 1 votes

---
Tags: views, location
---


# Question
Title: Drupal fullcalendar integration -> JSON Formatting?
I am working on a custom fullcalendar (http://fullcalendar.io/) implemenation for a custom module of mine.

I have created an hook\_menu that will provide the json output that contains the events that need to be placed onto the calendar:

```
function mymodule_fullcalendar_measurement_jsonfeed() {
$json = array(
 '0' => array(
   'id' => '182',
   'title'=>'My Event',
   'start'=>'2015-02-16 13:00:00',
   'end'=>'2015-02-16 16:00:00',
   'description' => 'event desc',)
 );

  $jsonstring = drupal_json_encode($json);
  drupal_json_output($jsonstring);
}

```

And an ajax call to the hook\_menu like below:

```
events : '/my_module_fullcalendar/jsonfeed',

```

This returns a json string like this:

```
 [{"id":"182","title":"My Event","start":"2015-02-16 13:00:00","end":"2015-02-16 16:00:00","description":"event desc"}]

```

The fullcalendar does not recognise this format, because it expects an event object.

I tried to use eventDataTransform to convert this into a correctly formatted object (as stated here: http://fullcalendar.io/docs/event\_data/eventDataTransform/), but not luck so far.

I'm pretty sure that this is a formatting problem, because when i change the full calendar jquery events property like this:

```
events: my_events

```

And use a variable to create a dummy object:

```
        var my_events = {
      events: [
        {
          title: 'event 1',
          start: '2015-01-04',
          color: 'tomato'
        },
        {
          title: 'event 2',
          start: '2015-01-09'
        },
        {
          title: 'event 3',
          start: '2015-01-09'
        }
      ],

```

Everything works perfectly...

For the record i am working with full calendar 2.2.7

Thanks so much!

# Answer
The solution was pretty straight forward actually.

I replaced the jscon encode and json output like this:

```
drupal_json_encode($json);
drupal_json_output($json);

```

And now it runs smooth :-)
> 1 votes

---
Tags: javascript, 8
---


title: How to output content to a page

text:
# Question
Title: How to output content to a page
I have a form on my page that is being submitted. I am implementing `hook_form_submit` and within that function I have a search algorithm that processes the entered data and returns a result. I would like to display that result on the page underneath the search box. For debugging purposes so far I've simply used `drupal_set_message()` but this is no permanent solution. I am new to Drupal module development so I am unsure how to go about this.

Any help would be greatly appreciated!

# Answer
> 2 votes
I'm afraid I posted to quickly, my apologies.

After re-reading your post, I would advise you to work with an AJAX callback that returns te search results.

First of all you need to create a form api implementation that holds the ajax callback

```
$form['search']['client'] = array(
'#type' => 'textfield',
'#title' => t('Search Client'),
'#description' => t('Search for an existing client'),
'#autocomplete_path' => 'searchclient/autocomplete',
);

$form['submit'] = array(
'#type' => 'submit',
'#value' => t('Search'),
);

```

Then you need to make sure that 'searchclient/autocomplete' is registered as a valid menu path (hook\_menu) like this for example:

```
/**
* @return array
* Implements hook_menu().
*/
function your_project_menu() {
$items = array();

$items['searchclient/autocomplete'] = array(
  'title' => t('AutoComp Menu'),
  'page callback' => 'your_project_search_client',
  'access arguments' => array('access content'),
  'type' => MENU_CALLBACK,
);

  return $items;
}

```

After this you need to create your page callback function that will actually return the content to the page:

```
function your_project_search_client($string) {

  $matches = array();

  // do what you want here

  drupal_json_output($matches);
  exit;
}

```

As some extra info:

-\> $string is the entered search text in the form element -\> $matches holds the data to be returned to the screen.

More information on ajax callbacks can be found here:

https://api.drupal.org/api/drupal/includes%21ajax.inc/group/ajax/7 https://www.drupal.org/node/2046693

# Answer
> 0 votes
@Codeling, two popular development debugging tools are devel, and Xdebug (often with PHPStorm)

Now, for your question about the search results. If you are new to Drupal it would probably be easier to go a non-ajax route at first. There is a `form_state` option called `rebuild` that, when set to true, will allow you to show the results, keep the text in the search box, etc.

In your form `#submit` callback, set `$form_state['rebuild'] = TRUE`. You could put your data in `$form_state['storage']` and then access it in your form builder, or even do the calculation in the builder itself.

Another option would be to look at the core search module. That implementation pulls the query it via `$_GET` instead, which would have less overhead as it passes around less data than the options mentioned above (assuming this approach covers your requirements).

---
Tags: forms
---


# Question
Title: Restrict User Roles in viewing a Node Content Type without installing a module
Currently I want to keep my site slim without having to install big modules to do a small function. I know I can use the content\_access module to restrict a user role to view a specific content type, but I was wondering how can this be done without any additional modules installed.

I have a content type of "widget" and I don't want it view-able by anonymous users. It should only be viewed by staff. How can you restrict/hide this content type from anonymous users without installing a module for it?

# Answer
> 0 votes
You can control node access using `hook_node_access`

e.g:

```
/**
 * Implements hook_node_access
 */
function MY_MODULE_node_access($node, $op, $account) {

  $type = is_string($node) ? $node : $node->type;

  if ($type == 'type_of_interest') {
    // Require administer nodes permission to view
    if (($op == 'view') && (!user_access('administer nodes', $account))) {
      return NODE_ACCESS_DENY;
    }
  }

}

```

# Answer
> 0 votes
You could keep the nodes "unpublished". This would hide these nodes from anonymous users. And only internal folks would be able to view these nodes and no modules need to be installed.

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


# Question
Title: Finding the Machine Name of an Module-based Field Added to $content variable
I need to edit a field added to my $content variable by a contrib module called Print, email, and PDF versions. It creates a link at the top of the content region that says 'Print PDF' and prints a PDF of the page. I've looked everywhere in the admin settings for the module for this information but can't find it anywhere.

Note: I've tried looking in my DB and trying what I found in there for the field, with no luck. I also tried using var\_dump but that doesn't help me. I looked in the print.module file but wasn't seeing anything in there, although to be fair it's quite voluminous so I might have missed something.

I'm trying to access it and hide it through code in node--resource.tpl.php so I can manipulate it independently of the rest of the vars in $content. This is the code I'm using successfully to hide OTHER items in $content for example:

```
// #nomarkup is a function defined in template.php
$content['field_body']['#theme'] = "nomarkup";
hide($content['field_body']);

```

With Firebug, the DOM shows followed by for the PRINT PDF link I want to hide, but neither of those seems to be recognized when I try to hide them using a similar format as the other items in $content, like so:

```
$content['print-link']['#theme']

```

or

```
$content['print_pdf']['#theme']

```

respectively. I even tried removing the \['#theme'\] part but that didn't help.

Anyone know a good way to find the machine name of this variable that seems to have been added to $content but is not showing in admin \> content type?

# Answer
Install the devel module and use `dpm($content)` to inspect the content variable.

A good place to adjust the contents of a page in your theme is in a preprocess function.
> 1 votes

---
Tags: nodes
---


# Question
Title: comment pager not showing in bootsrap theme
I create a new theme based on `Bootsrap` and the below template files, I limit show comment on every page on 50 comment in edit of content type in `comment` section, I have 126 comment in one of my node form that content type, but only see 50 comment and **there is not any pager**.

My question is that how can I add comment pager in below of comment?\**

**comment-wrapper.tpl.php**

```
    <div id="comments" class="<?php print $classes; ?>"<?php print $attributes; ?>>
      <?php if ($content['comments'] && $node->type != 'forum'): ?>
        <?php print render($title_prefix); ?>
        <h2 class="title"><?php print t('Comments'); ?></h2>
        <?php print render($title_suffix); ?>
      <?php endif; ?>

      <?php print render($content['comments']); ?>
      <?php if ($content['comment_form']): ?>
        <h2 class="title comment-form"><?php print t('Add new comment'); ?></h2>
        <?php print render($content['comment_form']); ?>
      <?php endif; ?>
    </div>

```

and **comment.tpl.php**

```
<div class="<?php print $classes; ?> clearfix"<?php print $attributes; ?>>

  <div class="attribution">

    <?php print $picture; ?>

    <div class="submitted">
      <p class="commenter-name">
        <?php print $author; ?>
      </p>
      <p class="comment-time">
        <?php print $created; ?>
      </p>
      <p class="comment-permalink">
        <?php print $permalink; ?>
      </p>
    </div>
  </div>

  <div class="comment-text">
    <div class="comment-arrow"></div>

    <?php if ($new): ?>
      <span class="new"><?php print $new; ?></span>
    <?php endif; ?>

    <?php print render($title_prefix); ?>
    <h3<?php print $title_attributes; ?>><?php print $title; ?></h3>
    <?php print render($title_suffix); ?>

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

    <?php print render($content['links']); ?>
  </div> <!-- /.comment-text -->
</div>

```

**Any idea?**

# Answer
Adapted from this post on putting pagers above and below comments:

```
function mytemplate_comment_wrapper($content) {
  $comments_per_page = _comment_get_display_setting('comments_per_page');
  $content .= theme('pager', NULL, $comments_per_page, 0);
  return theme_comment_wrapper($content);
}

```

should render a pager for you if placed in comment-wrapper.tpl.php
> 0 votes

---
Tags: comments
---


title: Default Price for Commerce Product

text:
# Question
Title: Default Price for Commerce Product
As it is not possible to set a default price to products I was trying to achieve that by using rules. I'm checking "Before saving a commerce product" Event. Condition is "Data value is empty" and my Action would be "Set a data value", but all I get is an error because price isn't set. Anyone know why this is happening?
As this is the first time I use rules, maybe I've done something wrong.

# Answer
> 1 votes
```
/**
 * Implements hook_field_widget_form_alter()
 */
function HOOK_field_widget_form_alter(&$element, &$form_state, $context) {
  if (isset($element['#field_name'])) {
    if ($element['#field_name'] == 'commerce_price') {
      if (empty($element['amount']['#default_value'])) {
        $element['amount']['#default_value'] = 0;
      }
    }
  }
}

```

---
Tags: 7, commerce
---


title: View file when node is viewed

text:
# Question
Title: View file when node is viewed
Lets say I have a node type that has a file field(docx,pdf etc). Is there a way to get drupal to show the file directly on node view instead of having the user to navigate to the node and then click on the file to view it?

# Answer
The PDF Reader module sounds like what you're looking for.
> 0 votes

---
Tags: nodes
---


title: Drupal Forum Solutions?

text:
# Question
Title: Drupal Forum Solutions?
Contemplating a new forum for a D7 site. There are many options floating around out there, and it's not very clear which of the solutions listed below would be the best direction for our use case. And which are still current (some posts and projects are quite old). Advice?

**Features we're looking for:**

• Has staff moderation. Volunteer moderators can be assigned.

• Private messaging between members.

• Users can earn or be given “badges” and have a nice leaderboard – we would like to use it to create an "expert" vs "new user" atmosphere for Q&A threads, with new contributors asking more seasoned ones (or staff moderators) for advice

**\[Advanced\]** A stub of the most popular discussion(s), i.e. *linked title (# of replies)* can be pulled into a relevant landing page, using categories or similar to define which forums belong to which landing pages. This is important to bring user generated content into landing pages. An extra bonus would be the feature of over-riding the 'most popular' discussion with another staff featured discussion at landing page level.

• Doesn't require subdomain or iframes to integrate - can reside at something like **domain.com/forum/thread** or **domain.com/landingpage/forum/thread**

• Clean and modern UI out of the box or can be themed, responsive for mobile

• Can use Drupal user authentication or replace/supplement it with OpenID or Facebook/Twitter logins

• Includes spam control, though this isn't a deal breaker.

**\[Advanced\]** Comments can get upvotes for helpfulness

**And here are the choices that seem to be out there:**

1) Core forum module - probably can't do a lot of the above?

2) Advanced forum module - how much of the above can it accomplish? If it can do most, this seems like it could be the easiest option to integrate ...

3) VBulletin - some of the larger Drupal sites with really active forums use vbulletin, typically implemented as a subdomain. There's also DrupalVB https://www.drupal.org/project/drupalvb ; phpBB is also an option

4) Acquia Commons Drupal project/modules

5) Harmony Drupal project/modules

6) Discourse - https://www.drupal.org/project/discourse . New and cool, but maybe their Docker isn't easy to integrate into a complex existing Drupal site.

7) A third party konwledgebase platform like GetSatisfaction or Zendesk. These have nice UIs, a lot of the required features from above, and Drupal integration modules already exist - but integration may still be quite complex...

Ease of integration is important, but so is how full-featured the solution is. And whether it's got a nice, modern UI.

# Answer
The Advanced forum module might be a good starting point, since Drupal has a modular approach you'll have to use a lot of building blocks (drupal contrib modules) to get to the extended functionality that you desire. There might be some custom code needed. In short: there is no out of the box solution for this nor a short answer to help you build this forum but here is a good start:

* Has staff moderation. Volunteer moderators can be assigned. -\> Use Workbench
* Private messaging between members. -\> Use Privatemsg
* Users can earn or be given “badges” and have a nice leaderboard – we would like to use it to create an "expert" vs "new user" atmosphere for Q&A threads, with new contributors asking more seasoned ones (or staff moderators) for advice -\> Badge/score system might be custom, the overviews you can build with Views
* \[Advanced\] A stub of the most popular discussion(s), i.e. linked title (# of replies) can be pulled into a relevant landing page, using categories or similar to define which forums belong to which landing pages. This is important to bring user generated content into landing pages. An extra bonus would be the feature of over-riding the 'most popular' discussion with another staff featured discussion at landing page level. -\> Probably some custom code with also views to pull the lists
* Doesn't require subdomain or iframes to integrate - can reside at something like domain.com/forum/thread or domain.com/landingpage/forum/thread -\> Use PathAuto and again views for the landingpages overviews with dynamic urls
* Clean and modern UI out of the box or can be themed, responsive for mobile -\> Omega's example theme Ohm might be a good starting point or you could build a child theme from scratch on omega
* Can use Drupal user authentication or replace/supplement it with OpenID or Facebook/Twitter logins -\> Try OpenID connect, Facebook connect, not sure if there is something like this for twitter
* Includes spam control, though this isn't a deal breaker. -\> Use Mollom or Honeypot
* Comment upvoting -\> Use Vote Up/Down
> 8 votes

---
Tags: 7, nodes
---


# Question
Title: Superfish module seems to "Ignore" it's very own library
I have a problem connecting the Superfish library to the module... I've tried to Google this issue and the error I got, but found no direct solution. Here are more details:

I've installed the module alright but when I go to `admin/config/user-interface/superfish`, it asks me for the library path. I've tried many variations such as:

```
/public_html/sitesname.com/sites/all/libraries/Superfish
/public_html/sitesname.com/sites/all/libraries/
sitesname.com/sites/all/libraries/Superfish/
sitesname.com/sites/all/libraries/
public_html/sitesname.com/sites/all/libraries/Superfish
public_html/sitesname.com/sites/all/libraries
/public_html/sitesname.com/sites/all/libraries/Superfish/superfish.js

```

Nothing seems to work and I keep getting the (kinda wired) error **"File not found"**. Any ideas?

# Answer
> 1 votes
sites/all/libraries/superfish with "superfish" all lower case might do the trick, if you have uppercase "Superfish" it will not work (at least on \*nix).

# Answer
> 1 votes
Download the Superfish library and extract it to sites/all/libraries/superfish (so that the superfish.js will be located at http://example.com/sites/all/libraries/superfish/superfish.js)

Also check if the permissions on the .js files are correct. Status report pages (admin/reports/status) may also be of help.

---
Tags: theming, navigation
---


# Question
Title: Re-indexing of site stalled, & running cron won't advance
I have a site recently moved from D6 to D7. The search in D7 was not finding nodes containing the search terms, so I began a re-index in the search settings. This has stalled at 11% of site (with 3570 items left to index), and running cron does nothing to advance the re-index.

The log messages show that when cron runs, it encounters this error:

> EntityMalformedException: Missing bundle property on entity of type comment. in entity\_extract\_ids() (line 7766 of /var/www/html/\[domain\]/includes/common.inc).

And this notice:

> Notice: Undefined variable: key in comment\_prepare\_thread() (line 901 of /var/www/html/\[domain\]/modules/comment/comment.module).

Also, there are many instances of this notice, which is associated with use of the site, not cron:

> Undefined index: weblinks in custom\_search\_form\_alter() (line 232 of /var/www/html/\[domain\]/sites/all/modules/custom\_search/custom\_search.module).

None of these seem to affect the function of the site, and it's not clear to me that they are actually related to the stalled re-indexing. But it's all I've got to go on at this point.

If anyone could give me some ideas for how to troubleshoot this, I'd very much appreciate it.

Thanks!

# Answer
> 1 votes
This problem was caused by discussion forum posts with a single comment from a user whose id was no longer in the user table (threads with more than one comment, even though one was from an invalid user id, did not cause the error).

The fix was to find comments with invalid user ids, then change those ids in the Comment table to 0.

This SQL query identified the problem user ids:

```
SELECT DISTINCT a.uid FROM comment a left join users b on a.uid = b.uid
WHERE b.uid IS NULL

```

With the problem user ids identified, you can either edit the table directly, or use UPDATE to change the column values.

With those values changed in the comment table, the re-indexing proceeded to 100% without a hitch.

# Answer
> -1 votes
If you have installed Drush in your root directory, then you can run the below command to begin a re-index in the search settings.

**drush search-reindex**

To rebuild the index immediately, instead of waiting for cron, please execute the below command.

**drush search-reindex --immediate**

This will bring upto 100% reindexing of a website.

---
Tags: search
---


# Question
Title: Play Buttons of SoundManager2 are disabled in Ajax o JS
I have a views that call a content type with soundmanager fields (360 style) with pager.

On the first page show 3 soundmanager fields and play ok, but in the second page by ajax the no longer played in the input play btn.

In the second page the input play not function.

I tested with 3 options: Infinite scroll module. Custom js code for the scroll in the same page. Views Module load more.

In all feel the same, in the second page loaded in ajax or js buttons play of SoundManager are disabled.

appreciate your help

# Answer
> 0 votes
Add below script in Ajax call

```
<script>
soundManager.reboot();
</script>

```

---
Tags: views, ajax
---