title: Form submit problem

text:
# Question
Title: Form submit problem
I have no idea why my form submit only work if I put on screen values of $form argument.

If I add:

```
echo '<pre>';
print_r($form);
echo '</pre>'

```

to my submit function I am getting new 'page' with this data printed out, but when I uncomment this nothing seems to work, I see form page again.

```
function gate_check_form_submit($form, &$form_state) {
    $post = $form['#post'];
//    echo '<pre>';
//    print_r($form);
//    echo '</pre>';
    echo '<pre>';
    print_r($post); //gives nothing
    echo '</pre>';

    $day = intval($post['gate_day']);
    $month = intval($post['gate_month']);
    $year = intval($post['gate_year']);
    $isRemember = isset($post['gate_remember_me']);
    if ($day && $month && $year) {
        $allowed_age = (int) variable_get('gate_minimal_age', 18);
        $min_born_time  = mktime(0, 0, 0, date("m"),   date("d"),   date("Y") - $allowed_age);
        $born_time = mktime(0, 0, 0, $month, $day, $year);
        echo '<pre>';
        print_r($min_born_time);
        echo '</pre>';
        echo '<pre>';
        print_r($born_time);
        echo '</pre>';
        if ($min_born_time >= $born_time) {
            echo 'yes';
           sess_write(GATE_SESSION_NAME, TRUE);
           if ($isRemember) {
               set_cookie(GATE_COOKIE_NAME, sha1($born_time + srand()), time()+60*60*24*7);
           }
           drupal_goto('/');

        }
        echo 'no';
    }
}

```

# Answer
> 5 votes
You are doing it wrong\*. You should read the Form API quickstart guide to understand how to use the validate and submit handlers properly.

* For several reasons, the biggest one being that you are using #post, which is a big no-no. You should use sanitized values from `$form_state['values']` instead.

---
Tags: 7, forms
---


title: Theme a specific block id

text:
# Question
Title: Theme a specific block id
I am looking for a simple and effective way to implement template for specific block IDs.

From what I read in Author information lost after saving node and Drupal 6 Template Suggestions, I came up with the following code, which doesn't seem to work:

```
function mytheme_preprocess_block(&$vars) {
  array_unshift($vars['template_files'], 'block-' . $vars['region'] . '-' .   filter_xss($vars['id']));
}

```

From the Drupal documentation it should block-module-delta.tpl.php.

* Delta is the block ID, that's ok
* Module? What's the module here it's a custom block created by adding a block.

# Answer
> 3 votes
Use Firebug to inspect the generated HTML to get the block name|module !

# Answer
> 0 votes
Have you checked out the skinr module? http://drupal.org/project/skinr

http://www.youtube.com/watch?v=NRsbVguQ7b4

You can add classes to particular blocks and reuse styles. This can be very helpful if you're using a grid system or any of the grid themes.

---
Tags: 6, blocks
---


title: hook_init() causes login problems

text:
# Question
Title: hook_init() causes login problems
I created a custom module which has the following `hook_init()` implementation.

```
function gate_init() {
  $curr_uri = check_plain(request_uri());
  if (strpos($curr_uri, 'admin') === FALSE) {
    if (strcmp($curr_uri, '/gate') != 0) {
      if (!sess_read(GATE_SESSION_NAME)) {
        if (!isset($_COOKIE[GATE_COOKIE_NAME])) {
          drupal_goto('gate');
        }
        else {
          sess_write(GATE_SESSION_NAME, TRUE);
        }
      }
    }
    else {
      if (sess_read(GATE_SESSION_NAME) || isset($_COOKIE[GATE_COOKIE_NAME])) {
        if (!sess_read(GATE_SESSION_NAME)) {
          sess_write(GATE_SESSION_NAME, TRUE);
        }
        drupal_goto('/');
      }
    }
  }
}

```

It's crazy, but this code causes login problems for authenticated users. I cannot login, I see no errors, I just cannot login if I provide correct username and password.

If I comment out these lines, I can login.

```
if (!sess_read(GATE_SESSION_NAME)) {
  if (!isset($_COOKIE[GATE_COOKIE_NAME])) {
    drupal_goto('gate');
  }
  else {
    sess_write(GATE_SESSION_NAME, TRUE);
  }
}

```

I check further and `if (!sess_read(GATE_SESSION_NAME))` is the part causing login problems. Could anybody give me an advice?

# Answer
sess\_read() should not be used in a module, as that function is passed to session\_set\_save\_handler() from \_drupal\_bootstrap(), which is the function that is called during Drupal bootstrap.
The purpose of the function is not to read values from the PHP session; if you need to do that, the you can just read the content from `$_SESSION[]`.
To notice that session\_start() is called from Drupal during its bootstrap; that means that after a full bootstrap (or any bootstrap that goes past the `DRUPAL_BOOTSTRAP_SESSION` phase) a session is initialized, and `$_SESSION[]` can be used.
> 2 votes

---
Tags: 7, hooks, users
---


# Question
Title: Storing variables in a theme outside preprocessing
I have some variables that I want to store in my theme, but I cannot always use `theme_preprocess()` to set and subsequently gain access to them.

What is the best way to do this?

I would like to **not** use a module, but with my experience in the past, a module has a `hook_install()` where an can use `variable_set()`; Is there anything similar for a theme?

# Answer
I'm not sure if that's exactly what you're looking for, but Drupal has the concept of theme settings, which allow to configure a given theme with variables.

See http://www.metaltoad.com/blog/how-add-theme-settings-drupal-7 for a great introduction to them.

And according to theme\_get\_setting(), you can for example store defaults in your theme's .info file, something like

```
settings[your_setting] = the_value

```

Should work.
> 3 votes

---
Tags: 7, theming
---


title: Using third-party functions

text:
# Question
Title: Using third-party functions
I have a third-party PHP script that I want to integrate and use in my site. The script is quite small and comes with its own functions and array indexes. How would I be able to call the functions and have them displayed in Views or CCK nodes?

# Answer
If this is you own script, you could simply convert it into a module. That is easy, just create a module (tons of guides to be found in the internet) and put your functions in the .module file, then they will be available to all other code running on the site.

If this is a script/library provides by someone else, you could either place it in a custom module folder and include it with module\_load\_include() or (better!) declare it as a library with the help of the Libraries module. You will however need to create a custom module with some code to connect the functions of your script with drupal (Usually implementing the correct hooks and calling your functions from that) for both methods.

See also How do I go about putting standalone PHP files into Drupal 6? and How do I load a library defined with hook\_library() on node/edit pages?.
> 3 votes

# Answer
The usual way is to create a custom module that include the PHP file when required.
If the custom module integrates with Views or CCK, it is not different; it can call module\_load\_include() to load the file.
> 0 votes

---
Tags: 7, views, entities
---


# Question
Title: Does Apache Solr assign a weight to HTML tags?
Would Solr consider HTML tags when it creates its indexes? Would `<h1>`, for example, be more important than `<h2>`, `<p>`?

# Answer
> 2 votes
If you are using the Apachesolr module, then yes. The module has some sensible weighting defaults for the tags, but they can be further customized at `admin/settings/apachesolr/query-fields`.

---
Tags: 7, search
---


# Question
Title: "Page Not Found" error when a google search form is submitted
I am using Google Site Search on a web site, and the search form submits to a page containing the appropriate code. I can access this page directly just fine, but whenever I test out the search form, I get a "page not found" error.

I believe this is because both Drupal and Google search use the parameter 'q', has anyone run into this problem and found a workaround?

# Answer
Instead of using *q*, you can use as\_q. The description given from the page I linked is the following:

> The as\_q parameter provides search terms to check for in a document. This parameter is also commonly used to allow users to specify additional terms to search for within a set of search results.
> 1 votes

---
Tags: 7, search
---


# Question
Title: Bulk update got slower after conversion of database tables to InnoDB
After I converted the database tables to InnoDB engine from MyISAM, I noticed some operations became very slow, especially on updating multiple nodes in bulk for administrative work. Front end performance seems to be good.

I have tried configuration settings suggested in these articles without any luck: MySQL \> YourSQL, and MySQL Performance Blog.

My test script would load 25 different nodes (`node_load()`) and save them right away (`node_save()`) in a loop. This script runs for 2 seconds on the server with MyISAM engine; after DB conversion to InnoDB, it now takes 13 seconds.

It also takes much longer to restore InnoDB database from a SQL dump of 500MB; 20 minutes (InnoDB) vs. 2 minutes (MyISAM).

Is this what I should expect from InnoDB engine?

New to InnoDB engine, I'd like to know what I might still be missing in configuring and optimizing InnoDB.

# Answer
Thanks for the nice tips. I tried most of the suggested InnoDB tuning tips and it was not enough to remedy my problem.

Here is how I was able to fix my issue. This may be a special case that is isolated to my situation, but I hope that this could help other developers who are in a similar situation.

When I ran node\_save() in a loop with 25 different nodes, it took 2 seconds with MyISAM and 13 seconds with InnoDB.

I captured 80 some database queries generated by node\_save() in a single loop. Some of them came from running node\_load(), which is needed before node\_save(). I used devel module's feature of database query info collection. I put the queries side by side. The same queries from InnoDB were slightly faster than MyISAM especially for simple SELECT queries, which took majority portion of all queries.

I identified an INSERT query from InnoDB side that took more than a 0.5 second when total 80 queries took 0.6 second. The query was from notifications module, whose hook implementation was fired every time a node was saved.

**I narrowed it down to the table notifications\_fields in the query and decided to create an index on the table for the column `value`. And that made all the difference.** After creating an index on `value`, saving 25 nodes now took only 0.2 seconds (down from 13 seconds), even ten times faster than MyISAM's! (BTW, creating index on MyISAM table also made it run ten times faster than before)

In this case, I have to admit that InnoDB's under performance gave clue to find out that an index was needed. I would not have found out about the index with MyISAM because it was relatively fast enough to hide the situation.

There have been several cases like this that adding indexes improved site performance quite a lot. However, actual application and result from it can differ in different sites. Back to my case with notifications\_fields table, adding another index on `field` column -- hoping to strech performance boost -- ruined the effect and actually made it slow again. So one needs to be careful with adding indexes and understand that one fix on a site may not work the same way on another site.
> 9 votes

# Answer
Especially DDL (creation of tables etc.) statements are slower in InnoDB. That's just the way it is.

Another difference is that InnoDB uses transactions and MyISAM doesn't. So by default, if auto-commit is set to on, it will do an explicit commit after each update/insert/delete query.

