# Question
Title: How can I get the parent term in a taxonomy with a hierarchy?
I have a node that is tagged with a taxonomy term which is part of a hierarchy of terms such as "state \>\> county."

As the user has selected one of the "county" tags, how can I get the name of the parent term?

# Answer
> 2 votes
You can query the database yourself, or you can use the API function: `taxonomy_get_parents`

Since you might have several parents, it might be easier to just query the database yourself:

```
$tid = ? // the tid of the county term
$parent_tid = db_result(db_query("SELECT parent FROM {term_hierarchy} WHERE tid = %d;",
  array(':tid' => $tid)
));
$parent_term = taxonomy_get_term($parent_tid);

```

**Update - Why I think the above query is smart in Drupal 6**

Some (kiamlaluno) would argue that it's wrong to use the above argument for `db_query` in Drupal 6

In Drupal 6 You can use db\_query in three ways:

```
$query = db_query($sql, $arg1, $arg2, $arg3);
$query = db_query($sql, array($arg1, $arg2, $arg3));
$query = db_query($sql, array(':arg1' => $arg1, ':arg2' => $arg2, ':arg3' => $arg3));

```

All of the above will return the same thing, so there are no functional difference using one over the over. Why then you might ask, do I think it's clever to use the last one?

If you look at how Drupal 7 does it you will see:

```
$query = db_query($sql, array(':arg1' => $arg1, ':arg2' => $arg2, ':arg3' => $arg3));

```

Drupal 7 requires the query arguments formatted in a special way. What you can't see in this example is that the SQL needs to be changed as well. Instead of using placeholders like `%d` you need to use place holders like `:arg1`. So while the latter of the 3 Drupal 6 ways of using db\_query is the most verbose, it will save you a lot of work, should you need to upgrade your Drupal 6 module to Drupal 7. Which might happen in a year, where you don't remember what you were doing and why.

But at the end of the day, it's just personal preference, as either way will work just fine.

# Answer
> 5 votes
taxonomy\_get\_parents() returns all the parent terms for the taxonomy term with the ID passed as argument.
The value returned from the function is an array having the following structure:

```
array(
  'term id' => [taxonomy term object]
)

```

The taxonomy term object contains a property for each of the fields contained in the "term\_data" table.

The code used from the function is essentially the following one.

```
$result = db_query(db_rewrite_sql('SELECT t.tid, t.* FROM {term_data} t INNER JOIN {term_hierarchy} h ON h.parent = t.tid WHERE h.tid = %d ORDER BY weight, name', 't', 'tid'), $tid);
$parents = array();
while ($parent = db_fetch_object($result)) {
  $parents[$parent->$key] = $parent;
}

```

As you see, it doesn't return the parent terms of the parent terms of the one passed as argument. For that you need taxonomy\_get\_parents\_all(), which executes the following code.

```
  if ($tid) {
    $parents[] = taxonomy_get_term($tid);
    $n = 0;
    while ($parent = taxonomy_get_parents($parents[$n]->tid)) {
      $parents = array_merge($parents, $parent);
      $n++;
    }
  }

```

The function returns all the parent terms in the hierarchy.

---
Tags: 6, taxonomy-terms
---


# Question
Title: How to set page-specific CSS classes on the page callback build array?
I have a page callback like this:

```
function example_page() {
  $build = array();

  $build['#attributes'] = array('class' => array('example-class'));

  $build[] = array(
    '#markup' => '<p>My text here</p>',
  );

  return $build;
 }

```

As you can see, I have attempted to add classes to the div that wraps the output of the render array in the same fashion as the form API works. I have also tried setting `$build['classes']` or `$build['classes_array']`, but all of these tree syntaxes are ignored, and the content is simply wrapped in `<div class="content">`, which is not very helpful.

# Answer
> 2 votes
`#attributes` is the correct property, but the problem is that $build itself is not actually an render element (unless make it one), it's just a collection of render elements.

To make it an actual render element, you have to set the #type property to for example 'container'. That is nothing more than a div with attributes that contains other elements. See When should the "container" form element be used? and theme\_container().

You can however not affect the mentioned content div, that is outside of your control. Adding a container will add a new div inside that one.

# Answer
> 1 votes
Assuming your module is called 'example', you can do this:

```
function example_preprocess_node(&$variables, $hook) {
  $variables['content_attributes_array']['class'][] = 'my_class';
}

```

# Answer
> 0 votes
In addition to the answer which Berdir gave you could also look at using `#theme_wrappers` to wrap the element using a theme function. I think it may have similar results.

```
<div class="content">

```

is a pretty standard element in Drupal to define the page content. You may find you have unwanted side affects if you remove it.

---
Tags: 7, theming
---


# Question
Title: How to configure a server with 4g of memory to run drupal 7
I'm installing Drupal 7 on a new server with 4 GB of memory. I'd like to get some hints on how to configure it properly, how much memory to give to MySQL, and how much memory to give to PHP. One thing I found out is that running Drupal 7 on Zend server is three times faster than running it on a normal Apache server. (I think it has to do with opcode caching. I noticed with devel module it uses one-third of the memory.

Can you share your configurations with me?

# Answer
If you already have Drupal7 Data, you should load it into a staging environment and perform some buffer sizing based on the amount of data you have.

Step 1) **You must first compute the buffer sizes for your dataset**.

Step 2) If the recommended sizes exceed 75% of your installed RAM (in you case 3GB) then cap the needed buffers at 3GB.

Step 3) **If you have InnoDB data and you did not enable innodb\_file\_per\_table, you need to cleanup InnoDB by segmenting each table into its own physical tablespace (this only needs to be done once)**.

Once you have done this, you should plan to perform this configuration audit (Steps 1 and 2) every 6 months to make sure you have the proper MySQL caching in place.

**Interestingly, I addressed a question similar to this and answered it on April 15th, 2011**.
> 5 votes

# Answer
**Some things to look at**:

**An article to read**:

Rackspace's: Deploying Drupal in the cloud with nginx and boost should give you lots of ideas.

Small quote on opcode caching:

> We use APC as an opcode cache. This saves the server from recompiling the PHP code on every page load. Moreover, the whole thing fits easily in RAM (we typically give APC 128MB of RAM). This drastically decreases the CPU usage. Logged in users can now browse the site much faster. But we can still only handle a limited number of them. We can do a bit better. Instead of querying MySQL every time we go to the cache, we can store these tables in memory. Here come memcached and the cacherouter module.
> 4 votes

# Answer
I started out with my\_huge conf from the mysql directory; I also added Varnish cache to the mix. As you already found out, Zend improves performance lots.

After running for a few days, I ran the mysqltuner script and acted on some of the recommendations, mainly about the temp-table cache.
> 2 votes

# Answer
Depending on the size of the site you may want to look at memcached as well. This will compete for resources with mysql but can reduce the load on it.
> 1 votes

---
Tags: 7, performance, database
---


# Question
Title: Display different form of user's name to different users?
Is it possible to render a user's username differently to different users?

Here's the use case: I have a username with a user's First + Last name (created using the Realname module). In the user's profile, I have a setting for 'name privacy' - if the user wants to keep his last name private, the name should show as just 'First' instead of 'First + Last' to anyone who is not a site admin.

Would hook\_username\_alter() work for this purpose? It seems that is not dynamically loaded, but rather is cached when the user object is cached... so it couldn't simultaneously display 'First' to one user and 'First Last' to another user.

# Answer
Reference: http://drupal.org/node/1194546

Basically, the easiest way to do this involves a couple steps:

First, implement hook\_username\_alter() in your custom module to change the username dynamically, depending on the context of the username's display (you can, for example, load the global $user object and display one form of the account in question's name to $user's with the role 'teacher', and another form to $user's with the role 'authenticated'...

Second, you will only be able to dynamically control the username as returned by $user-\>name or by theme('username', account) using hook\_username\_alter(). You can't change a username dynamically via realname, because that module stores the name in the database and caches it for performance reasons.
> 0 votes

---
Tags: users
---


title: How to implement upgrade for fields

text:
# Question
Title: How to implement upgrade for fields
I wrote a module that defines its own node type, adds the appropriate fields, etc. How do I write an upgrade function if I wanted to change, remove, or add a field to the type?

# Answer
> 1 votes
You should be aware that once there is data In the tables created for your fields, it's limited what changes you can make.

Anyways want you need to do, is to use hook\_update\_N in your module's install file. The number N should consist of 4 numbers

1. Major release of the module (the drupal version)
2. Minor release of your module.
3. Number
4. Number

3-4 is just a combined number that should increment for each time you need to use the hook.

The field module provides a host of functions to add, change and remove fields. You can use those to do what you need.

---
Tags: 7, updating
---


# Question
Title: template_preprocess_comment() overrides template.php
I try to override this function in my template.php in Drupal 7; I copied the function found on template\_preprocess\_comment().

The first line contains `function themename_preprocess_comment($variables)`.

It contains the following code, which doesn't work.

```
$variables['submitted'] = t('!username on !datetime', array('!username' => $variables['author'], '!datetime' => $variables['created']));

```

I clear the cache, I override `theme_textarea($variables)` and it works.

# Answer
You need to pass the variable by reference like this using &

```
function themename_preprocess_comment(&$variables) {

```
> 5 votes

---
Tags: 7, theming
---


# Question
Title: Is there a way to alter the implementation of a hook given by a third-party module, or a core module?
I have a module that should replace the implementation of a hook done by another module.
Is it possible to do it, with Drupal 7? If it is possible, under which conditions is possible?

By *replacing the implementation of a hook done by another module*, I mean using a function that is automatically called by Drupal when that module is enabled. For example, if the Poll module is enabled, then Drupal should call the `poll_user_restriction_info()` or the `poll_metatags_info()` (where `hook_user_restriction_info()` and `hook_metatags_info()` are custom hooks used by my module) function present in my module files.
I could use a function in my module that loads some include files from my module directory (e.g. poll\_custom\_hooks.inc) basing on the enabled modules, but I am looking for a system that would allow Drupal to automatically load such files.

# Answer
It is only possible when the module is implementing the hook in a file that is not the module file, and the module that wants to override that hook implementation is implementing it in its module file. In this case, it is possible to implement hook\_module\_implements\_alter() to report to Drupal that the hook implementation is not contained in an external file (i.e., the hook implementation is contained in the module file).

```
function mymodule_module_implements_alter(&$implementations, $hook) {
  if ($hook == 'token_info') {
    $implementations['poll']['group'] = FALSE;
  }
}

```

