# Question
Title: Change Standard Title for Adding Content Into Something New? Also Redirect to the Page You Were On?
What I have right now is an obituary page, with a listing of obituaries. Clicking on one of those listings takes you to that person's obituary page. There are links on that page for visitors to send their condolences to or make a memorial donation. The links look similar to http://shawnjacksonfuneralhome.simalam.ca/node/add/condolences?field\_obit=131 and http://shawnjacksonfuneralhome.simalam.ca/node/add/memorial-donations?field\_obit\_donation=131. The text after the question mark is there to prepopulate a select list of entity references on the next page.

There are 2 things we are trying to do here. First, we want to change the title from the standard "Create Condolences/Memorial Donations" to something like "Send Condolences to the family of X" where X is the name of the deceased person. I've tried using the drupal set message function to find the value selected in the list.

`drupal_set_message("Obit Name:`

```
" . print_r($node->field_obit, TRUE) . '
```
`');`

According to those results, the value of the prepopulated select list should be like this:

`$obit_name = $node->field_obit['und'][0]['entity']['title'];`

However, it doesn't display anything (either with echo, print, or print render()).

The second thing we are trying to do is after the visitor submits their condolence/donation, we want them to be redirected back to the obituary page they were just on, along with a message thanking them for their actions. I've tried using the Rules Module to redirect and display a message, but it won't do both for some reason. It will not redirect to the previous page, either.

# Answer
> 0 votes
For the dynamic node titles you might want to take a look at Automatic Nodetitles module. It allows you to use tokens in the node title. These token can represent text from node fields.

---
Tags: entities, redirection
---


