title: Splash page for drupal 7 website

text:
# Question
Title: Splash page for drupal 7 website
i need to put a splash page with flash intro.

I have already a front page with the name `page--front.tpl.php` and how can i put a new splash -page before this home page.

The new splash page will be a simple html page with a flash intro to navigate to the website's home page.

Any suggestion.

....

# Answer
> 5 votes
I would recommend to take advantage of jQuery over Flash. As Mohammed suggested, you could try the TinyBox module.

But, the other option is the Splashify module:

> Display a splash page anywhere on your site by redirecting the user, showing a lightbox, or displaying a popup. This module is designed to be search engine friendly, mobile device friendly and offers multiple configuration options.

# Answer
> 4 votes
Splash module is the rescue! It can do what you need. Drupal 7 version is Splashify.

# Answer
> 1 votes
you can also do it using cookies.

step1. create splash page

step2. write code in php to set and check cookies

step3. if cookies exists then no redirection. If not exists then set cookies and redirect to splash page.

The code can be written on front page tpl.

# Answer
> 0 votes
Also i found Front Page module

> The Front Page module allows for customised home pages dependant on role. The pages can be of the following types:
>
> * **Alias** (only 2.x branch) - Allows for another Drupal path to be shown as the home page without redirecting the user.
> * **Redirect** \- Allows you to redirect users to a local or remote URL.
> * **Themed** \- Allows you to enter some static text that will be placed into the content area of a standard Drupal page.
> * **Full** \- Allows for static content to be displayed to the screen as is. This method does not pass through Drupal's theming system.

# Answer
> 0 votes
Perhaps you should use the Panels module. Have a look at the Panopoly distribution.
More about Panels:

> The Panels module allows a site administrator to create customized layouts for multiple uses. At its core it is a drag and drop content manager that lets you visually design a layout and place content within that layout. Integration with other systems allows you to create nodes that use this, landing pages that use this, and even override system pages such as taxonomy and the node page so that you can customize the layout of your site with very fine grained permissions.

---
Tags: 7
---


# Question
Title: How to make Drupal 6 search result URL use "-" instead of space?
Example of Drupal 6 search result URL is like this:

```
http://www.site.com/search/node/Search for something

```

How to make Drupal 6 search result URL use `-` instead of space? (below is an example):

```
http://www.site.com/search/node/Search-for-something

```

# Answer
You could add the functions custom\_url\_rewrite\_inbound() and custom\_url\_rewrite\_outbound() in the settings.php.

`custom_url_rewrite_outbound()` would rewrite the URLs which are output from any module, and `custom_url_rewrite_inbound()` would rewrite the URL being requested to Drupal.

This is the example code used in the documentation of `custom_url_rewrite_outbound()`.

```
function custom_url_rewrite_outbound(&$path, &$options, $original_path) {
  global $user;

  // Change all 'node' to 'article'.
  if (preg_match('|^node(/.*)|', $path, $matches)) {
    $path = 'article' . $matches[1];
  }
  // Create a path called 'e' which lands the user on her profile edit page.
  if ($path == 'user/' . $user->uid . '/edit') {
    $path = 'e';
  }
}

```

In your case, the code could be something similar to the following one.

```
function custom_url_rewrite_outbound(&$path, &$options, $original_path) {
  if (preg_match('|^search(/[^/]+/(.+))|', $path, $matches)) {
    $path = 'search/' . $matches[1] . str_replace(' ', '-', $matches[2]);
  }
}

```

`custom_url_rewrite_inbound()` should do the exact opposite.
The code I wrote does not consider the case the `-` is included in the search string. The code should consider that case, for example adding another `-` where there is already one; when it does the opposite operation, the code should first replace a single `-` with a space, and then remove a `-` where there are more of those characters in row.
> 0 votes

# Answer
If you have installed pathauto module then Check admin/build/path/settings this setting.
> -3 votes

---
Tags: search, uri, 6
---


# Question
Title: jQuery_ui slider doesn't load for anonymous user
In my recent **drupal 7** install... I've installed **jquery\_update**. I configured it, and added a little module with a js.

**jQuery\_ui** is not loaded for anonymous use. I've done some researches on the web ... for most people jquery doesn't load for anonymous user because it wasn't called. But for me jquery loads correctly I can `alert(jQuery("#amount"))` succesfully.

My error message is **`TypeError: jQuery(...).slider is not a function`** : jquery\_ui slider method is not loaded for anonymous user... I searched in permissions too.. no jquery\_ui permission configuration.

What did I missed ? Couls anyone help ?

Thanks in advance.

# Answer
I found the quick answer : Add this line in the module using jquery\_ui to call jquery\_ui when needed.

```
drupal_add_js('https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.11/jquery-ui.min.js', 'external');

```

or this:

```
drupal_add_js(drupal_get_path('module', 'jquery_update') .'/replace/ui/ui/minified/jquery-ui.min.js');

```

The question now is : is this the best way?
> 0 votes

---
Tags: 7, users, javascript
---


# Question
Title: Redirect to a Multi-site Install Failing
We're trying to redirect a subdomain to a multisite install on an Amazon EC2 Server. The initial redirect worked like a champ -- it went to the raw IP and we created a directory in **`sites`** (**`sites/54.235.145.17`**) matching the IP address.

So, now we're trying to do "Masked Subdomain Forwarding" from godaddy.com and it isn't working. It is always resolving to the raw IP address directory. We've done:

* Created the matching subdirectory: (**`demo2.kcl.com`**)
* Created a separate database for the new site
* Modified settings.php to access said database

The directory listing:

```
drwxrwxrwx 6 bitnami daemon  4096 Feb  7 02:20 .
drwxr-x--- 9 bitnami daemon  4096 Jan 27 22:13 ..
drwxrwxrwx 3 bitnami daemon  4096 Jan 29 12:39 54.235.145.17
drwxrwxrwx 5 bitnami daemon  4096 Feb  2 07:53 all
drwxrwxrwx 3 bitnami daemon  4096 Jan 29 12:36 default
-rwxrwxrwx 1 bitnami daemon  2365 Jan 16 21:45 example.sites.php
drwxr-xr-x 3 bitnami daemon  4096 Feb  7 04:06 demo2.kcl.com
-rwxrwxrwx 1 bitnami daemon   904 Jan 16 21:45 README.txt

```

If I'm reading the documentation correctly, this should work but it is not. As I said, it simply resolves back to the raw IP address.

Any solutions or even just things to check would be greatly appreciated.

Thanks in advance!

Scott.

(NOTE: IP and domain names have been changed to protect the ... spammable.)

# Answer
From the looks of your folder structure you're missing the most important file for a multisite install...`sites.php`.

Copy example.sites.php to sites.php, edit it to add all sites in the installation to their respective paths, and try again...it should work.

These are the code samples example.sites.php for convenience:

```
// URL: http://dev.drupal.org
$sites['dev.drupal.org'] = 'example.com';

// URL: http://localhost/example
$sites['localhost.example'] = 'example.com';

// URL: http://localhost:8080/example
$sites['8080.localhost.example'] = 'example.com';

// URL: http://www.drupal.org:8080/mysite/test/
$sites['8080.www.drupal.org.mysite.test'] = 'example.com';

```

The format is:

```
'<port>.<domain>.<path>' => 'directory'

```
> 0 votes

---
Tags: multi-sites, subsites
---


title: Date Filter in drupal

text:
# Question
Title: Date Filter in drupal
Can anyone help me how to expose the date filter in a view in drupal 7.

I have added post date filter with in FILTER CRITERIA but it is not working

Can anyone help me

# Answer
Here is how I used exposed filter to filter content with date (assumed you have the **Date Views** module enabled).

I just create a view with all fields and the in the "Advanced \> CONTEXTUAL FILTERS" section, I add a new contextual filter and I select **Date : Date (node)**. In the next box, I can select the date field to filter (publication date or any date field). I can also give a default value if no date parameters is passed through the url : for example, the current date.

And that's it, I just pass the date as URL parameter : I have something like

```
http://mydomain.com/agenda/all/2012-03

```

where /all is my first parameter, I us it to match a country for my posts, and the second parameter is the month of the post.

I hope that helps.
> 1 votes

# Answer
You can add "your date filed" as filter and can expose the filter. so that the filter will appear in the front end, using that we can display the nodes that are created between two given dates.
> 0 votes

---
Tags: views
---


# Question
Title: Profile image goes over the text on advance forum in drupal 7
I'm fairly new to Drupal and I'm testing out Advanced Forum module on my site.

The problem I'm facing is that when photo which is uploaded is bigger than user info layout, then it goes over the text. Is there any way to force image to stretch and fit into the user info block?

I tried changing css, but I'm not really sure which one to change and in what manner. I'm using silver bells...

Can anyone guide me through this?

Thanks in advance!

# Answer
> 0 votes
It might not be exactly the answer you're looking for, but using CSS only, you can add this rule to your theme's main css file:

```
img{
max-width: 100%;
}

```

---
Tags: media, theming, nodes
---


# Question
Title: Remove features without lose functionality
I'm working on a project where in the past was added a lot of features and was did in a way where right now a lot of them has a lot of circular dependencies and conflicts.

I want to start again, delete all the features, create new ones and avoid to each of them make conflicts with another.

My question is, how i can "remove" the features but not lose the changes to they did it on the project?, in other words how i can move the configuration "in code" into the database? for i able to remove the feature but preserve the configuration in the site?

I'm using Drupal 6

# Answer
> 11 votes
You can use the Features Tools Module to disable a features module while leaving the functionality that was provided by the feature in place.

Instructions provided by autopoietic here.

> 1. First BACKUP YOUR DATABASE
> 2. backup your feature (files) if you would like to use it again.
> 3. Once installed, go to the 'recreate' page for a feature, uncheck all of the features components
> 4. In order to save the elements to the DB you need to go to the admin/build/features/unlink page, check the element you need to import and submit.
> 5. Now click on the 'Safe autocreate' button to recreate and replace the feature with an empty version.
> 6. You can now disable the module without affecting your site configfuration.

These instructions note that "if you are using D6 there is an extra step" which I have added (step 4 above).

---
Tags: 6, features
---


title: Drupal 7 Display a block on custom tab

text:
# Question
Title: Drupal 7 Display a block on custom tab
I would like to display a view block on a custom tab I created as follows, but the tab is always empty. The block has the option to be shown only on specified path node/%node/calendario-corsi. Is it correct to have an empty page callback?