In the case the module for which the hook implementation is being overwritten implements it in the module file, then it is impossible to do anything without altering the files used by that module, or adding a new file in the directory containing the module that needs to be "overwritten." The reason is that:

* module\_hook(), the function called from module\_invoke() is using the following code.

```
function module_hook($module, $hook) {
  $function = $module . '_' . $hook;
  if (function_exists($function)) {
    return TRUE;
  }

  // If the hook implementation does not exist, check whether it may live in an
  // optional include file registered via hook_hook_info().
  $hook_info = module_hook_info();
  if (isset($hook_info[$hook]['group'])) {
    module_load_include('inc', $module, $module . '.' . $hook_info[$hook]['group']);
    if (function_exists($function)) {
      return TRUE;
    }
  }
  // ...
}

```

This code calls `module_hook_info()` only when the hook implementation is not in a file already loaded from Drupal, for example the module file. Since `hook_module_implements_alter()` is invoked by `module_hook_info()`, this means that in this case my implementation of `hook_module_implements_alter()` would not be invoked.
* `module_implements()`, the function called by `module_invoke_all()` executes the following code.

```
foreach ($list as $module) {
  $include_file = isset($hook_info[$hook]['group']) && module_load_include('inc', $module, $module . '.' . $hook_info[$hook]['group']);
  // Since module_hook() may needlessly try to load the include file again,
  // function_exists() is used directly here.
  if (function_exists($module . '_' . $hook)) {
    $implementations[$hook][$module] = $include_file ? $hook_info[$hook]['group'] : FALSE;
  }
  // ...
}

```

The code is looking for the file to load in the directory containing the module implementing the hook. My code cannot tell Drupal where to look for the file containing the hook, so I could just put it in a file Drupal automatically loads, such as the module file of my module.

Overriding a module hook implemented in a module file with a function implemented in another module file does not work, as PHP would complain about a function defined twice.
> 5 votes

# Answer
You can use hook\_module\_implements\_alter() to alter the list of modules which implement a given hook. So just implement the hook in your module too and then remove the one from the module you want to replace.

Note that this hook should be used very carefully, you can do *really* weird stuff with it which will make it very hard to maintain and understand, among other things.
> 7 votes

---
Tags: 7, hooks
---


title: settings.php after migration

text:
# Question
Title: settings.php after migration
I transferred my files via FTP and database to a hosting service. I edited two files, settings.php and sites/default/settings.php whose content was originally the following.

```
$databases = array (
  'default' =>
  array (
    'default' =>
    array (
      'database' => 'db',
      'username' => 'loginname',
      'password' => 'passwd',
      'host' => 'localhost',
      'port' => '',
      'driver' => 'mysql',
      'prefix' => '',
    ),
  ),
);

```

I changed the database name, username, password and host (to yes.domainname.com) in both files.

There is probably something wrong because I get this warning.

> Warning: Cannot modify header information - headers already sent by (output started at /web/www/yes.domainname.com/sites/default/settings.php:1) in drupal\_send\_headers() (line 1044 of /web/www/yes.domainname.com/includes/bootstrap.inc).

Do you know what is wrong?

# Answer
Verify that there are not extra characters at the beginning of the file, right before the `<?php` part; this would cause the error you have seen.
Sometimes the editors add the BOM (**B**yte **O**rder **M**ark) when saving an Unicode file; verify Unicode is not the text encoding used to save the file, or that the editor is not set to add the BOM to the files it saves as Unicode.
The BOM characters are not normally visible in a text editor; if the editor has the option to show characters that have a specific code, or "invisible characters," that can help to notice them.

Alternatively, the file got corrupted when transferred.
> 6 votes

---
Tags: 7, migrations, configuration
---


title: Front end slider

text:
# Question
Title: Front end slider
I'm trying to create a slider on the front page of my template I have been working on. I have used the Views module to create a block. I have created a custom block for this view.

I am trying to make the posts in the block slide using jQuery coda. I am failing dismally. Has anyone managed to create a working posts slider for drupal 7?

# Answer
I wouldn't use views for this otherwise it s going to be more problematic to get your markup right.

Instead make a Databse query to the "node" table, grab all NID that match your node type and load them:

```
      $nodes = array();
      $nids = db_query('SELECT nid FROM {node} WHERE type = :type',
 array(':type' =>YOUR_NODE_TYPE))->fetchCol();
      if (!empty($nids)) {
        $nodes = node_load_multiple($nids);
      }
      return $nodes;

```

Then pass these nodes to your page using a page preprocess function.

Finally override the template page for your node type: `node--YOUR_NODE_TYPE.tpl.php,` and there you should have your nodes available in that page (in an arbitrary variable name that your defined in the preprocess function `$variables['my_bunch_of_node']=...`). You just need to loop through them so that the content fits exactly the original markup required by your script.

Oh and also don't forget to add your .JS , either via the .info file, either via drupal\_add\_js (in the page preprocess function)
> 2 votes

---
Tags: 7, javascript
---


title: Anonymous user form submission

text:
# Question
Title: Anonymous user form submission
I have a situation where after doing the basic registration the user is redirected to a page where he needs to fill a small form.

I aim at implementing the `hook_user_insert()` and `hook_menu()` to do something like this

```
function registration_user_insert(&$edit, $account, $category){
  drupal_goto('splan/'.$edit['uid']);
}

function registration_menu() {
  $items['splan/%'] = array(
    'title' => 'Select a Plan',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('selectplan_form'),
    'access callback' => TRUE,
    'type' => MENU_CALLBACK
  );

  return $items;
}

```

In `selectplan_form()` I will define my new form and then, using the user ID, I would save data into user table.

The basic user registration form is being submitted, the user is redirected to splan/uid, but I also get the following error.

> You are not authorized to access this page.

I have changed permissions to allow anonymous users to create and edit webform, but the problem still persists.

# Answer
> 1 votes
Implementing `hook_user_insert()` this way (calling `drupal_goto()` inside) is plain wrong:

* if there are any other implementations of this hook in other modules meant to be called after yours, they will not get called at all
* if for whatever reason `hook_user_insert()` from user module will not be called before your implementation, the user will not be saved at all
* if you look at `user_save()` function in user.module, you'll see that after invoking 'insert' hook there are many other things this function is doing, so if you use `drupal_goto()`, they will not be done.

What you can do though is to add your own submit function to `user_register_form`, and in that function set `$form_state['redirect']` to wherever you want (note that updating `$form_state['redirect']` in `hook_form_alter()` will not work in this case, as `user_register_submit()` sets its own redirect, so you need to do it after this - hence the need for your own submit).

# Answer
> 0 votes
How about using the LoginToboggan module to create a temporary role for the user after signing up and giving that role the permissions needed?

---
Tags: 7, users
---


# Question
Title: Detect front page in Drupal 6 with javascript
Using javascript in Drupal 6, is there a way to detect whether the present page is the front page? I have a custom Drupal 6 module that outputs different javascript codes based on whether the present page is front page or not. It adds a single javascript file to drupal, so I need to put the check in the javascript.

The site will be served through Varnish cache, so I don't want to add the check in PHP, though I know that would have been way easier with `drupal_is_front_page()`.

Is there any Drupal-native way to do this? jQuery based suggestions will be highly appreciated.

Thanks.

# Answer
> 19 votes
Generally Drupal adds a "**front**" class to the body element of whatever page is acting as the front page. If your theme's page.tpl.php is printing the body classes (i.e `<body class="<?php echo $classes; ?>"`), which it most likely is (it should), then your javascript can check if the body element has the "front" class.

So, assuming jQuery (because Drupal includes it) then you'd do:

```
if ($('body').hasClass('front')) { // do stuff...}

```

# Answer
> 0 votes
Print the result of drupal\_is\_front\_page() into a javascript variable, using json formatting if necessary. And just write a javascript function to check it when you need it.

---
Tags: javascript
---


# Question
Title: How to output a large amount of html markup
I need to output an entire region of a page from within my custom module.

I know I can output markup to be rendered with this code:

```
$page['region'] = array(
    '#type' => 'markup',
    '#markup' => t('markup here'),
);

```

This is good for small amount of markup but is there a better way to output a large amount of html from within my module?

# Answer
> 2 votes
You shouldn't output large amount of markup from your module without using the theme layer (unless your markup is actually editable content or large chunk of static content). So, the best is probably to define a theme function or template for your markup, and use it from your module. This way, any theme can change your markup without affecting your module logic. Even if this is supposed to be a single-project custom module, chances are that someday you, or somebody else, will have to update this site. Properly separating your module logic from its presentation will make things easier in the future.

```
// Rendering code
  $page['region'] = array(
      '#theme' => 'custom_foo',
      '#foo' => t('foo)',
      '#bar' => t('bar'),
      '#count' => 42
  );

/**
 * Implements hook_theme().
 */
function custom_theme() {
  return array(
    'custom_foo' => array(
       'variables' => array('foo' => NULL, 'bar' => NULL, 'count' => NULL),
     )
  );
}

/**
 * Default theme implementation for custom_foo.
 */
function theme_custom_foo($variables) {
  $output[] = '';
  for ($i = 0; $i < $variables['count']; $i++) {
    $output[] = array(
      'type' => '#markup',
      'markup' => ($i % 2 == 0) ? $variables['foo'] : $variables['bar'],
    )
  }
  return $output;
}

```

For static content, you can use a template (.tpl.php) instead of a theme function. This allow you to keep it outside a your .module (or .inc) file code. Again, this will be easier to maintain in the future.

Also, most of the time you shouldn't put markup into t(). `t()` is for translatable strings and most markup are not to be translated. One common, an acceptable, exceptions is (simple) link markup.

# Answer
> 0 votes
Something like this ? Be sure to escape double quotes: `\"` or better replace them by single quotes if you can.

```
$markup = "very very ...
...
long markup";

$page['region'] = array(
    '#type' => 'markup',
    '#markup' => $markup,
);

```

# Answer
> 0 votes
I would suggest not placing a large amount of content into form code, as this basically removes the ability for your content authors to edit this content, and any content changes will require code deployments (bad).

My suggestion is to use either

---
Tags: 7
---


title: How do I create custom tokens?

text:
# Question
Title: How do I create custom tokens?
> **Possible Duplicate:**
> Programmatically create a token

How do I create custom tokens? Also, is it possible to attach a token to a callback function? For example: If my string is 'this is my \[name\]', can I somehow make it so that \[name\] will be replaced with the return value of a function?

# Answer
Take a look this link: token.inc What you need is to create a module that implements hook\_tokens and hook\_token\_info.
> 0 votes

---
Tags: 7, tokens
---