# Question
Title: Where can I see screenshots of various themes?
On Drupal.org, there are literally hundreds (perhaps thousands) of themes. As far as I can tell, the only way to actually see what a theme looks like is to install it. (Some of them have screenshots of the actual theme, but many just have what the creators apparently believe to be a cool logo, which really doesn't help much in determining what the theme itself looks like.) Is there a gallery somewhere that contains screenshots of all the themes?

# Answer
> 1 votes
Some can be browsed here http://themegarden.org/drupal6/

# Answer
> 1 votes
Just adding an answer for Drupal 7 themes: http://drupal7themegallery.com/

---
Tags: theming
---


# Question
Title: Seeking module/technique for giving site visitors a download "gift" in exchage for their email
A friend has an eBook site where he sells his eBook. A customer bought a large bulk order for use as a large group gift, but he wants my friend's site to be able to collect the email addresses of all the people who goto the eBook site and retrieve their gifted eBook.

So, we're seeking some module or technique that an anonymous user can visit a page, and by supplying their email to a form, they get access to download their pre-purchased eBook.

Now, I know how to write a module to do this, but my friend can't afford me, I'm already working full time, an so on... anyone know of some technique or module to accomplish this without writing a new module?

Seems like something along the lines of a CCK form for getting each email, which would then need to be verified by something like the Email Verification module, and once passing that test the user simply gets a role assignment for access to the download page.

However, being a code-monkey, I have no idea how to handle the glue logic of this solution without writing a module.

# Answer
I would use Webform Rules Module. On submit and validation of an email address have a Rule that redirects the user to a download page. Of course, since it's Rules you might be able to conjure up all kinds of wonderful complicated things. I also found these lovely tutorials on Rules at NodeOne. However, you might be able to write a module faster than it would take to work through all those videos.
> 2 votes

# Answer
You can also use the FileField Track module.

> A simple module that tracks downloads of files added through CCK/Fields by asking anonymous users to enter their email address. Returning anonymous users are tracked using a cookie. A tracking interface shows email address and user account information for tracked files downloaded on the site.

The latest stable release (7.x-1.4), covered by security coverage advisory policy, has been release on October 1, 2012. The module isn't anymore maintained from the original maintainer, and it's marked as *Seeking new maintainer*.
> 1 votes

---
Tags: 7
---


# Question
Title: Error using module_invoke_all('requirements', 'runtime') in my custom module
Why do I get

> Additional uncaught exception thrown while handling exception.
>
> Original
>
> Exception: theme() may not be called until all modules are loaded. in theme() (line 920 of C:\wamp\www\test\includes\theme.inc).
>
> Additional
>
> Exception: theme() may not be called until all modules are loaded. in theme() (line 920 of C:\wamp\www\test\includes\theme.inc).

when try to call

```
    module_invoke_all('requirements', 'runtime')

```

from my custom module?

# Answer
> 3 votes
My guess would be that you have that line of code outside a function in your module. That doesn't work.

I have no idea what you are trying to do but you should at least move it into a hook, like hook\_init() so that it's only executed when Drupal is fully bootstrapped.

---
Tags: 7
---


title: allow anonymous post to organic groups

text:
# Question
Title: allow anonymous post to organic groups
Does organic groups allow anonymous posts of content to groups?

I want to enable a simple workflow on my site running organic groups - anonymous users should be able to post blog entries to groups. I've got permissions set up so that anonymous can post blog entries, and blog entries are a group type, but I can't get it to let them associate a new blog post with a group. Logged in as admin I can do this just fine.

**Debugging Notes**

I dug into og to see if it was a permissions issue. It looks like `og_form_add_og_audience` isn't adding the `og_groups` array to the form. Looking at the logic in that function, I don't see where it would add all the groups for an anonymous user. What am I missing?

# Answer
I wasn't able to make this work, so I ended up setting up a "fake anonymous" user in its own module - a bit of a superhack that I'm not happy with. That said, it works. This "fake anonymous" user id is set via an admin settings page, and gets added to every group created. When new posts are created I added a form hook to change the author to this "fake anonymous" user id if the submitter is anonymous. Maybe this is easier in D7?
> 0 votes

---
Tags: 6, users, organic-groups
---


title: How to theme a specified node?

text:
# Question
Title: How to theme a specified node?
I need to add some php codes into my "About" page.

Is it possible to make a template for a specified page?

I know that I can insert php code into textarea, but I like to do it in real php file.

# Answer
> 4 votes
Yes, you can use templates for this; there's an explanation of how it works on Drupal.org.

To override the page template for a specific node you would use a template file with a name like:

```
page--node--1.tpl.php

```

Where `1` is the nid of your node.

The name of the file is based on the path of the page you want to provide the template for, essentially with `/` characters changed to `--`. So for the path '/node/1/edit' the template file would be named:

```
page--node--1--edit.tpl.php

```

The easiest way to start the new template file is just to copy the existing page.tpl.php source into your new file, and add/edit what you need.

If it's the node specifically you want to theme (and not the whole page), you can provide template files for it in much the same way. There are more examples in the link above, but basically for node/1 the file would be:

```
node--1.tpl.php

```

Remember to flush the caches when you add the new template file so the changes get picked up.

---
Tags: nodes, theming
---


title: Best way to set up data architecture

text:
# Question
Title: Best way to set up data architecture
I have a system where (to start) I have three types of data I need to store. I'm familiar with relational databases so I'm going to describe it in those terms. The Author table just has a couple columns like a primary key, and a few text fields (it's info about an author). Location has a similar structure to Author, but it's for different data (info about locations). Article is basically what links the two together. It has some regular text data, but also has foreign keys to both Author and Location (it's an Article written by Author about Location).

I've played with two ideas for how to represent this in Drupal. First with the Field API creating content types. The main problem here is that I'm not sure how to set it up so that Article has the proper relations to Author and Location.

The second approach I'm considering is using the Entity API module, but I'm not really very familiar with the module. However, I am very comfortable using hook\_schema() to set up the tables and relationships. From there, I'm not sure if Entity API has much useful in the way of making the data manageable like a content type or if I'd have to write that all by hand to begin with.

Am I looking at this all wrong? What is the drupal way?

# Answer
> 2 votes
There are quite a few possibilities to deal with this.

To get an overview:

* The advantage of custom entities is that they don't come with all the overhead that nodes have. They're especially well suited for storing and managing completely custom data that you might not even want to display and you have full control over them (their data structure, workflows, UI). The commerce project for example defines own entities for orders, products, line items and so on.
* Nodes are still the main content pieces. They provide various features that you don't yet get for free with custom entities, like revisioning and comments. Various additional modules focus on nodes. In short, you get a ton of features, but have to live with the overhead that comes with them. Every additional data structure you need is a field, living in it's own table, and so on.
* Entity API provides a lot of features for custom entities, for example CRUD and allows you to easily integrate with various important tools like Views and Rules. It's definitely worth to rely on it, see http://www.trellon.com/content/blog/creating-own-entities-entity-api for a nice introduction.
* To connect entities (Hint: nodes are entities as well), you can for example use Entity reference (simple, directed relationship) or Relation (flexible, unidirectional relation between entities which is an fieldable entity on it's own).

Some specific tips based on that:

* Article sounds like a perfect use case to use nodes/a content type to me. People need an UI to create them, you might need revisions, maybe comments, they need to be displayed, probably want nice aliases (Pathauto) for them and so on.
* Author; Here you have a bunch of options. Nodes have an author by default, the user that created them. Users can have fields as well and can have a public profile, so your authors could actually be users. Especially if your authors are going to be the uses which will create the articles on your site themself. If not, then this might not be a perfect match because changing the author of a node requires administrative permissions. If not, you could either use another content type if you think that makes sense or create a custom entity.
* Location: The traditional answer are certainly taxonomies. They're still a good match to categorize content, provide a number of possibly useful features out of the box, like hierarchy (so you could do do Country \> State \> City), auto-create new locations from a autocomplete widget and a list of nodes attached to them. And, they're fieldable entities too (surprise!), so you can store additional information for them as well.

So, to me it sounds like the default entities provided by Drupal core are a pretty good match for your data.

---
Tags: 7, database, entities
---


# Question
Title: Any D7 modules similar to the Project Issues module?
Are there any D7 modules similar to the Project issues module?

# Answer
> 3 votes
There is a 7.x-2.x branch of the module in git.

---
Tags: 7
---


# Question
Title: How do I automatically deliver static content using a CDN?
I use "Rackspace Cloud Files" service as CDN, which provides a nice API for many CDN-related automation tasks.

How do I integrate Drupal with Rackspace Cloud Files without manually copying static files to the CDN?

# Answer
> 10 votes
Easy

1. Copy the static files to your CDN (Rackspace cloud files in this case)
2. Install http://drupal.org/project/cdn (drupal 7 requires no core patch)
3. Configure the CDN module

Update

You can automate the delivery of content files with the File Conveyor mode, this module integrates with the File Conveyor daemon. This allows for much more advanced setups: files can be processed (e.g. optimize images like smush.it, minify CSS with YUI Compressor, minify JS with YUI compressor or Google Closure Compiler, before they are synced and your CDN doesn't have to support Origin Pull, any push method is fine (supported transfer protocols: FTP, Amazon S3, Rackspace CloudFiles). File Conveyor is flexible enough to be used with any CDN, thus it enables you to avoid vendor lock-in.

# Answer
> 4 votes
Use the Cloud Files module. You can set the file system to Rackspace Cloud Files so that files uploaded to Drupal will be stored and delivered from Rackspace Cloud Files CDN directly (no copying).

---
Tags: 7, cdn
---


title: Override argument passed by URL

text:
# Question
Title: Override argument passed by URL
I think I must be missing something basic. I have a template that is usually called via a URL but I also want to be able to call it manually using theme()

```
/**
 * Implements hook_menu().
 */
function signup_menu() {
  $items = array();

  $items['list/signup/success/%'] = array(
    'title' => 'Sign-up Successful',
    'page callback' => 'theme',
    'page arguments' => array(3),
    'page arguments' => array('signup_success'),
  );

  return $items;
}

/**
 * Implements hook_theme().
 */
function signup_theme() {
  return array(
      'signup_success' => array(
      'arguments' => array('node' => NULL),
      'template' => 'signup-success',
    )
  );
}

function signup_preprocess_signup_success(&$variables) {
  $signup = signup_record(arg(3));
  $variables['signup'] = $signup;
}

```

How do I override the argument that is usually passed through the URL? So I can call it like this:

```
theme('signup_success', $signup-id);

```

The preprocess function only ever takes the argument that comes from the current URL which is incorrect.

# Answer
> 2 votes
Definitely you will have to change your preprocess hook to replace `arg(3)` that is hard coding it in an aspect and definitely not make it suitable for manual call.

Can you please investigate `$variables` for the value being passed as argument to `theme()`? I hope you will get it there.

---
Tags: 6, routes, hooks
---


title: How to do incremental cron?

text:
# Question
Title: How to do incremental cron?
I have to manage a rather large site which has problem with cron (white space of death on cron.php and 'segmentation fault' in drush). I could not fix the ong standing problem. Someone has suggested to do the cron job in several steps whcih can also hopefully pinpoint the problematic tables. I am wondering how to do the incremental cron and appreciate your help.

# Answer
If you write a simple script that calls `module_implements`, ala

```
$modules = module_implements("cron");
print_r($modules);

```

or

```
drush php-eval 'print_r(module_implements("cron"));'

```

you will see all modules that implement `hook_cron`. You can then manually call each hook via drush

```
drush php-eval 'search_cron();'

```

and see what happens.

You could also potentially

* Clear the `{cache}` tables manually, `drush cc all`
* Clear the `{watchdog}` table, `drush wd-del all`
* Clear the `{sessions}` table, though this may lose sessions for active users
* Manually reindex search, `drush search-reindex; drush search-index`

These can be the stinkers if cron hasn't run successfully in a while, as can XML sitemap rebuilds, too.
> 2 votes

# Answer
Have a look at Elysia cron.

That module allows you to configure each cron hook implementation separately and it allows provides you with information about how long each mean/max execution time of those hooks.
> 3 votes

---
Tags: drush, cron
---


# Question
Title: comment body size in hook_form_comment_form_alter
What is the correct syntax to alter the size of the comment form body text area? I can't for the life of me find it in devel dpm.

```
$form['comment_body']....something....

```

# Answer
You can use the `#rows` and `#cols` properties to define the height and width respectively:

```
$form['comment_body'][LANGUAGE_NONE][0]['#rows'] = 10;
$form['comment_body'][LANGUAGE_NONE][0]['#cols'] = 50;

```
> 1 votes

---
Tags: 7, comments, theming, forms
---


# Question
Title: How to "use Search by Page as its own entity"?
Can someone clarify what sort of menu item is needed for my D6 site to be able to "use Search by Page as its own entity"? I have SBP working -- in the sense that `/search/search_by_page/keyword` does a search and returns results, but I'm having trouble getting rid of the "Content" and "Users" tabs. I've tried a couple of different entries in `some_random_module_menu()`, but haven't found the right one. Any advice out there? Thanks!

# Answer
If it suits your workflow you could just deny access to those two search pages using `hook_menu_alter()`:

```
function MYMODULE_menu_alter(&$items) {
  $items['search/node']['access callback'] = FALSE;
  $items['search/user']['access callback'] = FALSE;
}

```

If you still need to provide access to those paths under normal circumstances, and just hide the tabs on the search-by-page page, you can provide a function for the `access callback` that does a quick check on the current URL:

```
function MYMODULE_menu_alter(&$items) {
  $items['search/node']['access callback'] = 'MYMODULE_search_page_access';
  $items['search/user']['access callback'] = 'MYMODULE_search_page_access';
}

function MYMODULE_search_page_access($name) {
  // Deny access when on a search-by-page page
  if (arg(0) == 'search' && arg(1) == 'search_by_page') {
    return FALSE;
  }

  // Otherwise return the default access callback
  return _search_menu($name);
}

```
> 1 votes

---
Tags: search
---


# Question
Title: Change database column type in hook_update_N
I have a column in my database, its type is `int`. Now I need to store decimal numbers. How can I change its type to `decimal` with `hook_update_N`?

# Answer
> 4 votes
In basic terms you just need to call `db_change_field()` in your update function, with the spec for the new field:

```
function MYMOUDLE_update_7001(&$sandbox) {
  // Create the definition for the field
  $new_field = array(
    'type' => 'decimal',
    'precision' => 16,
    'scale' => 2,
    'not null' => TRUE,
    // etc...
  );

  db_change_field('table_name', 'field_name', 'field_name', $new_field);
}

```

If your field is a primary key/part of an index, you'll need to manually drop those indicies and recreate them (see the documentation page for a more detailed explanation).

---
Tags: 7, hooks
---


# Question
Title: How to override system_time_zones in Drupal 7
How can I override the system\_time\_zones() function without hacking the Drupal 7 core?

I would like to modify how the dropdown list is presented, but cannot seem to get at it with hook\_form\_alter().

My end goal here is to reformat the timezone dropdown list to include only the location and offset by removing the date/time from the `<select>` lists `<options>` text.

For example,

'`Pacific/Honolulu: Friday, June 1, 2012 - 6:43pm -1000`' would change to '`Pacific/Honolulu: -1000`'

This would be a simple edit to system\_time\_zones() in system.module, but hacking core is not an option for me.

If I *were* to hack core, this is what I would like to do.

Before Edits (for reference):

```
function system_time_zones($blank = NULL) {
  $zonelist = timezone_identifiers_list();
  $zones = $blank ? array('' => t('- None selected -')) : array();
  foreach ($zonelist as $zone) {
    // Because many time zones exist in PHP only for backward compatibility
    // reasons and should not be used, the list is filtered by a regular
    // expression.
    if (preg_match ('!^((Africa|America|Antarctica|Arctic|Asia|Atlantic|Australia|Europe|Indian|Pacific)/|UTC$)!', $zone)) {
      $zones[$zone] = t('@zone: @date', array('@zone' => t(str_replace ('_', ' ', $zone)), '@date' => format_date(REQUEST_TIME, 'custom', variable_get('date_format_long', 'l, F j, Y - H:i') . ' O', $zone)));
    }
  }
  // Sort the translated time zones alphabetically.
  asort ($zones);
  return $zones;
}

```

After Edits (Changes are to $zones\[$zone\] in @zone string):

```
function system_time_zones($blank = NULL) {
  $zonelist = timezone_identifiers_list();
  $zones = $blank ? array('' => t('- None selected -')) : array();
  foreach ($zonelist as $zone) {
    // Because many time zones exist in PHP only for backward compatibility
    // reasons and should not be used, the list is filtered by a regular
    // expression.
    if (preg_match ('!^((Africa|America|Antarctica|Arctic|Asia|Atlantic|Australia|Europe|Indian|Pacific)/|UTC$)!', $zone)) {
      $zones[$zone] = t('@zone: @date', array('@zone' => t(str_replace ('_', ' ', $zone)), '@date' => format_date(REQUEST_TIME, 'custom', ' O', $zone)));
    }
  }
  // Sort the translated time zones alphabetically.
  asort ($zones);
  return $zones;
}

```

How can I accomplish this without messing with core?

# Answer
I was able to access the timezone dropdown list by implementing hook\_form\_alter() with an #after\_build function. You can filter, clean and modify the array here.

```
function MYMODULE_form_user_profile_form_alter(&$form, &$form_state) {
   $form['#after_build'][] = 'MYMODULE_timezone_modify';
}

function MYMODULE_timezone_modify($form, &$form_state) {
   $form['timezone']['timezone']['#options'] = array(/*Your New or Modified Array Here*/);
   return $form;
}

```
> 5 votes

---
Tags: 7, datetime
---


# Question
Title: Content Types and the db tables they create
I'm creating an application where I want a content type with quite a few extra fields. When I try and retrieve this type programatically the DB is showing that each of the extra fields are stored in their own table. This is fine I guess but will mean my queries/views will be quite long and any changes to the fields via the admin console will require a bit of back end work.

Is this just a price I have to pay or is there another option? If possible I want to be able to administer the fields as normal (changing their names say and maybe adding new ones) and not have this affect my code too much - so in essence I want my cake and eat it!

As always, thanks again...

(drupal-7.14 Lamp)

# Answer
You can use views to create the queries for you so you can easily change your views in the back-office without the need of messing with custom code.
Or if you want to write the views yourself use the EntityFieldQuery class to create custom views without writing joins yourself because this is defenitivly not the way to do it.
You can load the full node object programmaticly by using node\_load() and filter the fields you need. This loads the full node object so this can slow down the system when loading lots of nodes using node\_load\_multiple().
And finally if you think this isn't straightforward enough consider writing your own entity where you can add all fields inside your custom table(s) and get the entity data with simple queries.
When using the views module you can add your entity to the views data by using hook\_views\_data.
There is also the possibility of adding fields to your entity so this opens a lot of opportunities if really needed. It's a bit of extra work to install, especially the first time u use entities so you have to see if the budget allows room for testing and debugging.
An introduction to entities
> 1 votes

---
Tags: nodes
---


# Question
Title: What are these mysterious core.xxx files doing in my site's root?
I have never seen this before in my 2 years of building site's in Drupal. I just opened up one of my sites folder structure and found a large number of core.xxx files that I don't know what they do (and they are huge files, over 8GB worth). I found a couple of threads on this but no real answer. Any thoughts?

http://drupal.org/node/360867 http://drupal.org/node/115654

core.1688 core.2343 core.8485 core.3039 core.21233 core.23234

# Answer
> 3 votes
They are core dump files; they are files created when a program has terminated abnormally (crashed).

# Answer
> 0 votes
As kiamlaluno stated, the core.xxxx files are indeed core dump files. You can actually control those files with the ulimit clause (i.e. to turn them off, just use 'ulimit -c 0').

http://ss64.com/bash/ulimit.html

http://wiki.linuxquestions.org/wiki/Ulimit

---
Tags: 7
---


# Question
Title: New Relic performance monitoring and the Features Module
We've just started using New Relic to monitor our D6 sites, and are also taking advantage of New Relic's ability to report on Drupal module performance.

Our sites contain several modules with configuration exports that are controlled by Features (views, content types, etc).

New Relic's module performance page shows features.module as being the slowest and as having the highest function call count.

It was my understanding that Features doesn't do too much of anything except for when you are creating/updating/reverting your features, so I'm confused as to why New Relic would report it as being such a drag in terms of site performance.

Can anyone confirm that Features does indeed significantly impact site performance? Or confirm that it doesn't (in which case this seems like a New Relic issue).

# Answer
By design, Features shouldn't induce any performance hit besides what is inherent to any Drupal module. It doesn't implement `hook_init()` or `hook_boot()`, nor does it implement any `hook_form_alter()`s or Node API hooks, so there should literally be no Features activity on most page loads.

However, every time caches are cleared, Features does some heavy work — it interrogates all Feature modules and rebuilds Faux-Exportables.

---

There are two kinds of Features Components: Exportables and Faux-Exportables.

## Exportables

Anything that is a CTools Exportable is also a Features Exportable, such as Views, Contexts and Panels.

On this issue thread, one of the Features maintainers says:

> Generally speaking a View in the database and a View in code perform exactly the same. There are some slight differences in loading methodology (it helps to have a good PHP code cache like xcache or APC when using exportables as the data lives in code), but other than that you shouldn't see any differences.

## Faux-Exportables

Faux-Exportables include content types, CCK fields, taxonomy, roles, and permissions.

Faux-Exportables are by definition stored in the database, so they do not require any intervention from Features. Features only touches Faux-Exportables when rebuilding (as mentioned above).
> 1 votes

---
Tags: performance, features
---


# Question
Title: How do I make the title field in views as the title of the block?
So how do I make the field "title" also show in the title of the block? Thanks.

Here is the image of the view: https://i.stack.imgur.com/jyUmo.png

# Answer
> 2 votes
Add a contextual filter of type 'Content: Nid'. Set 'Provide default value' to 'Content ID from URL'

Under 'When the filter value IS available or a default is provided' set 'Override Title' to %1.

That should do the trick...

---
Tags: 7, views
---


# Question
Title: render($content) puts comment form above markup - why?
In my node--blog.tpl.php file, I have the following code:

```
<?php if ($teaser):?>
    <!-- Do some stuff -->
<?php else:?>
    <!-- A little HTML -->
    <?php print render($content);?>
<?php endif;?>

```

When I load up a blog page, the comments form is actually above the content. This isn't some CSS quirk - it's above the content in the HTML structure.

How have I managed that, then? Can anyone suggest a way to ensure the comments form appears in its rightful place, below the content?

# Answer
There is a **show weights** link in Drupal 7.14. If you go to Comment Fields in your content type /admin/structure/types/manage/.

I set the weight, and comments still show above the body.
> 2 votes

# Answer
Just try to check weight of `$content` elements. it seems that comments element has low weight number.
> 1 votes

# Answer
I have had this happen before with CCK forms.

If you have javascript enabled, it likes to reorder the weights of the fields with the drag-drop interface, and many of the hidden items don't appear in the selection.

The only way I found to fix the weight problem was to manually reassign the weights, which requires that you disable JS in your browser so the drag-drop interface goes away in favor of actual text boxes to enter the weight values.
> 0 votes

---
Tags: 7, theming, comments
---


# Question
Title: Is there a function to get the current user object that avoids accessing the global variable?
I've always gone with this `global $user;`. However, I seem to remember seeing something in a contributed module that returned the current user object without using the global `$user`.

Does such a function exist in Drupal 7 core, or is using the global variable the de-facto recommended way to get the current user object?

# Answer
The function you could use is user\_uid\_optional\_load(); without arguments, it returns the user object for the currently logged-in user. It still uses the global `$user`, and loads the full object from the database, including the fields associated to users, but it avoids your code accidentally change the content of the global variable `$user`, as it is not referenced from your code.

```
function user_uid_optional_load($uid = NULL) {
  if (!isset($uid)) {
    $uid = $GLOBALS['user']->uid;
  }
  return user_load($uid);
}

```

If you don't need the full object, then you can use the code already reported in the other answers. If you want to be sure you don't alter the global object, you can copy the global variable into a local variable, as in the following snippet.

```
$account = $GLOBALS['user'];
// Use $account.

```

In Drupal 8, you simply use the static method `\Drupal::currentUser()` to get the equivalent of Drupal 7 `$GLOBALS['user']` and `\Drupal\user\Entity\User::load(\Drupal::currentUser()->id())` to get a fully loaded object with all its field API fields. There isn't anymore the risk of overriding a global variable with all the consequences.
In the case you need to switch the current user with, for example, the anonymous user, the code you use in Drupal 8 is the following one.

```
$accountSwitcher = Drupal::service('account_switcher');
$accountSwitcher->switchTo(new Drupal\Core\Session\AnonymousUserSession());

// Your code here.

// Eventually, restore the user account.
$accountSwitcher->switchBack();

```
> 22 votes

# Answer
The `$user` object is declared as a global variable, so if you want to access it you need to use either:

```
global $user;
$account = $user;

```

or

```
$account = $GLOBALS['user'];

```

There doesn't actually seem to be a standard way to do this in Drupal. If you look at the node module for example, the `node_access_grants()` function uses this code:

```
if (!isset($account)) {
  $account = $GLOBALS['user'];
}

```

Whereas the very next function in the file, `node_access_view_all_nodes()`, uses this:

```
global $user;
if (!$account) {
  $account = $user;
}

```

The simple answer is that both are valid. I think the use of `$GLOBALS` is so that the variable named `$user` is not active in the current scope and therefore can't be overwritten by a careless call to, for example, `$user = NULL` further on in the function. I'm not 100% on that though.
> 20 votes

# Answer
It is as simple as declaring the (existing) global $user object within the scope of your function:

```
global $user;

```

Keep in mind that changes made to this object affect it globally, i.e.

```
global $user;
$user->uid = 1;

```

just gave the current user uid 1 privileges. This is why typically $user is assigned to $account so that data can be tinkered with without actually affecting the currently logged in user (unless, of course, you wanted to).
> 3 votes

---
Tags: users
---


title: How to replace links with images?

text:
# Question
Title: How to replace links with images?
I am wondering what is the best way to replace each of the internal links, e.g. 'Bookmark this' etc., with images?

# Answer
Not really a Drupal specific question, but use CSS image replacement. I personally use the Phark revisited method, because you don't need any additional markup and you use only three or four rules to make it work (in some cases you don't need to use width).
> 1 votes

# Answer
As ipwa said you can use css to replace links with images, though it's not dynamic, but this a good way if you dont need to update the images from time to time.

Ex:

```
.links {
  text-indent: -10000px;
  background: url('../images/file.png') no-repeat center center transparent;
  height: ; //Specify the height
  width: ; //Specify the width
}

```

Or you can do this also in Drupal-way via template.php preprocess. Example in node...

pseudo-code:

`"<a href='#'>". theme('imagecache', 'yourPreset') ."</a>"`

Or you can also use Jquery.
> 0 votes

---
Tags: media, navigation
---


# Question
Title: Stop caching images in views, force reload of jquery image slideshow when images are externally updated
In D7, I have a panel that contains a view that contains a jquery image slideshow.

Every day, the images that compose the slideshow are updated by a cron job---ie, every day's new images override the old ones (they are given the same names). So, say I have image1.png, image2.png and image3.png---every day these files are overwritten with new pictures.

I have added the following anti-cache protections in my meta section to both the page/panel and the view itself:

```
<meta http-equiv="Cache-Control" content="no-cache, must-revalidate">
<meta http-equiv="Pragma" content="no-cache">
<meta http-equiv="Expires" content="0">
<meta http-equiv="refresh" content="300">

```

I have also turned off all caching on the server of any duration, and of javascript/css. I also run the external cron with the cron-key after the image overwrite occurs.

Yet it seems that the only way my slideshow ever updates to reflect the new content of the image files is when I do an F5 or ctrl+r hard reload.

I don't want to ask my users to do this, so how can I force a reload and cache-clearing beyond the measures I've already taken above to get the browser to recognize that the images in the slideshow have changed on the server?

(I saw this recent similar post, How to tell if an image was updated, but it seems to apply to images created by Drupal, rather than created externally and pumped in.)

**Update:**

I have also added, in light of @mikeytown2's comment below, the following to my .htaccess file:

```
 # Requires mod_expires to be enabled.
<IfModule mod_expires.c>
  # Enable expirations.
  ExpiresActive On

  # Cache all files for 2 weeks after access (A).
  # ExpiresDefault A1209600
  ExpiresDefault A600 #NOTE, this means ALL sites expire in 5 minutes by default!

  <FilesMatch \.php$>
    ExpiresActive Off
  </FilesMatch>

</IfModule>

```

The .htaccess is in my public folder.

Even with this, which should be telling Drupal that all caches from my page expire at 5 minutes, I am still not seeing an update when new images replace old ones of the same name in my slideshow.

I have made sure to completely clear my cache and await an external cron, and the old images remain cached in the browser and/or server.

# Answer
> 0 votes
None of these internal-to-drupal settings worked. It turned out I had to curl my cron.php remotely to actually reset the caching.

# Answer
> 3 votes
with firebugs net panel click on image1.png, select cache and get this information

```
Last Modified
Last Fetched
Expires

```

Your currently setting the html page to not be cached in the browser (which is already the case by default). If the images are hosted on your server, you need to adjust your apache .htaccess rules and have these images not be cached. Drupal's default htaccess uses a 2 week cache for everything other than php scripts. You need to make an exception for your images with filesmatch. Example:

```
# Requires mod_expires to be enabled.
<IfModule mod_expires.c>
  # Match image1.png, image2.png, etc...
  <FilesMatch ^image\d+\.png$>
    # Disable browser caching.
    ExpiresActive Off
  </FilesMatch>
</IfModule>

```

If the images are not hosted on your server simply append a question mark with the current unix time to the end of the image src. Example:

```
image1.png?1317717247

```

---
Tags: views, media, javascript, caching, cron
---


# Question
Title: Colorbox not working for anonymous users, but works fine for logged in
I am having an issue getting my colorboxed images to load while viewing the page as an anonymous user. As an anonymous user, there is no reference to anything related to colorbox at all. However, when logged in as admin, everything works fine.

This feels like a permissions issue, but I don't see any settings in permissions. also, the configuration in the 'manage display' settings leave a bit to the imagination.

What am I doing wrong? Is this indeed a permissions issue? 7.x 1.3 and drupal 7.14

# Answer
> 0 votes
I had a javascript conflict in my theme. Works great now that that has been cleared up. Thanks!

---
Tags: 7, media, javascript
---


# Question
Title: How do I use translated taxonomy terms in exposed views filters?
I have a multilingual website with 5 languages. I want to add exposed filters to the top of my views generated pages. Everthing works fine in English, my source language, but when I create a view for a foreign language and create the exposed filter for taxonomy, I can only choose the English list. I thought this would translate automatically once the page changed languages, but this is not the case.

To see what I am talking about, please click here http://noboribetsu-spa.jp/ja/泊まる

What module do I need or what do I need to do to get these transalted terms to show up in the exposed filter select list?

thanks

# Answer
> 1 votes
The answer to this is to use the i18nviews module, which is independent of the modules included in i18n. Once the module is installed then in your view chose Filter: Has taxonomy (translated terms). Even though the selection will be in the source language they will then translate properly on the page views.

Note: at the time of this post il8nviews is in development, has little to no documentation, and is a bit difficult to work with, but hopefully that should be cleared up soon.

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


# Question
Title: Merging new contents with new functionalities
Assuming a situation when you develop a new functionality on a local copy of an already published site for quite a while, during which period the client adds new content over and over again.

How do you then merge the new additions from both sources? Do you use Features or something else? What's the safest way to go?

# Answer
> 0 votes
**Use below modules and git**

**Modules:**

1) Backup and migrate(By this module you can take the backup of database from the production site).

2) Features(You can export content types, admin settings and global settings).

3) Drush(You can use this module for the production deployment).

**Version control system**

1) GIT