The easiest way to speed that up is to explicitly start a transaction before your bulk updates and then commit it at the end.

Unfortunately, the D6 database API does not have a way to do that in a database agnostic way, so you will have to rely on the actual SQL comments which are for MySQL:

```
db_query('START TRANSACTION');

```

and

```
db_query('COMMIT');

```

See http://dev.mysql.com/doc/refman/5.0/en/commit.html for more details.

That should already greatly speed up these updates.
> 7 votes

---
Tags: database
---


# Question
Title: Pathauto taxonomy terms in content paths
I'm using pathauto and want to set it up so that when a new page is created (which has the taxonomy field) it will add the taxonomy terms into the url. For example, if I have the following vocabulary:

* Page Categories
    + About
    + Articles

When I create a page called 'My Page', and select 'About' as the taxonomical term, I would like the url to be http://example.com/about/my-page.

I've messed around with the URL Aliases settings page but 'Taxonomy term paths' does not apply to Basic pages.

I've looked everywhere for this and I'm going crazy.

# Answer
You are looking under the wrong section. You want to look at 'node paths' in the path auto settings. Under that section you need to put '/\[term-raw\]/\[title-raw\]' for content of type 'Page'.

Install token module as well
> 1 votes

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


title: Link to a large image

text:
# Question
Title: Link to a large image
In D7 Commerce module, I've created a product\_display content type. With this content type, it is possible to create nodes from product entities that come from my store.
In these nodes, the images are shown but I can't figure out how to link them to a large image when hovered or clicked on.

I guess this has to be done through a basic D7 configuration.

# Answer
> 0 votes
Assuming these are normal image fields, you can go to Structure \> Content types, then select manage display for your product node type.

There, click on the settings button on the right side of your image field. A settings form should be expanded now, where you can configure in which image style you want them to show up and to what they should link. If you choose link to file, clicking on it will link directly to the original file (only).

An alternative is provided by the Colorbox module, which allows to display the images in a popup-like overlay. The same settings form should have more options to choose from once you installed that module.

---
Tags: nodes, commerce
---


# Question
Title: Syntax error: <!DOCTYPE html> (line 1) in Firebug
Firebug is complaining about a error in `<!DOCTYPE html>`, but the HTML source is passing without problems the HTML W3C validator.

Do you have any idea? Sorry, I can't share the source code.

# Answer
The reason was a failed loaded javascript file.
I use the following code to add a JavaScript file:

```
drupal_add_js($p . '/slider.js','module','footer');

```

So the following HTML was added in the footer of the page:

```
<script type="text/javascript" src="/sites/default/modules/custom/slider/slider.js?G"></script>

```

At some point I **renamed the file slider.js**, so it stopped being loaded, and this is the reason behind the Firebug error.

In the "Net" tab, Firebug was not showing any error; it was showing just a "301 Moved Permanently" next to the slider.js file.
> 4 votes

# Answer
Maybe this is your Problem, too: http://blog.rki-home.de/2008/10/22/firebug-syntax-error-und-doctype/ It's german so here what it says in short:

* Do you have a script tag with empty src?
* Do you link a html-file with script src anywhere?
* Do you use some mod\_rewrite rules wich could result in returning html instead of the real js-source?

When FireBug states an error, i would think it's always an JS-Error. So FB tries to parse html as js.
> 3 votes

---
Tags: 7
---


title: Cron jobs in Drupal 7

text:
# Question
Title: Cron jobs in Drupal 7
I have a PHP file that does some task in consistent intervals.

I have placed that PHP file inside a custom module folder, but I found that Drupal functions like `drupal_set_message()` are not available inside the PHP file.

How do I include Drupal functions inside this PHP file? How do I set up this php file to be run as a cron job?

# Answer
> 12 votes
You need to implement hook\_cron() in your module and execute these tasks there.

Then, drupal will automatically execute these tasks during the default cron handling.

You probably have used `drupal_set_message()` only as an example but note that using that function in a hook\_cron() implementation makes no sense because there is no user to read these messages. As an alternative, you could log messages with watchdog().

# Answer
> 3 votes
What reported by Berdir is correct; implementations of `hook_cron()` are invoked during Cron jobs, if you have set the cron task correctly. This means that you need to add a cron job that executes one of the following commands:

```
/usr/bin/lynx -source http://example.com/cron.php > /dev/null 2>&1

```

```
curl --silent --compressed http://example.com/cron.php

```

As far as I remember, you also need to use the cron key that is reported in Drupal administrative pages.

If, for any reason (I doubt there is any reason for you to do so) you need just to execute that PHP script, and not all the Drupal cron tasks, which means that you have actually set two cron jobs and one is already executing the Drupal cron tasks, then you should add the following lines at the beginning of the PHP file you are trying to execute cron task:

```
define('DRUPAL_ROOT', 'Set here the directory where Drupal is installed');
require_once DRUPAL_ROOT . '/includes/bootstrap.inc';

```