title: How to add a jQuizzy?

text:
# Question
Title: How to add a jQuizzy?
I've been searching and trying for two days to add the jQuizzy engine to my site with no luck!
I've successfully added some jQuery plugins to my site, but I can't seem to be add this one?!

I created a block. In the block is a link that calls a menu item. The menu item gets a drupal form. In the form I added all the JS and CSS ... Nothing is happening?!

Help!!!

# Answer
> 1 votes
Are you retrieving that form via AJAX ? Then you get the HTML, but in your page is not present the JavaScript/CSS files. You need to add them before, so they are ALREADY present in whatever page the block is placed.

---
Tags: javascript
---


# Question
Title: Allow creation of new content type just like taxonomy
I like the way the Taxonomy module allows users to create a new taxonomy term "on-the-fly." Are there any modules that can also allow users to create new "content" of a node "on-the-fly"? Here is my scenario:

* Content Type A (Companies)
* Content Type B (Users)

Users have node reference to Companies, so every time a new user is added, a company is selected for this user.

I need to be able to just add a user directly on a Drupal 6 site, and if a company does not exist, I can also add a new company right there on the same page while adding that user. This works very similary with taxonomy, but I don't want to reference a taxonomy since Content Type A has also a lot of fields attached to it, which a taxonomy cannot do.

# Answer
Do you mean the Node Reference Create module?
> 3 votes

---
Tags: 6, nodes
---


title: Drupal Hide "Create Content" Page

text:
# Question
Title: Drupal Hide "Create Content" Page
For clever auth users who know you have a drupal site, they can type in "node/add/whatever" into your site and the page, "Create Content" pops up with all the links to the content that user is allowed to create.

I wish to hide this specific page. I found one way, not too practical, though. You would theme the "page-node-add.tpl.php" to redirect to 404, but then you need to manually add page-add themes for each content type for those links to work. Ugh.

I think the best way is to create some theme function to read if the page title is "Create Content" then redirect to 404.

Does anyone have any insight? Code? Cheers!

# Answer
I put this in a comment already, but here are some more detailed instructions on how to set up permissions to restrict access to content types. I assume you are using Drupal 7; if you're still on Drupal 6, the exact sequence of clicks will be different, but the basic approach is the same.

1. Log in as an administrator.
2. Click People in the nav bar at the top.
3. Click the Permissions tab (top right of the People overlay).
4. Click the Roles sub-tab (immediately below Permissions tab).
5. Add a new role using the text box at the bottom of the overlay. For example, "editor".
6. Click the "Permissions" *sub-tab* immediately to the left of Roles.
7. Go down the list of permissions and choose which role can do it. For example, if you want any authorized user to be able to pose comments, check the "Post comments" check box in the Authenticated User column. And if you want only editors to be able to post book pages, Check "Post book pages" in the editor column and NOT the Authenticated User column.
8. Click the "List" tab at the top of the People overlay, next to Permissions.
9. Find the user accounts of everyone you think should be an editor, and add that role to their account.

If you have a lot of users already, you can add the role en masse by checking the box next to the names you want to grant editorial permission to, and then pick "Add a role to the selected users - editor" from the drop-down box in the Update Options part of the overlay.
> 2 votes

# Answer
If, for some reason, you want to allow your users to create node at the API level (using some custom pages) but not from the `node/add/$type` pages, you can use an hook\_menu\_alter() implementation to change the required permission to access to pages.

```
function MODULE_menu_alter(&$items) {
  foreach (node_type_get_types() as $type) {
    $type_url_str = str_replace('_', '-', $type->type);
    $items['node/add/' . $type_url_str]['access callback'] = 'MODULE_node_add_access';
  }
}

function MODULE_node_add_access($op, $type) {
  $access = node_access($op, $type);
  if ($access && $op === 'create') {
    return user_access('access ' . $type . ' content creation page')
  }
  else {
     return $access;
  }
}

function MODULE_permission() {
  $permissions = array();
  foreach (node_type_get_types() as $type) {
    $info = node_type_get_type($type);
    $permissions['access ' . $type . ' content creation page'] = array(
      'title' => t('%type_name: Access content creation page', array('%type_name' => $info->name)
    )
  }
}

```
> 0 votes

---
Tags: entities
---


# Question
Title: Theme function overrides and preprocess functions - for the non-programmer
I'm trying to get my head around what these are. I've read a few articles and posts introducing Drupal theming where these are mentioned, but I'm struggling to understand what they are and what they do - each explanation I've seen so far (including on Drupal.org) makes an assumption that I know PHP or have programming experience.

Could someone explain in layman's terms or point to a good, simple-to-understand explanation, please?

# Answer
> 11 votes
Well, the theme layer *is* PHP, so you will need a minimal understanding of some programming concepts (e.g. what a function is). Especially since you will have to write some basic PHP within them. So the following might not be perfectly suited for a non programmer initally, but I tried to link everything so you can read more about it. Also, add comments if something is not clear.

The theme layer builds upon naming conventions on how to name your functions to have them called automatically. Similar to the so called hooks. At least preprocess functions are a special variant of hooks. I'll come back to that later.

Any module can register theme functions (or templates) by using hook\_theme() (You don't need to understand how that works right now). ) For example, it can basically tell Drupal that it has a theme function called `mymodule_fancything`. This module is then also responsible for providing the default theme function, which is prefixed with `theme_`. In the previous example, that module needs to define the function `theme_mymodule_fancything`.

Later on, that, or any other, module can call that theme function with the function theme() like this: `theme('mymodule_fancything', $arg1, $arg2);` (D6) or `theme('mymodule_fancything`, array('arg1' =\> $arg1, 'arg2' =\> $arg2));\` (D7).

Then, that function will figure out which function to call. First, it will check if there is a theme override for the active theme. That means, a function that is prefixed with `themename_` instead of `theme_`. So in our example, `themename_mymodule_fancything`. If it finds that function it will call that and if not, it falls back to `theme_mymodule_fancything`.

As you've seen in the example code, you usually pass a number of arguments to a theme function or a template which contains the data that should be displayed. Sometimes you want to further process/change that information before it's passed to the theme function or the template. Or a module wants to change something of another module. Also because theme functions/templates should not contain any complex PHP processing. Unlike with the mentioned hooks (which can be implemented by all modules and all are called), a theme function can only by overridden once.

That is where preprocess functions come into play. They are invoked by the theme() and receive all arguments passed to that theme function (only in D7) or template. Then they can be altered/extended in any way. There is a large number of rules what preprocess functions are called when but basically, you usually only use one that is specific for a given theme function/template. That looks like this: `name_preprocess_hook(&$vars)`. `name` can be the name of a module or theme and `hook` is the name of the template/theme function. There are tons of examples for preprocess functions in core, search for *preprocess*.

Remember to rebuild theme registry (e.g. with devel.module or by re-saving the theme configuration form).

---
Tags: theming
---


title: Disabling accounts programmatically

text:
# Question
Title: Disabling accounts programmatically
I want to disable user accounts programmatically inside hook\_cron() after a synchronisation job. I don't want to delete the users because of their generated content. But they should not be able to log in and receive any notification-mails and stuff like that.

Should I use the user status field for that? And if so should I use user\_save to change this as I don't want drupal to send out mails to the users (via \_user\_mail\_notify inside user\_save) or just set the status fields inside the db? Are there any other hooks or functions that I would miss doing that?

# Answer
> 1 votes
Updating status through `user_save()` is a good way of doing it.

Also note that when you set status to a value different from 1, `$op` will get set to 'status\_blocked', for which no email will be sent.

---
Tags: 6, users, cron
---


title: A page with custom parameters

text:
# Question
Title: A page with custom parameters
I have a page to do this:

```
Boats/
Boats/Veterans
Boats/Nine
Boats/Used

```

Where \['Veterans', 'Nine', 'Used'\] would be the parameters passed into the URL! I would like to use my page customize

> page--boats.tpl.php

This is a page theme. Currently, I have a white page.

How can I do?

# Answer
I think you are asking about hook\_menu().

what you need is to create an item which has a base of boats, and takes an argument.

```
function mymodule_menu() {
  $items = array();
  $items['boats/%'] = array(
    'page callback' => 'mymodule_boats',
    'page arguments' => array(1),
  );
  return $items;
}

```
> 5 votes

---
Tags: 7
---


title: Setting up catalog taxonomy

text:
# Question
Title: Setting up catalog taxonomy
I'm fighting with pathauto patterns for a particular content type. The content type is bound to a taxonomy (a product catalog). I thought that the taxonomy tree should only hold container items (categories, subcategories, subsubcategories, etc) but not the end-nodes (products), and that it'll be possible to have the following URL pattern, consisting of the container node url + product alias + extension, as in \[taxonomy-alias\]/\[node-alias\].html.

This appears to be a wrong assumption though and causing trouble and bogus aliases. I'm closer to an approach that the taxonomy should descend down to the very product node, and product pages should be tagged with the final taxonomy node.

This however brings up a question: Is this a way to go if a product can fit in more than 1 category? This smells like more maintenance issues later, because if a product were to be removed, we would have to remove it in X places; my intuition tells me it's not the right way.

Above this all there is a goal to have the URLs and breadcrumb consistent, in sync.

I'm curious to know your opinion and experience in organizing a catalog taxonomy.

# Answer
Your first assumption was right. The taxonomy items should be for categories and the products should be nodes to type product.

It looks like this is not as simple to setup for D6 where you could use

```
[term-raw]/[title-raw]

```

This comment on drupal.org has some helpful suggestions

* Download Entity API
* enable **entity** and **entity tokens**
* Setup a path something like \[node:field-category:name\]/\[node:title\]
> 1 votes

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


# Question
Title: Adding wysiwyg (ckeditor) to textarea on node edit form
I'm trying to add wysiwyg to a textarea added through CCK.

In my hook\_form\_alter I can alter the properties of the field no problem. Using this it seems like it should be possible to add 'format' to the element and then use filter\_format, it's adds the filter select information but seems to break the body implementation of wysiwyg.

Documentation seems to be pretty sparse on this topic, does anyone know the correct way of implementing this or any complete documentation?

# Answer
> 1 votes
I usually do this by installing better formats module. This give you the option to set the default format for a cck field when you create it.

---
Tags: 6, wysiwyg
---


# Question
Title: Does this look right for adding a terms of use checkbox to register form?
And also, how can I get node/terms to open target="\_blank"?

```
<?php