**Below are the steps how to sync your code and database with the production site.**

1) Take the database backup from the production site before you start working on the local machine and import that database into the local machine.

2) Take the updated code base from the git repository of production site.

3) Complete your work whatever you want and in the evening after completion of your work create features(If you have done some changes in content type, permission or any other settings) and pull code from the git repository if there is conflict then resolve it otherwise just commit your code on the git repository and move those changes from git repository to prod server.

4) Test whether it is working fine or not. If it is not working perfectly then revert your changes from git and commit your files and then move your files from git repository to prod server.

---
Tags: 7, nodes, deployment
---


# Question
Title: use menu item title instead of page title in breadcrumbs
I have been trying to display the menu item title as the trailing item in my breadcrumbs, other than the page title.

At this point, I override the `template_breadcrumb()` function with a custom function. At the end of the string variable, I have put `drupal_get_title()` to append the page title to the breadcrumb trail.

Please find a snippet out of the breadcrumb function below:

```
foreach($breadcrumb as $value) {
  $crumbs .= $value;
}
$crumbs .= drupal_get_title();

```

Now, **when available**, I would prefer the linked navigation item title to be displayed as trailing breadcrumb item. If not available, I will display the page title.

How can I check if this page is attached to a menu item, and retrieve the title, in order to display it as a breadcrumb item ?