Doing so, the PHP file will have access to all the functions available in bootstrap.inc. If you need a function that is available in another Drupal include file, then you need to include that file with `require_once()`; if you need a function that is available from a Drupal module, then you need to add `drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL)` after the `require_once()` lines.
If you need a function from a module, then you should really implement a custom module (if you don't have already one) that implements `hook_cron()` and that includes the PHP file you have to execute it.

As reported by Berdir, a Drupal cron task should not call `drupal_set_message()` because when cron tasks are executed, those messages would not be visible. If you need to report an error message that administrator users could see, then the code needs to call watchdog(), which needs Drupal to be full bootstrapped; the function is defined in bootstrap.inc.

---
Tags: 7, cron
---


# Question
Title: Is it possible to use %user_uid_optional as a view path?
I am using %user\_uid\_optional in the path of a view, but it doesn't seem to be working because the tab is not showing. It looks like that the user\_uid\_optional\_to\_arg function is not being called. Do you have any idea?

# Answer
When declaring a views path, you can only use '%'. This is because Menu API can't handle two loader functions in the same path, and Views already has its own (that loads the view itself).
> 1 votes

---
Tags: 7, views
---


title: FileField Database

text:
# Question
Title: FileField Database
I like the idea of using a field within a database to hold a file.

Is it possible to store files within a database instead of within folders with Drupal 7?

My current setup is Drupal 7, Ubuntu Server 10.10/11.04, MySql, Apache2. I could switch to IIS if need be (I like Ubuntu for test server since it's lightweight and more flexible, but work is mainly windows servers... so I could go either way)

# Answer
> 0 votes
There is the dbfm module, but it is still only for Drupal 6.

You could try to update or improve it.

---
Tags: 7, database, files
---


# Question
Title: CCK Node Reference options not showing "this post can't be referenced."
I have a CCK field of node reference. As user 1 I can set the node ference field to a node. I will see something like *Node Title\[nid:123\]*. When I go in as another user I see *\[nid:123\]*. When I go to save the node I get the message:

> Field: this post can't be referenced.

I can't work out why I am getting this. Any ideas?

# Answer
> 0 votes
Apart from restrictions placed directly on the field configuration (see Andy's answer), nodereference also checks if a user can access referenced (or to be referenced) nodes and only allows to reference those that the user is allowed to view according to the content access rules.

Make sure your content access modules, if you're using any, allow access to those nodes for that user.

# Answer
> 0 votes
Nodereference checks that the node is valid before allowing it to save. This check is either a 'standard' check that sees if the node is of the appropriate content type (if you configured the nodereference under the *Content types that can be referenced* checkboxes); or if you're using Views it can be a 'views' check (if you configured the nodereference under *Advanced - Nodes that can be referenced (View)*) that sees if the specified node is in the output of the view.

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


# Question
Title: Form API select list remove blank entry (default select an entry)
I populate an select list using the following code.

```
$getCompanies = 'SELECT nid, title FROM node where type = "my_type"';
        $companiesResult = db_query($getCompanies);
        $companyArray = array();
        $companyArray['empty'] = "";
        while ($data = db_fetch_object($companiesResult)) {
            $companyArray[$data->nid] = $data->title;
        }
        $form['company'] = array(
            '#title' => t('Type'),
            '#type' => 'select',
            '#description' => t(''),
            '#options' => $companyArray,
        );
    }

```

This gives me an empty result first. I want to remove this empty result. I tried adding #required by it does not add a default selection. What can I do to remove an empty element?

# Answer
> 2 votes
The blank option was added by yourself:

```
$companyArray['empty'] = "";

```

If you remove that line you wont have a blank line, or alternatively your could change it to

```
$companyArray['empty'] = t("Please select");

```

To make the phrase *Please select* appear as default in the select option.

# Answer
> 0 votes
Try adding the property: `'#required' => TRUE` into `$form['company']`.

---
Tags: 7, forms
---


# Question
Title: Moving data from a Drupal 6 site to a new Drupal 7 site
This is not an drupal 6 to 7 upgrade question, at least not in the way it's conventionally asked or done. I have an ill pressflow 6.17 site with loads of not necessary modules, configurations, etc, which I need to convert to Drupal 7 (Pressflow 7 doesn't seem to be round the corner as work on Drupal 8 has just started) so this will be a new site with its own set of modules and configurations but with the same data as the old site. I don't want anything from the Pressflow site to creep into the Drupal 7 site except for content; I don't want the views, imagecache presets, etc. I am looking to get advice on just moving the data (content) from Pressflow to Drupal 7 site; therefore, the usual upgrade process will not work for me.

I have used the migrate module before for an ASP to Drupal migration and it works great, but it's also kind of messy with source tables residing in the same database, and since task at hand is to move data from one Drupal version to another I am hoping for a much simpler/quicker technique.

What would be the best/quickest way to move content and only content (including ratings, comments) from Drupal/Pressflow 6 to Drupal 7 site (except migrate and table wizard, not that they don't fit the bill).

**\[UPDATE\]** \- I am currently investigating nate's approach when he migrated his site from drupal 5 to 7. It might work for me; I will update.

# Answer
> 2 votes
I think the approach you are looking at is good. You may need to reconsider your requirements slightly.

* Move content but not upgrade.
* Move some content which is provided by modules (which need to be upgraded).
* Move content which is provided by modules but not the modules themselves.
* Not use Migrate or table wizard.
* Do so in the best way.
* Do so in the quickest way.

I think many of these requirements are mutually exclusive.

The best approach I can see, is to clone your existing site. Turn off everything you don't want in the D7 site. Then consider your upgrade options.

A Drupal install is a complex interaction of code configuration and content. it is difficult to completely consider one without the others.

*update*

You could look at migrate Drupal 2 Drupal for migrating your content.

# Answer
> 0 votes
I have had a lot of success with the Migrate module. The Economist.com used migrate to go from their custom CMS to Drupal 6 Economist.com data migration using migrate. You setup classes inside of migrate to make lookup so when the data comes over, it does not loose any of its relationship (or makes new relationships based on Drupal architecture). Just my two cents to see if it helps you along.

# Answer
> 0 votes
I finally went with customizing nate's custom import modules and it works great except for couple of issues I am facing with a different module. I hope I will resolve it and as expected that solution was quicker and had less clutter as my migration needs were simple. Hopefully I can post back a more general version of that module removing my business logic out of it as it could be really useful in some cases.

---
Tags: migrations
---


# Question
Title: How do I set the Views Plugin handler path different from the theme path?
The file path of the module is set up like this:

```
addressfield/views/addressfield.views.inc
addressfield/views/addressfield_plugin_row_jmappingfields.inc
addressfield/views/addressfield_plugin_style_jmapping.inc
addressfield/theme/addressfield-jmapping-view.tpl.php
addressfield/theme/addressfield-view-jmappingfields.tpl.php

```

The problem is I can not figure out how to set the path in the plugin definition for the View. If I set the 'theme path' key to drupal\_get\_path('module', 'addressfield'). '/views' the handlers will register but the themes can not be found and vis versa.

```
/**
 * @file
 *  Provide the Addressfield plugin definition.
 */

function addressfield_views_plugins() {
  $path = drupal_get_path('module', 'addressfield') . '/views';
  return array(
    'module' => 'addressfield',
    'style' => array(
      'jmapping' => array(
        'title' => t('jMapping'),
        'help' => t('Display a view jMapping map.'),
        'handler' => 'addressfield_plugin_style_jmapping',
        'theme' => 'addressfield_jmapping_view',
        'theme path' => $path,
        'uses row plugin' => TRUE,
        'uses options' => TRUE,
        'uses grouping' => TRUE,
        'type' => 'normal',
        'parent' => 'default',
      ),
    ),
    'row' => array(
      'jmappingfields' => array(
        'title' => t('jMapping Fields'),
        'help' => t('Choose the fields to display in the jMapping Map.'),
        'handler' => 'addressfield_plugin_row_jmappingfields',
        'theme' => 'addressfield_view_jmappingfields',
        'theme path' => $path,
        'uses fields' => TRUE,
        'uses options' => TRUE,
        'type' => 'normal',
      ),
    ),
  );
}

```

How do I keep the theme templates for the style plugin and the handlers in separate folders for clarity?

I'm using Views 3 in Drupal 7.

# Answer
You should create an addressfield/theme/theme.inc that contains the `template_preprocess_addressfield_*` functions. Then add: `$theme_path = drupal_get_path('module', 'addressfield') . '/theme';` at the top.

```
'handler' => 'addressfield_plugin_style_jmapping',
'path' => $path,
'theme' => 'addressfield_jmapping_view',
'theme path' => $theme_path,
'theme file' => 'theme.inc',

```

That should work just fine.
> 1 votes

---
Tags: 7, views
---


title: Entity API and Contrib Modules

text:
# Question
Title: Entity API and Contrib Modules
When using the Entity API, is it fairly simple to interact with Taxonomy, Path/Pathauto, XML Sitemap, and Views? If so, what parts of the API should I be looking at?

# Answer
> 3 votes
Your question is a little confusing because Entity API is actually a separate contributed module that works *with* the core entity/fields api's

I've been working with the core `EntityFieldQuery` class and have been using it to query nodes (and other entities), their fields and properties with great success. You can checkout another question that's building some examples at: What's the proper use of EntityFieldQuery?

Overally, I found the Entity API was very handy for creating my own entities but didn't find the documentation all that great for doing queries on my site's content.

note, that node/user are now entities & node types/etc are now considered "bundles".

Further Reading:

# Answer
> 7 votes
In response to the original question and to electblake's answer, I would second the fact that the Entity API contributed module is separate and distinct from the core entity system. It is meant to augment the core system by providing a more robust entity controller (the piece of code used to create, load, save, and delete entities), provide some automatic token generation, and allow modules to define metadata for their entities' properties.

electblake mentioned that the core entity system includes a class for querying entities in the database based on their property and field data called EntityFieldQuery. This is in fact the recommended way for making entity queries. The Entity API isn't actually meant to be a querying tool. However, it provides in my opinion the other missing piece for building robust contributed modules using entities and fields - the entity metadata wrapper.

As I mentioned, the Entity API module provides a hook that lets you define metadata for your entity's properties (i.e. $node-\>uid, $node-\>created). It combines this information with what it knows about field definitions and instances. It then lets you "wrap" an entity to make it easier to access and manipulate field data and (what I'll call) referenced entity data through the wrapper object. One of the main things this has made easier for me is not having to worry about the language of entities when I'm trying to access their field data. Without the wrapper, you need to know the schema array of the data you're trying to access or manipulate. Using it, you can simply access field data like any other property.

Additionally, it makes it easy to access the data of referenced entities. In Drupal Commerce, I make extensive use of this functionality since a couple of our entities serve primarily as containers of references to other entities. An example approaching the usefulness you mention in your original post would be to have quick access to all the taxonomy terms referenced by a node. A simple way to do this with the wrapper would be to wrap the node and then loop over your taxonomy reference field's data to access the fully loaded term data. It's hard to demonstrate this without including extensive code snippets, but you can easily see how I put this to work by grepping the Drupal Commerce source for entity\_metadata\_wrapper.

The jury's still out on how useful or widespread the Entity API will be, but as it's a dependency of Rules 2, I doubt it's going anywhere soon. This may be a little too much information based on your response to electblake, but my hunch is the information should be useful for additional people who find this question when searching for more information on the Entity API. : )

# Answer
> 4 votes
I've been using the Entity API to create some new entities and bundles. Here's what I can report so far:

Using views: Pretty easy and straightforward, once you expose the module to views, describe the tables, etc. See: hook\_views\_data and the Advanced Help info about Views

Using taxonomy: (Sad trombone). The taxonomy tables store data by nid. That is, no way that I see to tell taxonomy to look in your entity's table. I've had to work around by creating my own version of the taxonomy\_index table and glom onto taxonomy as best I can.

No experience with the other modules you mention, but I'm guessing the same principle will apply: if the module assumes nodes and nid, it won't work well with your entity. Otherwise, I'd guess you can get things integrated.

HTH

# Answer
> 0 votes
The easiest and most consistent way to handle entities is by using the Entity API module:

> This module extends the entity API of Drupal core in order to provide a unified way to deal with entities and their properties. Additionally, it provides an entity CRUD controller, which helps simplifying the creation of new entity types.

---
Tags: 7, entities
---


title: Get content based on taxonomy

text:
# Question
Title: Get content based on taxonomy
I can't figure out what I am doing wrong, as my block isn't showing up with the content from the taxonomy.
I am trying to create a block that shows the content based on the taxonomy; I made a path on the taxonomy, and the main content shows up, but when I try to add a block using Views, it never shows.

This is the settings page for the taxonomy.

This is the view I am using with the argument.

**Edit**: I fixed the issue; all I had to do was create a new content and it worked. I guess my only question now is how to keep the block on the front page after adding the filter.

# Answer
> 2 votes
the way I did was i used global:null as the contexual filter and then selected provide default value and then went to type: taxonomy term ID from URL and added it in and then added content: has taxonomy term ID and gave it the same settings as the global:null and saved the view, now the reason why i didnt see it is because you have to add new content, for some reason it doesnt pick up the current content with taxonomies

---
Tags: 7, taxonomy-terms, views, blocks
---


title: Drupal Advanced Analytics

text:
# Question
Title: Drupal Advanced Analytics
I need to do some advanced analytics for my site. I need the basics Google Analytics stats (nb visits, bouncing rate, etc) and how many times each particular users came back in a specific period of time.

For example, I need to answer these specific questions:

* How many users came back more that 2 times during the last week?
* How many users added two nodes or more in the last month?
* Graphs showing users repartition between fans, average users, first time users, etc

Is there any module implementing that kind of funneling in Drupal? Ideally, it should interface with Google Analytics (with Google Analytics events tracker) and/or Mixpanel.

Any thoughts or ideas?

# Answer
> 0 votes
You might be able to use custom variables within Google Analytics. That way you can get all your sexy graphs in one easy place.

You would have to use existing tokens or create some new ones and attach them to your users report to Google.

You can then install : https://chrome.google.com/webstore/detail/jnkmfdileelhofjcijamephohjechhna?hl=en

This shows you what variables are being tracked. For example I track my users on what content type they are viewing, what taxonomy, tags, roles etc.

What you are asking for is very specific, so I think you would end up creating custom tokens.

As an example you could show all first time users by attaching the token \[user-created-date\] then filter in GA to only show today's date for that custom variable.

# Answer
> 0 votes
have you tried taking a look at Google Analytics Counter?

It integrates with Google Analytics & its API

---
Tags: 7
---


# Question
Title: Which is the function that initializes the content of the "$scripts" variable used in html.tlp.php?
The template file html.tpl.php has access to the `$scripts` variable, which is not initialized in template\_preprocess\_html(). I have also looked at template\_preprocess(), and template\_process(), but neither of those functions initialize `$scripts`.

# Answer
> 2 votes
The `$scripts` variable is initialized in `template_process_html()`, which uses the following code.

```
$variables['css'] = drupal_add_css();
$variables['styles'] = drupal_get_css();
$variables['scripts'] = drupal_get_js();

```

---
Tags: 7, theming
---


title: Node Template Panel Node

text:
# Question
Title: Node Template Panel Node
I am using a node template to layout a node and I want to reference content from other nodes. Obviously I have the current node fields available to me, but I want to select any of the sites nodes.

I understand I can create view blocks and include these in the template but looking at the node tab in the panel content, there is an option to set the node, the only option being 'node being viewed'. This kind of suggests there may be a way of references any node.

# Answer
It depends on the type of reference. You can load any node-content with node\_load(). The question is simply if you know when to load which nodes. This reference could via Taxonomy or Contentype or User or anything else.
> 1 votes

---
Tags: panels
---


title: How can I create a single login page?

text:
# Question
Title: How can I create a single login page?
I do not want to display a login block or link on every page. I would instead like to create a single login page accessible from http://example.com/login. How can I do that?

# Answer
> 3 votes
/user/login exists by default; you could use that.

---
Tags: 7, users
---


# Question
Title: Form, populate select lists values after unsuccessfull validation
I would like to have select values in my select lists that user poster to script. However when validation is not valid, those fields aren't populated with posted data, so user have to make the choice again. Could somebody give me any advice?

Code:

```
   for($i = 0; $i < 3; $i++) {
            $form['register']['cocktails']['cocktail']['bartender_cocktail['.$i.'][]'] = array(
                '#type' => 'select',
                '#default_value' => variable_get('bartender_cocktail['.$i.'][]', NULL),
                '#options' => $cocktails,
            );
        }

```

# Answer
> 0 votes
Your use of \[\] in the select name most likely confused the form API.

Try something like this instead:

```
for($i = 0; $i < 3; $i++) {
  $form['register']['cocktails']['cocktail']['bartender_cocktail'][$i] = array(
    '#type' => 'select',
    '#default_value' => variable_get('bartender_cocktail_' . $i, NULL),
    '#options' => $cocktails,
  );
}

```

Then, you need to set #tree to TRUE, so that you your cocktails into an array.

```
$form['register']['cocktails']['cocktail']['bartender_cocktail']['#tree'] = TRUE;

```

Then, you should be able to access the vaules like this: `$form_state['values']['bartender_cocktail']`.

---
Tags: 7, forms
---


title: Limit the creation of tags

text:
# Question
Title: Limit the creation of tags
I wish to create a taxonomy where the administrator users limit which terms can be tagged.

Suppose I have a vocabulary containing the following terms:

* Football
* Golf
* Snooker

I want the tag autocomplete to show the tags that can be used. If I typed "Foo", the autocomplete should show "Football"; if I typed "Basketball," the autocomplete would not show anything, the node would submit, but no term is created.

Is this possible?

# Answer
> 1 votes
It looks like the Content Taxonomy modules provides the ability to do this.

Without this, you'd have to implement hook\_nodeapi('presave') and remove terms that don't exist yet.

Not even Drupal 7 seems to allow this without a contrib module, even though it does have specific edit terms permission for each vocabulary. Strange.

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


title: Creating threaded nodes

text:
# Question
Title: Creating threaded nodes
I know with Drupal you can have threaded comments. I wish to create something similar using nodes.

Where a node can be replied to with a node of the same type. I would then like to try and create a view of this. Do you think this is possible or should I look at bending comments to be more like nodes.

# Answer
Sounds like Node comments to me. With it you can use normal Contentypes as comments. There is already a view included in the module.
> 0 votes

---
Tags: 7, nodes
---


# Question
Title: Force Drupal to attach Drupal behavior to new ajaxed content [only Drupal.attachBehaviors() is not working the right way]
I was doing lot of posts on drupal.org about this topic, but unfortunately in the wrong context.

I think that is not the problem, so i try it with a different approach, and maybe this could be the solution. Loading the whole PHP Page and extract a certain div with ajax didn't works the right way. So i thought, that i could let drupal load just the content and inject it with ajax into the div. I made a query with the hook\_preprocess\_page and hook\_preprocess\_node that is looking for a "ajax=1" in the requested URL and then only gives out the content without the whole page. And now with help of certain tpl.php files, in theory, i could limit the output of drupal to only $content. And here is the problem. My approach is working even when i leave the tpl.php files the original way, but removing the "$content" from node-ajax.tpl.php. With "working the right way", i mean that drupal doesn't reload the whole page, but off course not the content. But i can not explain that to myself, cause in the $content variable, so i thought, is only the html of the generated content. So my question is, how can i limit the output of drupal, to just the content, or am i doing the wrong steps to get this working. Here is the module and js file i'm using: my\_ajax.module:

```
<?php

function my_ajax_init()
{
    drupal_add_js(drupal_get_path('module', 'my_ajax') . '/my_ajax.js');
}

function my_ajax_preprocess_page(&$vars, $hook)
{

    if (isset($_GET['ajax']) && $_GET['ajax'] == 1)
    {
        $vars['template_file'] = 'page-ajax';
    }
}

function my_ajax_preprocess_node(&$vars, $hook)
{

    if (isset($_GET['ajax']) && $_GET['ajax'] == 1)
    {
        $vars['template_file'] = 'node-ajax';
    }
}

```

my\_ajax.js:

```
Drupal.behaviors.my_ajax = function (context) {
    $('#content-group-inner .node a').live('click', function (e) {
        var url = $(this).attr('href');
        //$('#content-region-inner').slideUp('slow');
        $('#content-region-inner').empty().html('<img src="ajax-loader.gif" style="margin-left:50%;"/>');
        xhr = $.ajax({
            data: 'ajax=1',
            type: 'GET',
            url: url,
            success: function (data) {
                $('#content-region-inner').html(data);
                Drupal.attachBehaviors(context);
            }
        });
        return false;
    });
};

```

Please help me with this. Every suggestion is appreciated.

# Answer
I've got it. This is working the right way:

```
Drupal.behaviors.my_ajax = function (context) {
    $('#content-group-inner a').live('click', function (e) {

        $('#content-group-inner a').addClass('my_ajax-processed');
        var url = $(this).attr('href');
        $('#content-region-inner').empty().html('<img src="ajax-loader.gif" style="margin-left:50%;"/>');
        $('#content-region-inner').load(url,'ajax=1',function() {
                        Drupal.attachBehaviors('#content-region-inner');
                        });
        return false;
        });
   };

```

Thank you for all your help.
> 12 votes

# Answer
I think your issues is that your success function won't have the variable context in scope so attach behaviors will be working on undefined.

I would guess that you could do

```
Drupal.attachBehaviors($('#content-region-inner'));

```
> 11 votes

---
Tags: 7, ajax, javascript
---


title: Simple REST request to create nodes

text:
# Question
Title: Simple REST request to create nodes
I'm having the following issue trying to create nodes from Drupal 7 to a Drupal 6 install. The target Drupal site is running Services 3.x.

Here's my code:

```
$base_url = $params['path'];
$data = array(
  'username' => $params['username'],
  'password' => $params['password'],
);
$data = http_build_query($data, '', '&');
$headers = array();
$options = array(
  'headers' => array('Accept' => 'application/json'),
  'method' => 'POST',
  'data' => $data
);

$response = drupal_http_request($params['path'] . '/user/login', $options);
$data = json_decode($response->data);

// Check if login was successful
if ($response->code == 200) {
  // Now recycle the login cookie we recieved in the first request
  $options['headers']['Cookie'] = $data->session_name . '=' . $data->sessid;

  // Create a new node
  $data = array(
    'node' => array (
      'type' => 'cloudnode',
      'title' => 'node1',
      'field_ip_address' => array ('value' => '1.2.3.4'),
    )
  );
  $options['data'] = http_build_query( $data, '', '&');
  $options['method'] = 'POST';
  $response = drupal_http_request($base_url . '/node', $options);
}
else {
  die ('Failed to login');
}

```

I get a 200 response; the node is being created, but somehow it doesn't take care of my 'field\_ip\_address' CCK field at all.

I've tried any kind of variations but they don't work. There is not much documentation around as well.

If anyone has succeeded in creating nodes using REST, I would be very interested for any help.

# Answer
CCK fields are always stored as an array of fields, even if the actual field is limited to only a single value.

So you it should be something like:

`'field_ip_address' => array(array('value' => '1.2.3.4'))`

Note that in Drupal 7, field values are additionally grouped by the language, which is 'und' (LANGUAGE\_NONE) if the field is language-agnostic. So it would be something like this:

`'field_ip_address' => array('und' => array(array('value' => '1.2.3.4')))`

Copied from my comment, so that the question can be marked as fixed :)
> 5 votes

---
Tags: services, 8
---


title: (Un-) formatting each form element

text:
# Question
Title: (Un-) formatting each form element
When we declare something like

```
$form['textfield'] = array(
  '#type' => 'textfield',
  '#title' => 'textfield title',
  '#maxlength' => 8,
  '#required' => true,
);

```

The output will be something like:

```
<div id="edit-textfield-wrapper" class="form-item">
  <label for="edit-textfield">textfield title: <span title="This field is required." class="form-required">*</span></label>
  <input type="text" class="form-text required" value="" size="60" id="edit-textfield" name="textfield" maxlength="8">
</div>

```

However, I am willing to remove the container `div` and `label` from some of my fields, something like this:

```
<input type="text" class="form-text required" value="" size="60" id="edit-textfield" name="textfield" maxlength="8">

```

Is it possible? Are there any examples somewhere?

# Answer
> 4 votes
You just need to implement hook\_theme\_registry\_alter() to change the theme function that is called when `theme('form_element')` is invoked; normally the invoked theme function is theme\_form\_element().

```
function theme_form_element($element, $value) {
  // This is also used in the installer, pre-database setup.
  $t = get_t();

  $output = '<div class="form-item"';
  if (!empty($element['#id'])) {
    $output .= ' id="' . $element['#id'] . '-wrapper"';
  }
  $output .= ">\n";
  $required = !empty($element['#required']) ? '<span class="form-required" title="' . $t('This field is required.') . '">*</span>' : '';

  if (!empty($element['#title'])) {
    $title = $element['#title'];
    if (!empty($element['#id'])) {
      $output .= ' <label for="' . $element['#id'] . '">' . $t('!title: !required', array('!title' => filter_xss_admin($title), '!required' => $required)) . "</label>\n";
    }
    else {
      $output .= ' <label>' . $t('!title: !required', array('!title' => filter_xss_admin($title), '!required' => $required)) . "</label>\n";
    }
  }

  $output .= " $value\n";

  if (!empty($element['#description'])) {
    $output .= ' <div class="description">' . $element['#description'] . "</div>\n";
  }

  $output .= "</div>\n";

  return $output;
}

```

```
function mymodule_theme_registry_alter(&$theme_registry) {
  if (isset($theme_registry['form_element']) {
    $theme_registry['form_element']['function'] = "theme_mymodule_form_element";
  }
}

```

Using the code of `theme_form_element()`, you can write your own theme function, and remove the HTML tags you don't want. Take in mind that `theme('form_element')` is invoked for every form element output with the form API; if you want to change the HTML output of just a form element, then you need to check the #type value.
theme\_textfield() is the theme function that themes a text field, but it doesn't output the label, or the wrapping `<div>`, which is already output by `theme_form_element()`.

Alternatively, this can be done in a theme that overrides `theme_form_element()`.
Which approach you should use depends on if you need to alter the output in a specific theme, or for all the themes enabled in your Drupal site; in the latter case, you need to implement the hooks I reported in a module.

# Answer
> 0 votes
As far as I know, it is not possible to remove the `<div>` wrapper, if you don't modify the theme.

---
Tags: theming, forms
---


# Question
Title: Download a File Outside of Web Directory
I have a scenario where certain files are stored outside of the Document Root directory, like this...

```
/home/user/public_html/{drupal files are in here}
/home/user/data/{special data files are in here}

```

I would like to allow users with special permissions to download files from /home/user/data using Drupal's built-in file wrapper, but I'm not sure how to link to the files.

**Addendum**: Most of my files are stored in the usual location:

```
/home/user/public_html/sites/default/files

```

It is only some of them I need to store in the external data folder. For security reasons I do not want to change the sites/default/files/ directory to /home/user/data.

# Answer
> 3 votes
Drupal 6 doesn't support having both private and public files enabled, but there are some modules that provide this, for example http://drupal.org/project/private\_download.

If that modules doesn't do what you need, you can also write your own, see file\_download() for inspiration. This is the page callback that serves private files through PHP by checking access with hook\_file\_download().

# Answer
> 1 votes
I'm not good in \*nix, but I think you should to create symlink to this directory from public\_html/ and cmod -R 777 to foreign folder.

# Answer
> 1 votes
I do this all the time for security reasons.

1) You'll need to configure your open\_basedir to include the directory or directories where you store your files outside of the web server's docroot.