function MYMODULE_form_alter(&$form, $form_state, $form_id) {
    if($form_id == 'user_register') {
  $form['legal'] = array(
      '#type' => 'fieldset',
      '#title' => t('legal'),
    );
  $form['legal']['select'] = array(
      '#type' => 'checkbox',
      '#required' => TRUE,
      '#title' => t('Terms of Use<span class="form-required" title="' . t('This field is required') . '">*</span>'),
      '#default_value' => 0,
      '#description' => t('I certify that I am over the age of 18, and I have read and agree to the '.l('Terms of use.','node/terms').''),
    );
  $form['#validate'][] ='customfunctions_form_validate_custom';
  }

}

function MYMODULE_form_validate_custom($form, &$form_state) {
    $legal = $form_state['values']['select'];
    if ($legal == 0) {
        form_set_error('select', 'Please check the agreement.');
    }
}

?>

```

# Answer
Yes, but I would change

```
$form['#validate'][] ='customfunctions_form_validate_custom';

```

to

```
$form['#validate'][] ='MYMODULE_user_registration_form_validate';

```

and

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

```

to

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

```

Nothing wrong with your code, but this just keep with the Drupal naming convention ie search\_form\_validate, node\_form\_validate, etc

Also

```
'#title' => t('Terms of Use<span class="form-required" title="' . t('This field is required') . '">*</span>'),

```

is bad

```
'#title' => t('Terms of Use') . "<span class='form-required' title='" . t('This field is required') . "'>*</span>",

```
> 0 votes

---
Tags: 6, users
---


# Question
Title: Internal Server Error - Downloading attachments
I've recently migrated a Drupal 6.22 site from my local host (Xampp 2.5) to a remote, shared server - Fasthosts hosting services.

After uploading the files through ftp and importing the database, I couldn't access the site at all - it would return a 500 Internal Server Error. Trawling the Drupal forums and searching online, I found out that this was down to the .htaccess file, which I subsquently removed.

This allowed the site to load, but only the homepage. I then found a .htaccess file in the Drupal forum which someone had edited and I uploaded that, which gave me full access to the site - good times! However, after performing a walk-through of the site, I've found that I cannot download any of the attachments I've uploaded to some of the pages.

Is this a .htaccess issue? I've trawled many forums and posted several questions around the place, but no one has given a response yet. My mate highly recommended StackOverFlow, so I hope someone can help!

I've checked the server logs and it's states the error is that the file is not found! But I've deleted and re-uploaded then several times now.

Can anyone advise?

# Answer
Drupal can put .htaccess files in some folders. It is likely that something in your Apache setup is different and the .htaccess files are no longer valid on your new server.

Removing the .htaccess file from the sub folder could leave you open to hacks, so it may be worth looking to see what it was trying to do and make sure that you are secure.
> 1 votes

---
Tags: 6, migrations
---


title: How do I hide the code of my theme?

text:
# Question
Title: How do I hide the code of my theme?
Is it possible to hide the code of the theme that I have created for my client? In other words, when I open the page with firebug I dont want to see the HTML and all the CSS of my theme, also when I click with the right mouse button.

# Answer
> 1 votes
No, the browser needs to download the markup and stylesheet to do its job, and you shouldn't try this kind of thing, It doesn't work and is annoying to site visitors.

Please read the answers on this similar StackOverflow question: https://stackoverflow.com/questions/6597224/how-to-hide-html-source

---
Tags: theming
---


# Question
Title: How do I add a span class to form item title in register form?
```
'#title' => t('I have read and agree to the') . "<b><a href='/terms' target='_blank'> terms of service</a></b>",

```

How do I add a span class to the whole title, so It would end up like so:

```
 <span class="myclass">I have read and agree to the <b><a href='/terms' target='_blank'>terms of service</a></b></span>

```

# Answer
> 0 votes
You can use the following code:

```
'#title' => '<span class="myclass">' . t('I have read and agree to the <b><a href="@terms" target="_blank">terms of service</a></b>', array('@terms' => url('terms'))) . '</span>',

```

---
Tags: 6, forms
---


# Question
Title: Easiest way to make body of text wrap around image
I would like to have a body text wrap around the the image below. Here is an example:

http://www.fareham.ac.uk/events/2011/06/creative-arts-summer-exhibition

And here's an excerpt of the code:

```
<div class="content">
  <div class="field field-type-date field-field-event-date">
    <div class="field-items">
      <div class="field-item odd">
        <span class="date-display-single">Fri 24 Jun 2011</span>
      </div>
    </div>
  </div>
  <p>
    Don't miss your chance to see the incredible artwork produced by this year's Creative Arts students at Fareham College.
  </p>
  <p>
    The exhibition will be held on the College campus, featuring work from our Art, Graphic Design, Photography, Fashion and Media students.
  </p>
  <p>
    This event runs on weekdays from 10am–4pm on 24th June–1th July 2011 in both the A-Block and the Function Room at Fareham College.
  </p>
  <p>
    We look forward to seeing you.
  </p>
  <div class="field field-type-filefield field-field-event-image">
    <div class="field-items">
      <div class="field-item odd">
        <img class="imagefield imagefield-field_event_image" width="188" height="266" alt="" src="http://www.fareham.ac.uk/sites/default/files/creative-arts-summer-exhibition.jpg?1310378590">
      </div>
    </div>
  </div>
</div>

```

How can I get the with the text in to wrap around the with image in?

Thank you.

# Answer
> 1 votes
Put the field before the text and apply a float class to the field.

```
.field-field-event-image {
float: left;
}

```

# Answer
> 1 votes
I would overriding the node template for this content type.

This can be achieved by copying the node.tpl.php file and renaming it to something like

node-event.tpl.php (change event to the machine readable name of the content type)

You can then output the fields manually in whatever order you need them along with your markup.

I find the easiest way of working out the variable names is by installed the Content Templates module which lets you see the variables going to that node template.

Hope this helps.

---
Tags: 6, theming
---


title: Drupal theme bare minimum

text:
# Question
Title: Drupal theme bare minimum
I'm looking for the most absolute basic way to create a custom theme. By this I mean, what are the absolute bare minimum requirements for Drupal to run my theme. So, basically, I guess what files does Drupal need and what settings absolutely need to be specified? I tried looking at the Theming Guide over at drupal.org but I didn't find it to be very helpful.

Cheers.

# Answer
If you're using D7, it ships with the stark theme which is a pretty good example of how basic you can get.
> 9 votes

# Answer
You need a .info file to tell about your theme. That should be enough or you might need to include an empty template.php file as well.

The rest you don't need which are

* template files (.tpl.php)
* CSS files
* JS files
* Theme overrides located in your template.php file.
> 2 votes

# Answer
Check out Creating a CSS-only theme, which shows you how to make an entire theme with basically two files (minimum): a .info file and a .css file.
> 2 votes

# Answer
Checkout the omega theme. It has everything you need and a pretty good backend interface to start.

There's lots of great documentation on the omega theme website as well on how to get started and theme your website.
> 0 votes

---
Tags: theming
---


# Question
Title: Is there a way to know the node being viewed?
I have a context where I'm placing a block onto a wiki page. Is there anyway for the block to know the node id of the wiki page?

I'd like to write some code in the block's views-view--block--field.tpl.php template file to display something only to the wiki page's owner. With the block being placed on the wiki's page via context, the block needs what node(wiki) page it is displaying and who the node's owner is.

# Answer
Wow - I just got a reply back from Acquia support that answers the issue. menu\_get\_object() seems to be one of those magically functions I never knew about. Neat.

```
global $user;
$node = menu_get_object();

if ($node && $user) {

  print '<br/>node uid = ' . $node->uid;
  print '<br/>user uid = ' . $user->uid;

  if ($node->uid == $user->uid) {
    print t('<br/>You are the author of the current node.');
  }

}

```
> 1 votes

# Answer
I think the best way to achieve this would be to use nodereference to reference the content type for the block to the wiki page, and then create an argument in views to limit display to current user.
> 0 votes

# Answer
I would use `hook_node_view()` as well but it depends.
> 0 votes

---
Tags: 7
---


# Question
Title: Ubercart or learn a new ecommerce package?
Im a big Drupal fan which is why Ubercart is the obvious choice for me when it comes to ecommerce. Ive made a couple of Ubercart sites and I havn't been massively impressed.

Ubercart doesn't seem very powerful when you need extensive business logic, can be hard to theme and has javascript reliance. Admittedly ive only played with others like magento and zencart, but Ubercart doesn't seem to lead in its field the way Drupal does in its.

Im reluctant to learn a new ecommerce package due to the time required, but the javascript reliance alone makes me wonder if I have to. Has anyone else had a Drupal background and faced a similar dilemma with ecommerce?

Thanks

# Answer
*Disclaimer I help develop commerce (commit patches) from time to time and maintain a few commerce modules, so I might be a bit biased in my opinions*

I haven't done ecommerce outside of Drupal, but I have extensive experience with both (Ubercart) Drupal 6 and (Drupal commerce) Drupal 7.

Drupal commerce has a lot of great advanced both for developers and site builders.

Since it has heavy views and rules integration, it makes it very easy to configure the modules to do what you want to do. With Rules you can add a lot of custom logic like discounts. The tax support is also very good already and is very easy to customize for your location.

The only things that's missing with Drupal commerce right now is the host of modules for various stuff compared to ubercart Drupal 6. But this is not as bad as it might sound, and there are a lot of modules being created in the community around commerce.

For developers the experience developing with commerce is the best I've tried for a long time. I started when commerce was still in alpha and have had to deal with API's chaining etc. This has all stabilized now, and the result is very impressive. You can tell that commerce is built from the ground up by people who know how commerce should be made with Drupal. It's very flexible and there's no inconstancy and strange hacks like there is in ubercart. One area in particular where there is a big difference is the price handling system is very cleverly built. Commerce is built to handle multi currency unlike ubercart which I've found to be a major pain.

**Conclusoin**

All in all I find that commerce is more powerful out of the box using only the UI, and the code you write is in my experience generally more clean and easier to maintain. It doesn't have any legacy code, which is easy to see and it is built to take advantage of all the new Drupal 7 features.
> 2 votes

---
Tags: ubercart
---


title: A user-centric multi-site installation

text:
# Question
Title: A user-centric multi-site installation
How do I go about creating a similar content-structure as wordpress.com?

* I want the user experience to only be of the sub-site (sub-site.example.com) and not of the main website (example.com). E.g. the home link goes to the sub-site, like this http://fiveandspice.wordpress.com/
* In my case I will not offer blogs, but a web-application.
* I'm thinking of utilizing Drupal for the user-system to handle the subscription-based accounts and generating the web pages.
* The account-owners will have visits to their "page", and those visitors in turn would as well need account to do certain actions. Similar to how Basecamp work.

# Answer
> 1 votes
You can do this with the Aegir hosting System http://www.aegirproject.org/ It presents an intuitive front end to multisite.

# Answer
> 1 votes
You can also use the Subdomain module. Here is a quote about it (from the module's project page):

> Automatically creates subdomains and places content on them. There are 4 modes:

---
Tags: nodes, multi-sites
---


title: Change text-format through the theme

text:
# Question
Title: Change text-format through the theme
Is it possible to change the text-format (display output only) of a long-text field through the theme in Drupal 7? Similar to the way you can override the imagecache output for an image. The reason I don't want to change the database value is because the user role doesn't have permission for the desired output (full\_html), but I'd like to have this output on a specific content-type - benefit 2 is that the user doesn't have the input/text format options on the form.

# Answer
First of all you should be aware that if you were to display the input of a input like is was full HTML, it would be the same thing as giving the user who created the content access to using the full HTML filter. The only difference is that you wont tell the user that he can type full HTML. This could potentially open your site to exploits, if people write harmful HTML. You should instead give users access to the filters that you want to use for their input.

Now if you want to display any text through any filter, you can do that by using check\_markup. You simply pass the text and filter id to the function and it will return a text you can use on your site.
> 3 votes

---
Tags: entities, input-formats
---


# Question
Title: How to add new items to existing menu using custom module
Is there any way to add new items to an existing menu using custom module in Drupal7.

# Answer
> 1 votes
For Drupal 6 you do use menu\_link\_save:

```
$item = array(
  'link_title' => 'Menu title',
  'link_path' => 'menu/path',
  'menu_name' => 'menu_name',
  'module' => 'your_module',
);
menu_link_save($item);