# Answer
> 1 votes
Perhaps you could look at this module: http://drupal.org/project/menu\_breadcrumb It sounds perfect for your needs.

Some details from the module's project page:

> By default, Drupal 6+ use the Navigation menu for the breadcrumb. This module allows you to use the menu the current page belongs to for the breadcrumb.

# Answer
> 1 votes
You can use Crumbs module. In the configuration (Admin \> Structure \> Crumbs), look for

```
menu.link_title.*
menu.link_title.devel      - Development
menu.link_title.main-menu  - Main menu
menu.link_title.management - Management
menu.link_title.navigation - Navigation
menu.link_title.user-menu  - User menu

```

This is already enabled by default. To disable it for specific menus, move the respective line into the "disabled" section.

---
Tags: navigation, 7, breadcrumbs
---


title: Print result of $body

text:
# Question
Title: Print result of $body
on D7 and I've made this:

```
function project() {
  global $user;
  $uid = $user->uid;
  $name = $user->name;

  $teaser = 0;
  $page = 1;
  $type = 'page';
  $status = 1;
  $format = 3;

  $body = "<script language=\"JavaScript\" src=\"/misc/collapse.js\" type=\"text/javascript\"></script> ".
                "<div><p>Projects from user ".$name."</p></div>";
}
?>

```

And I need to print the result on the main content of my theme, how can I do it? If I do `echo "$body";`I view the result not in the main content but as a single page. Thanks a lot.

# Answer
> 1 votes
```
<?php print $node->body['und'][0]['value'];?>

```

# Answer
> 1 votes
I suppose that `project()` is a page callback, a function that is associated to a path used from the module, and that needs to output what contained in `$body`. In that case, you need to returns its content, and your code should be like the following one.

```
function project() {
  global $user;
  $uid = $user->uid;
  $name = $user->name;

  // The rest of your code.

  return '<script language="JavaScript" src="/misc/collapse.js" type="text/javascript"></script>' . "<div><p>Projects from user $name</p></div>";
}

```

The reason is that drupal\_deliver\_html\_page() (indirectly called from index.php) contains the following code.

```
  if (is_int($page_callback_result)) {
    // The page callback returned an integer.

    // …

  elseif (isset($page_callback_result)) {
    // The page callback returned a string or an array.
    // Print anything besides a menu constant, assuming it's not NULL or
    // undefined.
    print drupal_render_page($page_callback_result);
  }

```

If your page callback doesn't return anything, but it just prints its own output, `drupal_render_page()` will not be called, and the output of your page callback will be all the content you see in the page.

---
Tags: nodes
---


# Question
Title: Making a Content Type the subpage of a Views page for the sake of Breadcrumbs
I have a Content Type named Cars and a Views page which lists all those cars. Is it possible to put the Cars content type under The Views page so my breadcrumbs would come out as `Home > Cars > Sample Car`. **Cars** is the Views page, **Sample Car** is the Content Type.

# Answer
> 1 votes
Alternate way.... Using Custom module.

```
function hook_node_view($node, $view_mode, $langcode){
  if($view_mode == 'full' && $node->type =='cars'){
    $bc[] = l('Home', '<front>');
    $bc[] = l('Cars', url('cars'))
    $bc[] = l($node->title, url('node/'. $node->nid));

    drupal_set_breadcrumb($bc);
  }
}

```

# Answer
> 0 votes
For this you will have to use Menu Breadcrumb and Path module

Define your view's path as `cars` and define path for your Cars type nodes as `cars/sample-car`

Menu Breadcrumb will do the magic for you to arrange hierarchy of your view and nodes in bread crumb

# Answer
> 0 votes
The Menu Position module should allow you to do this, and it works for Drupal 7.

# Answer
> 0 votes
Use the Crumbs module (7.x-1.2 +). Go to Admin \> Structure \> Crumbs \> Node parent, here you can configure a parent path for each node type, with token support.

---
Tags: views
---


# Question
Title: How to alter add content form to include a new setting panel?
Here is the code for creating a new Tab in the settings panel on "Add article" node. But it is not displaying.. what could be the errors ?

```
function mltag_form_alter(&$form, &$form_state, $form_id) {
if ($form_id == 'article_node_form') {
drupal_set_message('Editing a node');
$form['mltag'] = array(
    '#type' => 'fieldset',
    '#title' => t('MLTag settings'),
    '#access' => TRUE,
    '#collapsible' => TRUE,
    '#group' => 'additional_settings',
    //'#attached' => array(
    //        'js' => array(drupal_get_path('module', 'autordf').'/autordf.js'),
    //),
    '#tree' => TRUE,
    '#weight' => -2,
    '#attributes' => array('class' => array('mltag-settings')),
);
$form['mltag']['enabled'] = array(
    '#type' => 'checkbox',
    '#title' => t('Generate tags use Mltag'),
    //'#default_value' => (empty($form['nid']['#value'])),
);
}
}

```

# Answer
> 0 votes
Your code works perfectly for me; dropped straight into a form alter hook I get the following on the article add page:

There are 3 reasons I can think of that might explain why you're not seeing the new tab:

1. You haven't cleared Drupal's caches since implementing the new hook (probably the most common cause for problems like this).
2. Your module isn't actually called "mltag", in which case your form alter hook will never actually be run.
3. Your code is in a file other than the main .module file. Hooks declared in files that are not explicitly included from the .module file will not necessarily be found when Drupal is updating the `module_implements` cache.

---
Tags: hooks
---


title: Find Quick-Tabs id?

text:
# Question
Title: Find Quick-Tabs id?
I'm new to drupal and I apologize if this is a silly question. I used the quicktabs module to create tabbed content. I wish to add it to a node template file. In order to add the quick tab, I need the ID of the quick tab instance. **How to find the ID of a quick tab instance** ?

# Answer
Looking at the install file for the module each QuickTab is identified by a machine name, rather than an ID. It used to use an ID up until version 7.x-3.x, but the `quicktabs_update_7300()` function dropped the `qtid` field and replaced it with `machine_name`.

Normally when machine names are used in Drupal the admin UI will tell you what this is for each instance. I can't comment as to whether the QuickTabs UI does that though.

If it doesn't, just go in to the `quicktabs` table and grab the machine name from there...it's not pretty but if you don't plan on changing the machine name of that instance it shouldn't cause a problem.

After you've got the name you can use `quicktabs_load()` to get the instance:

```
$instance = quicktabs_load($machine_name);

```
> 2 votes

---
Tags: 7, blocks
---


# Question
Title: How do I implement drag and drop node re-ordering in a view?
I am creating a simple content admin view, and I need to implement drag and drop re-ordering (instead of weights in drop down menus). Is that possible, and how?