2) You'll need some separate logic to insure that the person is allowed to get the file(s), such as placing the download link/button on a page that only these users have access.

3) When the authorized person hits your special download link, they are triggering logic of yours that uses something like file\_get\_contents() on the desired file outside of docroot, which is possible because you configured open\_basedir to know about the desired file's directory

4) Now you have the desired file in a variable, just pass it to this routine, and the user's browser will pop a "save file" dialog - the file is being pushed, rather then pulled, to the user. TaDa!

```
/***************************************************************************************************
* prompt the user to download the passed string as a file.
*/
function _push_download( $output, $filename )
{
  header("Pragma: public");
  header("Expires: 0");
  header("Cache-Control: private");
  header("Content-type: application/octet-stream");
  header("Content-Disposition: attachment; filename=$filename");
  header("Accept-Ranges: bytes");
  echo $output;
  exit;
}

```

---
Tags: 7, files
---


# Question
Title: Aggregate uploaded files for simplified download
I have a content type that users are uploading a *lot* of files into, and the client would like to be able to download all of the attached files with a single click. It seems that a server-side compression of all the files would be a good solution, something like Stephen.Colson is trying to do here stephen.colson's sandbox.

I haven't found anything appropriate, though. Is anyone aware of a good solution for aggregating file downloads?