```

---
Tags: routes
---


title: imagefield and temp files?

text:
# Question
Title: imagefield and temp files?
I am using imagefield and D6 with filepaths to upload images to a custom directory using a custom token.

I'd like to validate whether an image that was uploaded is the same as another image in the repository.

I see that imagefile appears to be uploading the file to: default/files/, then deleting it there and saving in the directory I specify using my custom token.

Is default/files where imagefield is saving the file as a "temp" file until validation passes? I would think it would save a temp file in the temp file location specified by php.ini. If the later is true, can I get a hold of the tmp name in $form\_state? I believe with image module, I could get the temp name of the file from $form\_state, but I don't see that info using imagefield. Thanks in advance.

# Answer
> 1 votes
In file settings you specify a temp path and a files path, which is what is used by Drupal.

The temp path which could be `/tmp`, but it could also be `default/files` that is entirely up to you. the temp file folder is where files are uploaded to after being submitted in a form. After validation checks, `file_save_upload` should be used to save the file. There is no reason for the file to be saved to the `default/files` folder and then be moved, as it can be saved directly to whichever folder you want. I do believe that is how the imagemodule does it..

---
Tags: media
---


title: Can't send email with Bulk Operation?

text:
# Question
Title: Can't send email with Bulk Operation?
*Drupal 6 site running on remote server.*

I created a **View** of the User type. Then I create a display to show all users of my site. I set the Style of the display to **Bulk Operation** and in Selected operations I checked: `Send e-mail (system_send_email_action)`

In **Fields** I added the `User: E-mail E-mail` and other fields

Now I go to the path where I can see my users, I select one user (John) and click in `send email` under Bulk operation. I continue to complete a send the email and finally I get the message: `1 rows processed in about 23 ms:
Performed Send E-mail on user John.`

I understand that the email is sent to John user email from the administration site email.

But I don't receive the email. The email is not **really** sent.

I have a Webform node in my site which send email with no problems. So, I know there is nothing wrong with my server setting.

Thanks for any help

# Answer
Just given it a quick test with VBO 1.10, and as you said, emails are not being sent. Also, got "Cannot use %author token in this context." error in log.

See this issue - http://drupal.org/node/1003354 \- "Can't sent email (or 'send tokenized email') on a user view. Reverting to 6.x-1.9 works" - seems that 1.9 should work better, or - if dev is acceptable to you - 6.x-1.x-dev

Or use Views Send instead (http://drupal.org/project/views\_send)
> 3 votes

---
Tags: emails, views
---


# Question
Title: Regcode/OG Issue - Need D7 Equivalent of og_all_groups_options()
I'm trying to use the Registration codes module to automatically assign users to an organic group when they login with a registration code.

For Drupal 7, it appears that the Registration codes module is still using a Drupal 6 function (`og_all_groups_options()`) that is supposed to list all organic groups on a form.

I need to know the D7 equivalent of this function; I can't seem to find it.
Do you have a suggestion for how I could print out a multi-select option list of organic groups like `og_all_groups_options()` did?

# Answer
The closest one seems to be `og_get_all_group()` in og.module.
> 1 votes

---
Tags: forms, organic-groups, users
---


# Question
Title: Drupal 7 Webform settings: how to change the default text in button "next page"?
I have created a webform with drupal 7 with two pages with "pagebreak" field, but when i go in mysite webform and i view the webform at the bottom of the page there is the button "next page": i have to change the text in this button... and also probably set an image at the place of simple text "next page".. Thank you !

# Answer
You can use hook\_form\_alter to alter things in forms like button texts. This can in drupal 7 be done in both the theme and a module, but in Drupal 6 it can only be done in a module.
> 1 votes

---
Tags: 7, theming, forms, webforms
---


# Question
Title: Drupal 7: Custom content types become un-editable and do not output correctly
I've had the following problem a few times and can't find a satisfactory answer to it anywhere.

* I create a new content type
* add content for this new type
* then, when the system displays the finished content after save, all of the new fields are missing (yes I made sure they were set to 'display' in the manage display tab)
* on editing this new node, none of the fields display, all I get is the node title field and the tabbed options (eg comments, create version, menus etc)

I've read that this is caused by a permission problem. That sounded good, so I checked the permissions after creating the new content type and sure enough, there were no boxes checked for the new content type.

I checked all of the boxes for the admin role for the content type and still nothing. I've rebuilt the permissions and cleared the cache. Still nothing.

# Answer
Dylan - have you looked here? http://drupal.org/node/1029230
> 1 votes

---
Tags: users
---


# Question
Title: How to make content of a (cck) field visible when pressing a button?
I am working on a Drupal 7 website and I would like to create a node where a specific (cck) text field is only shown to the users after they press a button.

The effect I would like to achieve is exactly the same you can find in the Careers 2.0 website where, at the end of each job post, there is a button titled "Find out how to apply". When you click on this button the "how to apply instructions are shown". To see how it works you can check http://careers.stackoverflow.com/jobs/10860/foursquare-software-engineer-scala-lift-foursquare?campaign=Featured.

Can somebody please help?

Thank you so much!

# Answer
> 1 votes
Javascript you would need is

```
(function ($) {
  $(document).ready(function() {
    if ($('.togglebutton').length) {
      //hide box if there is a button to toggle it on
      $('.cckfield').toggle();
    }
    $('.togglebutton').click(function() {
      $('.cckfield').toggle();
    });
    $('.togglebutton').css('cursor', 'pointer' );
  });
})(jQuery);

```

there is many places where you can add this script. The first one that comes to my mind is `MYTHEME_preprocess_node(&$variables)` in MYTHEME/template.php file

```
MYTHEME_preprocess_node(&variables) {
  if ($node->type == 'jobposting') {
    drupal_add_js(drupal_get_path('theme', MYTHEME') . '/name-of-js-file.js')
  }
}

```

# Answer
> 1 votes
The best way to do this is in the theme. Simply add the CSS and JS needed for this effect. Should be pretty simple as all fields has unique ids.

---
Tags: 7, nodes
---


# Question
Title: How to I retrieve default checkbox values using Form API?
**How do I retrieve saved checkbox values from a field using the FormAPI?**

The form/node saves successfully, and when I look in the DB, the data was successively saved in the 'field\_data\_field\_test' table, but I can't figure out how to pull that back out and apply the 'checked' status using #default\_value.

`$form['field_test']['und']['#default_value'] = $How_Can_I_Get_This_Data_From_DB`

Is there a function I can use to retrieve checked values for a given field within a given node? I'm trying to avoid direct queries. :)

Edit:

Ended up using

```
function _get_review_site_defaults() {
    $query = new EntityFieldQuery;
    global $user;
    $result = $query
            ->entityCondition('entity_type', 'node', '=')
            ->entityCondition('bundle', 'field_test', '=')
            ->propertyCondition('uid', $user->uid, '=')
            ->propertyCondition('status', 1)
            ->execute();
    if (count($result) == 0) {
        $defaults = array(1);
    } else {
        $entities = entity_load('node', array_keys($result['node']));
        foreach ($entities as $key => $value) {
            if ($value->field_default_field_test[$value->language][0]['value'] == 'Yes') {
                $defaults[] = $value->nid;
            }
        }
    }
    return $defaults;
}

```

# Answer
> 1 votes
after you save it, it saves the value of the checkbox as #value (not #default\_value).

When defining the field settings: (pulled from D7 cck\_table.module)

```
  $form['css_class'] = array(
    '#type' => 'textfield',
    '#title' => t('CSS Class'),
    '#description' => t('Specify a class to be added to the table element.'),
    **'#default_value' => isset($field['css_class']) ? $field['css_class'] : '',**
  );

```

**Revised**:

More likely you would want to do this:

If you want to grab the default values, you can call \`field\_info\_field($field\_name

> Returns data about an individual field, given a field name.

---
Tags: forms
---


title: Best way for implement 'Site Gate'

text:
# Question
Title: Best way for implement 'Site Gate'
I try to add 'site gate' to http://bartenderlab.it. It's alcohol content so people under 18 are not allowed to view this site.

I created module with hook\_init:

```
function gate_init() {

    $curr_uri = request_uri():
    if (strpos($curr_uri, '/gate') === FALSE) {

        if (! isset($_SESSION[GATE_SESSION_NAME])) {

            if (! isset($_COOKIE[GATE_COOKIE_NAME])) {

                    if(strlen($curr_uri) > 1) {

                        drupal_goto('gate', array('destination' => substr($curr_uri, 1)));

                    }
                    drupal_goto('gate');

            } else {

                $_SESSION[GATE_SESSION_NAME] = TRUE;

            }
        }
    } else if(isset($_SESSION[GATE_SESSION_NAME])) {

        drupal_goto('<front>');

    }
}

```

Under /gate url is form with:

```
function gate_form_submit($form_id, &$form_state) {

    $post = $form_state['values'];
    $day = intval($post['gate_day']);
    $month = intval($post['gate_month']);
    $year = intval($post['gate_year']);
    $isRemember = $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);

        if($min_born_time >= $born_time) {

            $_SESSION[GATE_SESSION_NAME] = TRUE;
            if($isRemember) {

                setcookie(GATE_COOKIE_NAME, sha1($born_time + srand()), time() + 60 * 60 * 24 * 7, '/');

            }
            $dst = '<front>';

            if(isset($_GET['destination'])) {

                $dst = $_GET['destination'];

            }

            drupal_goto($dst);
        }
    }
}