# Answer
I think you're looking for the Draggable Views module:

> DraggableViews makes rows of a view "draggable" which means that they can be rearranged by Drag'n'Drop.
> 3 votes

# Answer
You can use a Nodequeue. If you have Views installed an enabled, you will get a view for each nodequeue if you have the settings configure appropriately. I prefer this solution over DraggableViews.
> 1 votes

---
Tags: views
---


# Question
Title: modules for building ajax application and friendly urls?
I'm building an ajax application using drupal 7, i found a module with some help ajax\_nodeloader, but also i need load panel pages, views, etc.

Until now i'm overriding template theme file (zen) for ajax requests, and trying to use jquery address for good seo.

Also i will use jQuery UI Layout Plug-in on my template.

Which modules do you recommend ?

# Answer
> 1 votes
You shouldn't need an additional module, Drupal's AJAX framework should provide the needed features. For instance, it can easily be used to *ajaxify* links.

See the AJAX Example, AJAX Graceful Degradation and AJAX Commands example modules for API usages.

---
Tags: javascript, ajax
---


# Question
Title: My pager disappears when I use hook_views_pre_execute
I need to modify a query of one view. So, I use the `hook_views_pre_execute`. The query is modified but the pager disappears. My question is why? Do I need to add more lines to hook to use to display the pager?

Code:

```
function view_format_render_views_pre_execute(&$view) {

    if ($view->name == 'view_probe' && $view->display['block_1']->display_title =='List of categories') {
        $tid = $view->args[0];
        $tids = array_keys(taxonomy_get_children($tid));
        $tids=implode(', ',$tids);

         $search = "node_data_field_formatos_colecc.field_formatos_colecc_value = %d";
            $search_new = "node_data_field_formatos_colecc.field_formatos_colecc_value IN ( ".$tids." )";

            $query = &$view->build_info['query'];
            $query = str_ireplace($search, $search_new, $query);

            $view->build_info['query'] = $query;

        if (isset($tid) && isset($arguments)) {

                $query = str_ireplace($search_new, '', $query);
                $view->build_info['query'] = $query;
        }
    }
}

```

# Answer
> 1 votes
if query exec is too long (for pagination views must return total count of rows at all pages and correspond it to rows per page ) pagination not returned by views.

nid of nodes returns from one table in database and this queries is very simple & fast

another fields (cck, ubercart, stock) returned from another db tables and it can be too long. for this views just returns first page to prevent timeout

---
Tags: views, 6, paging
---


title: How to unserialize D7 session?

text:
# Question
Title: How to unserialize D7 session?
This is how the user session is stored in Drupal 7:

```
batches|a:46:{i:13;b:1;i:14;b:1;i:15;b:1;i:16;b:1;i:17;b:1;i:18;b:1;i:19;b:1;i:20;b:1;i:21;b:1;i:22;b:1;i:23;b:1;i:24;b:1;i:25;b:1;i:26;b:1;i:27;b:1;i:28;b:1;i:29;b:1;i:30;b:1;i:31;b:1;i:32;b:1;i:33;b:1;i:34;b:1;i:35;b:1;i:36;b:1;i:37;b:1;i:38;b:1;i:39;b:1;i:40;b:1;i:41;b:1;i:42;b:1;i:43;b:1;i:44;b:1;i:45;b:1;i:46;b:1;i:47;b:1;i:48;b:1;i:49;b:1;i:50;b:1;i:51;b:1;i:52;b:1;i:53;b:1;i:54;b:1;i:55;b:1;i:56;b:1;i:57;b:1;i:58;b:1;}updates_remaining|a:0:{}dblog_overview_filter|a:2:{s:4:"type";a:0:{}s:8:"severity";a:1:{i:2;s:1:"2";}}

```

How do I convert it to a PHP array? `unserialize()` does not work.

# Answer
> 3 votes
That's a session encoded string (different from a PHP serialized string). There's no built-in way to decode it directly into a variable, so you'll have to use a custom function.

Here's one nicked from the docs page for session\_decode().

```
function unserializesession( $data ) {
  if(strlen( $data) == 0) {
    return array();
  }

  // match all the session keys and offsets
  preg_match_all('/(^|;|\})([a-zA-Z0-9_]+)\|/i', $data, $matchesarray, PREG_OFFSET_CAPTURE);

  $returnArray = array();

  $lastOffset = null;
  $currentKey = '';
  foreach ( $matchesarray[2] as $value ) {
    $offset = $value[1];
    if(!is_null( $lastOffset)) {
      $valueText = substr($data, $lastOffset, $offset - $lastOffset );
      $returnArray[$currentKey] = unserialize($valueText);
    }
    $currentKey = $value[0];

    $lastOffset = $offset + strlen( $currentKey )+1;
  }

  $valueText = substr($data, $lastOffset );
  $returnArray[$currentKey] = unserialize($valueText);

  return $returnArray;
}

```

It works well with the example in your question, returning a nested array of values.

---
Tags: 7, sessions
---


title: Conditionally override link path

text:
# Question
Title: Conditionally override link path
Have the following code

```
    $links = array_merge($links, array(
      l(t('Administration pages'), 'admin'),
      l(t('Front page'), '<front>'),
     ));
    }

    $output = theme('item_list', array('items' => $links, 'title' => t('Next steps')));

```

It does `<ul>` html list. My goal is to override, for example, "admin" path on given page from my custom module. Since it's themed output, I can use `hook_theme_registry_alter()` to override the theme function. But seems I can't do that dynamically (because of cache).

Is it wise solution to copy whole `theme_item_list` function, rename it to `my_theme_item_list` and write there my own path logic?

Another solution?

# Answer
I think you can do anything you could do in my\_theme\_item\_list in a preprocess function. You can do this in your template.php file with a function like:

```
function mythemename_preprocess_item_list(&$vars) {
  // Change things here
}

```
> 1 votes

---
Tags: 7, theming
---


# Question
Title: Programmatically assigning new users to groups
I have a specific need where if a user is created and assigned to the role "manager" that user should be automatically subscribed to all groups. I can do this without issues if I hard code the uid. I have problems when i use hook\_user\_insert and I am not sure why. The problem is that none of my code actually executes. The hook does fire when I load a user object of a hard coded uid however.

Here is my hook:

```
 function mm_custom_user_insert(&$edit, &$account, $category)
{

    if(in_array('manager', $account->roles)) {

      //get all gids
      $results = db_query("SELECT gid FROM og");
      $gids= array();
      while($record = $results->fetchAssoc())
      {
        $gids[]= $record['gid'];
      }

      foreach($gids as $gid)
      {
        og_group($gid, array(
                "entity type"       => "user",
                "entity"        => $account,
                "membership type"   => OG_MEMBERSHIP_TYPE_DEFAULT,
            ));
        og_role_grant($gid, $account->uid, 3);

      }
    }
}

```

My main questions are a.) are the user-\>roles not available at this time? how would I find this out? b.) could it be that the the uid is not available?

Appreciate the help

# Answer
The user ID is definitely available, as `hook_user_insert()` is called after the user data has been committed to the database.

I've just put the following code into a test module called `foo`:

```
function foo_user_insert(&$edit, $account, $category) {
  dpm($account);
}

```

Then I created an account through the admin UI and the output from `dpm()` looks like this:

So as you can see, the roles are available too.

If you're not familiar with the `dpm()` function, it's part of the Devel module. It will print any PHP variable to the standard messages area and will display objects/arrays like the screen shot above. It should help you with most of your debugging needs.
> 1 votes

---
Tags: hooks, organic-groups, users
---


# Question
Title: Globally providing title attribute to links
Recently I've been asked by a SEO-managing person to copy the text of all links within main menu into their title attribute. As my menu is run by OM Maximenu and contains mostly Views, it was relatively easy to add it in corresponding view, but I started to wonder if there's a way to globally alter links in such a way. It would have to be performed in PHP level (template.php or a module). I haven't found a hook though like "drupal\_link\_alter", except for some old Drupal 5 function?

Any insights?

# Answer
A lot of links end up going through `theme_link()` at some point (even those that go through the `l()` function by default); so providing a preprocess function for that theme, that adds a title to any link that doesn't already have one, would be a very good start:

```
function MYTHEME_preprocess_link(&$vars) {
  // If there is already a title set, and it's not empty, we don't need to continue.
  if (isset($vars['options']['attributes']['title']) && !empty($vars['options']['attributes']['title'])) {
    return;
  }

  // Otherwise we use the link text as the title.
  $vars['options']['attributes']['title'] = strip_tags($vars['text']);
}

```

This won't catch links that are outputted directly in HTML, or don't go through `l()`/`theme_link()`, but I think you'll struggle to intercept those anyway (it would require some DOM parsing or ugly regex).
> 2 votes

---
Tags: navigation
---


# Question
Title: How does Drupal find contributed modules and themes?
I have a development site with a peculiar problem Although the contributed modules and themes are in their proper place under `sites/all/modules` (& themes) I am getting an error message that says that my custom theme cannot be found. Also, the modules list does not include any of the contributed modules.

The error message indicates that it does not find my default theme:

> Notice: Undefined index: CR\_Stark in drupal\_theme\_initialize() (line 100 of /example.com/includes/theme.inc). Notice: Trying to get property of non-object in \_drupal\_theme\_initialize() (line 145 of /example.com/includes/theme.inc).

While I would assume that the relative locations of these custom directories is hard coded in Drupal core, the fact that it cannot find the modules when they are in the correct place suggests that there may be a missing variable or setting. I have checked the sites/default/settings.php file and looked through the variables table in the database, but cannot find a reference that would serve this purpose. Can anyone point me in the right direction?

EDITS: per suggestions in comments:

* Caches have been cleared frequently without change
* Changing to a default theme removes the theme error, but it is replaced with an error I believe is tied to not knowing where the custom modules are.

> Warning: opendir(sites/all/modules): failed to open dir: Permission denied in file\_scan\_directory() (line 2034 of example.com/includes/file.inc).

Line 2034 is in the core function `file_scan_directory ()` and reads `if (is_dir($dir) && $handle = opendir($dir)) {`; so it looks like Drupal is searching for a custom module (or theme) directory it cannot find or access. The directory access settings are correct.

* The directory settings in the systems table are correct and the contributed modules and theme are all included.

---

This may not be the solution, but it is one resolution, of a sort.

I recreated the site from scratch with a new core install and copied all of the contents of the sites/all/... directories to the new site. I then imported the entire database from the affected site into the new one and ran `update/php`. This new site is seeing everything fine. These dev sites are being run on a virtual box running Ubuntu. It may have had something to do with settings on the directories from the OS, but I could not find it.