```
function custom_morebuttons_menu() {

  $items['node/%custom_node_calendario_corsi/calendario-corsi'] = array (
   'title' => 'Calendario corsi',
   'page callback' => 'custom_node_calendario_corsi_page',
   'page arguments' => array(1),
   'access callback' => 'user_is_logged_in',
   'type' => MENU_LOCAL_TASK,
   'weight' => 10,
  );

  return $items;
}

function custom_node_calendario_corsi_load($arg) {

  $node = node_load($arg);

  if($node->type == 'centro' || $node->type == 'sede') {

    return $node; }

  return FALSE;
}

function custom_node_calendario_corsi_page($arg) {

  return '';
}

```

# Answer
> 0 votes
This is my working solution:

```
function custom_morebuttons_menu() {

  $items['node/%custom_node_calendario_corsi/calendario-corsi'] = array (
   'title' => 'Calendario corsi',
   'page callback' => 'custom_node_calendario_corsi_page',
   'page arguments' => array(1),
   'access callback' => 'user_is_logged_in',
   'type' => MENU_LOCAL_TASK,
   'weight' => 10,
  );

  return $items;
}

function custom_node_calendario_corsi_load($arg) {

  $node = node_load($arg);

  if ($node->type == 'centro' || $node->type == 'sede') { return $node; }

  return false;
}

function custom_node_calendario_corsi_page($node) {

  if ($node->type == 'centro') { return views_embed_view('centro_autenticato_calendario_corsi', 'block_1', $node->nid);

  } else if ($node->type == 'sede') { return views_embed_view('sede_autenticato_calendario_corsi', 'block_1', $node->nid); }
}

```

# Answer
> 0 votes
Should be next:

```
function custom_morebuttons_menu() {
  $items['node/%node/calendario-corsi'] = array(
    'title' => 'Calendario corsi',
    'page callback' => 'custom_node_calendario_corsi_page',
    'page arguments' => array(1),
    'access callback' => 'user_is_logged_in',
    'type' => MENU_LOCAL_TASK,
    'weight' => 10,
  );

  return $items;
}

function custom_node_calendario_corsi_page($node) {
  $node = node_load($arg);
  if (($node->type == 'centro') || ($node->type == 'sede')) {
    // I assume you will add some behaviour code for this, next make no sense.
    return $node;
  }
  return false;
}

```

---
Tags: blocks
---


# Question
Title: Duplicate view results when adding a filter related to field with multiple values?
I have a view to list the Voucher content type. I added a filter: `Configure filter criterion: Content: Voucher codes (field_voucher_code)` NOT EMPTY.

The idea is to show the node only if its field `field_voucher_code` is not empty

The `field_voucher_code` is field which has set the **Number of values to 10** at `admin/structure/types/manage/vouchers/fields/field_voucher_code`

The problem is that the view is duplicating each as many time as values has in its field `field_voucher_code`.

How can I eliminate the duplicates?

# Answer
> 1 votes
You can do this by enabling `Aggregation` or set distinct in Query settings

1. Go to your `View->Advanced->Use Aggregation -> set YES`
2. Next in your field filter criteria chose - Count DISTINCT

One more way - 1. Go to your `View->Advanced->Query Settings -> check DISTINCT`

---
Tags: entities, views
---


# Question
Title: Ajaxify certian content on the front page
My site uses dashboard as front page and loads boxes to show content. As there are many boxes, the page takes some time to load. So what i want to do now is to load the theme and interface first and then load the boxes using ajax. Is there any kind of solution already available or something that needs to be tailored.

My site is here

# Answer
You might be interested in Ajax Blocks, which allows you to load a block on a given page via AJAX, after the page has loaded.

See also: Calling a block by AJAX
> 1 votes

---
Tags: ajax
---


# Question
Title: How can I track stale content and alert content owners to it?
I'm building a new version of a corporate web site, and want to make it easy for content owners to keep their content updated regularly.

In the current site, most of the content has not been updated for years, and it's unclear who is responsible for various pieces of content. In the new site, each part of the site (usually a section but in some cases individual pages) will have a person or group of people designated as the owners of that content, and responsible for keeping it updated. I'm pretty certain, however, that they won't do anything unless they are prodded.

One possibility is to add a Dated boolean to all nodes to flag certain content as something that will go out-of-date regularly, such as an About Us page that says "we currently have 127 locations across states X, Y, and Z in the U.S. and provinces A, B, and C in Canada. Then there would need to be some mechanism to send e-mail notifications to the designated owner of that content after (for instance) 3 months, including the content and a link to edit it, and asking them if it is still accurate. Content not marked "Dated" could have e-mails sent out after (say) 9 months, or whatever time frame seems logical.

I've searched for a module that helps solve this problem, but have found nothing. How would you go about doing this, or something like it (if you have an alternate idea to solve the problem)?

# Answer
It's been awhile since you asked and I'm assuming you found an answer. For those who come across this post, the Rules module should handle this requirement.

1. Create a rule to react when content is viewed, which should suffice as a trigger.
2. Add a condition to run a data comparison on node modification date or write custom PHP comparison code.
3. Set the rule to send an email to the node's author.
> 2 votes

---
Tags: 7, nodes
---


# Question
Title: Display/hide CCk field with custom PHP and rules or
I have custom variables stored in sessions, those variables are obtained remotely via URL arguments fired by remote website.

I am currently using Drupal 7, and I want to enable custom custom field A or B based on the value of the custom variable; if the custom variable is empty, it should enable field A, otherwise, enable field, B.

Can you please assist on what needs to be done?

# Answer
> 1 votes
Two quick ways come to mind.

Off the cuff...

You could use the preprocess\_node() hook, something along the lines of:

```
MYMODULE_preprocess_node(&$variables) {

  if ($variables['node']->type=='THISKINDOFNODE') {

    if (empty($_SESSION['VARIABLE')) {
      unset($variables['node']->field_B;
    } else {
      unset($variables['node']->field_A;
    }

  }

  // other preprocessing here

}

```

You also could create a `node--TYPE.tpl.php` file and inside it, do something like this:

```
if (empty($_SESSION['VARIABLE'])) {
  hide($content['field_B');
} else {
  hide($content['field_A');
}

```

---
Tags: rules, entities
---


# Question
Title: How to fix "This display does not have a source for contextual filters"
I've set up a view to produce a block of content nodes based on taxonomy. I have the filter criteria to include Has Taxonomy term (not empty). Then under advanced I added a contextual filter '*Has Taxonomy Term ID*'.

But when I set it up (or edit it) there is a message:

> This display does not have a source for contextual filters, so no contextual filter value will be available unless you select 'Provide default'.

And that type (has taxonomy term ID) comes under 'provide default value'.

I don't mind all of this, but this particular example has 3 taxonomy terms that are quite similar:

* Virtual meetings
* Virtual classroom
* Virtual seminar rooms

These block views are pulled onto a panel page, again based on taxonomy. But on each of the 3 pages there are 3 listings, instead of one!

>

Can anyone think of what I might be doing wrong here?

I am using Drupal 7 and Views 7.x-3.3.

# Answer
> 0 votes
This is frustrating. AFAIK

"Content Pane" displays do not have context passed to them ever. Views have "master" displays that do get context passed.

The "master" display is essentially the view's defaults. To see it, there is an option here: admin/structure/views/settings/basic (or just delete all other displays)

To add a view's "master" display to a panel, you need to see it first: http:///admin/structure/panels/settings

Now go back to the panel, add content, select "views" instead of "view panes" to see your view.

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


# Question
Title: Using Webform Hooks to submit and display custom module forms?
So i created my custom module form and submit handler...then realized i needed to use Webform hooks to save and hopefully view. Basically i wish for webform to manage the heavy lifting by taking care of the save and submissions.. also is it possible to save the values from the form as nodes or send them as emails? please any help is appreciated iv been staring at the webform API for days..

# Answer
> 1 votes
Webform has nothing to do with your form if you created it in a module.Your form is a form not a webform type node. Form API! reference is what you need and to install Devel module

Then

```
dpm($form)

```

inside your form builder function to check which function is your #submit which is your #validate and add\[\] your own if you like

form values are stored in $form\_state array dpm($form\_state) it also in your submit function and do whatever you want with these submitted values.

Store them in drupal database using variable\_set() , mail them using drupal\_mail() etc.

Some links

http://drupal.org/node/717740 http://api.drupal.org/api/examples/form\_example%21form\_example\_tutorial.inc/7

---
Tags: forms, hooks, webforms
---


# Question
Title: how to create shell command 'd' as equivalent to 'drush'?
Typing "drush" over and over again, I find it is quite time consuming. How can I shorten the command so I can just type "d"?

I am using Mac OS X.

# Answer
> 5 votes
If you are using Drush-5 (recommended), then see examples/example.bashrc for a bunch of very useful ways to enhance your experience in your shell when using Drush. Installation instructions are in the file. One of the things it does is create an alias 'dr' for Drush; if you wanted this to be 'd' on your system, it would be easy enough to make that change.

# Answer
> 2 votes
If you want to do this in Bash (or Zsh or Ksh or whatever) you can create an alias. Type

```
alias d=drush

```

on the command line for an ephemeral alias (that will go away when you close your shell). To have the alias permanently available, add that same line to a startup file. That would be `.bashrc` or `.bash_profile` if you use Bash, `.zshrc` if you use Z shell, etc. If you're on OS X and haven't changed your shell, you're using Bash (unless you're on a *very* old version of OS X).

An advantage to creating shell aliases is that you can create similar aliases for any other shell command you want, not limited to Drush commands. The advantage to creating Drush aliases (IIRC) is that you can create Drush 'subcommand' aliases, which you can't do with shell aliases. E.g. `drush perform-my-secret-command` or whatever.

---
Tags: drush
---


# Question
Title: Query custom node by user Entity Reference
I am trying to build a query that finds all nodes of a custom type where one of the fields is a user Entity Reference. I am trying to use EntityFieldQuery but just as open to db\_select(). The following is just an example of one of the queries I have tried.

```
$query = new EntityFieldQuery();

$query
  ->entityCondition('entity_type', 'node', '=')
  ->propertyCondition('type', 'custom_node', '=')
  ->fieldCondition('field_marketer', 'value', $user->uid, '=');

$entities = $query->execute();

```

Thanks in advance for any help.

# Answer
The column name for an entity reference field is `target_id`, so your code should be:

```
$query = new EntityFieldQuery();

$query
  ->entityCondition('entity_type', 'node', '=')
  ->propertyCondition('type', 'custom_node', '=')
  ->fieldCondition('field_marketer', 'target_id', $user->uid, '=');

$entities = $query->execute();

```
> 8 votes

---
Tags: database
---


# Question
Title: How can I avoid broken filenames in cached content?
I'm using Feeds to import data from Site A to Site B. Feeds runs every 15 minutes to check for new content, via cron / job\_scheduler. I have caching turned on, with minimum lifetime and expiration both set to 15 minutes, with the hope that content will be rebuilt for anonymous users every 15 minutes.