```

If checkbox for $isRemember is not checked user should only view site until browser close.

so I set:

```
ini_set('session.cookie_lifetime',  0);

```

in settings.php

But after restart browser gate page doesn't appear.

Also after user logout I am redirect to gate page instead of front page.

Please help.

# Answer
Have a look at Disclaimer module; it seems to be the functionality you're looking for.
> 3 votes

# Answer
The nice code I have which work is:

```
function gate_init() {
    global $user;

    $curr_uri = request_uri();
    $request_type = substr($_SERVER['HTTP_ACCEPT'], 0, strpos($_SERVER['HTTP_ACCEPT'], ','));

    if($request_type == 'text/html') {

        // check if the user is going to logout and have gate enabled
        if($curr_uri == '/' && $user->session == '' && isset($_COOKIE['keep_logged_in']) && $_COOKIE['keep_logged_in'] == 1) {
            _gate_allow_entrance();
            setcookie('keep_logged_in', '', time() - 42000, '/');
        }

        // maybe they have cookie set before
        if(isset($_COOKIE[GATE_COOKIE_NAME]) && $_COOKIE[GATE_COOKIE_NAME] == TRUE && !isset($_SESSION[GATE_SESSION_NAME]))
            _gate_allow_entrance();

        if($curr_uri != GATE_URL) {
            if(!(isset($_SESSION[GATE_SESSION_NAME]) && $_SESSION[GATE_SESSION_NAME] === TRUE))
                drupal_goto('gate');
        }

        // if there is a gate key and logout was called, then keep the key within next request
        if($curr_uri == '/logout' && isset($_SESSION[GATE_SESSION_NAME]) && $_SESSION[GATE_SESSION_NAME] === TRUE)
            setcookie('keep_logged_in', 1, time() + 10, '/'); // only for 10 seconds

    }

    return true;
}

```
> 0 votes

---
Tags: 6, users, redirection, cookies, sessions
---


title: How can I use this code?

text:
# Question
Title: How can I use this code?
I'm trying to get this code to work in Drupal 7.

```
$(document).ready(function(){

  $("#sample").mouseover(function() {
    $(this).animate({ backgroundColor:'#f00'},1000); }).mouseout(function() {
    $(this).animate({ backgroundColor:'#ccc'},1000);
  });

});

```

For some reason, when I paste it into the front--page.tpl template, it doesn't work.

I've also tried including a JavaScript file into the template.php file.

# Answer
jQuery in D7 is in noConflict mode. You need to use jQuery instead of $, or a closure. See http://drupal.org/node/171213
> 5 votes

# Answer
> All animated properties should be animated to a single numeric value, except as noted below; most properties that are non-numeric cannot be animated using basic jQuery functionality. (For example, width, height, or left can be animated but background-color cannot be.)

The .css() function doesn't queue behind running animations, it's instantaneous.

To match the behaviour that you're after, you'd need to do the following:

```
(function($) {
  $(document).ready(function() {
    $(".box_teaser").mouseouver(function() {
      var p = $(".box_teaser").css("background-color", "yellow");
      p.hide(1500).show(1500);
      p.queue(function() {
        p.css("background-color", "red");
      });
    });
  });
})(jQuery);

```

The .queue() function waits for running animations to run out and then fires whatever is in the function supplied.
> 1 votes

# Answer
Or try:

```
$(document).ready(function(){
  /* your function inside here */
});