If anyone else has had a similar problem and found a source for the problem, please post it here.

# Answer
> 7 votes
Based on the error message you are getting, "failed to open dir: Permission denied in file\_scan\_directory()," I would assume that directory access settings are in fact not correct. The user running your webserver can apparently not open sites/all/modules. The best way to check this is to actually switch to the user running the webserver and try to open the directory. A common example would be a user named "apache" for the apache httpd.

On a Linux/OSX system one would often run the following command to accomplish this, though it could vary if your distribution already has a default shell for the user, or supplies a different one from bash. The example is from ubuntu, assuming you are using a normal user account with sudo privileges.

```
sudo su apache -s /bin/bash

```

How to do this in Windows I don't know, though I assume it's possible.

# Answer
> 1 votes
To see what ownership files and directories have, is the ls command: ls -l To change them, use chown as root: sudo chown ... or su -c chown ... use the man command for fuller details: man 1 chown man 1 ls

In some distributions, notably RHEL and its clones, selinux also has a vote. Such errors might be logged in /var/log/messages or an audit file. Note, if selinux gets in the way, turning it off is seriously stupid. Fix the access and policy rules.

# Answer
> 0 votes
Letharion was correct, but implementing the solution required a bit of nuance. I am using Ubuntu Linux on a vbox. The various themes and modules were placed on this development site by copying them over from another site. Apparently the settings for owner and access to the directories and files were either changed when copying them to this site (they had worked fine on the other site). To change the permissions required that the terminal be opened with the correct user name (you can verify the name of the user for the terminal by entering the command `WhoamI`). I then had to make certain that the files and directories were owned by the Group 'www-data' which is the identity used by Apache. In order to change the group owning the files I used the command `sudo chgrp -R www-data directory-path` The -R tells the command to iterate through any subdirectories below the directory path. The command to change permissions is `sudo chmod -R ### directory-path`. The three # represent three numbers. that define permissions for the owner, the group and others respectively. To assign a number for each add the values for each setting. Thus read = 2, write = 4, and execute = 1. To give all three powers the proper number would be 2+4+1=7.

---
Tags: database
---


# Question
Title: How can I enforce a minimum length for private messages?
I previously asked how to enforce a minimum length for fields and received some great answers.

Now, I would like to enforce a minimum length for private messages only when it is the first message in a conversation (the private message module calls "threads" of messages conversations).

Use case: I don't want users to be able to send messages consisting only of "hey" or "hi"; thus, I need to enforce a minimum length for the first message. However, once users are talking to one another, it is completely possible that a reply could be "yes" or "no", etc., so follow-up messages should not be limited in length.

Looking through the Privatemsg API, it looks like this might be able to be done with hook\_privatemsg\_message\_validate(), but I'm not much of a coder and I'm at a loss about how to proceed from here.

# Answer
You will need to create a custom module to use that hook it will allow you to run custom validation on top of the standard validation done by private msg.

A hook allows you to add functionality to a module without having to hack the module causing issues when the original module needs to be updated. When a module makes a hook available it allows other modules to perform additional processing during the execution flow in this case additional validation more on hooks here - http://drupal.org/node/292

As a minimum your module will need a info file telling Drupal about your new module and a module file containing the hook with your extra validation code.

You can see what to put in your info file here - http://drupal.org/node/1075072

This page will guide you through setting up your module folder and naming http://drupal.org/node/1074362

Now you have your module structure set up you need to add the hook\_privatemsg\_message\_validate() to the module file

```
function MYMODULENAME_privatemsg_message_validate($message) {

}

```

Replace MYMODULENAME with the name of your module.

From looking at this page it looks like the original message id becomes the thread id if its a reply http://api.worldempire.ch/api/privatemsg/privatemsg.api.php/group/message\_hooks/7-2

```
array (
 'mid' => 3517, // message id, identifies a message
 'author' => 27, // author id
 'subject' => 'Message subject',
 'body' => 'Body of the message',
 'timestamp' => 351287003, // unix timestamp, creation time
 'is_new' => 0, // If the message has been read by the user
 'thread_id' => 3341, // thread id, this is actually the mid from the first                          message of the thread
)

```

My guess is you could do something like this to test:

```
if($message['thread_id'] == 0 || empty($message['thread_id']) && strlen($message['body']) < 25) {
form_set_error("Message must be n chars long");
}

```

I'm not that familiar with the module so you might need to investigate by printing out the message array to confirm this.

Putting it all together it would look something like this

```
function MYMODULENAME_privatemsg_message_validate($message) {
    // Uncomment next line print out the message array if you need to confirm what contiton to use for checking if first msg or not
    // echo print_r($message);
    if (empty($message->thread_id) && strlen($message->body) < 25 /* Change this to whatever length you want*/) {
        form_set_error('body][value', t('Message must be n chars long.'));
    }
}

```

Hopefully thats enough to get you started
> 2 votes

---
Tags: privatemsg
---


# Question
Title: Internal server error on admin/modules/list/confirm
I have recently decided to move one of the sites to another hosting provider, and now started to receive this 500 error when submitting changes to admin/modules. The new hosting has different environment where all sites might have their core and contributed modules connected to the central repository; now, in admin/modules all 850 local repository modules can be seen as they were in sites/all/modules. In server logs this error reflect as:

> mod\_fcgid: stderr: PHP Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 87437 bytes) in /opt/drupal7/includes/cache.inc on line 463, referer: admin/modules
>
> mod\_fcgid: stderr: PHP Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 71 bytes) in /opt/drupal7/includes/form.inc on line 1820
>
> mod\_fcgid: stderr: PHP Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 8208 bytes) in /opt/drupal7/modules/field/field.crud.inc on line 711, referer: admin/modules?render=overlay
>
> mod\_fcgid: stderr: PHP Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 32 bytes) in /opt/drupal7/includes/file.inc on line 200, referer: admin/modules

The site has a 128 MB memory limit; it is more than on previous hosting, but now some of the enabled modules (like OpenLayers) sometime also issue memory errors (like those above, but on site they work without any 500 errors).

What can be the reason of this errors? Is there any additional information that can help find what to fix?

# Answer
You need to check your PHP memory limit on php.ini.
If you use Linux, go to /etc/php.ini to find it out.
> 2 votes

# Answer
You can also set the PHP memory in `settings.php` file:

```
ini_set('memory_limit', '128M');

```
> 2 votes

---
Tags: 7
---


# Question
Title: Changing the link title in a view for generic file
I have a bunch of files that are displayed in a view; i'm using 'generic files' setting to display them; the problem is that some files have really ugly names like '1002-32-eda.pdf' i'd like to change the name to 'download' but keep the 'mime' detection (small icon on the left side; like pdf, word etc).

Any example on how to change this ?

# Answer
**I'm guessing that you are using a field to save the data about the files.**

When the file is displayed in views, it's displayed through a formatter which acts like a theme function. The different ways an image can be shown, is in reality just different formatters that link to different theme functions (or the same, but with different arguments).

You have two options. * You can override the theme function, which would change how ALL files are shown, when displayed using 'generic files'. * Yo u can create your own formatter, and theme function which could be a copy of the one `Generic files` uses, but with a few alterations.

The hooks you need to use, depend on which version of Drupal you use, but you can search the modules and copy how it's done for `Generic files`.

For a long explaination you can check out this blog post I wrote a while back.

The short version is:

use Hook\_field\_formatter\_info:

```
/**
 * Implementation of CCK's hook_field_formatter_info().
 */
function module_formatter_info() {
  return array(
    'default' => array(
      'label' => t('My generic files'),
      'field types' => array('filefield'),
      'multiple values' => CONTENT_HANDLE_CORE,
      'description' => t('My description.'),
    ),
  );
}

```

Next use hook\_theme, creating a theme function with a hook like name:

```
function filefield_theme() {
  return array(
    'module_formatter_default' => array(
      'arguments' => array('element' => NULL),
    ),
  );
}

```

Lastly create the theme function

```
/**
 * Theme function for the 'default' filefield formatter.
 */
function theme_module_formatter_default($element) {
  $file = $element['#item'];
  $file['data']['description'] = t('Download');
  $field = content_fields($element['#field_name']);
  $output = theme('filefield_item', $file, $field);
  return $output;
}

```

The above code should work and do what you want, but haven't actually tested this.
> 5 votes

# Answer
There is another option, if you want to do this for all files on the site: create an override for the function `theme_file_link` (found in the file `file.module`):

```
function THEMENAME_file_link($variables) {
  $file = $variables['file'];
  $icon_directory = $variables['icon_directory'];

  $url = file_create_url($file->uri);
  $icon = theme('file_icon', array('file' => $file, 'icon_directory' => $icon_directory));

  // Set options as per anchor format described at
  // http://microformats.org/wiki/file-format-examples
  $options = array(
    'attributes' => array(
      'type' => $file->filemime . '; length=' . $file->filesize,
    ),
  );

  // Use the description as the link text if available.
  if (empty($file->description)) {
    $link_text = $file->filename;
  }
  else {
    $link_text = $file->description;
    $options['attributes']['title'] = check_plain($file->filename);
  }

  // DO SOMETHING WITH THE LINK TEXT HERE, FOR EXAMPLE:
  // $link_text = urldecode($link_text);

  return '<span class="file">' . $icon . ' ' . l($link_text, $url, $options) . '</span>';
}

```

The drawback is that all file links on the site will now look different, but in some cases that is precisely what you are after. Remember to flush all caches afterward, to make it all work :)
> 3 votes

---
Tags: 7, views, files
---


# Question
Title: How do you include a user's default image in a Drupal 7 view that lists people?
I have a view in Drupal 7 that lists people (users). It shows the username and the standard user picture field. If a user has a set image, it comes through perfectly. However, for users that didn't set a profile image no image is shown, even though I have a default profile image set in the people settings for the site.

How do I get views to use the default profile picture for people that do not have a profile image set?

**Update**: I wasn't clear. I know how to use the default image in the no results behavior. The issue is that I can't get the default image to use the imagestyle I use for the other images.

# Answer
Grab the path on the default image setting. Head over to your view and click on your image field. Look for "no results behavior". In the text area add

Verify that your view does not have hide if empty checked.

Save your view.
> 3 votes

# Answer
I have just found the answer to this question via Drupal.org. You have to use a URI like this:

```
public://user_pictures/default.png

```

in your account settings.