The problem I'm having is that if Feeds updates a node and brings over a new image (or the same image; Feeds renames the same image every time the parent node updates) then the image on the rendered node is broken, as the original image doesn't exist anymore. e.g. example.com/files/image.jpg is deleted and replaced with image\_0.jpg, while the cached page still has image.jpg in its source. Is there a good way to combat this, outside of having Feeds replace the existing file?

# Answer
> 2 votes
You might attach a cache\_clear\_all() at the end of your import task.

So every time Feeds updates your content, your cache will be reset.

Your cache will be handled right when it's needed. It's not safe in my opinion to rely on "coincidence" between import time and cache lifetime.

---
Tags: 7, feeds, caching
---


# Question
Title: Delete all nodes from database except from user1 and admin
I have got thousands of junk entries in my Drupal 6 website. Is there a way I can Delete all nodes from database accept from user1 and admin.

I also want to delete all users accept user1 and admin.

# Answer
> 3 votes
Yes, you could do that with

views\_bulk\_operations

It will delete the nodes and users progressively using the Batch API.

* Create a content / node based View
* Add the bulk operations field
* Configure bulk operations field to add "Delete item'
* Add filters to View to exclude content from user1 / admin
* Run the View, check to select all rows, and bulk delete the relevant nodes.

Repeat using a user-based View to delete users.

Note, prior to deleting users, check the account cancellation settings at `Admin > Configuration > Account settings > Registration and cancellation`

---
Tags: database
---


# Question
Title: Restrict a users node posting total dependent on a paid subscription role
I am interested in how one would restrict a users node posting total dependent on a paid subscription role.

For example, there maybe 3 subscription roles which allow different Node posting for a user dependent on which Role they have chosen on site registration. Using UberCart for example, 3 packages (Low, Mid, High) offer 10,25, 50 respectively to a user. The total posting per month cannot exceed that amount at anyone time in that they can either add/edit/delete an applicable Node (only of their own posting), but not exceed that subscription's total given amount for that role. I would be interested in the best easiest and best approach to this using Rules/Views/UberCart framework. Or possibly knock up a custom table in the backend to tally up the number of said posts per user if that need be the case.

Alternatively, the restriction or limitation of Node content 'viewing' per subscription role. ie Pay to read more of the said Node content. Which appears nowadays to be an emerging trend for online content access as I see it.

Any comments and ideas greatly appreciated for a learning developer.

# Answer
In my opinion the best solution would be Ubercart for selling roles to users and Node Limit module to set a block on how many nodes can be created by certain roles (in a given period, optionally).

You should set up different roles, one for every different amount of nodes a user can create. Then with Ubercart you have configure a product for every role to be sold.

Then with Node Limit module you can configure the restrictions for every role.
> 0 votes

---
Tags: users
---


# Question
Title: How do I get rid of a table doesn't exist warning?
I have a Drupal 6 installation for my website, and over time, without any doing on my part, I started getting an error, below:

> user warning: Table 'pharmtec\_pharmtechinc.xmlsitemap' doesn't exist query: SELECT * FROM xmlsitemap WHERE type = 'node' AND id IS NULL in /home/pharmtec/public\_html/sites/all/modules/xmlsitemap/xmlsitemap.module on line 544.

I have no clue what the issue is. I did find out, though, that it does come up for both existing and new pages.

I'm stuck because I can't update the content of the site. When I add information and preview, it shows all the source code for the entire page, rather than just the text. :(

Thanks for any help you can provide.

# Answer
If ok with some code, you could also try running

```
drupal_install_schema('xmlsitemap');

```

and that should recreate the xmlsitemap tables, backup db first.

more info:
> 1 votes

# Answer
The table seems to be related to XMLSitemap Module, are you using this module for anything? if not simply disable it and this error will go away, if you are then something has gone wrong with the module configuration/your database and it needs fixing.

If you need XMLSitemap enabled, try first running update.php and make sure you are on the latest stable version of XMLSitemap.
> 0 votes

---
Tags: nodes
---


title: Track Individual User Page Visits

text:
# Question
Title: Track Individual User Page Visits
Drupal 7 - Is there an easy way to track individual user page visits using Google Analytics or can I just do this within Drupal?

# Answer
> 8 votes
Worth noting that tracking individual users is against the Google Analytics terms of service:

> 7.PRIVACY . You will not (and will not allow any third party to) use the Service to track or collect personally identifiable information of Internet users, nor will You (or will You allow any third party to) associate any data gathered from Your website(s) (or such third parties' website(s)) with any personally identifying information from any source as part of Your use (or such third parties' use) of the Service. You will have and abide by an appropriate privacy policy and will comply with all applicable laws relating to the collection of information from visitors to Your websites. You must post a privacy policy and that policy must provide notice of your use of a cookie that collects anonymous traffic data.

However, Drupal can track authenticated users using the core statistics module.

More info:

---
Tags: users
---


# Question
Title: Undo to Taxonomy term system path unset with _menu_alter
I have a question about taxonomy term system path. I have run this code:

```
function MYMODULE_menu_alter(&$items) {
  unset($items['taxonomy/term/%taxonomy_term']);
  unset($items['taxonomy/term/%taxonomy_term/view']);
  unset($items['taxonomy/term/%taxonomy_term/feed']); // If you want to hide the feed as well.
}

```

Now I want to know how to reverse this for the future need. How can I set system paths for all taxonomy terms. Thanks in advance.

edit:

Hi David

In first place I have a problem how to forbid anonymous access to all taxonomy terms (eg. mysite/vocabulary/term). I don't want anonymous user to see this pages. I was searching for answer whole day and I found the **alter\_menu snippet** as the only suitable answer, because for now I don't need terms links from outside world.

So, if I put this script in custom module and run once it clears all system paths for all taxonomy tearms (as it can be seen from admin/URl aliases/list). This is good solution, but I don't think the best one. I need a proof that in the future if I will need this system paths, I can rebuild them. I don't know how to do it!?

I have tried to comment that hook\_menu\_alter snippet but what next I have to do. I mean, system paths will not be automatically rebuilded. Am I right?

Also, i didn't find suitable module to control access to taxonomy terms from outside for anonymous users. Some modules can control that, but my site is using terms thru views and with that modules views are also invisible for anonymous users (eg. Taxonomy Tools module, access part).

# Answer
The question is a little unclear, to reverse that effect, you would simply delete that hook\_menu\_alter snippet.

To change the paths to something else, you would use hook\_menu and create the relevant menu callbacks.

The last step there would be to change the taxonomy\_term entity\_uri so it uses your new callback.

i.e redefine taxonomy\_term\_uri in hook\_entity\_info\_alter

```
/**
 * Implements hook_entity_info_alter
 */
function mymodule_entity_info_alter(&entity_info){
  $entity_info['taxonomy_term']['uri callback'] = 'mymodule_taxonomy_term_uri';
}

/**
 * Custom taxonomy_term entity_uri callback
 */
function mymodule_taxonomy_term_uri($term){
  return array(
    'path' => 'mymodule/taxonomy/term/' . $term->tid,
  );
}

```

Not sure why you'd want to do that though ;)

**edit**: If you want to deny access, better to use hook\_menu\_alter to add your own access callback to the taxonomy menu paths. Alternatively, override the path with Panels or Views and set access control there.
> 0 votes

---
Tags: taxonomy-terms
---


# Question
Title: render field collection with already defined custom formatter
I defined a formatter for a field with hook\_field\_formatter\_info()/view(). This field is a field collection and renders fine when I choose my custom formatter through the ui.

I can get my (already defined) field collection with:

```
$field_collection = entity_load('field_collection_item', array($field_nid))[$field_nid];

```

This returns a FieldCollectionItemEntity. (info) But how can I render this field colleciton programatically.

```
render($field_collection);

```

Does not seem to work and I don't see any methods to render this field collection through code even though the ui config has no problem rendering it as I've defined it.

Thanks!

# Answer
So it turns out that the field collection 'field' will be treated like a normal field and rendered properly. You don't need to load the field with entity\_load. (We don't need any of the fields in the collection, we just want the entire collection). And using field\_view\_field you can choose your custom formatter:

```
  //get the nid of the node that contains the field collection from any number of methods
  $node = node_load($nid);
  // the custom formatter was already defined using hook_field_formatter_info() and
  // hook_field_formater_view() (see drupal docs)
  $display = array('type' => 'custom_formatter_name');
  //print or 'return' depending if this is a module or a template file
  print drupal_render(field_view_field('node', $node, 'field_name', $display));

```

The two hurdles for me were (1) finding out that you can add the custom formatter to field\_view\_field() and (2) that I needed to print out this info (not return) as I was in a template file, not a function of a module (doh!).
> 2 votes

---
Tags: entities
---


# Question
Title: DB API: How to get a list of nodes ordered by highest comment creation date?
The DB API is once again kicking my tail...

I've got a bunch of nodes of a certain type, each of which can have any number of comments, all in the usual way. I'm trying to do a db\_select()-based query that will give me the set of nodes of that type, ordered by the creation dates of each node's comments: The first node in the set would be the one that has the most recent comment, the second node would be the one that has the second most recent comment, and so on. I'm sure / strongly suspect that this takes some sort of subquery, but I'm just not getting it right. Can anyone offer some help? Thanks!

# Answer
> 3 votes
The best place to query for that is the **node\_comment\_statistics** table.

It contains the relevant comment statistics such as comment count and last comment timestamp for a node.

e.g: Query for article nodes ordered by last\_comment\_timestamp DESC

```
$query = db_select('node_comment_statistics', 'c');
$query->join('node', 'n', 'n.nid = c.nid');
$query->fields('c', array('cid', 'last_comment_timestamp')); // fields
$query->fields('n', array('nid', 'title'));
$query->condition('n.type', 'article'); // e.g filter for articles only
$query->condition('n.status', 0, '>');
$query->orderBy('c.last_comment_timestamp', 'DESC'); // Order by last commented
$results = $query->execute();

foreach($results as $row) {
  drupal_set_message('<pre>'.print_r($row,1).'</pre>'); // debug
}

```

node\_comment\_statistics table schema:

```
mysql> desc node_comment_statistics;
+------------------------+------------------+------+-----+---------+-------+
| Field                  | Type             | Null | Key | Default | Extra |
+------------------------+------------------+------+-----+---------+-------+
| nid                    | int(10) unsigned | NO   | PRI | 0       |       |
| cid                    | int(11)          | NO   |     | 0       |       |
| last_comment_timestamp | int(11)          | NO   | MUL | 0       |       |
| last_comment_name      | varchar(60)      | YES  |     | NULL    |       |
| last_comment_uid       | int(11)          | NO   | MUL | 0       |       |
| comment_count          | int(10) unsigned | NO   | MUL | 0       |       |
+------------------------+------------------+------+-----+---------+-------+

```