```
> 0 votes

# Answer
Try in this way: create your script example.js that have this code for example:

```
**var $ob= jQuery.noconflict();
$ob(function(){

```

$ob("a").fadeOut(); });\**
> -1 votes

---
Tags: 7, javascript
---


title: Drupal speed issues

text:
# Question
Title: Drupal speed issues
I've just moved my Drupal 6 site to a VPS, and it's running terribly slowly. Things like running update.php and flushing the cache can take around 10 minutes, which was not the case when the site was running on a shared server. I'm guessing this points to a server issue?

I just don't know where to start in order to debug this, not being at all great at server admin. Has anyone got any ideas about how to identify what the issues could be?

# Answer
> 3 votes
There are a number of things you can do on this front, both in testing and in tweaking the performance.

On testing one of the first things you should do is enable the core "Database logging" module which will help you find hidden errors in the system (it could be a bunch of php errors caused by missing php extensions or bad settings). It could also be the database connection and this can record the queries so that you can run them manually. You should also enable the core "Syslog" module.

The Devel module also includes a few other modules including performance logging and code review, both of which can help with the troubleshooting problem.

The next thing you should do is setup a test lamp environment on your local machine (your computer) that has the same php settings and extensions and see if it has the same problem. If it does then the problem may not have anything to do with the database.

Now on to improving overall performance...

First you will want to enable the "Throttle" core module. This will enable content throttling. The primary thing you can do though is in admin \> Site Configuration \> Performance you should enable the normal caching mode. Also enable page compression and optimize the CSS and JS.

Another tool that might help your site user experience a bit is using the ImageCache module to deliver custom sized, cached images.

Then there is PressFlow. Now this is actually a custom build of the Drupal core files that are optimized specifically for use in PHP 5 only and with only MySQL. It uses improved function calling and structures as well as improved database queries. To use it you simply download the version that is compatible with your version of Drupal and replace your core Drupal files with PressFlow's. As they say on their site "Pressflow makes Drupal scale".

Check out Pressflow here: http://fourkitchens.com/pressflow-makes-drupal-scale

I hope that helps!

# Answer
> 4 votes
Try to debug it outside of Drupal first. See how long it takes to serve a pure HTML page, then a HTML page with a bit of PHP in it. Then try a PHP script that does several simple queries to the database. I'd personally bet on the database being the problem.

In Drupal you can install the Devel module which gives you stats for every query run, so that should be helpful as well.

---
Tags: performance, migrations
---


title: Caching in Drupal 7

text:
# Question
Title: Caching in Drupal 7
How should I set my Drupal web for better performance when I'm already satisfied with my theme and won't do many new theme adjustments?
The settings is probably in `admin/config/development/performance`

thank you

# Answer
> 1 votes
If you don't anticipate important theme changes in the near future, you can well extend the cache expire time of your asset files like CSS and image files to multiple hours. You can do this via Expire rules in .htaccess.

For optimal efficiency, I'd recommend installing a Varnish proxy cache that accepts requests on port 80 and forwards them to Apache (running on another port, say 81). Varnish will then cache and deliver your asset files for multiple hours, thus reducing the load of the web server heavily. After installing and configuring Varnish and Apache, visit the performance page to also activate external caching of pages and set the page cache lifetime to a value you deem sensible.

We've seen huge improvements in page delivery time and server load by including Varnish in our Drupal hosting packages.

# Answer
> 0 votes
You can swap out the default drupal caching mechanism for a memcached Implementation, also you could try using a nginx instead of an apache.

The perceived page load is also affected by the order in which the ressources on your page load. For example: If the Browser loads a page, it starts from top to bottom. CSS loads non blocking, which means that the browser does not have to wait while loading and executing the CSS. Javascript however is blocking, the browser has to load and execute every Javascript file one by one. Because of this it is recommended to put large javascript files which do not interact with the page before the onload Event is fired in the bottom of the page (right before the closing tag).

---
Tags: 7, caching
---


title: Profile Fields in D7?

text:
# Question
Title: Profile Fields in D7?
How do you add fields to a user in Drupal 7 for say, first and last name? I see that Profile is deprecated, is there an easy way to do this without using Content Profile?

# Answer
> 9 votes
You can directly add fields to users (at admin/config/people/accounts/fields) if that's all you need. You can set for each field if it should show up on the registration form.

What Profile2 allows *additionally* is to create multiple profiles for each user, similar to the categorization feature of the core profile.module.

# Answer
> 3 votes
There is Profile2.

---
Tags: 7, users
---


# Question
Title: Are the parameters of saved exposed Views filters saved in the database, and if so, how can I access it?
So in a View (using Views 3) we can expose filters and these filters are "saveable" by particular users, where is this saved, and can I access it?

I want to be able to "save" the parameters and then be able to email the user later with updated search results periodically...

I'm assuming that if no filters have been applied, the view will display all of the content...

# Answer
> 1 votes
Use Saved Searches

> Saved Searches provides a simple workflow for saving search queries from Drupal core search. It will take advantage of Apache Solr facets, if the Apache Solr Search Integration module is installed.
>
> Saved Searches gives users with permission access to a "save this search" form in a block, which appears on search result pages, and lists the user's saved searches in another block. Depending on a user's permissions, Saved Searches will provide a simple "Save this search" button, a text field for entering a short URL slug, and/or a dropdown to "Re-use an existing saved search name". Clicking the "Save this search" button without entering a URL slug will generate a short URL for the search, like "http://example.com/s/cwmc". A link to the search will appear in the savedsearches\_user block.
>
> Saved Searches is useful for sites with complex search options, or sites where users may want to revisit or share dynamic sets of search results.

---
Tags: views
---


# Question
Title: How to add custom Views filters (for example, date between X & Y, but specified by myself)
As per title. I am aware that there is a specific filter for date between X and Y, but if I wanted to programmatically develop it, what ways are there to do this?

EDIT : To be more specific, I am using Views 3 so that I can use apache solr views on Drupal 6.

# Answer
Date ranges in solr views still being worked on - see http://drupal.org/node/642430 for latest patch from July 11 2011
> 1 votes

# Answer
Check out http://www.hashbangcode.com/blog/creating-custom-views-filters-exposed-form-element-drupal-6-561.html. Maybe this helps you.
> 0 votes

---
Tags: views
---


title: Get variables from checkboxes

text:
# Question
Title: Get variables from checkboxes
I'm creating my very first Drupal module (Drupal 7, btw) and I'm almost done with it. There is one last thing and that is that I need to get the values from multiple checkboxes.

My module list certain nodes and each of them gets a checkbox using a foreach $nid. All using the Form API.

Now, when the form is submitted, only one (1) value is returned - and as of now, not even the one that I check, but the last nodes ID.

Perhaps it is because each new value replaces the previous(?). Or something is wring with my code. Someone in the IRC channel told be that the forms checkbox returns an array of the values, but I'm trying to use foreach of that value, without any success.

What could be the problem? Here is my code - shorted down.

```
function my_module_cmp($a, $b) {

  $a = (array) $a;

  $b = (array) $b;

  return strcmp($a['name'], $b['name']);

}

function my_module_form() {
$url = taxonomy_get_term_by_name(arg(1));
foreach($url as $term) {
    $tid = $term->tid;
}
$term = taxonomy_term_load($tid);
$name = taxonomy_term_title($term);
$terms = taxonomy_get_tree(3,0,1);
usort($terms, "my_module_cmp");
$counter = 0;
$result = taxonomy_select_nodes($tid);
foreach($result as $nid) {
    $form[$nid] = array (
        '#type' => 'fieldset'
    );
    // title
    $form[$nid]['title'] = array (
        '#markup' => '<div class="title"><a href="/'.$nid.'">' . $node->title . '</a></div>',
    );
    // checkbox
    $form[$nid]['company'] = array (
        '#type' => 'checkbox',
        '#title' => t('Check the nodes balbla'),
        '#title_display' => 'attribute',
        '#return_value' => $nid,
        '#default_value' => 0,
        '#prefix' => '<a class="checkbox">Skicka förfrågan till företaget >>',
        '#suffix' => '</a>',
    );
$counter++;
}
return $form;
}

    function my_module_form_validate($form, &$form_state) {
// Validate that a company has been checked, at all
$valid_company = $form_state['values']['company'];
    if (!$valid_company) {
    form_set_error('company', 'Forgot to check something');
    }
}

function my_module_form_submit($form, &$form_state) {
$company = $form_state['values']['company'];
drupal_set_message('<pre>'.print_r($form_state['values'], 1).'</pre>'); // Check out the values

foreach ($company as $nid) {
    // Get the node from nid
    $node = node_load($nid);
    // Get the author of that node
    $user = user_load(array('uid' => $node->uid));
    drupal_set_message(t('DEBUG node:'.$nid.', user: '.$user->name.','.$user->mail.'')); // TEST

    // Check if the mail has been sent and show a message based on that
    if (drupal_mail('my_module', 'token', $user->mail, language_default(), $message, $from, TRUE)) {
        drupal_set_message(t('Offert been sent %name',array('%name' => $user->name)));
    }
    else {
        drupal_set_message(t('Error'));
    }
}
}

```

# Answer
Your problem is that you have named the chechboxes the same thing which is why you only get one value.

You could replace `['company']` with `[$nid]` or use `'#tree' => TRUE` on the field set to make the values turn into a nested array.
> 1 votes

---
Tags: 7, forms
---


# Question
Title: Devel kpr, dpr, dpm, etc. only print after cache flush
I'm writing a small module and using the Devel print functions (dpr, kpr, dpm, etc.) to print out some values.

However, I only see the values in the page after I flush certain caches. if I just reload the page or go to it I see nothing. This is true for both the message-area and the regular debug print functions. Is this expected?

I am logged in as admin so I'd think ordinary page caching is off.

(This is in D7.)

# Answer
hook\_field\_widget\_info\_alter() is cached. Follow these steps to Suppress caching (for development) or to use an external page cache

> when developing for Drupal you might want to suppress all caching of data to make sure new hooks, theme functions, etc are recognized immediately.
>
> This will have performance detriments, of course, so must not be used in production. To turn on this development mode, add the following to your Drupal 7 settings.php file:
> 4 votes

---
Tags: 7, debugging
---


# Question
Title: Add Additional Logic To Node Save/Submit Process
Where can I hook into drupal to modify the value of a specific field just before it is inserted into the database?

For example, lets say I wanted to trigger an email or run an arbitrary piece of code just before the node is inserted into the database?

I've been looking at hook\_node\_presave and it looks like it will do what I want, but I need it to only apply to one content type.

# Answer
You can probably use either hook\_entity\_presave(), hook\_node\_presave() hook\_field\_attach\_presave(). These hooks are all pretty similar right now. Actually not sure why there are 3 of them :)

Simply add a check for the content type and/or the existense of the field you want to alter.
> 1 votes

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


title: form_alter correct coding question

text:
# Question
Title: form_alter correct coding question
```
function MYMODULE_form_views_exposed_form_alter(&$form, $form_state) {
 if ($form['#id'] == 'views-exposed-form-search-page-1') {
 $form['submit']['#value'] = 'Go';
 $form['text']['#size'] = '100';
  }
}

```

In the code above, which is the correct way:

```
   $form['submit']['#value'] = 'Go';

```

Or

```
   $form['submit']['#value'] = t('Go');

```

And:

```
  $form['text']['#size'] = '100';

```

Or

```
  $form['text']['#size'] = 100;

```

# Answer
Always wrap all strings in t() so that it can be translated. And always use english for strings in the source code because Drupal assumes that it is english. Even if your site is in a different language (You can translate it afterwards through the UI or create .po files).

The other one doesn't matter. Technically, it's an integer, so without quotes but it will be converted to a string when displayed anyway.
> 2 votes

---
Tags: 6, forms, hooks
---


# Question
Title: How do I get the name of the content type?
in Drupal 7, which function do I need to call to get the name of the content type? I have the $node object and I also have the id of the content type if I use `$node->type`. But I need to get the name of the content type set in the system, not the ID as something like 'name\_of\_the\_content\_type'. I need it as 'Name of the content type'.

Thank you.

# Answer
Try calling this function

node\_type\_get\_name($node)

> Returns the node type name of the passed node or node type string.
> 19 votes

---
Tags: 7, nodes
---


# Question
Title: Search page summary customization using views
I can figure out how to create a search results page using views in Drupal 7. What I cannot solve is how to format it the same way as a search results page with two lines of summary text and the keyword(s) in bold. Do I have to use the "fields" display?

# Answer
> 1 votes
Yes you need to use fields. One for the title, one for the teaser and any additional fields you want to add in. You can configure the amount of text that appears in the teaser so you can get your two lines of text.

---
Tags: views, search, theming
---


title: Dynamic webform recipient

text:
# Question
Title: Dynamic webform recipient
I am developing a site which has many advertisers. The idea is to have a specific advertiser emailed when a user shows interest in their product.

To do that, I need to create one webform which will change the recievers address dynamically depending on the advertiser who posted the product of interest.

It sounds like a custom module solution but I need the opinion of those who know better than I do.

Thanks

# Answer
As it turns out, webform 3 has the ability to create an email component which will serve as the recipient. All I then did was to copy the desired email address into the email field using JQuery. I did so dynamically on each user page and it works just fine.
> 4 votes

# Answer
Drupal 6 or 7?

I would do a custom module with a simple hook form submit in that webform (that must include some node id for later reference), then checks the node author account to grab his email and use `drupal_mail` to send the notification.

Otherwise, if you really don't want to code, maybe `Rules` module could fit in your case. It's some time ago that I don't use this module and don't remember all the possible triggers.
> 3 votes

---
Tags: webforms
---


# Question
Title: Drupal 7 Views 3 Contextual Filter - preview works as expected, the actual page not, why?
**Background:**

Drupal 7.2, Views 7.x-3.0-rc1

I have a view with a single Contextual Filter, 'User: Full Name'. ('User: Full Name' is a field added to the user, stores the full name of the user, like 'Peter Jackson Junior'.) In this filter's settings, under 'More', 'Case in path' is set to 'Lower' and 'Transform spaces to dashes in URL' is enabled, because the format of the path would be like this: 'site/team/peter-jackson-junior'. 'No results behavior' is set to 'Global: Text', contains 'No such user'. So the result of the view would be the profile of the user that has full name equals to argument in url.

**Problem:**

On the view settings page, when I test it through the preview, it works perfectly, I enter 'peter-jackson-junior' and it returns the profile of 'Peter Jackson Junior'. But, when I would like to see it in practice, and enter the url 'site/team/peter-jackson-junior' (this is actually also shown on the view preview area) in the browser url bar, I get back 'The requested page could not be found.'.

Actually, if I 'provide default value' 'when the filter value is not in the url' that is 'fixed', like 'another-full-name' it works on both the preview and the actual page (so 'site/team' gives back the profile of 'Another Full Name'), but 'site/team/another-full-name' gives back 'The requested page could not be found.' again.

**Question:**

What could be the problem? Could this be a bug?

# Answer
> 5 votes
Found the answer to the problem...

There are path aliases to nodes that were deleted before, and accidentally those aliases look exactly like how the view with arguments should look like. So, there were an alias of 'team/peter-jackson-junior' to 'node/xyz', this overridden the path to the view, but 'node/xyz' was deleted and so it is natural that it gives back 'The requested page could not be found.'.

---
Tags: 7, views
---


title: Drupal user one off settings

text:
# Question
Title: Drupal user one off settings
I am putting together a complex Drupal user driven website. One thing I need to accomplish early on is to put users into groups as they register.

**Can anyone tell me how I can get them to register particular details which they will not be able to amend in the future?** Such data as the users gender etc....?

Thanks.

# Answer
For the user groups, use the auto assign role module and you could use content profile and CCK to create profile fields that the user can fill in. You could use the content permissions module that's a part of CCK to allow a user to create a profile but not to edit certain fields once they've been created.
> 1 votes

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


# Question
Title: How to validate node field for minimum length for a custom content type?
I notice body has some preselectable minimum lengths.

How do I do this for text fields?

Also, how do I set a custom minimum length for node body of a content type?

# Answer
> 5 votes
`hook_form_alter()` would alter your node edit form to define a custom validate handler.

```
function custom_module_form_alter(&$form, &$form_state, $form_id){
   ...
   case 'form_id': //applying this check will help to restrict only on certain content type form
      $form['#validate'] = 'custom_validation_handler';
   break;
   ...
}

```

And when this validation handler is invoke upon submitting the node form it will validate the field value in following logic.

```
function custom_validation_handler($form, $form_state){
   if(strlen($form_state['values']['field_id']) < 200){
       form_set_error('field_id', t('message about validation error'));
   }
}

```

If `form_set_error()` is invoked the form will not be submitted and will be back with validation error message.

---
Tags: nodes, entities
---


title: Minimum comment length?

text:
# Question
Title: Minimum comment length?
I have yet to find a snippet or a solution to enforce a minimum comment length.

Most validation modules deal with fields.

# Answer
> 4 votes
Add a custom validator to form using `hook_form_alter` in your custom module.

```
function custom_mod_form_alter(&$form, &$form_state, $form_id){
  switch($form_id){
    case 'comment_form':
      $form['#validate'] = array_merge( $form['#validate'], array('custom_validator'));
    break;
  }
}

```

Define the logic to restrict the length of comment length

```
function custom_validator($form, $form_state){
    if(strlen($form_state['values']['comment']) < 50)
       form_set_error('comment', t('No No....'));
}

```

---
Tags: comments
---


# Question
Title: How to dynamically change the CSS style of a node-type?
I want to modify dynamically the style of a page in base of your content type: I tried with a preprocess function insert this code:

```
if(isset($variables['node'])){
  if($variables['node']->type=='article'){
    drupal_add_css(drupal_get_path('theme','my_theme').'/css/style_node_article.css');
  }
  if($variables['node']->type=='page'){
    drupal_add_css(drupal_get_path('theme','my_theme').'/css/style_node_page.css');
  }
}

```

This doesn't set the right CSS if I change page from article to page... Thanks

# Answer
> 6 votes
Unless you have a ton of CSS you should add the CSS for all the nodes and use the node type class on the wrapper div of the node.

I can't remember the exact classes you can view them in the source. You could do something like this

```
.node {}
.node-page {}
.node-blog {}

```

Where the first class is on all nodes and the latter is dynamic for the node.

---
Tags: theming
---


# Question
Title: Is Paypal payments pro gateway available for Drupal Commerce
I am aware of the module Commerce PayPal but according to the description it only handles redirects to Paypal and not the Payments Pro gateway which allows site users to stay on the site and have their payment processed by Paypal.

What I'm wondering is - has anybody crossed this bridge? It seems like a pretty major issue for any commerce system worth its salt to address.

I'm also curious if there is any code out there that folks are using which may not be ready for contrib, but could be plugged into the back end of a site.

Are there any development efforts in this direction?

# Answer
> 2 votes
In Commerce Paypal's issue queue, there is a patch that is a start on WPP. http://drupal.org/node/1155768

---
Tags: 7, commerce
---


# Question
Title: how do I get Rounded Corners to work on a ddblock in drupal 7?
I am trying to make the borders of a dd-block that I am using round. They are round in Firefox 5.0, but anything earlier than that, or in any other browser, it doesn't work. I have the CurvyCorners module installed, and I have the CSS set up to make it round. the problem is, that in chrome, only the header is round, and nothing else. and in Internet explorer, everything is round, except the dd-block, making it look like the dd-block is overlapping, and going over and past the corners of the region that it is in (being the Content region).
here is a copy of the CSS that is supposed to be making it round (I used 4 different classes/blocks at the same time just for a single dd-block, and it still won't work!):

```
#block-ddblock-7 {
    margin-left: -10px;
    -moz-border-radius: 20px;
    -webkit-border-radius: 20px;
   border-radius: 20px;
}

#block-ddblock-7 .slider {
     border-radius: 20px 20px;
    -moz-border-radius: 20px 20px;
    -khtml-border-radius: 20px 20px;
    -webkit-border-radius: 20px 20px;
    -o-border-radius: 20px 20px;
    width: 553px;
    height: 332px;
}