Here, `public://` stands for your public files location (often `sites/default/files/`). What comes after that, is the location of your image within public files. If you do this, the default image is treated like normal user images.
> 30 votes

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


# Question
Title: How can I add extra parameter to URL when click "apply" button of Views exposed filter?
I need to add extra parameter at the end of the page view URL when "apply" button of exposed filter is clicked.

For example,

normally URL looks like:

```
my-view?nid=1

```

But I need to add `"my_parameter=1"` at the end of the URL and it eventually needs to be:

```
my-view?nid=1&my_parameter=1

```

How can I do this?

# Answer
You can use a hook\_form\_FORM\_ID\_alter() to add a hidden form element with the value that you want (1 in your example). You'll have to check the View name and display name to ensure you only affect the right exposed filter.
> 1 votes

---
Tags: 6, views
---


title: How to implement a multi-themed site?

text:
# Question
Title: How to implement a multi-themed site?
I will soon start building a new reasonably large site, that will be presented to the end-user as several different sites. Different domains will map to different sections within the site, and will also have different themes.

How should I implement the "multi-theme"?

I'll be posting some ideas of my own, which I would love some feedback on, but would also very much like to hear other suggestions.

# Answer
I use the Themekey module. This allows me to give each area a distinct look without even touching any code. It also integrates with the Print, Revisioning, Organic Groups, and other major modules out-of-the-box.

Some of the things this module enables you to do (from the module page):

> * individually-styled channels
> * a front-page / "splash" screen
> * a date/time-selected Christmas theme
> * mobile themes for different auto-detected mobile devices
> * special themes for "limited" or "old" browsers
> * content, user, or role -specific themes
> * indicating your environment (production, staging, testing, sandbox, … )
> * testing your redesign safely on a live server
> 7 votes

# Answer
Implement several themes, possibly with a common base theme, and switch theme in code, such as suggested over here: How do I change a theme based on the URL?
> 1 votes

# Answer
Implement a single theme, with all the different themes inside it, and stick a `class="name_of_sub_section"` onto the body element.
> 1 votes

# Answer
I am not sure if it will fit your bill, but the Domain Access module may work for you. With it, you can map different themes to different domains (the Domain Theme submodule) does this. I haven't used it for theme switching, but I have use other features of the module with good success.

Another option is to use the Context module, possible with combination with Delta. With this you can have different portions of your site mapped to different contexts, and then have various reactions associated with them. I don't use this technique, but I have colleagues who do.
> 0 votes

---
Tags: theming, multi-sites
---


# Question
Title: Get error when displaying a token in a header view
I have a view working fine. Now I added a header text (Global Text) printing a token for the first contextual filter :

```
<?php print t('Subastas de ') . !1 ; ?>

```

The token is printed right but I get this error. The token value is: DIBUJO

```
Notice: Use of undefined constant DIBUJO - assumed 'DIBUJO' en eval() (línea 1 de /Applications/MAMP/htdocs/subastaspintura.com/sites/all/modules/ds/ds.module(954) : eval()'d code).

```

In this capture you can see how the Global text header is set up:

# Answer
> 1 votes
I think you can do it without PHP code. Just enter "Subastes de !1".

---
Tags: views, display-suite
---


# Question
Title: template file for content header of a view
I am using views 2. In views, it asks you for the title of the view and this title is displayed on the screen at div id=content -\> div id=content-inner -\> div id=content-header -\> h1 id=title I would like to know if there is a template file which I can modify that can modify this title (ie: add some text to it). I think I can do this with javascript or with css using :after, but I would like to use a template if is available.

# Answer
As far I understood you want to modify title of your views page. This title is the title of entire page. You can modify this title using drupal\_set\_title('Your Title');

If you want to modify this title you can load current title first by drupal\_get\_title() and then set new title.
> 0 votes

---
Tags: views, theming
---


# Question
Title: Drupal 7 url with hex code for special characters?
The URLs for a Drupal 7 site are like the following ones:

I am into module development and this is quite irritating. How do I display the special characters, the "slashes/", "#", "&" symbols that have been converted to hexadecimal codes?

# Answer
You can use the following snippet.

```
$decoded_url = rawurldecode(rawurldecode($url));

```

For example, for the second URL, the code returns http://example.com/drupal7/?q=node/1#overlay=?q=admin/config/content/formats.

That URL anyway is not usable as it is, as it would be wrongly parsed. For example, if on my browser I enter http://tero.local/dr72/?q=node/1#overlay=?q=admin/config/content/formats (tero.local is the local name used from my computer), what I get is the following page.

As you see, the overlay is not shown.
Differently, when I enter http://tero.local/dr72/?q=node/1#overlay=%3Fq%3Dadmin%252Fconfig%252Fcontent%252Fformats, I get the following.

In this case, the overlay is rendered.
> 1 votes

# Answer
@kiamlaluno- thanks man ! seems like drupal 7 displays the url's with the corresponding hex codes for special symbols when the overlay feature is 'ON'.

For those who dont want to work with these url's the solution is to disable the overlay core module from-  **Configuration \>\> Core modules \>\> Overlay \>\> Save Configuration**

This disables the Overlay and '**Normal'** Urls with no hex code appear in the address bar.
> 0 votes

---
Tags: nodes, uri
---


title: Modifying a Form submit button behavior

text:
# Question
Title: Modifying a Form submit button behavior
Basically, there is a module I'm using and there is a submit button on the page.

When the user clicks submit, it validates and processes the user input before going to the next page.

What I want to happen is that when a user clicks submit, the form does the default behavior of validating and processing the user input. But then I want to add a popup depending on if the previous input is valid. There will also be a button on the popup to take you to the next page.

How can I do this, if at all?

# Answer
In a custom module, implement `hook_form_FORM_ID_alter()`. In there, the `$form['#submit']` element is an array of all the functions that will handle a valid form submission. You can add your function to that array to have it executed on (valid) submission. Submit handler functions are executed in the order of the array, so the best is probably to append yours at the end. If the array is empty, you need to create the array and it must contains default submit handler in addition to yours, otherwise your will loose the default behavior.

To open a popup, you will need some custom JavaScript to the page trough `drupal_add_js()` (which you would call from your submit handler). In your custom JavaScript, you can use jQuery UI Dialog library bundled with Drupal 7. To have the library available on the page use `drupal_add_library('system', 'ui.dialog')`. You can use `drupal_add_js()` to pass data from your validation handler to your JavaScript code using the `setting` type.
> 1 votes

---
Tags: forms
---


title: Using Filter on NULL Values in Views 3

text:
# Question
Title: Using Filter on NULL Values in Views 3
I'm using Drupal 7 with views 3.

I am listing the student fees in a view and one of the field in view results is pid (payment id) which has some numeric value or NULL value. The NULL value means the payment is unpaid. I have used a custom field handler to show in view result as paid and unpaid for pid = some value as Paid and pid = Null value as Unpaid.

I want a filter on this field also which will have a drop down of two options as paid and unpaid. Which views filter I should use and how can I rename the drop down options?

hook\_views\_data()

```
// Status of payment paid or unpaid if pid is null in joined result set : unpaid
    $data['fee_schedule_payments']['payment_status'] = array(
        'real field' => 'pid',
        'title' => t('Fee schedule payment status'),
        'label' => t('Status'),
        'help' => t('Fee schedule payment status'),
        'field' => array(
      'handler' => 'fee_management_handler_field_payment_status',
      'click sortable' => TRUE, // This is use by the table display plugin.
    ),
    'filter' => array(
      'handler' => 'views_handler_filter_WHICH_ONE_I_SHOULD_USE',
    ),
    );

class fee_management_handler_field_payment_status extends views_handler_field {
    function construct() {
    parent::construct();
    $this->additional_fields['pid'] = 'pid';
  }
  function render($values) {
    $pid = $this->get_value($values, 'pid');
    if (!empty($pid)) {
            return 'Paid';
        }
        return 'Unpaid';
  }
};

```

Thanks in advance for your help.

# Answer
I have implemented this custom filter. All Thanks and credit goes to Amar :). I am just sharing the code.

```
// Status of payment paid or unpaid if pid is null in joined result set : unpaid
    $data['fee_schedule_payments']['payment_status'] = array(
        'real field' => 'pid',
        'title' => t('Fee schedule payment status'),
        'label' => t('Status'),
        'help' => t('Fee schedule payment status'),
        'field' => array(
      'handler' => 'fee_management_handler_field_payment_status',
      'click sortable' => TRUE, // This is use by the table display plugin.
    ),
    'filter' => array(
      'handler' => 'fee_management_handler_filter_payment_status',
      'numeric' => TRUE,
    ),
    );

```

Handler

```
class fee_management_handler_filter_payment_status extends views_handler_filter_many_to_one {
  function get_value_options() {
    $this->value_options = array('1' => 'Paid', '0' => 'Unpaid');
  }

    function query() {
    // as per your database st
        ;

  }

}

```
> 0 votes

---
Tags: views
---


# Question
Title: Does Drupal 7 Entity Translation Translate?
I've gone through the process of setting up Entity Translation and get the option for Translation, (for example a basic page). When editing the node, I get the translate tab, but see nothing there that actually translates. It appears that the functionality is the ability for the user or admin to supply the translation, and Entity Translation provides the link to the proper content depending on the translation option(s) specified by the user or browser, or other language selecting trigger.

I was hoping for an actual translation of content. Does that happen, or can it happen?

Modules installed and/or enabled on 7 include:

* Entity Translation
* Title
* Entity
* i18n
* Variable
* Localization Update

# Answer
> 0 votes
You need to edit your fields and make them translatable.

EDIT:

Ah, misunderstanding. Entity translations provides a user interface that allows you to translate entities. It doesn't translate itself.

What you are looking for in that case is Translation Management Tools\*. It integrates with content translation, entity translation and more and allows to send text to a translator and save the translation in the correct place. There is a large list of supported translators, including a simple export/import, translation agencies, a local translator and Microsoft Translator, which is a machine translator and probably what you are looking for.

It's goal is to facilitate the management of a multilingual site with overviews, bulk operations, configurable review processes and a flexible, extendable architecture. It is, however, a new and large project, currently only available as an alpha and not every subsystem is finished. Notably, Microsoft Translator is currently broken because they changed their API, see http://drupal.org/node/1574516.

\*Disclaimer: I am the maintainer of that project.

---
Tags: i18n-l10n
---


# Question
Title: Create a simple module to retrieve record from database?
I need to create a simple module to fetch some record from database related to a node.