# Answer
> 1 votes
Something like the following should work:

```
$query = db_select('comment', 'c');
$query->join('node', 'n', 'n.nid = c.nid');

$query->fields('c', array('nid'))
    ->addExpression('max(c.created)', 'max_created');
$results = $query->condition('n.type', 'article', '=')
    ->condition('c.status', 0,'>')
    ->condition('n.status', 0,'>')
    ->groupBy('c.nid')
    ->orderBy('max_created', 'desc')
    ->execute();

foreach($results as $record) {
    // $record->nid contains the nid of one node
}

```

# Answer
> 0 votes
After some more searching, I bumped into How to do an embedded select (with count()) with the Drupal 7 database api? which, has it happens, I had posted some time ago about a similar issue. In any case, the following seems to be working for me:

```
$q = db_select('node', 'n');
    $q->condition('n.type', 'whatever');

    $sub_query = "(select max(created) as max_created from {comment} c where c.nid = n.nid)";
    $q->addExpression($sub_query, 'max_created');

    $q->fields('n', array('uid', 'nid'));

    $q->orderBy('max_created', 'desc');
$q = $q->execute();

```

As an aside, this needs to be done as a db\_select on `node` so I can run a pager against it. In any case, comments are welcome.

---
Tags: 7, database
---


# Question
Title: How to add taxonomy term reference field in a custom drupal form
A menu item is defined with `drupal_get_form` as callback function and returning the form from call back function. How can I add `taxonomy_term_reference` field to this form?

```
$items['files/add'] = array(
      'title' => 'Add file',
      'description' => 'Allows users to add files',
      'type' => MENU_CALLBACK,
      'page callback' => 'drupal_get_form',
      'page arguments' => array('mymodule_add_file'),
      'access callback' => TRUE,
    );
function mymodule_add_file($form, &$form_state) {
    drupal_set_title("Add file");
    $form['mymodule_form'] = array(
      '#type' => 'fieldset',
      '#tree' => TRUE,
      '#collapsable' => FALSE,
      '#title' => 'Adding file to locker room',
    );

    $form['mymodule_form']['file'] = array(
      '#type' => 'managed_file',
      '#title' => 'Upload file',
    );

    $form['mymodule_form']['tag'] = array(
      '#type' => 'taxonomy_term_reference',
      '#title' => 'Tags',
    );

    return $form;
}

```

I am not sure how to add taxonomy\_term\_reference field for `$form['mymodule_form']['tag']` . I want this field to be a text field with auto complete from a vocabulary terms and new term to be added when entered term is not found

# Answer
> 5 votes
For Drupal 7, the code is something like this, where `field_tags` is a taxonomy field in the node with widget type autocomplete.

```
<?php
   $node=node_load($nid);
    $tags = array();
    foreach ($node->field_tags['und'] as $item) {
      $tags[$item['tid']] = isset($item['taxonomy_term']) ?  $item['taxonomy_term'] : taxonomy_term_load($item['tid']);
    }
    $form['tags'] = array(
      '#type' => 'textfield',
      '#default_value' => taxonomy_implode_tags($tags),
      '#title' => 'Add Tags',
      '#autocomplete_path' => 'taxonomy/autocomplete/field_tags',
      '#maxlength' => 1024,
      '#element_validate' => array('taxonomy_autocomplete_validate')
    );
?>

```

# Answer
> 0 votes
You need to include the vocabulary id - you should be able to hardcode it so either

```
$form['mymodule_form']['tag'][$vocabulary->vid] = array(
  '#type' => 'textfield',
  '#default_value' => $typed_string,
  '#maxlength' => 100,
  '#autocomplete_path' => 'taxonomy/autocomplete/'. $vocabulary->vid,
  '#required' => $vocabulary->required,
  '#title' => $vocabulary->name,
  '#description' => t('Some description ...").')

```

);

or for vocab id 5

```
$form['mymodule_form']['tag']['5'] = array(
  '#type' => 'textfield',
  '#default_value' => $typed_string,
  '#maxlength' => 100,
  '#autocomplete_path' => 'taxonomy/autocomplete/5',
  '#required' => $vocabulary->required,
  '#title' => $vocabulary->name,
  '#description' => t('Some description ...").')
);

```

Not tested, but that should work. Else have a gander here: http://drupal.org/node/854216

# Answer
> 0 votes
I used this and I got autocomplete callbacks working, however not for the specified taxonomy vocab. Instead it returned results from all vocabs

```
  $element['test'] = array(
      '#type' => 'textfield',
      '#default_value' => isset($items[$delta]['test']) ? $items[$delta]['test'] : NULL,
      '#maxlength' => 100,
      '#autocomplete_path' => 'taxonomy/autocomplete/37',
   );

```

I'm not quite sure why that is to be honest.

# Answer
> 0 votes
@tecjam For Drupal 7, you almost had it. All you have to do is use the field name instead of the vocab id.

Like this:

```
 $element['test'] = array(
 '#type' => 'textfield',
  '#default_value' => isset($items[$delta]['test']) ? $items[$delta]['test'] : NULL,
  '#maxlength' => 100,
  '#autocomplete_path' => 'taxonomy/autocomplete/field_name',
);

```

Replace field\_name with the name of your field.

---
Tags: 7, taxonomy-terms, forms
---


# Question
Title: How to add a CCK field to custom template file?
I am working on a Drupal 7 site, and I am setting up a template that will be used with the Print module when PDFs are created using that module. The PDFs will draw from pages that list specifications of products, and the PDF itself will act as the printed spec sheet.

I want to completely customize the output of the PDF so that I can choose where each and every field will be placed. Unfortunately, the PDF creation is currently not respecting all of the layout specifics on the website page, so I have decided to customize the print.tpl.php file (part of the Print module) to enact those specific layout elements.

The part I am stuck on is... how do I call in the various individual fields/fieldsets from the content item and have them show up on the template file for printing? For instance, the content type is "Shirts" and one of the fields in question is "Color" ("field\_shirtcolor")... how can I access that field/print that field in my custom tpl file?

Thanks!

# Answer
> 1 votes
Add to your `print.tpl.php` code like next for printing certain field:

```
<?php print render(field_view_field('node', $print['node'], 'field_shirtcolor')); ?>

```

If field is multiple:

```
<?php
  $field = field_get_items('node', $print['node'], 'field_shirtcolor');
  $delta = 0;  // Put here index of multiple field or use `foreach ($field as $val) {}` for scanning multifield values.
  print render(field_view_value('node', $print['node'], 'field_shirtcolor', $field[$delta]));
?>

```

If field is image:

```
$image = field_get_items('node', $print['node'], 'field_image');
print render(field_view_value('node', $print['node'], 'field_image', $image[0], array(
  'type' => 'image',
  'settings' => array(
    'image_style' => 'STYLENAME',
    'image_link' => '',
  ),
)));

```

p.s. Drupal 6 CCK in Drupal 7, 8 called as just **Fields**.

---
Tags: 7, theming
---


# Question
Title: Node edit page not showing up using page.tpl.php?
I'm working on a new drupal 7 site right now (I'm new to drupal) and currently have given the ability to users to create nodes. The node creation page (url.com/node/add/) works just fine and uses the page.tpl.php template.

However, when I'm using the edit page (url.com/node/NODEID/edit/), it doesn't even load a page.tpl.php file. I went ahead and added some code to my page.tpl.php file to see if it would even read out--which it didn't. I've found that the edit page is inserting itself at the html.tpl.php level of the site. Is there a quick way I can get this to use page.tpl.php or by creating a node--edit.tpl.php or something? Hopefully I have made enough sense, but am stuck.

# Answer
> 1 votes
Make sure you have the setting 'Use the administration theme when editing or creating content' unchecked in you 'appearance' settings page. This would override your theme on the node edit pages causing your page.tpl.php file not to be used.

---
Tags: nodes, forms
---


# Question
Title: How to reset a form element to its ordinary default value?
I do a form alter on a node form and make some callbacks which restrict value lists in a \< select \> element, which is a entity reference. When the triggering element is changed, I want to load the node forms default value just like it is in the beginning of the form process. I remember there was an api function to do that. Someone nows it?

# Answer
> 6 votes
field\_get\_default\_value \- Helper function to get the default value for a field on an entity.
Usage:

```
<?php
  $field = field_info_field('YOURFIELDNAME');
  $instance = field_info_instance('node', 'YOURFIELDNAME', 'YOURNODETYPE');
  $defvalue = field_get_default_value('node', $node, $field, $instance, $node->language);
  print_r($defvalue); // Here structure, like $defvalue[0]['value']
?>

```

---
Tags: forms, entities
---


title: Where to place drush in MAMP

text:
# Question
Title: Where to place drush in MAMP
I placed drush in MAMP folder outside of htdocs folder and downloaded drupal successfully but obviously to wrong folder. Where should drush be placed to have it work with drupal folder in htdocs folder?

# Answer
I use the drush qd command and add the --root parameter. You can use it to download the Drupal installation into /Applications/MAMP/htdocs
> 0 votes

---
Tags: drush
---


title: Drupal Module for Zoom Print and Save

text:
# Question
Title: Drupal Module for Zoom Print and Save
I would like to ask about finding a particular module on Drupal. I need to add "Zoom", "Print", and "Save" functionalities.

I am sure there must be a module to handle this. Is there any solution about which module I should use? For your information, I am using Drupal 7 and need to add the functionality to Views page.

# Answer
I'm not sure what do you mean by zoom!! Image zoom or text resize?

Anyways you need to install 3 modules
> 0 votes

---
Tags: views, 7
---


# Question
Title: What are the performance implications of running a frequent simplenews cron task to send emails?
In the Simplenews docs there is the following tip:

> The Elysia Cron module (http://drupal.org/project/elysia\_cron) can be used to start the simplenews cron hook more often than others, so that newsletter are sent faster without decreasing site performance due to long-running cron hooks.

This is great because it will clear the mail spool without waiting for several cron runs to occur. However what are the performance implications of running this cron task on an ongoing basis with a short interval of say 30 minutes? Especially if a newsletter only gets sent once a month. i.e. My simplenews cron task in running every 30 minutes with nothing to do.

# Answer
Once every 30 minutes will most likely not cause any issues. I've never used that module before so I can't saw with 100% certainty. If you where to change the frequency from 30 minutes to 1 minute I might start to worry as that could increase your server load.
> 0 votes

---
Tags: performance, cron, emails
---


title: adding js into body

text:
# Question
Title: adding js into body
I use drupal 7 an I want to add very simple jquery code to only one page on my site.

```
 $('#var1').on('keypress keydown keyup', function(){
   $(this).val($(this).val().replace(/([^\d]+)/, ''));
});
 $('form').submit(

 function (e) {
e.preventDefault();
 var xyz = parseInt($('#var1').val());
$('#result').text("Result is " + ((xyz / 1.25)*30) + " days");
 });

 <form>
<input type="text" id="var1" />
<input type="submit" value="=" />
 </form>
 <span id="result"></span>

```

The problem is that pressing submit button allways reloads wlole page which I do not need. How to prevent this? Thank you. I need it to work as smooth as this without reloading http://jsfiddle.net/eWXUT/3/

EDIT: I put the code on livesite but it is not working www(dot)vypadavanie(dot)net/ako-rychlo-rastu-vlasy?

In drupal 7 had to wrap the code inside jQuery(document).ready(function($) as well

# Answer
You have more than one solution for your problem

First solution add your javascript after the form or in the footer

```
 <form>
<input type="text" id="var1" />
<input type="submit" value="=" />
 </form>
 <span id="result"></span>

 <script>
 $('#var1').on('keypress keydown keyup', function(){
   $(this).val($(this).val().replace(/([^\d]+)/, ''));
 });

 $('form').submit(function (e) {
   e.preventDefault();
   var xyz = parseInt($('#var1').val());
   $('#result').text("Result is " + ((xyz / 1.25)*30) + " days");
 });
 </script>

```

Second solution add ready() handler like this

```
 <script>
 jQuery(function($) {
   $('#var1').on('keypress keydown keyup', function(){
     $(this).val($(this).val().replace(/([^\d]+)/, ''));
   });

   $('form').submit(function (e) {
     e.preventDefault();
     var xyz = parseInt($('#var1').val());
     $('#result').text("Result is " + ((xyz / 1.25)*30) + " days");
   });
 ));
 </script>

 <form>
<input type="text" id="var1" />
<input type="submit" value="=" />
 </form>
 <span id="result"></span>

```

Third solution add your javascript code with ready() handler in `drupal_add_js` function

```
<?php drupal_add_js('/* javascript code */', 'inline'); ?>

```
> 0 votes

# Answer
There is actually a drupal api for javascript and drupal\_add\_js() is exactly what you are looking for..

Example:

```
  drupal_add_js('jQuery(document).ready(function () { alert("Hello!"); });', 'inline');

```

As for stopping the page from refreshing, why not just add `action='#'` to your form
> 0 votes

---
Tags: 7, javascript
---


title: Clean output "View source"

text:
# Question
Title: Clean output "View source"
I just pasted a google analytics snipped into my template. When I preview the view source for the page, the script snipped is displaying all in one line.

How do I get it to display as it does in the page.tpl.php file?

I am using netbeans.

# Answer
> 1 votes
My guess is that you are running into EOL marker differences. That boils down to editor settings, and NetBeans copnfiguration help would be best at a sister side, If the code works, then don't worry about it.

As a side note, I don't recall running into any situations that prevented me from using the normal Google Analytics module. Recent versions let you adjust the code, so you should be able to match up with any tracking code you have. In addition, you can configure it to ignore admins, track downloads, and do a lot more.

---
Tags: google-analytics
---


title: Cannot get dompdf to work

text:
# Question
Title: Cannot get dompdf to work
I have extracted the dompdf libraries folder to `/sites/all/libraries`

Re: 2. Edit `dompdf_config.inc.php` to fit your installation.

What exact changes do I need to make to this file???

Also, I am getting this warning in the drupal admin:

> Warning: in\_array() expects parameter 2 to be array, integer given in print\_pdf\_settings() (line 22 of /home/mysite/public\_html/sites/all/modules/print/print\_pdf/print\_pdf.admin.inc).

# Answer
> 3 votes
Print module works best when you copy the library `dompdf` (or `tcpdf`) to the module folder directly. In this was you don't need to edit the file, and the print module will detect the library automatically.

* Extract the `dompdf` directory into `sites/all/modules/print` so that you have `dompdf_config.inc` at `sites/all/modules/print/dompdf/dompdf_config.inc`.
* Ensure that you have write access to `PUBLIC/print_pdf/dompdf/fonts` directory.
* Your print module should now show the detection of the library at `admin/config/user-interface/print/pdf`.
* You should now be able to export the nodes to PDF :)

---
Tags: files
---


title: Add rel = "dofollow" to internal links

text:
# Question
Title: Add rel = "dofollow" to internal links
I wanted to add `rel = "dofollow"` to all internal links only like menu links, title links, user links etc. I managed to add `rel = "nofollow"` to comments and user posted contents. But I am not able to add `rel = "dofollow"` attribute to internal links.

Any suggestions how can I do this?

-- Thanks

# Answer
What some people call a "dofollow" link is just a normal link - i.e. a link that is *not* tagget with the `rel="nofollow"` attribute.

In other words, this what a dofollow internal link looks like:

```
<a href="target.html">target</a>

```

There is no `dofollow` (or similar) attribute you can add to the link. The *absence* of `nofollow` is what you're looking for.
> 2 votes

---
Tags: 7, routes, nodes
---


# Question
Title: How to define ranges for integer/decimal/float fields in D7?
I would like to add an **integer/decimal/float field** to a content type where users can define **ranges** for these numbers as two separate fields.
Like when adding a Date field, and being able to add an end date as a separate field with a little checkbox:

(So the output will be like this: `2011 - 2012`.)

Use case: users would like to define approximate numbers, they don't know data exactly, for example:

*Stream bed's average depth*: `0.3 m` \- `1 m`
*Stream bed's average width*: `1 m` \- `2 m`

(`m` would only be a suffix) etc.

# Answer
> 3 votes
I needed the same functionality for a project I am working on.

I have created a sandbox project http://drupal.org/sandbox/thepearson/1842424 which I'll be working on hopefully releasing as contrib. I still need to do some more testing, tidy up and documentation.

Obviously it's in sandbox so, use at your own risk. Currently supports `int` and `float`. Supports defining min and max limits on both start and end values along with prefix, suffix and range indicator. ie:

```
[prefix] [min] [indicator] [max] [suffix]
[$ ]     [123] [<----->]   [157] [per person]

```

alnum type is there but limit validation seems a bit buggy. I would recommend not using alnum until more testing is done.

It's also supports some `hook_info`/`hook_info_alter` functions for you to either define your own range datatypes, or change the existing ones. Look at the sub-module `range_integer` to see how it's done.

If you find any bugs please raise bug reports at drupal.org.

# Answer
> 2 votes
There is also Taran2l's Range field module, which already passed module review and is now on its way on taking over Range project (which is stuck on 6.x version and seems to be abandoned). It would be nice if @thepearson collaborated with the author of this module.

UPD: Taran2l is now official owner of the Range project.

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


# Question
Title: query API calling db_query result a non-object, but SQL works
I query my database using the following query API code, but Drupal tells me that the result is a non-object. I can't find any reason to it

in what situation does **db\_query** return anything but?

The error:

> Fatal error: Call to a member function execute() on a non-object

the code:

```
for ($counter = 1; $counter <= 12; $counter++) {
  $query[$counter] = db_query("SELECT `foo` FROM `{bar}` WHERE DATE(FROM_UNIXTIME(`thing_$counter`)) = CURRENT_DATE");
  $results = $query['$counter']->execute()
    ->fetchAll();
}

```

The SQL works and produced results when I ran it in PHPmyAdmin.

The answer in this exchange looked tantalizing:

```
$date = date_create();
$date_to_test_against =  $date->format('U');
 $query[$counter] = db_query("SELECT `foo` FROM `{bar}` WHERE `thing_$counter` = $date_to_test_against");

```

however that produced the same result, calling execute on a non-object.

I know I don't have enough experience with this API yet. Can someone please point me to what I'm missing?

# Answer
First, in the third line of your first snippet, you're using `$query['$counter']`. Remove the quotes.

Second, a db\_query return value is a query already executed, so you want `$results = $query[$counter]->fetchAll();`
> 1 votes

# Answer
In the case of db\_query, what you get back from it is a resource (it is just a wrapper around php's mysql\_query.

But the answer depends on if you're in Drupal 6 or 7

**Drupal 6:**

In order to turn that into an object, you need to run db\_fetch\_object on the result, and if you have multiple results you'd need to loop through it.

For example:

```
<?php
    $sql = "SELECT buckles FROM foo WHERE llama = 'cheese'";
    $result = db_query($sql);

    while ($rowObj = db_fetch_object($result)) {
        echo $rowObj->buckles;
    }

```

**Drupal 7**

Use the nifty db\_select api! The examples on that page pretty good, but basically it builds a query and then returns something that's very similar to a PDO object (see SelectQuery::execute for the following example)

```
<?php
  $matches = array();
  $query = db_select('table')
     ->fields('table', array('field_name'));

  foreach ($query->execute() as $row) {
     $matches[$row->relation_type] = $row->label;
  }

```
> 1 votes

---
Tags: database
---


# Question
Title: How to programmatically set a file field to allow multiple uploads/values?
I have created a file field with `field_create_field()` and added an instance of it to my custom node type with `field_create_instance()` in my module's `hook_install()`function. But how do I set it to allow unlimited file uploads. I can do it in the drupal interface by going to `structure > content types > manage fields` and clicking edit for my file field. I can set `number of values` on that page but how do I do it programmatically? There must some settings key I suppose but could not find it online.

I am using drupal 7.

# Answer
my example, see "cardinality" value:

```
$field = array(
  'field_name' => 'field_ws_file',
  'type' => 'file',
  'cardinality' => FIELD_CARDINALITY_UNLIMITED,
);
field_create_field($field);

```

Instead of FIELD\_CARDINALITY\_UNLIMITED you could also simply use `-1`.
> 2 votes

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


# Question
Title: BOA Aegir Octopus, APC disabled: Module's php files seem to be cached, changes are not reflected. Why?
I installed BOA on a VPS and everything seems quite alright except the fact that when I change a module's php file, the changes are not reflected in the website.

When I change something in drupal's index.php I can see the changes.

My first thought was APC which I disabled globally in php.ini for testing but that didn't help.

It looks like the file is never called, though I double checked that I'm working in the right directory and drupal setup.

Obviously I'm missing something and even Google didn't shed light no this.

Do you know what this could be?

# Answer
After several hours I got it.

Funnily it had nothing to do with Apc, Redis or the drupal cache :)

In the site I migrated for some reason I don't know, were copies of several modules inside one module which were not in use. I played around with the features module a while ago, maybe this was the reason for that.

When importing the site Aegir apparently looks for the directories of the modules and it found one of my modules in that additional place and stored it in the system table.

So drupal thought the module lived there, and never ever called the "real" module version.

I found this out by calling drupal\_get\_filename which returned a strange path like
"sites/all/modules/vocabindex/ppp/mymodule"
and by looking into the original site I was astonished to find about 15 modules there.

In the end I simply delete the whole vocabindex directory as we don't use the module anymore and now everything seems fine. Yay!

Maybe this will save someone a lot of time at some point.

Thanks Clive and Grace for your help!
Martin
> 0 votes

# Answer
Clearing Drupal cache may be not enough in this case.

Since Redis is active by default, it may still cache some include paths, or there can be old paths still present in your system table, so you need to run the "Rebuild registry" task followed by "Flush all caches" task (the second is the same as running `drush cc all` on command line).

If this still doesn't help, upgrade to latest BOA-2.0.6-dev (head), which includes recent APC 3.1.14 version to avoid this known APC bug.
> 1 votes

---
Tags: caching, aegir
---


# Question
Title: How can I make downloads available only to authenticated users?
With Drupal 7, I created a content type with a field to attach files. I am using private file uploads. When viewing the node, the list of attached files is visible to every user, including anonymous users.

I want that logged-in users are able to click on a file link to download the files attached to nodes; anonymous users should be able to see the list of files, but clicking on a file link should show them the login page, forcing them to log in, and them download the attached files.

How can I achieve this?

# Answer
You can try Private Files download permission module for drupal 7 and you can set permission to download to certain users.
> 6 votes

# Answer
You can try setting 'View Published Content' permission only to authenticated users. The body field of the node can be still made available if required, but the file will not be visible to anonymous users
> 0 votes

---
Tags: users, files
---


title: dynamic link to view page

text:
# Question
Title: dynamic link to view page
So i have set up a page view which has the path about/% with % representing the argument used in that view. I now want to link to this page on the main navigation bar.

I created a menu item about/%dest but that didnt work as i guess the route is already registered by the view? so i altered it to look like this:

```
$items['%dest/about']= array(
  'page callback' => '_bps_path_redirect',
  'page_arguments' => 'about',
  'title' => 'about',
  'title callback' => 'get_title',
  'access arguments' => array('access content'),
  'type' => MENU_NORMAL_ITEM,
  'menu_name' => 'main-menu',
);

function dest_to_arg() {
  $arg = arg(1);
  return $arg;
}

function _bps_path_redirect($arg) {
  drupal_goto($arg.'/'.arg(1));
}

```

But to no success, the redirect doesn't work. So am i missing something? Is there a simple way to link a view which has a wildcard in its path?

# Answer
> 0 votes
Solved. I modified the page views to use a static path and then set up a contextual argument to grab the parameter of the url to use as an argument.

---
Tags: views, routes
---


# Question
Title: Translatable strings and Drupal primary language
I use a lot of modules and templates, in which I have to `print` a lot of display markups.

My website has primary language FR, but whatever I do, each time I use a **translatable string**, it's always EN that is set for that `t('whatever')`.

I'd like to be able to write all my custome code in French, and then translate strings into english in the interface.

Is it any way to achieve that?

# Answer
> 0 votes
No unfortunately, strings passed to t() should always be in English.

---
Tags: 7, i18n-l10n
---


# Question
Title: How to deal with unverified users in Drupal?
What do you do with unverified emails in Drupal? I see some have been unverified for several months.

Is it possible to resend the email or to auto delete them?

# Answer
> 3 votes
I think it is common for all sites that permit public registration but require email verification to get some "unverified" users.

To be honest, I do not think there is much point in resending the verification email. Some people are afraid of their email being harvested for spam purposes, so they register with a bogus or black-hole address they never read. Some may just be typos. And some may be spam-bots that know how to register, but don't have the AI to deal with verification. When learning to deal with this, I tried resending the verification email, but with no results. I think the important thing is to prevent those who use bogus or black-hole addresses from registering in the first place (spammers, like death and taxes, will always be with us).

This is how I deal with this now:

1. I put text on the "Create new account" page that explain upfront that an verification email will be sent and response will be required - and that failure to comply with this within 48 hours will result in automatic account cancellation. I also have similar language in the body of the verification email that is sent out.
2. I then cancel accounts that remain unverified after 48 hours.

You can cancel accounts in bulk on the Adminstration/People page. Sort on the column "Last access" and the unverified ones will appear on top. Then tick the ones that are unverified (it says "never" in the "Last access" column), and select "Cancel the selected user accounts" from the drop-down menu.

# Answer
> 4 votes
you should try the Logingtoboggon module. it has this feature

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

I have put the feature you are looking for in bold.

# Answer
> 3 votes
It's possible to resend the verification email with PHP, using

\_user\_mail\_notify

e.g:

```
_user_mail_notify('register_no_approval_required', $account);

```

see \_user\_mail\_notify for other account mail types, e.g status\_activated.

To auto-delete you can use

hook\_cron

or perhaps also the Rules module, e.g system event "on cron" or as a Scheduled Rules component.

---
Tags: users
---


title: Retrieve Drupal Commerce order history

text:
# Question
Title: Retrieve Drupal Commerce order history
Is it possible to retrieve a user's order history programatically?

Ideally, I would be able to user the user's profile ID to then load multiple past orders.

# Answer
> 6 votes
Yes you can use the `commerce_order_load_multiple()` function and take advantage of the `$conditions` parameter, e.g.

```
$orders = commerce_order_load_multiple(array(), array('uid' => $user_id));

```

---
Tags: commerce
---


# Question
Title: Prevent "AJAX HTTP request terminated" error on early form submit
I'm doing an ajax validation for duplicate check on link field in node form. When the link field is edited, an ajax call is triggered as programmed (using form api #ajax default blur event), it takes a while for the ajax response to reach browser, in the meantime the form gets almost ready to submit by user. Doing an early form submit (i.e before the receipt of ajax response) Drupal ajax API throws below error message in JavaScript alert box,

```
An AJAX HTTP request terminated unexpectedly
Debug information follows.
Path: /system/ajax
Status text:
Answer Text:
Ready State: 4

```

I have noticed this issue in a few contrib modules as well. I think the fix is to prevent submitting the form to server until the ajax request completes. Wondering to know if there is any way to set client side callback function in form api that I can use to stop form submit.

# Answer
> 1 votes
This might help you.

```
Drupal.behaviors.merchant = {
  attach: function(context, settings) {
    jQuery('form.node-form')
      .ajaxStart( function() {
          jQuery(this).submit(function() {
            return false;
          });
        })
       .ajaxStop( function() {
          jQuery(this).unbind('submit');
          jQuery(this).submit(function() {
            return true;
          });
        });
  }
}

```

---
Tags: 7, ajax
---


title: Add birthday field on user account

text:
# Question
Title: Add birthday field on user account
I want to enable my users to add their birth days in their profile. The users should select the date either from a calendar or insert them in three different fields of day,month, and year manually...The image should make it clear:

# Answer
I'd just get the Date module and add a date field to the profile called something like `field_user_birthday`.

> This package contains both a flexible date/time field type Date field and a Date API that other modules can use.
> 3 votes

---
Tags: users, datetime
---


# Question
Title: How to dynamically add css after image upload on node?
I have used `drupal_add_js()` for my profile content type and modified CSS using jquery `.css()` function. in this content type i have image upload field but when i upload image the image preview display is changed. my question is how can i apply the style for image preview field which is added after image upload.

# Answer
> 1 votes
If you use drupal behaviors to modify the css, it should run after the ajax too.

eg.

```
(function ($) {
  Drupal.behaviors.exampleModule = {
    attach: function (context, settings) {
      $('.example', context).css('backgroud-color', '#ff0000');
    }
  };
})(jQuery);

```

More info at: http://drupal.org/node/756722

---
Tags: 7, javascript, theming
---


# Question
Title: module_load_include not working including inc file
I am trying to make it work, but it seems simply not working in Drupal 6. Maybe this is the issue, it does not work on D6?

This is the code:

```
// $file_path = module_load_include('inc', 'MYMODULE.inc', 'includes/MYMODULE.inc');
$file_path = module_load_include('MYMODULE', 'MYMODULE.inc');

// Testing.
if ($file_path === FALSE) {
  dpm('Failed to include: ' . $filename);
}
else {
  dpm('Successfully included: ' . $file_path);
}

```

I have tried also adding a drupal\_load before and some other things, like changing params, moving the inc file to the root module folder and so, but I allways get the same:

```
Failed to include: sites/all/modules/MYCOMPANY/MYMODULE/MYMODULE.module

```

any idea of what am I doing wrong?

Thanks a log.

# Answer
> 7 votes
You need to add `inc` into your implementation of the function. Also you don't need to add the extension `.inc` as part of the filename:

```
$file_path = module_load_include('inc', 'MYMODULE', 'FILENAME');

```

Documentation: `module_load_include();`.

# Answer
> 4 votes
The arguments expected from module\_load\_include() are, in order, the following:

* The extension of the file to load
* The name of the module whose directory is looked for the file
* The name of the file (without extension)

In your case, the call to `module_load_include()` should be:

* `module_load_include('inc', 'MYMODULE', 'includes/MYMODULE')`, in the first case
* `module_load_include('inc', 'MYMODULE')` in the second case

In the first case, the loaded file is includes/MYMODULE.inc, contained in the "includes" directory contained in the directory containing MYMODULE.module; in the second case, the file is MYMODULE.inc contained in the same directory containing MYMODULE.module.

When the third argument is not passed, the name of the file is the name of the module without .module extension.

---
Tags: 6, debugging
---


# Question
Title: How is it possible for users to submit a node without a required image field?
I am using Drupal 7 and I have defined a custom content type, **Picture**, which has only one required field, an image field. I am using the default core image field with the Manual Crop module. The number of images to be added is limited to one. The field is marked as required.

If it matters, the title is not required because it is automatically generated by the Automatic Node Titles module.

I created this content type to allow users to upload their pictures to the site. However, sometimes users are somehow able to create nodes of this content type that do not have any image file attached. Since the image field is marked as required, I do not understand how Drupal can permit the creation of the node without such a file attached. However, when I click *edit*, there is no file in the image file dialog box.

I have tried to debug this problem, but I am unable to create a node without an image file myself. What kind of situation can cause this problem, or how can I debug it?

# Answer
A contributed module was to blame-- the Manual Crop module. Thankfully, the issue is already fixed.
> 1 votes

---
Tags: media, forms
---


# Question
Title: Drupal 6 site running slow on my localhost
Hi I am working with a drupal 6 site and have a setup for this on my localhost the site is very huge and consists of almost 290 tables but the site is working super slow on my localhost specially the admin pages. It took almost 1hr to create a simple content type and 20-25 min to load module page, 30 min to enable/disable a module if not using drush about 10 mins using drush. This is becoming really time consuming for me to work like this. I have also configured the site performance but still no change. Rest of drupal 6/7 sites on my localhost are running fine.

# Answer
Profile it; it's on your local box, so it can be done. Until you do that it's a bad guessing game. What all contributes to drupal page execution time?
> 2 votes

# Answer
On which plateform are you running your website ? maybe you need to run things like memcached and APC, this really improves drupal performances. Therefore try to see if you have tables with lots of lines, like search\_index table which can be growing up as the cron executes... Also if you are behind a proxy be sure to unable any modules that tries to get stuff from the net, this causes the admin to be very slow as every request that not passing through the proxy would stand by until a timeout to come... (like 30s) see Update status behind a proxy ...and sorry for my bad english ;)
> 0 votes