#ddblock-container clearfix ddblock-processed .inner {
     border-radius: 20px 20px;
    -moz-border-radius: 20px 20px;
    -khtml-border-radius: 20px 20px;
    -webkit-border-radius: 20px 20px;
    -o-border-radius: 20px 20px;
    width: 553px;
    height: 332px;
}

.slider ddblock-processed  {
    border-top-left-radius: 20px 20px;
    border-top-right-radius: 20px 20px;

    -moz-border-top-left-radius: 20px 20px;
    -moz-border-top-right-radius: 20px 20px;

    -khtml-border-top-left-radius: 20px 20px;
    -khtml-border-top-right-radius: 20px 20px;

    -webkit-border-top-left-radius: 20px 20px;
    -webkit-border-top-right-radius: 20px 20px;

    -o-border-top-left-radius: 20px 20px;
    -o-border-top-right-radius: 20px 20px;
}

```

what is it that I am doing wrong?

this is a picture of basically what it looks like. the part in blue is the "Content" region, and the part in orange is the ddblock:

# Answer
> 2 votes
I've used ddblock before with round corners. I was able to do it all, across every browser, with the csspie module.

But atlas you are using CurvyCorners. With this demo, they are only using

```
.myBox {
    ....
    border: 3px solid #FFFFFF;
    border-radius: 20px 20px 20px 20px;
    ...
}

```

nothing to do with o-border, webkit-border, khtml-border, -moz-border, border-top-right etc. half of these are browser specific (ie -moz-border is for firefox only).

---
Tags: 7, theming
---


title: Theme the View/Edit Tabs

text:
# Question
Title: Theme the View/Edit Tabs
I would like to be able to theme the view/edit tabs.

That is, I'd like to add a class to the `<li>`.

Any help with this would be much appreciated.

Cheers in advance.

# Answer
If you want to create tabs use this module: http://drupal.org/project/tabs

else you can modify the tab wrapper in your **page.tpl.php** and then costumize your tabs with the api functions, to see more read: http://api.drupal.org/api/drupal/includes--menu.inc/function/theme\_menu\_local\_task
> 1 votes

---
Tags: theming
---


# Question
Title: Add an image selection list to a content type
I'd like to add an image selection to a content type, what would let the user chose for instance an icon, from a predefined list, to attach to this content type.

Any suggestions on how i could achieve that ?

Thanks,

# Answer
I Found a way to do so Using Node reference field type, enabled by Drupal 6 CCK module or in Drupal 7 it's with: Reference Module

Once the module enabled, Node reference will be available as CCK field type :)
> 0 votes

---
Tags: 7, nodes
---


title: 'Most popular' view

text:
# Question
Title: 'Most popular' view
I created a view which is supposed to list the 5 most popular stories on my site, so I sorted by node statistics: total views, and included several content types in filters. Only problem is the view only checks the stories in the first content type selected and ignores all the others. Is there something I am doing wrong?

Here is an export of the view:

```
$view = new view;
$view->name = 'popular';
$view->description = '';
$view->tag = '';
$view->view_php = '';
$view->base_table = 'node';
$view->is_cacheable = FALSE;
$view->api_version = 2;
$view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */
$handler = $view->new_display('default', 'Defaults', 'default');
$handler->override_option('fields', array(
  'created' => array(
    'label' => '',
    'alter' => array(
      'alter_text' => 0,
      'text' => '',
      'make_link' => 0,
      'path' => '',
      'link_class' => '',
      'alt' => '',
      'prefix' => '',
      'suffix' => '',
      'target' => '',
      'help' => '',
      'trim' => 0,
      'max_length' => '',
      'word_boundary' => 1,
      'ellipsis' => 1,
      'html' => 0,
      'strip_tags' => 0,
    ),
    'empty' => '',
    'hide_empty' => 0,
    'empty_zero' => 0,
    'date_format' => 'small',
    'custom_date_format' => '',
    'exclude' => 0,
    'id' => 'created',
    'table' => 'node',
    'field' => 'created',
    'relationship' => 'none',
  ),
  'title' => array(
    'label' => '',
    'alter' => array(
      'alter_text' => 0,
      'text' => '',
      'make_link' => 0,
      'path' => '',
      'link_class' => '',
      'alt' => '',
      'prefix' => '',
      'suffix' => '',
      'target' => '',
      'help' => '',
      'trim' => 0,
      'max_length' => '',
      'word_boundary' => 1,
      'ellipsis' => 1,
      'html' => 0,
      'strip_tags' => 0,
    ),
    'empty' => '',
    'hide_empty' => 0,
    'empty_zero' => 0,
    'link_to_node' => 1,
    'exclude' => 0,
    'id' => 'title',
    'table' => 'node',
    'field' => 'title',
    'override' => array(
      'button' => 'Override',
    ),
    'relationship' => 'none',
  ),
));
$handler->override_option('sorts', array(
  'totalcount' => array(
    'order' => 'DESC',
    'id' => 'totalcount',
    'table' => 'node_counter',
    'field' => 'totalcount',
    'override' => array(
      'button' => 'Override',
    ),
    'relationship' => 'none',
  ),
));
$handler->override_option('filters', array(
  'type' => array(
    'operator' => 'in',
    'value' => array(
      'news' => 'news',
      'story' => 'story',
      'opinion' => 'opinion',
      'video' => 'video',
    ),
    'group' => '0',
    'exposed' => FALSE,
    'expose' => array(
      'operator' => 'type_op',
      'label' => 'Node: Type',
      'use_operator' => 0,
      'identifier' => 'type',
      'optional' => 1,
      'single' => 1,
      'remember' => 0,
      'reduce' => 0,
    ),
    'id' => 'type',
    'table' => 'node',
    'field' => 'type',
    'relationship' => 'none',
  ),
));
$handler->override_option('access', array(
  'type' => 'none',
));
$handler->override_option('cache', array(
  'type' => 'none',
));
$handler->override_option('items_per_page', 5);
$handler = $view->new_display('block', 'Block', 'block_1');
$handler->override_option('block_description', '');
$handler->override_option('block_caching', -1);

```

# Answer
> 3 votes
Make sure that Content view counting is enabled in the Access Log Settings (`admin/reports/settings`). If this isn't enabled all content views will be equal to `0`.

# Answer
> 3 votes
You might want to consider the radioactivity module Radioactivity module which gives a more accurate and relevant reflection on the current popular content on the site.

The problem with using total views is that over time, the oldest content will always appear at the top of the list as they've been around longer. Whereas with the radioactivity module, it uses a points system and radioactivity "halflife" to rank content. This way, it will give a true reflection of the current trends of your site.

There's a handy video here which explains it all.

Hope this helps!

---
Tags: 6, views, nodes
---


# Question
Title: How to show only content created by the user in the find content (administrative) page
I've got some users who are allowed to create content. In the administrative interface, they actually see a list of all contents in the site but edit/delete only the content created by them. Is it possible to show in this page only the content they created and do not show content created by other users?

# Answer
> 1 votes
I've found that it's better to leave the admin areas to the admin user alone, and to build custom Views for "manager/editor" users. This gives you more control over the presentation and lets you easily add in additional information and links that aren't normally available in the admin screens. Not only that, you get easy access control to the listings.

If you really must do it the way you're talking about, there's an article on the drupal.org site discussing the theme hook for that screen, which I believe you could override and then filter based on ownership of the nodes in the node listing:

http://drupal.org/node/108986

---
Tags: 7, users
---