I have `product` nodes and users who makes `bids` in this product. Then at the time I load a `product` I need to retrieve all bids in this product to show them in a block.

I need some start guide/documentation to do it.

This is my first module attempt and this is the code I start working with: no error yet but it doesn't print out the values I need.

```
function myModule_load($node){

$result = db_query("SELECT * FROM {uc_auction_bids} WHERE nid = :nid", array(':nid' => 258,));
$record = $result->fetch();

// print the fields/values of $record
print('<pre>');
print_r($record);
print('</pre>');

```

}

Any help for creating this simple module, please?

I just need to know which is the right function/hook where I can fetch the data from the database, and prepare the data to create the block.

# Answer
> 5 votes
The Creating modules tutorial covers block creation: implementation of `hook_block_info()` to declare your block, implementation of `hook_block_view()` to generate the block content, usage of `theme()` to format retrieved records and usage of `user_access()` to check user permission before giving him/her access to the information

The only missing information is the `menu_get_object()` function which you can use to retrieve the currently displayed node (if any).

```
function myModule_block_view($delta) {
  if (($node = menu_get_object()) && ($node->type === 'product')) {
    $results = db_query("SELECT * FROM {uc_auction_bids} WHERE nid = :nid", array(':nid' => $node->nid));
    $records = $results->fetchAllAssoc('bid');

    $content = ... // Format records here...

    return array(
      'subject' => t('Bids'),
      'content' => $content
    );
  }
}

```

A more complex solution, but a flexier one, would be to expose the `uc_auction_bids` table to views using a `hook_views_data()` implementation. You could then create a block display using a contextual filter to retrieve the current node ID.

# Answer
> 4 votes
I think you can do this with the Views module. Or is the Bid Table not something made with Drupal?

Just create a block (in views) and choose the data you would like to show for a particular node. Then add a "Contextual filter" with the node ID you're currently viewing.

---
Tags: database, blocks
---


# Question
Title: How do I insert content fields above title in a content type template?
While customizing `node--mycontenttype.tpl.php` full view, I wanted to insert a couple of fields above the main page title. Can this be done in `node--mycontenttype.tpl.php`? or should I step up into the `page--whetever` level of suggestions?

This if:

```
<?php if (!$page): ?>

```

seems to never be true for that full view I'm using. I'm afraid I don't understand this flag enough. Any hints, please?

# Answer
You will have to use the page template instead of node template so you can add fields before the node title. page--content-type.tpl.php
> 0 votes

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


# Question
Title: Programmatically changing theme after hook_custom_theme
I'm trying to change the theme in code in drupal7. hook\_custom\_theme is too early since I need spaces\_init to have happened already. The themekey module uses custom\_theme so that's out.

The only method I've found so far is to change the theme callback using menu\_alter. What other options are there?

# Answer
> 4 votes
Both `hook_custom_theme()` and `hook_init()` are invoked from \_drupal\_bootstrap\_full(), which contains the following code.

```
menu_set_custom_theme();   // It invokes hook_custom_theme().
drupal_theme_initialize();
module_invoke_all('init');

```

The reason of the order is explained in the comment before that code, which says:

> Prior to invoking `hook_init()`, initialize the theme (potentially a custom one for this page), so that:
>
> * Modules with `hook_init()` implementations that call `theme()` or `theme_get_registry()` don't initialize the incorrect theme.
> * The theme can have `hook_*_alter()` implementations affect page building (e.g., `hook_form_alter()`, `hook_node_view_alter()`, `hook_page_alter()`), ahead of when rendering starts.

It seems that your situation is a circular-reference situation, where an implementation of `hook_custom_theme()` depends from `hook_init()`, and an implementation of `hook_init()` could depend from the value returned from `hook_custom_theme()`.

If you are sure that the result of `hook_custom_theme()` doesn't influence the code of `spaces_init()`, which doesn't need the theme to be initialized, then you could invoke `spaces_init()` in your `hook_custom_theme()` using `module_invoke('spaces', 'init')`, but that sounds like a hack, and subject of problems if `spaces_init()` is changed, and it actually needs a theme to be initialized before being executed.

# Answer
> 2 votes
Implementations of `hook_custom_theme()` are only invoked from `menu_get_custom_theme()`. The `theme callback` set for the current menu item is invoked right after the `hook_custom_theme()` implementations. So if your `hook_custom_theme()` implementation is invoked too early, the `theme callback` for your page will also be invoked too early.

These seems to be the only safe ways to change the theme used on the page.

Having `drupal_theme_initialize` (which is what invoke `menu_get_custom_theme()`) invoked before implementation of `hook_init()` (such as `spaces_init()`) doesn't seems right. The theme should not be initialized so early. Unless a theme initializing function (such as `theme()`) is invoked in an `hook_init()` or `hook_boot()` implementation.

I would check if any of the `hook_init()` on your site initialize the theme. If one does, try changing the modules' weight or `hook_modules_implements_alter()` to ensure `spaces_init()` is invoked before. This should allow your `hook_custom_theme()` implementation to rely on `spaces_init()`.

---
Tags: 7, theming
---


title: Boost Module problem in logged in user

text:
# Question
Title: Boost Module problem in logged in user
I have a problem in Boost module I have a dynamic site that Allow user to logged in to edit his content

after log into the site the login links disappear and another links loaded that contain user links (I use a custom block that check if user\_is\_logged\_in echo `<a href="nide/3/edit">you content</a>` else echo `<a href="user">sign in</a>`)

but after installing boost the menu of login still appear after registration (still read the caching page)

is there any option that make pages to anonymous user only

This is my code

```
function login_block_info() {
    $blocks = array();
    $blocks['mylogin'] = array(
        'info' => t('Custom Login'),
    );
    return $blocks;
}
function login_block_view($block_name = '') {
    if ($block_name == 'mylogin')
    {
        $output ="";
        if(user_is_logged_in())
        {
            global $user;
            $query = "select nid from node where uid = " . $user->uid;
            $result =db_query($query);
            $nodes = array();
            $output ='<ul class="register-menu">';
            if(count($result)>0)
            {
                foreach ($result as $node) {
                    $alias = drupal_get_path_alias('node/'.$node->nid);
                    $output .= '<li>'.l($node->title,'node/'.$node->nid.'/edit').'</li>';
                }
            }
            $output .= '<li>'.l(t('Change password'),'user/'.$user->uid.'/edit').'</li>';
            $output .= '<li>'.l(t('log out'),'user/logout').'</li>';
            $output .= "</ul>";
        }
        else
        {
            $output .='<ul class="register-menu">
                         <li><a onclick="open_login()">log in</a></li>
                         <li><a onclick="open_register()">sign up</a></li>
                       </ul>';
            $output .= render(drupal_get_form('user_register_form'));
            $output .= '</div>';
        }
        return array(
            'subject' => t(''),
            'content' => $output,
        );
    }
}

```

thanks

# Answer
> **Boost**
> Boost provides **static** page caching for Drupal enabling a very significant performance and scalability boost for sites that receive mostly **anonymous traffic**.

I am not sure if Boost can be used for authenticated users as well. Boost will capture rendered HTML pages and store them and when a request comes for same page instead of overloading the server with PHP execution it will send the already compiled HTML pages which will **greatly** increase performance. Auth cache is an alternate that allows caching for both authenticated and anonymous.
> 1 votes

---
Tags: 7, performance, caching
---


# Question
Title: How to offset only a subselection of a set of nodes in a view
Sorry for the cryptic title, but could not find a better descriptive title. Suggestions welcome.

Situation: There is a newssite with on the frontpage two blocks:

1) a block of the latest 6 'promoted to frontpage' articles in form of an image caroussel
2) a block with the latest 12 newsheadlines, contains both 'promoted' as 'regular' articles

What should happen is:

* block one displays the latest 6 'promoted to frontpage' articles
* block 2 does not only contain older 'promoted to frontpage' articles, but also regular articles
* when an article shifts out of bock 1 it should shift towards block 2, assuming it is not older than the 12th article in this block
* there should be no overlap in articles between block 1 and 2, ie: the articles displayed in block 1 should not be displayed in block 2

Problem:

The problem is block 2. I can't figure out howto establish what I want without having an overlap between the two blocks.

The view of block 2 is pretty easy: select 12 nodes of the type 'article', order by date.

Question:

But how do I make sure that this selection takes out the first 6 promoted to frontpage articles? Offset 6 won't work, because then it might also skip regular articles. Only the promoted articles should be offsetted.

Is this feasible with some custom php code?

--- update ---

I think the most feasible solution would be either:

1) merge two views (one that selects the latest promoted articles with an offset of 6 and one that selects the latest regular articles together with some sort of union functionality and then limit it to 12
2) remove duplicates: so create a view that displays the latest 12 articles of any type, but which has been filtered in order to remove duplicates between the articles that are displayed in block 1

Haven't found a solution on either though...

# Answer
Build a single view with two displays. One for the first block, which will list the latest 6 promoted articles, and one for the second block which will list the latest 18 articles (promoted or not). Then in a custom module, implement `hook_views_pre_render()` to filter out the six first promoted articles from the second block and limit them to 12.

```
function MODULE_views_pre_render(&$view) {
  if ($view->name === 'VIEWNAME' && $view->current_display === 'block_2') {
    $count = 0;
    $promoted_count = 0;
    foreach ($view->result as $key => $value) {
      If ($promoted_count < 6 && $value->node_promoted) {
        $promoted_count++;
        unset($view->result[$key]);
      }
      else {
        if ($count < 12) {
          $count++;
        }
        else {
          unset($view->result[$key]);
        }
      }
    }
  }
}

```

Note: `$value->node_promoted` is dependent on the view display mode being *fields* and having the *Promoted* field. `node_promoted` may not be the correct property name.
> 0 votes

# Answer
Here is one approach.

Make a view that lists all articles, no filter on "promoted to front page"

Now sort first by "promoted to front page", descending (so promoted articles come first), then by post date (or what ever else you want)

Now limit it to 6 items.

Clone the view (or block display)

Change the limit setting so there is an offset of 6 (if you cloned the block display) make sure you save the new setting only for the new block (an override)
> 0 votes

---
Tags: views, nodes
---


# Question
Title: How to search the body of text by content type?
Is it possible to create a view where the user enters a text to query, and the view will only display results for certain content types?

# Answer
There is a search field called something like "Search: Search terms" which you can add as a filter criteria. Just expose it so the user can enter a search phrase.

Works only for indexed content, so make sure your index is at 100%.
> 1 votes

---
Tags: views, search
---