# Answer
3 tips: 1. install x-cache, PHP OP-code caching is very efficient for Drupal, especially for Drupal 7 but in Drupal 6 site will run much faster. I've optimized it a bit for my needs but only installing and enabling this Apache module with default settings should be OK 2. Apache settings - default are in most cases not efficient (are efficient for static HTML pages - not for very extendable CMS) set KeepAlive to max 3 seconds, you may also disable it at all

I've also set on my PC small limit of Apache server processes which may be run at one time, but if not many users access to your site an once (ie. installation for testing only), this should not be a problem
> 0 votes

---
Tags: 6, performance
---


# Question
Title: db_query - Get all nid in more than one nodetype
This is a simple query , but i really dont know why its not working. I think the problem is with single quote used!

```
$type = array('node_type_1', 'node_type_2', 'node_type_3');
$placeholders = db_placeholders($type, 'text');
$query = "SELECT nid FROM {node} WHERE uid = %d AND type IN ($placeholders) AND status = 1 ORDER BY nid DESC";
$result = pager_query($query, 10, 0, NULL, $user->uid, $type);

```

It tried this also

```
$result = pager_query($query, 10, 0, NULL, $user->uid, implode(', ',$type);

```

I am getting error

```
warning: mysql_real_escape_string() expects parameter 1

```