# Answer
Take a look at the pclzip suite of modules ZipCart.
> 1 votes

---
Tags: 7, files
---


# Question
Title: How to promote nodes to front page using MySQL command line
What is the command to promote unpromoted nodes to front page using MySQL command line? I want to promote 200 nodes at once. The node type is "story."

# Answer
`UPDATE node SET promote=1 WHERE type="story" AND promote=0 LIMIT 200;`
> 6 votes

---
Tags: 7, nodes, database
---


title: drupal_to_js() and anonymous functions

text:
# Question
Title: drupal_to_js() and anonymous functions
I'm using the flot module to create some graphs in Drupal. Generally, it is working pretty well. However, I have come across an issue which is more general.

I am defining a settings array, which works for most things, but some flot settings allow for anonymous functions:

```
  xaxis: {
    transform: function (v) { return Math.log(v); },
    inverseTransform: function (v) { return Math.exp(v); }
  }

```

How could I encode this in PHP so that it will be output correctly? The flot module uses `drupal_to_js()`, and I can't put it outside of quotes as PHP will try to interpret it. If I put it inside quotes it will be treated as a string.

From my googleing it looks like `json_encode()` also doesn't support this.

A little more explanation: `drupal_to_js()` takes a PHP structure and transposes it to JavaScript.

```
  $top = array(
    'a_string' => 'A string will convert fine',
    'a_number' => 123 // as will a number,
    'an_array' => array('a' => 'nested arrays work fine too'),
  );

```

This will be transposed to something like

```
 [ a_string: 'A string will convert fine', a_number: 123 ...

```

I want to transpose a function; the following code will give me the string `'function (v) { return Math.log(v); }'`.

```
  $top = array(
    'a_string' => 'function (v) { return Math.log(v); }',
  );

```

The following code will give me a PHP parse error (as it should be).

```
  $top = array(
    'a_string' => function (v) { return Math.log(v); },
  );

```

I want the text in the string to be used as a JavaScript literal, but I don't think it can be done.

Has anyone found a good way round this? I could output some raw JavaScript, but then I will lose a lot of functionality.

# Answer
> 2 votes
This guide can be used as a work around http://echodittolabs.org/blog/2011/04/setting-js-callbacks-drupal-json-and-some-jquery-sauce-jcarousel-controls

We are looking for a generalized solution to this here http://drupal.org/node/1148204

# Answer
> 1 votes
If I understand the problem correctly, you have two options here.

The first is to use drupal\_add\_js with the inline option set to true. `drupal_to_js()` deals specifically with transforming PHP variables into their JavaScript equivalent; in this case, you aren't dealing with variables, but rather with functions, so it's not a proper fit.

The second option (which I probably favor) is to not use anonymous functions at all. Instead, create your own JS file which looks something like this:

```
// Give yourself a namespace to play nice with other JS.
if ( !ProjectName.flot ) { ProjectName.flot = {}; }

ProjectName.flot.transform = function (v) {
  // …
}

ProjectName.flot.inverseTransform = function (v) {
  // …
}

```

From there, your code to call these functions would look more like:

```
xaxis: {
  transform: ProjectName.flot.transform(v),
  inverseTransform: ProjectName.flot.transform(v)
}

```

Which would still be added via `drupal_add_js()`. I prefer this method because maintaining your JS is a lot easier/more logical if it's in its own file. Either methods should work, though.

---
Tags: javascript
---


# Question
Title: Modifying login/user panel position in a theme
For our site, we're looking at designing a relatively simple log-in widget/panel. We want it to be in the header of our site (for reference, we're modifying the excellent "Orange" Drupal theme), and we want to design it in the following way:

* When a user is logged out, it merely shows the log-in form. It would sit in the upper right-hand corner, embedded in a rectangular shape.
* When a user is logged in, it would show a "Welcome Back, $USERNAME$!", with an avatar, a message counter for private messages, and a few links for managing a profile, accessing a shopping cart, etc.

My question is, where do I start with all of this? As far as I'm aware, documentation for this type of thing appears to be a little bit sparse. What do I need to do in order to set up this small widget so that it:

1. Sits in the correct position.
2. Displays the user avatar, links, etc.
3. Replaces the default log-in form?

Do I need to go into Panels and Views and try to build a custom log-in form there? Do I need to write it all in CSS and jQuery? What's the best way to approach this?

# Answer
The user login form is a core block you can position. The other bit you'll have to write in a custom module as a custom block. The menu links part should be a menu block.
> 1 votes

---
Tags: 7, blocks, users, theming
---


# Question
Title: How to tell the difference between multiple image_buttons on the same form?
Using FormAPI to create a simple set of three image\_buttons, in the form\_submit handler there is no 'op' value set in $form\_state and therefore no way to tell which image\_button was clicked. Is this a limitation of image\_buttons?

Here's what I used to create the form, and it's bare-bones submit handler that shows no information telling me which button was clicked:

```
function cex_dash_top_icons_block_form( $form_state ) {
  $form = array();
  global $base_url;
  $projects_icon_path  = '/'.drupal_get_path('module','cex_dash').'/Projects-icon-med.jpg';
  $reporting_icon_path = '/'.drupal_get_path('module','cex_dash').'/Reporting-icon-med.jpg';
  $help_icon_path      = '/'.drupal_get_path('module','cex_dash').'/Help-icon-med.jpg';

  $form['projects'] = array(
    '#type'  => 'image_button',
    '#value' => 'Projects Dash',
    '#src'   => $projects_icon_path,
  );

  $form['reports']  = array(
    '#type'  => 'image_button',
    '#value' => 'Analytics Dash',
    '#src'   => $reporting_icon_path
  );

  $form['help']     = array(
    '#type'  => 'image_button',
    '#value' => 'Documentation Dash',
    '#src'   => $help_icon_path
  );

  return $form;
}

function cex_dash_top_icons_block_form_submit($form_id, &$form_state) {
  _devReport( 'cex_dash_top_icons_block_form_submit: form_state is "'.print_r($form_state,1).'"' );
}

```

And no matter which button is clicked, $form\_state\['values'\] looks like this:

```
[values] => Array(
  [projects] => Projects Dash
  [reports] => Analytics Dash
  [help] => Documentation Dash
  [form_build_id] => form-b6c762d22d0fd2360d1804ef19043c7d
  [form_token] => 4f0ce5275cc923e8fb27c305b57bf414
  [form_id] => cex_dash_top_icons_block_form
)

```

Now, in the larger `$form_state` array there is a 'clicked\_button' array, but that always only has the information for the last image\_button.

Do I need to create one mini-form for each image\_button?

# Answer
> 1 votes
This issue on drupal.org might help.

# Answer
> 1 votes
If you just need to know which button has been clicked to take the necessary action, then you should assign a different submission handler to each button; see Form buttons can define custom #submit and #validate handlers for more details.
Since Drupal 6, the 'op' element in the form values, corresponding to the button clicked when there are several in a form in Drupal 5.x, should no longer be relied upon and may not be present; see what reported in The 'op' element in the form values is deprecated and should not be relied upon.

---
Tags: 7, forms
---


# Question
Title: Getting the taxonomy parent term as Views argument
I am trying to get a taxonomy parent name with this code; when I put 1 as the argument, I keep getting the ID, but when I try using 2, I get a error. It should wor,k but it keeps throwing the error back at me. I am trying to get the parent name, not the ID.

```
$view = views_get_current_view();
print $arg0 = $view->args[2];

```

> Notice: Undefined offset: 2 in \__lambda\_func() (line 3 of /home/loansdotorg/public\_html/modules/views\_php/plugins/views/views\_php\_handler\_area.inc(39) : runtime-created function).

# Answer
I believe that Views uses `$view->args` to store the arguments it has received from the url, or passed to it when embedded.

So in the above case, you would need a url structure where the parent term is located in the views url after the actual term. Most likely this is not the case.

If you want to get the parent term you can use the function `taxonomy_get_parents`
> 1 votes

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


title: A function to get the term parent