# Answer
> 2 votes
The correct way to use `db_placeholders()` with `page_query()` is shown in taxonomy\_select\_nodes(). In your case, the code should be the following one.

```
$type = array('node_type_1', 'node_type_2', 'node_type_3');
$placeholders = db_placeholders($type, 'text');
$args = array_merge(array($user->uid), $type);

$query = "SELECT nid FROM {node} WHERE uid = %d AND type IN ($placeholders) AND status = 1 ORDER BY nid DESC";
$result = pager_query($query, 10, 0, NULL, $args);

```

---
Tags: 6, database, security
---


# Question
Title: How can i access only the text of a comment?
In the comment.tpl.php there is

```
<?php
    print render($content);
 ?>

```

and this converts to this html

```
<span rel="sioc:reply_of" resource="/drupal/?q=node/5" class="rdf-meta" data-thmr="thmr_44">
</span>
<div class="field field-name-comment-body field-type-text-long field-label-hidden" data-thmr="thmr_49">
 <div class="field-items">
  <div class="field-item even" property="content:encoded">
   <p>THE COMMENT</p>
  </div>
 </div>
</div>

```

What can i do if only want text "THE COMMENT" printed and not all this html? I know $content is an array but can't find a way to dig into it's elements.

# Answer
> 3 votes
Install devel and try `dpm($content);`

This will give you an easy way to browse that array.

---
Tags: comments
---


# Question
Title: Print edit/create/delete node link with jQuery
Been searching for a while so I came here to ask...

How can I print edit/create/delete node links with jQuery? I just want to show the links when I hover over the \< li \>'s. I already have the hover code... So I really just need to code to get the edit/create/delete node links.

Edit: So, not the current URL but fetch the ID/NID's. These are in a list. I want to show the edit/delete buttons of that specific article when hovering over an item.

Thanks in advance!

# Answer
> 0 votes
You need to see where you want these links. What you can do is, you can use drupal\_add\_js, to add a js variable, in drupal.settings, and thus use it as required. But for me, this is mainly useful when you have only one node on a page.

If you are showing multiple nodes, or a listing of nodes, you can add nodeID as an attribute to hidden input value, or div or span or any HTML element. As you said that you have the HOVER code, then you will have to get the value of a particular div/span/hidden field on which mousehover event is fired, and then take appropriate action.

Hope that helps.

# Answer
> 0 votes
If I understand correctly you need the urls to the node creation/edit/deletion. So, here it goes.

The link to add a node is:

```
node/add/your_content_type_name

```

to delete a node

```
node/node_id/delete

```

to edit a node

```
node/node_id/edit

```

You can fetch the node ID with jQuery from the url, But your kinda stuck with the content type name.

# Answer
> 0 votes
If your question is for drupal 7, you already have this feature. It's called "**contextual links**", see this screenshot :

To see these links, you need to have sufficient permissions and you must print `$title_suffix` variable in your node template(s), eg.:

```
<?php print render($title_suffix); ?>

```

See this link for more details.

# Answer
> 0 votes
So, I came up with my own solution with the help of you guys of course... It was very easy actually. I was thinking a bit too deep.

*What I did:*

I already added an edit link to the view... So I just added another delete link to the view. Both of them have a custom class. I used drupal\_add\_js to ***hide()*** and ***show()*** them. Pretty dumb...

Thanks for all the help, appreciate it! I can't upvote yet but will do as soon as I'm able to...

---
Tags: javascript, nodes
---


title: Print filename from url

text:
# Question
Title: Print filename from url
Im using Drupal 6 with Audio.

I have created a view that shows a list of files to download and play. There are two fields which both show the download link. I would like to change the second download link field so that it strips all the info and only prints the filename from the url contained in its content. So instead of

```
<*a href-"file/path/music20.mp3">Download <a*>

```

I would like to see

```
music20.mp3

```

or

```
music20

```

Thanks in advance

# Answer
In drupal 7, views 3 if you add a relationship **File Usage: File** you get some new fields you can add to your view, including the filename. The filename includes the extension (.doc, .pdf etc). But even with that you could theme the specific field with a template where you could easily use php to cut the .mp3 part.
> 1 votes

---
Tags: views
---


title: Drush & Fbconnect on Windows 7

text:
# Question
Title: Drush & Fbconnect on Windows 7
I have installed fbconnect module with Drupal 6 on Windows 7. Everything seems to be working fine. From front end I can login to my site via fbconnect. However when I try to run and drush script, for example drush updatedb, it throws me following fbconnect error

**Message is**

> WD php: Exception: Facebook needs the CURL PHP extension. in require\_once() (line 19 of E:\wamp\www\foo\sites\default\modules\contrib\_modified\fbconnect\facebook-php-sdk\src\base\_facebook.php). Drush command terminated abnormally due to an unrecoverable error.

Edit: Curl is enabled but still I am getting this error, please see below screenshot

# Answer
Drush uses a different php.ini than the web server does. The phpinfo() you are looking at above is from your web server's php.ini. Run `drush status` to see the path to the php.ini that Drush is using. Then, compare the two and copy directives from the web server php.ini, such as the directives that enable the CURL PHP extension and memory\_limit, and put them in Drush's cli php.ini. Then everything should work fine.
> 5 votes

# Answer
The answer is in the error. You need to get the CURL PHP extension.

How do I install cURL on Windows?

If it's installed, then make sure it's enabled.
> 0 votes

---
Tags: drush
---


title: Manage images manually

text:
# Question
Title: Manage images manually
For our new Drupal site, it would be ideal if we could manage all images manually. We need to able to resize/crop and put the files where an author decides to put them. The reason is that these images are used in multiple locations, e.g. a podcast and as thumbnail images for the corresponding video. Another reason is that these images are served from a subdomain, which is connected to a CDN (through CloudFlare).

Basically what I/we need is a URL field where an author can paste the image URL, that is then turned into an image on the website. The author would generate the various image types, e.g. thumbnail, medium, large.

I could not figure out what the best approach is to add an image/text field to a content type in order to display the image on the website. Any pointers would be much appreciated!

Thanks.

# Answer
> 0 votes
Your best option for remote images is the Filefield Sources module, however this will not provide the ability to manually create the thumbnail, medium, large, etc versions.

You can achieve auto-creation with image-styles and preset the dimensions or criteria that you would like for the "cropped/smaller" versions.

Lastly, if you want manual creation of those files you would have to create a new field for each version and have them pre-cropped/sized, and paste in the url from the CDN.

---
Tags: media, nodes
---


# Question
Title: How can I achieve taxonomy workflow (allowed next states of taxonomy terms)?
I have a vocabulary containing some terms for issues' states:

* Open
* In progress
* Closed

I want to be able to define allowed "next" states for each term. So that a user can only change:

* Open -\> In progress
* In progress -\> Open, or Closed
* Closed -\> None

I am using Drupal 7.

# Answer
I don't think there's a ready made solution for this. The maintainer of workbench\_moderation has said that a goal is to collaborate with other workflow modules and made one module to rule them all, and one of the primary goals of that initiative is "workflows for non-node entities" but this is still a long way off and doesn't seem to be very far past the planning stages at this point.

So I think the closest you can get currently is the taxonomy\_revision module but that just adds revisions and doesn't help in automating a workflow out of them, so you'll have to do some custom development on top of that.
> 1 votes

# Answer
Have you checked Workflow module ? Though workflow module allows the creation and assignment of arbitrary workflows to Drupal node types, but if you want only for vocabulary then probably you have to develop custom module only.
> 0 votes

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


# Question
Title: Migrate theme settings between multisite installations
I have set up a second site on a multisite development instance of Drupal 7. We're using a subtheme based on Adaptive Themes. Being that plans call for about a dozen sibling sites, I would like to copy this over theme settings from the first site to each subsequent sibling sites.

What tools would be recommended for this arena?

Someone suggested using Features. However, of the options I don't see a way to package up theme settings.

# Answer
> 0 votes
So far what I've been able to figure out, the answer is -- it depends. It depends on what you're moving between installations.

Features module has worked best for me to move *configuration* settings or for modules (and their dependents). Sometimes, you'll have to include the strong arm values inside the Feature export.

For user content, it's best to use Migrate (or Backup and Migrate).

---
Tags: 7, migrations
---


# Question
Title: Creating a menu structure based on Content Types Alias
I have imported in a bulk of content via a CSV Feed Importer (see Migrating content from older custom CMS). It worked splendidly. I was even able to take in each of the pages old URL and create an path alias for each page. Now I would like to rebuild the menu structure and it would be a certain help if I could create a menu structure based on all of the path aliases.

Is there a module to accomplish this?

# Answer
I have never seen a module that does that, but you could try Import HTML. More details from the module's project page:

> Import an old existing, static HTML site structure into the Drupal CMS as structured nodes!
>
> Allows an admin to define a source directory of an existing traditional static HTML website, and import (as much as possible) the content and structure into a drupal site.
>
> Source files will be stripped of exisiting chrome and navigation elements before being inserted as nodes.

As alternative, I would use the https://www.drupal.org/project/menu\_editor module to quickly build out the menu structure of the already imported content.
> 1 votes

---
Tags: routes, path-aliases
---


title: Why is Drupal deleting my images?

text:
# Question
Title: Why is Drupal deleting my images?
I have images going mysteriously missing from my Drupal site, sometimes several all at once. There are currently only two people who have access to edit these, myself and a manager in Corporate Communications. She just alerted me to a half a dozen disappearing all at once, and claims she did not delete them. I have no reason to doubt her word, and I know I did not delete them. This started happening months ago, and I had thought I may have fixed it a couple of months ago by deselecting "Delete unused files" in the One-click Upload settings. Apparently that did not fix the problem.

Why is Drupal eating my content? How can I stop it?

# Answer
I'm not familiar with the One-Click Upload module, but you might want to check the file\_usage table after adding an image to see if it's recording a usage. If it's not recording a usage, it's being deleted because on cron run, Drupal automatically deletes files from file\_managed that don't have a usage recorded in file\_usage.

Drupal does not detect linking from entities other than the one(s) on which a usage was originally recorded. For example, if you added a link to an image in the markup of node 5, but the image was uploaded as an attachment on node 3, the image will disappear when node 3 is deleted, and node 5 will show a broken link.

If this is your problem, you could solve it by using the File Lock module to add file usages so they aren't deleted, or you could switch to the Media module, and apply this patch that has been committed to the latest dev (and that I personally wrote some tests for) to ensure that a usage is being recorded for files uploaded via WYSIWYG.
> 4 votes

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


# Question
Title: "Save Configuration" in Drupal 7 Module not visible
I inherited a customized Drupal 7 site and am trying to add some things without a lot of knowledge of how drupal works (I have general html/css/JS, and some classic ASP, .Net experience). I was able to install a couple of modules (Widgets, Widgets Service Links, Widgets Services - for Social Media buttons) but can't seem to enable them. They have dependencies with each other, but they are all there. I can click the check boxes but I see no where to save the enabling of the modules. According to what I see out there, there should be a Save Configuration button, but it is not visible to me. We have a couple of security updates that we haven't done, but when we did these previously they mucked up our configuration so we decided to hold off on them until we know what we're doing a bit more (we were able to restore from a backup). Could the security update alerts be preventing the saving of modules? That's the only thing I can think of other than our whole configuration being messed up somehow?

# Answer
Something is wrong with your Drupal installation or one of the modules breaks the module scanner, have you checked your webserver logs? if so, what do they say?

You should definetly upgrade to the latest version of D7 before trying anything else.

If that doesn't solve the problem, it's most likely one of the 3:e party modules causing the issue, you'll have to manually disable them one by one to find out which one it is.

You can disable/enable modules using other methods than the module configuration page, i'd recommend a command-line utility called Drush. It's a very usefull tool for alot of Drupal related maintenance.

The other method would be to manually disable the modules directly in the database, here's instructions on how to do that.
> 0 votes

# Answer
Sounds very much like a custom module is hiding the module save button to stop people adding/changing things. I've had the misfortune of inheriting sites with these sort of "security features" before too.

If you do have any custom modules installed. the simplest thing you can do to test is get Drush installed, run `drush dis CUSTOM_MODULE` and check to see if the button comes back. Then you'll know if it's the custom module's fault at least. You can also disable them manually in the `system` table but you should only do that if you *really* know what you're doing.

The upshot of that is you can also use Drush to install the other modules outside of the UI, so even if that's not the problem you'll still be able to install new modules.

Also, to find out if a change to core files is responsible for the problem, grab the Hacked module and run a report. If you install the Diff module along with it you'll get a side-by-side diff of exactly what has changed in core/contrib modules.
> 1 votes

---
Tags: 7
---


title: Search API with Panels in Drupal 7

text:
# Question
Title: Search API with Panels in Drupal 7
I want to create a search that is able to index panels. The content in my Drupal system is mainly located in Panels (which contain Blocks with the content).

I installed Search API along with Fuzzy Search and i only get results for "normal" nodes/pages, but none for my Panels. Is there any way to add Panels to the search index?

# Answer
> 1 votes
Here is your answer: Page manager search. It works with the Search API module. Here is an excerpt about it from the module's project page:

> ... adds the ability for Page manager pages to be searchable via the Drupal core Search module or the Search API module.
>
> Support for:
>
> * Drupal core Search module.
> * Search API module (via the Entity API module)

Note: this is a new module.

---
Tags: 7, panels, search
---


# Question
Title: Drupal 7/Zen - How do you move the header (field_image) image above the title on a page?
How do you move the header (field\_image) image above the title on a page?

**Drupal 7/Zen Theme**

This seems like it would be a simple thing to do. I've been messing around with trying to accomplish this by doing a few things suggested on other websites but cannot seem to get it to work.

I've tried editing the page.tpl.php file but that messes up my homepage.

I'm trying to do this without using panels or any other module.

Thanks!

# Answer
If you want to change the page.tpl.php template file, but avoid it gets used for the front page, just:

* Create the page--front.tpl.php file from the current page.tpl.php file
* Edit the page.tpl.php file to move the image above the title

In this way, page--front.tpl.php will be used with the front page, and page.tpl.php will be used with the other pages.
> 2 votes

# Answer
What version of Zen? And is this a background image, or just an image in the header?

For a fixed width theme, you can insert a background image into the #header with the following CSS:

```
#header {
  margin: 0px 0 0 0;
  height: 193px;
  background: transparent url(images/header.png) no-repeat top center;
}

```

The Zen 5 markup is a little leaner, and you probably have to add a #header-bgimg div in your page.tpl.php file just inside the regular #header div. Then you can add a header image like this:

```
#header-bgimg {
  width: 100%;
  padding-top: 33.3%; /* Responsive Scaling: 333px/1000px = 0.3333 */
  background-image: url(../images/header.jpg);
  background-size: cover;
  -webkit-background-size: cover;
  -moz-background-size: cover;
  -o-background-size: cover;
  background-position: center;
}

```

This time I used additional directives to make it a responsive header image. If you don't use the additional wrapper, you collide with some of the Zen 5 CSS.

Placing other objects in your header might require a #header-inner wrapper just inside the #header-bgimg div.
> 1 votes

# Answer
page--\[node-type\].tpl.php may help.

What I mean is if you have made a page.tpl.php which achieves the desired functionality then simply renaming this file to page--\[node-type\].tpl.php will mean that this template will not interfere with your homepage.
> 0 votes

---
Tags: 7, theming
---


# Question
Title: Custom node template based on field condition
Is it possible at all to create a node template file based on a specific field value?

For example I already have a node template file called "**node--video.tpl.php**" for nodes of content type **video**. I would now like to add a **checkbox field** in that content type.

If the box is unchecked then it will use the above template.

If the box is checked then it will use a different template.

**UPDATE**: I added the following to my template file as Mohammed suggested, but I am not getting the changes.

```
function motg_preprocess_node(&$vars) {

$node = $vars['node'];
  if($node->field_solo[0]['value'] == 1)
  {
       $vars['theme_hook_suggestion'] = 'node__solo';
  } else
  {
       $vars['theme_hook_suggestion'] = 'node__video';
  }
}

```

My field "field\_solo" is correctly outputting a value of 0 or 1 also.

# Answer
Figured it out! I had to add "\[und\]" to the if statement:

```
$node = $vars['node'];
  if($node->field_solo['und'][0]['value'] == 1)
  {
       $vars['theme_hook_suggestion'] = 'node__solo';
  } else
  {
       $vars['theme_hook_suggestion'] = 'node__video';
  }

}

```
> 2 votes

# Answer
You can actually do that in the preprocess node function something like this:

```
function THEME_preprocess_node(&$vars) {
  $node = $vars['node'];
  if($node->field_solo[0]['value'] == 1)
  {
       $vars['theme_hook_suggestions'][] = 'node__theme1';
  } else
  {
       $vars['theme_hook_suggestions'][] = 'node__theme2';
  }

}

```

Here if the condition is true then the node template would be `node--theme1.tpl.php`

and if the condition is false then the tpl would be `node--theme2.tpl.php`.
> 3 votes

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


# Question
Title: General Approach in Zen-Theming: 3 different fixed-width layouts based on viewport-size
I am building a zen-subtheme which should have 3 breakpoints depending on viewport-size, but none of the layouts has sidebars, there is a small horizontal navigation for all layouts. By default, Zen provides a responsive-sidebars.scss and fixed-width.scss - since i need media-queries on one hand but no fluid sidebars etc. on the other hand, i don't know, what's the best way to go.

# Answer
> 1 votes
Zen 5 has mobile/responsive built-in, and it works really well. I found the conversion from Zen 3 fixed to Zen 5-Responsive fairly easy, and I went with the dev version (Jan 2013). As suggested, you could take out all the sidebars, but they don't really get in the way.

I had to spend some time learning responsive images, in particular responsive background images.

---
Tags: theming
---


title: Drupal 6 Migration: Files not showing?

text:
# Question
Title: Drupal 6 Migration: Files not showing?
I am creating a dev site from production and I read the migration guide and it's basically -- export database, rsync files. So, I cleared the cache (drush cc all) and also turned off Clean URLS because that was suggested in the guide.

I then proceeded to export the database & web directory & files... structure originally;

```
/home/drupal
/home/drupalfiles
MySQL DB

```

I decided to change the locations...

```
/var/www/html/drupal
/var/www/html/drupalfiles

```

However, all the images are now displaying with an 'x'. When I right click on the image, it says it's looking for files in /system/files ... which, I have a symbolic link in /sites/default/all for files to drupal\_files (which wasn't needed on production, btw). Even then, I don't know why it's trying to look in a directory called system.

The file-system settings is listed as 'files' on production and dev. So, I have no idea what's going on :( .. in the database, files are listed as /files/.

So frustrating :(! Any help would be appreciated.

# Answer
If you're using symlinks, you'll have to allow that in your .htaccess file.
> 0 votes

---
Tags: media
---