text:
# Question
Title: A function to get the term parent
```
function term_parent($tid) {
  $row = db_result(db_query("select * from {term_data} where tid = ?",array($tid)));
  if ($row['pid'] > 0) {
    $term = term_parent($row['pid']);
    $row['classid'] = $term['tid'] . '^' . $row['classid'];
    $row['classname'] = $term['name'] . '^' . $row['name'];
  }

  return $row;
}

```

I don't know why it is using `tid = ?`. When should I use `?`.
What's the meaning of `$row['pid']` and of the following line?

```
$row['classid'] = $term['tid'].'^'.$row['classid'];

```

# Answer
> 3 votes
In a Drupal query, `?` should never be used. Drupal uses placeholders, which are listed in db\_query(), and that allow to

* type casting to a integer the value passed for the %d placeholder
* escape the string passed as value for the %s placeholder
* convert the value to a floating point value for the %f placeholder
* convert and escape the value passed for the %b placeholder

This means that, for example, `db_query("SELECT * FROM {table} WHERE value = %f", "12")` would convert the string "12" in the floating point value 12.0, and `db_query("SELECT * FROM {table} WHERE string = '%s'", "It's an example")` will change the string passed as argument to `"It\'s an example"`.

The query is wrong, in a way, as taxonomy\_schema() doesn't define pid (nor classid) as fields of the {term\_data} table. The following part of the function will never be executed:

```
if ($row['pid'] > 0) {
  $term = term_parent($row['pid']);
  $row['classid'] = $term['tid'] . '^' . $row['classid'];
  $row['classname'] = $term['name'] . '^' . $row['name'];
}

```

The {term\_hierarchy} table define a parent field, which is the ID of the parent taxonomy term, but the reported code is not making a join between the tables, and it could not find the ID of the parent taxonomy term, which then is not stored in the pid field.

---
Tags: 7, database
---


# Question
Title: Help with content structure of a typical art gallery website
As a way of learning a bit more about how Drupal 7 works, I'm trying to replicate the features of a local art gallery website. I'm having a few problems setting up the content types so I was hoping someone could point me in the right direction. I want to get all the content correctly configured and stored so I can then play around with Views and different ways of presenting that content. Here's what I've come up with having broken down the different types of data:

* ARTIST will have one name, a bio and a website
* ARTWORK will be associated with one artist only, will have a title, may or may not belong to a SERIES, will also have dimensions, an image, a year of creation, and will have the material used to create the artwork (term reference to a taxonomy vocabulary with terms such as "oil on canvas", "photograph", "mixed media" etc)
* SERIES will be associated with one artist only.

So I've set up my content types. Well, the Artist and Artwork ones anyway, but how do I link them? I think I'm supposed to set up Artist as a taxonomy vocabulary, and list the Artist names as terms, and then when creating the content type Artwork have a term reference to it. This is OK but I don't want to have to manually add the term to the vocabulary each time a new content type Artist is created. So I guess what I'm asking is two questions:

1. Is my approach completely wrong? If so, please guide me in the correct direction!
2. If it's not wrong, is there some way to automatically generate the terms of the vocabulary Artist based on the Artist name? So when new Artist content is created, the term is automatically added?

# Answer
> 2 votes
This problem is often solved using the Node Reference URL Widget. Here is a video podcast on Node References and another on how to create a gallery.

You should use taxonomy to categorize the different series. Use Views to show the series will take a node reference relationship as an argument as well as the taxonomy id of the series.

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


title: Pagination for entities

text:
# Question
Title: Pagination for entities
I have an entity called announcement, and I have a page (user/%/announcement) where I display a table of three columns (name of entity,an edit entity link and an delete entity link).

```
function announcements_user($account) {
  $uid = $account->uid;
  $return = '';
  $total = 0;
  $i=0;
  $pid = array();
  $text = array();

  $query = db_select('announcements','a')->extend('PagerDefault');
  $query->fields('a',array('pid','value'));
  $query->condition('uid', $uid);
  $result = $query->execute();

  foreach($result as $row) {
    $pid[] = $row->pid;
    $text[] = $row->value;
    $total++;
  }

  $return .= '<table border="1">
    <tr>
     <th>Announcement</th>
     <th>Edit</th>
     <th>Delete</th>
    </tr>';

  while ($total) {
    $return .= '<tr>';
    $return .= '<td><a href="'.$base_url.'/announcement/'.$pid[$i].'">'.substr($text[$i],0,10).'......</a></td>';
    $return .= '<td><a href="'.$base_url.'/announcement/edit/'.$pid[$i].'">Edit</a></td>';
    $return .= '<td><a href="'.$base_url.'/announcement/delete/'.$pid[$i].'">Delete</a></td>';
    $return .= '</tr>';
    $i++;
    $total--;
  }

  $return .='</table>';
  $return .='<br>';
  $return .='<a href ="'.$base_url.'/announcement/add">Add Announcement</a>';

  return $return;
}

```

Now my problem is that keeping this format of tabular structure, how do I display my result in a paginated format with 5 announcements per page? I have seen pager.inc for Drupal 7 and howto-print-out-the-pagination-for-entityfieldqueries link, but I just can't figure out how to apply them to my case.

# Answer
> 3 votes
```
function announcements_user($account) {
  $header = array(
    'announcement' => array(t('Announcement')),
    'operations' => array('data' => t('Operations'), 'colspan' => '2'),
  );
  $rows = array();

  $result = db_select('announcements','a')
    ->fields('a', array('pid','value'))
    ->condition('uid', $account->uid)
    ->extend('PagerDefault')
    ->limit(5)
    ->execute();

  foreach ($result as $data) {
    $row = array();
    $row[] = l(truncate_utf8($data->value, 10, FALSE, TRUE), 'announcement/' . $data->pid);
    $row[] = l(t('Edit'), 'announcement/edit/' . $data->pid);
    $row[] = l(t('Delete'), 'announcement/delete/' . $data->pid);

    $rows[] = $row;
  }

  $form['announcements'] = array(
    '#theme' => 'table',
    '#header' => $header,
    '#rows' => $rows,
    '#empty' => t('No announcement available.'),
  );

  $form['pager'] = array('#markup' => theme('pager'));
  return $form;
}

```
* Query methods generally return the object for which they are invoked; this means that method calls can be concatenated as I did in the code.
* PagerDefault::limit() has a default limit of 10; if you don't call that method, the limit is the default value.
* Strings that appear in the user interface should always be translated; the only strings that cannot be translated (which means, you cannot pass them to t()) are dynamic strings obtained from a function/method.
* Drupal URLs should always be obtained from url() or l(). `l()` returns the HTML tag for links (`<a>`), while `url()` returns the relative or absolute URL for the Drupal path passed as argument.

For an example of function that does something similar, see blog\_page\_last(), which returns the last blog posted by a user.

---
Tags: 7, entities, paging
---


# Question
Title: How do I restrict the type of characters that can be used at registrations?
I want to disallow the use of spaces and all symbols except "\_".

# Answer
> 1 votes
Based on what you said in your comment, you should just use Pathauto. Pathauto allows you to remove special characters from user/node/taxonomy URLs; if someone's username is 'hey$3#@", you could make their user profile URL http://yourdomain.com/user/hey3.

---
Tags: 7, users
---


title: How to overwrite the add content page

text:
# Question
Title: How to overwrite the add content page
I created a content type "test", and I want to overwrite the add "test" content page (http://www.example.com/node/add/test); for example, I want to show something on the right part of the page. How can I do it?

the following is i want to do:

i used `garland` theme as my site's admin theme and my custommed theme `company` as my site's template. i created a content type named `"hello"` this content type is used for anonymous to submit content, the page's layout is (header, left, right, footer) some static content and the site navigation locate on the header. the left part is the form which is used by the anonymous to submit content. the right part will be put into some blocks which are generated by the views module. now the default `create hello content page` for the anonymous is garland theme's create content page. how to change the page shows like the above layout as what i said. thank you.

# Answer
> 1 votes
Maybe implement hook\_theme() in your template.php and add an extra template for the test\_node\_form:

```
return array('test_node_form' =>
    array('arguments' =>
        array('form' => NULL), 'template' => 'test-node-edit'
    )
);

```

Now you can write a test-node-edit.tpl.php for the form. But that's only for the form, not the whole page.

# Answer
> 1 votes
The Panels module is a good way to do this. Watch this video http://www.gotdrupal.com/videos/drupal-panels

It will allow you to override your add 'hello' page with a page that you can fully customize.

---
Tags: 7, forms
---


# Question
Title: Custom taxonomy; link with two content types
I've successfully created a new content type ("my\_type") and added a taxonomoy into it.

How can I combine this new taxonomy also with the default content type "post", so that I can select it in the default content type backend?

# Answer
> 3 votes
## Drupal 7

Go to Structure \> Content types, select "Manage fields" for the post content type. Either add the existing taxonomy field to it or add a new one. For a new one, choose which vocabulary should be used for this field.

## Drupal 6

Go to Admin \> Content \> Taxonomy, edit your vocabulary. Then under content types, select the content types for which this vocabulary should be displayed.

---
Tags: taxonomy-terms
---


# Question
Title: Interface translation - Body, Title built-in interface
I use i18n and I10n\_client to translate English to Dutch in my web page, however some interface variables are not changing.

I searched 'Body' and try to replace it with its Dutch word, it doesnt take effect no matter what I do http://imageshack.us/photo/my-images/831/searchbody1.png/

and http://imageshack.us/photo/my-images/576/searchbody2.png

How can I change this type of built in interfaces. I cant change "Title" as well.

# Answer
> 1 votes
If having it only in Dutch is enough for you, you could change it to Dutch directly in the Edit content type form; go to Admin -\> Content -\> Content types, select edit for the one you want to change. You can set a title and body label in the "Submission form settings" fieldset.

There is a bug report open for this, see http://drupal.org/node/1016006.

I also found some reports that this *should* work now with multiple languages, with i18n: http://drupal.org/node/149349#comment-1135605.

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


title: Views sort criteria

text:
# Question
Title: Views sort criteria
There is a criteria named "node statistics: Most recent view." What's the time beginning and end of the most recent view?

# Answer
It's the time when a certain node was viewed last time.
> 3 votes

---
Tags: 7, views
---


# Question
Title: How to keep Views argument results in panels display
I'm working with Views and Panels and I am having troubles keeping the results of a View argument within Panels.

I have a content type for events, and I want to display a list of previous events grouped by year. Through Views, I created a Views panel with an argument based on the year of the event date to display the list of years (2011, 2010, 2009, etc.). The Views panel displays just fine within my Panels variant, but whenever I follow one of the links, the results are not within Panels anymore.

I'm sure I'm missing something very obvious but I can't seem to get this to work properly.

# Answer
> 1 votes
Ok, I think I have this sorted out but wouldn't mind some advice if I went about it the wrong way. To recap, the goal was to have a list of previous programs sorted by year and have that results page stay within the layout set in Panels.

**Within Views**

1. Create a Content Pane to filter out only the programs content type with the Argument set to display a 'Summary, sorted descending' based on the year of the program. This will be used to display just the years of the previous programs in a list and will be added to main Programs page.
2. Create a Page to filter out only the programs content type with the same Arguments. Set the path of this page to 'programs/previous'. This will be used to view the actual results of the list created above.

**Within Panels**

1. Create a new Page with the Path set to 'programs/previous/%view'. In the Arguments section, set it to Managed Page. In the Content section add the page created within Views and make sure the Send Arguments option is checked.
2. Within Node Template (which controls the main layout of the entire site), add the Content Pane to the Programs page.

Therefore, when a visitor goes to the main Programs page ('/programs'), they will see a list of the previous programs in the right hand corner and clicking on each one will bring them to the appropriate page (such as '/programs/previous/2001') while keeping everything in Panels.

I'm a little confused as to how all works (for instance, how does the Content Pane inherit the '/programs/previous' path from the Page?) but am glad it works as planned. Hope this helps others and please don't hesitate to let me know if I could have achieved this in a simpler way!

Bob

---
Tags: 7, views, panels
---


# Question
Title: How can I restrict view pemissions to a node related child nodes?
Let's say I have a parent node with ID equal to 233 that has the following related nodes: 234, 235, 236 (in a relationship field).
Is it possible to restrict access to paths node/234, and node/235, if they are a specific content type, but still show them for the same users in a embedded view inside a local task of ID equal to 233?

# Answer
> 2 votes
Looking at the comments I realized that in my case at least the best way of limiting the access for unauthorized users (anonymous mainly) is **to not publish the child nodes**. And I removed the 'published'='yes' filter in the view itself so I can show those nodes in the parent template. And it works nicely. Thank you for the tips.

---
Tags: 7, users
---


title: How do I print out a field

text:
# Question
Title: How do I print out a field
I created a new content type with several fields in it. How would I print out those fields anywhere on the page that I need them like in the sidebar and other areas? What is the syntax for printing out a field? Also, I think I have to name a PHP file after the content type. What do I name it in Drupal 7?

# Answer
> 2 votes
This is best accomplished with Render Arrays. Please read Theming Node Form into Regions for a tutorial.

# Answer
> 1 votes
I think the question is how to put fields from a node to the page itself. You have to use hook\_page\_alter() and you can do something like this:

`$page['sidebar_first']['node_links']=$page['content']['system_main']['nodes'][$nid]['links'];` for putting node links in the sidebar.

For a field from a node you can do something like this: `$page['sidebar_first']['test_block']=$page['content']['system_main']['nodes'][$nid]['field_your_field'];`

Note: `$nid` si the desired nid from the `$page['content']['system_main']['nodes']` array. The idea is that you can modify anything that a region contains and you can easily create blocks in any region with this hook.

# Answer
> 0 votes
I think you should install the devel module and do a

```
dpm($node);

```

You'll be able to see all the data contained in the node and therefore, you'll be able to use them as you want.

---
Tags: 7, entities
---


# Question
Title: Can Rules create a node reference that is empty except for a title?
Is it possible to automatically create a reference node or entity with Rules? The idea is to have a node with information and an image Gallery reference. If the image gallery is clicked on the node view then it just shows the images with a link back to the original node. This way the original node can have one author while several different users can add photos. There isn't a need to populate the gallery on the original node creation since it will be an obvious second step view the node to add images or wait till later. I just think that it would make sense to have it available from the beginning even when empty.

# Answer
> 1 votes
The solution is to use the URL Node Reference widget.

# Answer
> 0 votes
I would use hook\_node\_insert() for this.

---
Tags: 7, nodes, rules
---


# Question
Title: Are there any alternatives to drupal_add_js()?
Are there any alternatives to `drupal_add_js()` that permit to write inline JavaScript code?

# Answer
> 5 votes
`drupal_add_js()` allows inline code:

```
drupal_add_js($your_js, 'inline'):

```

You should however not rely on it too much. JS can be better cached by the browser (and aggregated with other JS) if delivered in a separate file.

---
Tags: 7, javascript
---


title: How to add extra save buttons

text:
# Question
Title: How to add extra save buttons
In Drupal 7, my user profile page is getting really long. If someone sets or forgets a password, they don't see the Save button, and hence their password is not changed. Using the Corolla theme, how can I add an extra save button right below the password fields?

# Answer
You need to implement hook\_form\_alter() and duplicate the Save button.

Something like this should work:

```
function yourmodule_form_user_profile_form_alter(&$form, &$form_state) {
  // Copy the existing submit button into the account fieldset.
  $form['account']['submit'] = $form['actions']['submit'];
  // Give it a high weight to have it show below the other fields.
  $form['account']['submit']['#weight'] = 50;
}

```

However, I suggest you also look for ways to shorten your form, maybe through theming or by using http://drupal.org/project/field\_group.
> 2 votes

---
Tags: 7, users
---


title: Watchdog database size

text:
# Question
Title: Watchdog database size
I was checking out one of my Drupal sites and noticed that the watchdog table is \> 3GB. I have plenty of space but it seems a big. Are there any best practices in regards to maintaining this table? I have run and cleared the cache.

# Answer
> 10 votes
Make sure that cron is running, that should clean that out the watchdog table regularly.

http://api.drupal.org/api/drupal/modules--dblog--dblog.module/function/dblog\_cron/6

Drupal has a setting that controls how many rows should be kept, which you can configure at:

**Drupal 6:** `/admin/settings/logging/dblog`

**Drupal 7:** `/admin/config/development/logging`

Additionally, you should check what kind of logs you have in that table. Maybe a module or something is causing a lot of notices which are all logged there (And considerable slow down your site!)

You can of course simply truncate the table, but you should first figure out why it's not getting cleaned and what is filling it up like that. How many rows are there?

---
Tags: 7, database
---


title: node publish state

text:
# Question
Title: node publish state
is there a simple way to control the node's publish state under a content type? eg: a content type "`test`", when the content is created by the admin, the article will be published. when the user iseditor, the article will be approved by admin that can publish. when i unchecked the box(published) which in the content type `test` `workflow settings`. both the admin and editor creating articles are can't be published

# Answer
As Berdir stated you could use the rules module to un/publish specific content depending to the role of the creator. You could also implement hook\_nodeapi() in a module to get this done. The operation would be 'presave' and the code something like that:

```
YOURMODULE_nodeapi(&$node, $op, $a3 = NULL, $a4 = NULL) {
    if($op == 'presave' && $node->type == 'YOURTYPE') {
        global $user;
        if (in_array('YOURROLE', array_values($user->roles))) {
            $node->status = 0;
        }
    }
}

```

Here I checked the contenttype and user role to upublish content. You can do all sort of things.
> 4 votes

# Answer
If you change the default to don't publish, only users with the appropriate permission can change it, for all others, it will use the default.

You could then for example build a view with unpublished content, that you can go through and publish want you want. The default content list has a filter to show only unpublished content too, so that might work too.
> 0 votes

---
Tags: 7
---


title: Tokens available in views

text:
# Question
Title: Tokens available in views
I am trying to change the output in my view; the problem is that I cannot access the \[URL\] token to rewrite to `<a href="[URL]">this is my link</a>`.

It seems I can only access the \[title\] token. Do you have any idea?

# Answer
> 4 votes
The tokens available when rewritting the output of a field correspond to the values of the other fields you have selected in the view. They must also be above the field you are rewritting in the field order.

In order to get the URL, you should add a node path (or link to node) above your current field and mark it as "hide from display".

The token will now be available!

PS - If you want to link to the node's url, you can always just select the option to display the field as a link to its node.

---
Tags: views, tokens
---


# Question
Title: How to style the help text that appears at the top of pages?
I'm using the "Piano" theme, and I just don't like the way it displays the help text that would normally appear as a red box when there's an error or a green box for information or to indicate that something processed successfully. I really just want it to be back to normal because right now it's easy to miss and it kind of blends in to the rest of the text.

# Answer
What you're looking for is the `$messages` variable, which is given the following styling by core, yet seems to be removed from that contributed theme:

```
div.status {
  background-color: #f8fff0;
  border-color: #be7;
  color: #234600;
}
div.warning {
  background-color: #fffce5;
  border-color: #ed5;
  color: #840;
}
div.error {
  background-color: #fef5f1;
  border-color: #ed541d;
  color: #8c2e0b;
}

```
> 4 votes

---
Tags: 7, theming
---


title: How to make a better backup

text:
# Question
Title: How to make a better backup
I backuped my website with Backup and Migrate. I made some tests and restored a few times successfully.

Then I created some fields (one of them is named field\_date), and made some tests; I was not satisfied so I restored again.

Then I wanted to create a field named field\_date, which should not be in the database after restore to previous state, but I got the following error message:

```
DatabaseSchemaObjectExistsException: Table field_data_field_date already exists in DatabaseSchema->createTable() (line 630 of /var/www/includes/database/schema.inc).

```

How is this possible? None of my backups works to turn the site to the initial state. Is this bug in the module I used for the backup, or is this feature and I should use more reliable backup utility?

# Answer
> 8 votes
When restoring, you first need to drop your old database (or all tables within). The restore can only replace the tables that existed when you created the export, it doesn't know about any tables that you created later on.

---
Tags: 7, backups
---


title: What is the best practice for theming?

text:
# Question
Title: What is the best practice for theming?
I'm about to start theming a Drupal 7 website for the first time. I've watched Moshe's video, Lia Clark's introduction to theme overrides using context naming, and Franz's talk at Drupalcon Chicago. These are all great, but like everything else in Drupal there must be a thousand different ways to theme now.

What is are the best techniques and practices to theme now in Drupal 7? More specifically, how do I best use hook\_page\_alter($page)? I'm imagining that after I move all the parts of the page around it will be huge and unwieldy. Are there ways to add a region to a node template?

Edit:

Here is an example of moving a page region that is populated with the Context module while the block module is disabled completely. It was the first way of doing this that came to my mind. Why someone would want to put a region between the links and comments, I don't know. Still it's cool to be able to put stuff there.

In template.php:

```
function hook_page_alter(&$page){

  $main_content_display = &drupal_static('system_main_content_added', FALSE);

  // Need to beat common.inc drupal_render_page() line 5485 to this
  if (!$main_content_display) {
    $page['content']['system_main'] = drupal_set_page_content();
  }

  if ($node = menu_get_object()) {
    $region_to_embed = $page['sidebar_first'];
      $page['content']['system_main']['nodes'][$node->nid]['#node']->region = $region_to_embed;
    unset($page['sidebar_first']);
  }
}

```

And in node.tpl.php:

```
  <?php print render($content['links']); ?>
  <?php if ($node->region): ?>
    <?php print render($node->region); ?>
  <?php endif; ?>
  <?php print render($content['comments']); ?>

```

# Answer
Kind of a "big"/multiple question(s), that is hard to answer. Try to ask more specific, single questions in the future.

About hook\_page\_alter(). In a theme, you should customize the output by overriding default templates. IMHO, that hook is more meant if modules want to alter the output of other modules, especially if they return render arrays instead of arbitrary strings.

Speaking of render arrays, that is one of the main things I do with my modules now, instead of arbitrary templates. I've already replaced quite a few specific "page callback templates" by building and returning a so called render array. The advantage is that, if you for example want to change the order of the table rows, or add/hide a table row, you can do that without duplicating a template with maybe 100 lines of code. And, multiple modules can add/change things.

Two examples:

Edit:

And for your last question: Regions in "Theme-speak" are places where blocks can be placed. Regions are defined in the .info file of a theme. The node template itself is more or less a block (The "Content" block, which is the output of the executed page callback). Since it is not possible to nest regions within regions/blocks you can also not place regions in a node template.

That said, you can make your node template as complex as you want, and split the content up into "visual regions" for example.
> 3 votes

---
Tags: 7, theming
---


# Question
Title: How does the global variable $user work?
Here is my scenario:

I create a new user and dynamically create for him some content on which he is the owner.

Each user can log in, see his content and edit his profile. I use a block in which I have a menu links to each content and to his profile.

The theme output of the block function uses `global $user;` to get the current logged user.

However, the strange thing is that `$user->uid` return the last created user in the system and not the current logged user. Also the `$user->language` is of the last created user in the system. Why?

The user logs out with `user/logout`; this is the command to log out, right? Do I need to do more after user logout such as GLOBAL variable resets?

# Answer
> 5 votes
I would check to see that the block is not getting cached, or that you are not using something like Boost (static caching).

Sounds like the block contents are being cached to me.

# Answer
> 3 votes
`global $user` should ALWAYS refer to the currently logged in user.

There is a good chance that you are probably resetting the global `$user` variable in your custom code. A good practice when dealing with user accounts is to use the `$account` variable to distinguish between the two, see user\_save() for an example.

---
Tags: 7, users
---


# Question
Title: How do I output the entire page template?
I've created a custom module that defines a menu callback; that menu path will call a function which performs some actions and once it's finished, it needs to display the theme with a message as the body.

This used to be doable using `theme('page', $message)` but in Drupal 7 it only returns the HTML content that would normally appear within the BODY tags.

I know that there is now a `html.tpl` template, but I'm unsure how I can combine the two to generate a full page.

# Answer
> 1 votes
Turn out that you have to return a render array instead of HTML markup like you could of in Drupal 6.

# Answer
> 1 votes
This is a wild guess but have you tried:

```
$html = array('page' => $message);
theme('html', $html);

```

(or something along those lines)?

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


# Question
Title: How to pass formatter settings to field theme function?
I've created a field by implementing `hook_field_info`, I've created the widget which works perfectly and I've hit a road block with the formatter.

I've implemented `hook_field_formatter_settings_form` to add some extra output options but I can't work out how to get those values passed to the theme function when the field is rendered.

Here is a simpified version of my code, it's not all the hooks just the ones related to the formatter and the field's theme:

```
function test_field_formatter_info() {
    return array(
        'test' => array(
            'label' => t('Test'),
            'field types' => array('test'),
        ),
    );
}

function test_field_formatter_view($entity_type, $entity, $field, $instance, $langcode, $items, $display) {
  $element = array();

  foreach ($items as $delta => $item) {

    $element[$delta] = array(
      '#theme' => 'test',
      '#item' => $item,
      '#myextravalue' => $display['settings']['myextravalue'],
    );
  }

  return $element;
}

function test_theme() {
  return array(
    'test' => array (
      'variables' => array('item' => NULL, 'myextravalue' => NULL),
    ),
  );
}

function theme_test($variables) {
    $item = $variables['item'];
    ...
    return $output;
}

```

The widget, field and formatter are working fine, I just can't work out how to get the formatter settings that were defined by `hook_field_formatter_settings_form` to the test theme function.

When I `$variables` variable I only see an array for `item`. `myextravalue` is not there!

There is very little information on how to create fields/widgets/formatters for Drupal 7 and I'm pulling my hair out with this.

# Answer
> 4 votes
Your formatter\_view implementation looks ok, very similar to image\_field\_formatter\_view().

However, you're info hook seems to be missing default values for your settings, I'm not sure if they are required or not, but try to add them, again see image\_field\_formatter\_info()

Does the field\_formatter\_settings form work correctly? Does it show correctly in the summary and keeps the values when you edit it again?

Without more information, the only advice I can give you is install devel.module if you haven't already and make extensive use of `dpm()` to see where you get which information. For example, contains $display the necessary information in your formatter\_view() function?

If yes, it could simply be a outdated theme registry that does not yet know about your additional theme argument (if you added later on for example).

# Answer
> 4 votes
Like any other theme functions, you need to define those array indexes as variables used by the theme function.

For example, you can use the function theme\_table() using the following code (the code is present in node\_admin\_nodes()):

```
$form['nodes'] = array(
  '#theme' => 'table',
  '#header' => $header,
  '#rows' => $options,
  '#empty' => t('No content available.'),
);

```

`theme_table()` is defined in drupal\_common\_theme() as:

```
'table' => array(
  'variables' => array('header' => NULL, 'rows' => NULL, 'attributes' => array(), 'caption' => NULL, 'colgroups' => array(), 'sticky' => TRUE, 'empty' => ''),
),

```

If you want to use "#myextravalue," then you need to define "myextravalue" as one of the variables used by your theme function.

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


title: Similar By Terms without vocabulary

text:
# Question
Title: Similar By Terms without vocabulary
Other modules doing well but not actively developed.

How to make Similar By Terms works without vocabulary?

# Answer
You might consider using Open Calais or Auto Tags to tag all your content. Open Calais will require a little configuration. It works wonderfully with Similar Terms.
> 1 votes

# Answer
You may want to look at http://drupal.org/project/similar

> A module that displays a block with the most similar nodes to the currently viewed one, based on the title and body fields. Related pages show as a list in a block

I am using it on my own website with good results
> 1 votes

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


title: How can I create a simple tab?

text:
# Question
Title: How can I create a simple tab?
I'd like to create a tab like the one show in the screenshot for a simple contact address list.

or see this drupal site HERE

I have "contact one," "contact two," and "contact three."
I want to put some text under each contact section.

How can I achieve this?

# Answer
> 4 votes
I think you want to use QuickTabs. I am using it on my website (check near the bottom). It seems to be exactly what you want to do. Under each quick tab, you can display nodes, views, blocks or other quick tabs.

# Answer
> 0 votes
You could use an implementation of hook\_menu(). Here's an example in code:

```
function services_menu() {
  $items['services'] = array(
    'title' => 'Services',
    'description' => 'Description of services',
    'access callback' => TRUE,
    'page callback' => 'services_page_callback',
  );
  $items['services/development'] = array(
    'title' => 'Drupal Development',
    'access callback' => TRUE,
    'type' => MENU_DEFAULT_LOCAL_TASK,
    'weight' => -10,
  );
  $items['services/design'] = array(
    'title' => 'Design',
    'page callback' => 'design_tab_callback',
    'access callback' => TRUE,
    'type' => MENU_LOCAL_TASK,
    'weight' => 0,
  );
  $items['services/seo'] = array(
    'title' => 'SEO',
    'page callback' => 'seo_tab_callback',
    'access callback' => TRUE,
    'type' => MENU_LOCAL_TASK,
    'weight' => 10,
  );
  $items['services/hosting'] = array(
    'title' => 'Hosting',
    'page callback' => 'hosting_tab_callback',
    'access callback' => TRUE,
    'type' => MENU_LOCAL_TASK,
    'weight' => 30,
  );
  $items['services/support'] = array(
    'title' => 'Support',
    'page callback' => 'support_tab_callback',
    'access callback' => TRUE,
    'type' => MENU_LOCAL_TASK,
    'weight' => 40,
  );

  return $items;
}

```

for more info see the documentation for hook\_menu().

---
Tags: 7
---


title: ApacheSolr integration

text:
# Question
Title: ApacheSolr integration
I have a Drupal multisite website, with Apache Solr Search Integration, which is up and running very well in the live server. I am trying to replicate the same website, on another server to use it as a development environment. I have copied all the code and replicated the DB and changed the settings.php file accordingly, but I am getting the following errors.

* Memeber profile is not completed.
* Apache solr is not integrated on to the server.

Can anyone help me with the steps which I have to follow during the process?

# Answer
Solr is a server and you must set up the parameters to this server correctly in your site at this address: `admin/settings/apachesolr/settings`.

Is there any errors in the status report ?
> 1 votes

# Answer
When cloning your live site, you inherited the Solr settings from its database. It's likely that the Solr server for live site is either running on the same server or on some host un-reachable from the development environment.

You need to setup a Solr server for your development environment and configure your development site to use this server. You can use the same server to host your live and development Solr, but you need to use different indexes for each site.
> 1 votes

---
Tags: 7, search
---


# Question
Title: Building a view with arguments from a search select list
I have a block with custom search options based on taxonomy terms (hierarchical dropdown).
When you submit the form, it renders the ID of the taxonomy terms. I want to have a query in another block on the same page which renders all nodes containing the taxonomy terms.
How can I link the IDs? Is this possible to do it with Views? Should I build a custom view through a hook, or is there another way to achieve this goal?

I am using the 7.x-3.x-dev version of Views.

# Answer
> 0 votes
In the block display, add a *contextual filter* for your taxonomy term field. Set it to *Provide a default value* when *the filter value is not in the URL*. Use *Taxonomy term ID from URL* as *type* for this default value and select *Load default filter from term page*.

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