# Question
Title: Why do certain fields not behave like fields?
Why do certain fields not behave like fields? For example 'Product title' and 'Product price' fields from Drupal Commerce:

You can tell that these two fields are composed very differently. I have noticed that most fields have the same composition as 'Product price' above; whereas 'Product title' doesn't even look like a field.

Matter of fact, the question could be rephrased as: **why isn't 'Product title' a field, what is it? And how can I make it behave more like a field?** Specifically, how to attach RDF mappings to 'Product title' using the RDF module, like you can with regular fields?

# Answer
Product title is an entity property instead of a field. See blog post by Wolfgang Ziegler for an explanation.

You should be able to add RDF definitions by using `hook_rdf_mapping()`. I looked into the Commerce module and it didn't use the hook. You might want to file an issue on the Commerce project page.

Luckily you can define the RDF mappings by yourself. Below is an example code which might work.

```
function your_module_rdf_mapping() {
  return array(
    array(
      'type' => 'commerce_product',
      'bundle' => RDF_DEFAULT_BUNDLE, // might be something else
      'mapping' => array(
        'rdftype' => array('sioc:Item', 'foaf:Document'),
        'title' => array(
          'predicates' => array('dc:title'),
        ),
      ),
    ),
  );
}

```

If you want to expose entity properties to the UI, you can use `hook_field_extra_fields()`. Node module is using that to expose the title property to the UI. Below is an example code of that.

```
/**
 * Implements hook_field_extra_fields().
 */
function node_field_extra_fields() {
  $extra = array();

  foreach (node_type_get_types() as $type) {
    if ($type->has_title) {
      $extra['node'][$type->type] = array(
        'form' => array(
          'title' => array(
            'label' => $type->title_label,
            'description' => t('Node module element'),
            'weight' => -5,
          ),
        ),
      );
    }
  }

  return $extra;
}

```
> 3 votes

---
Tags: entities, rdf
---


title: Join multiple tables in D7 Views

text:
# Question
Title: Join multiple tables in D7 Views
I'm trying to create a View Block to display related information on a node.

I'm creating an image gallery where each image node is tagged with one/more taxonomy terms, and a block on each of those nodes then displays a list of users who have expressed an interest in the same taxonomy term(s).

So the node is tagged with e.g "landscape" and a user has a Profile2 profile in which they have have also selected "landscape" with a taxonomy ref field.

I'm having trouble building the view to achieve this. If I create a new view with a block and select that i'm displaying "Profiles" from the initial dropdown, views seems to remove some of the kinds of objects I can choose in the Contextual Filters or Relationships menus: Node isn't available for linking in a relationship.

If I go about in the "other direction" and make a view of Nodes, then try and create relationships backwards to the Profiles I want, I'm unable to select fields present in the Profile for output - the only fields available are those on the Node.

It seems that by choosing a specific kind of object to list, Views immediately excludes certain possibilities for joining.

Is this not possible? I know what the exact SQL would be, but I'd rather not write a module if a View would do.

# Answer
Should the relationship not go via the taxonomy reference rather than direct profile to node? Or have I misunderstood what you've tried/want to achieve?
> 0 votes

---
Tags: views, database, users
---


title: Schema not getting installed

text:
# Question
Title: Schema not getting installed
I'm working the SchemaAPI but can't get it to create the tables. This is the content of my schema\_test.install which is mostly copied form the examples modules.

```
<?php
function schema_test_install() {
  drupal_install_schema('schema_test');
}
function schema_test_schema() {
  $schema['schema_test_one'] = array(
    'description' => 'Stores example person entries for demonstration purposes.',
    'fields' => array(
      'pid'  => array(
        'type' => 'serial',
        'not null' => TRUE,
        'description' => 'Primary Key: Unique person ID.',
      ),
      'uid' => array(
        'type' => 'int',
        'not null' => TRUE,
        'default' => 0,
        'description' => "Creator user's {users}.uid",
      ),
      'name' => array(
        'type' => 'varchar',
        'length' => 255,
        'not null' => TRUE,
        'default' => '',
        'description' => 'Name of the person.',
      ),
      'surname' => array(
        'type' => 'varchar',
        'length' => 255,
        'not null' => TRUE,
        'default' => '',
        'description' => 'Surname of the person.',
      ),
      'age' => array(
        'type' => 'int',
        'not null' => TRUE,
        'default' => 0,
        'size' => 'tiny',
        'description' => 'The age of the person in years.',
      )
    ),
    'primary key' => array('pid'),
    'indexes' => array(
      'name'    => array('name'),
      'surname' => array('surname'),
      'age'     => array('age'),
    ),
  );
  return $schema;
}
/* vim: set ts=8 sw=2 tw=79 cc=80 ft=php:*/

```

I also have the Schema Module enabled and it lists this schema under "Missing". So it's recognized but never installed when the module is being enabled. What am I missing here?

# Answer
I got caught out in Drupal 7 by the fact that you don't need to call `drupal_install_schema`. Also, `hook_install` should now be used to perform actions on your tables, rather than set them up.

Drupal 7 sees your schema and installs it automatically when your module is activated, so because you're calling it manually, it's trying to install the schema twice.

This might help explain it a bit.

Also, try checking in your database to see if the tables already exist. If it's installed incorrectly, Drupal might be seeing the tables and thinking they're correct when actually they're not.
> 8 votes

# Answer
I Found out that in Drupal 7, you need to manually uninstall the module to create/recreate the tables defined by your schema.

To do this, first disable the module, then click the "uninstall" tab on the Modules page. Then Uninstall your module and reenable it. This should run the install hook.
> 3 votes

---
Tags: 7, database, hooks
---


# Question
Title: How do I edit the CSS based on node, page, or placement on page?
I've been learning how to navigate around and edit my global.css file, but am confused as to how to edit specific elements. I've come across answers to this question that don't specifically describe how to do this

To clarify, say that I have 3 pages on my site titled Red, Blue, and Black. If I want to edit just the h1 headers on page Red, how do I go about doing that? Is there a way to do this without PHP or installing extra modules?

Currently, whenever I try to edit the h1 header on supposed Red page, every single h1 header on my site is updated and edited.

Sorry if this is a duplicate, I honestly couldn't find any answer to my question while I was searching

# Answer
> 2 votes
This isnt a Drupal API question. It's more of a CSS and how does that work in the browser question. That being said there are docs on how to theme drupal 6 and 7. Since drupal is a web application they cover topics such as:

1. Working with CSS
2. Standard Drupal Core Styles and Classes

Within (2) it describes the `.node` and `.node-title` CSS classes:

> .node
>
> A wrapper div around all of a node, including its title.
>
> .node-title
>
> The title of the node.

Depending on the theme your using you may or may not have those exact classes, every theme is slightly different. Basically in your theme you want to use Firebug or Chrome Developer Tools to look at the HTML markup and CSS classes and IDs attached to things. You can then target a page or node title, and create a rule to target specific page urls if need be. As an example Drupal page (using AdaptiveTheme subtheme):

The `<body>` tag has a million css classes on it including `page-node-2` that specific CSS class would target only this node (by its NID). You can inject other more useful body classes into any theme using hook functions and template files -- but thats beyond this writings scope.

In this case you can also see the node title has an ID of `h1#page-title`

A general CSS rule to target this 1 page's title you could put in `global.css` is `body.page-node-2 h1#page-title { color: red; }`

For your theme it would be the same process:

* examine the body tag in your Theme and find a useful CSS class to specifically target the page(s) with a CSS rule.
* examine the `Section Header` tags within the page to find the exact CSS classes/ids to target just that element as well.

Lastly, I dont think every theme has a `global.css` file ... though most probably do. My exact CSS rules herein will likely not work for your usecase, they're just examples of what you could do. See the documentation pages listed above to better understand Drupal Themeing.

---
Tags: 7, theming
---


title: drupal_http_post redirect

text:
# Question
Title: drupal_http_post redirect
I am currently experimenting with drupal\_http\_request to send my users information to a payment service - there is more configuration to be done so it is not working yet.

When I do get it successfully POSTing users details, it is important that the user is redirected to the payment service.

**Can anyone tell me if drupal\_http\_request does redirect as it POSTs data?**

If it doesn't I would appreciate suggestions on how I can achieve simultaneous POSTing and redirection.

# Answer
Here is an example of how to use `drupal_http_request()`.

```
$options = array(
  'method' => 'POST',
  'data' => 'name=Test&email=example...',
  'headers' => array('Content-Type' => 'application/x-www-form-urlencoded'),
);

$result = drupal_http_request('http://example.com', $options);

```

In `$result`, you will get an object with the data of the request. Check the `$result` object and make sure the payment is gone through (or whatever the condition that should pass before redirecting the user).

Then, use drupal\_goto() to redirect the user to the new location.

Note that this is just a normal redirect (GET) and data is already submitted to the Payment server by your site.

If you want to use Paypal IPN-like requests that the **user** POSTs data to the server, you need to create a form instead.

```
function _test_payment_form() {
  $form = array();

  $form['user'] = array(
    '#type' => 'hidden',
    '#name-info' => 'user', // this is the field name that will become name attribute of the input tag. No need to use this if your $form['KEY'] is same as this one.
  );

  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Proceed to @server for the payment', array('@server' => 'Paypal')),
  );

  $form['#action'] = 'http://example-payment-server.com/example/2/3/4'; // Information will now be submitted to this URL other than Drupal.
  $form['#method'] = 'POST', // Just for clarification. This is the default value.

   return $form;
}

```

You can print the form using the following code.

```
print drupal_render(drupal_get_form('_test_payment_form'));

```

You can also use the following code, where render arrays are accepted.

```
drupal_get_form('_test_payment_form');

```
> 3 votes

---
Tags: 7
---


# Question
Title: Enabling a custom module after uninstalling it
I have simple question concerning enabling a custom module after having disinstalled it. The module provides a simple creation of a new content type based on node content. It implements a `hook_install()` function that first time i enabled the module worked perfectly. For debugging reasons i had to disable and unistall the module, then when i tried to enable again the module the system checks it as enabled but the new content type that is the result of the `hook_install()` function does not appear anymore.

It seems to me that when i try to re-activate the module the installation script doesn't work anymore, and this although i cleared the cache after unistallind the module the first time.

Any ideas?

Here's the install code:

```
function bachecanews_install() {
  $t = get_t();
  $node_bachecanews = array(
    'type' => 'node_bachecanews',
    'name' => $t('Bacheca News'),
    'base' => 'node_content',
    'description' => $t('Usa *Bacheca News* per inserire le notizio sul sito.'),
    'body_label' => $t('Contenuto della News')
  );
  $content_type = node_type_set_defaults($node_bachecanews);
  node_add_body_field($content_type);
  node_add_date_field($content_type);
  $status = node_type_save($content_type);
  $t_args = array('%name' => $content_type->name);
  if ($status == SAVED_UPDATED) { // in caso di modifica
    drupal_set_message($t('Il nuovo tipo di contenuto %name è stato modificato.', $t_args));
  }
  elseif ($status == SAVED_NEW) { // in caso di creazione
    drupal_set_message($t('Il nuovo tipo di contenuto %name è stato creato.', $t_args));
    watchdog('node', 'Creato il nuovo tipo di contenuto %name.', $t_args, WATCHDOG_NOTICE, l($t('view'), 'admin/structure/types'));
  }
}

function bachecanews_uninstall() {
  $sql = 'SELECT nid FROM {node} n WHERE n.type = :type';
  $result = db_query($sql, array(':type' => 'node_bachecanews'));
  $nids = array();
  foreach ($result as $row) {
    $nids[] = $row->nid;
  }
  node_delete_multiple($nids);
  node_type_delete('node_bachecanews');
}
```

# Answer
I found out that you have 2 issues with your `hook_install` code.

1. You're adding body field first then saving the node type. It should be the opposite.
2. There's no such function called `node_add_date_field` in Drupal package, unless you've created it yourself in your custom module.

Your `hook_install` should be as the following code:

```
function bachecanews_install() {
  $t = get_t();
  $node_bachecanews = array(
    'type' => 'node_bachecanews',
    'name' => $t('Bacheca News'),
    'base' => 'node_content',
    'description' => $t('Usa Bacheca News per inserire le notizio sul sito.'),
    'body_label' => $t('Contenuto della News')
  );
  $content_type = node_type_set_defaults($node_bachecanews);
  $status = node_type_save($content_type);
  node_add_body_field($content_type);
  $t_args = array('%name' => $content_type->name);
  if ($status == SAVED_UPDATED) { // in caso di modifica
    drupal_set_message($t('Il nuovo tipo di contenuto %name è stato modificato.', $t_args));
  }
  elseif ($status == SAVED_NEW) { // in caso di creazione
    drupal_set_message($t('Il nuovo tipo di contenuto %name è stato creato.', $t_args));
    watchdog('node', 'Creato il nuovo tipo di contenuto %name.', $t_args, WATCHDOG_NOTICE, l($t('view'), 'admin/structure/types'));
  }
}

```

If you want to add additional field to your custom content type and this field is not body field, you use field\_create\_field()

As an example, you can look at standard\_install().
> 1 votes

---
Tags: 7
---


# Question
Title: What module can create a gateway or doorway popup AD page before viewing content for Drupal 7?
I'm looking for a module that can create gateway or doorway pages like on many publication sites where you have to view an AD first before letting you view the article.

# Answer
The Splashify module should do exactly what you need. You can specify a list of the pages you want to redirect to an ad (you can use the wildcared (\*) too) and a list of different pages to use for the ads, and they're choosen either random or in order. You'll have to create the pages for the ads though. How they get from the ad page to the content they requested may require a little PHP/javascript, I'm not sure.

http://drupal.org/project/splashify
> 1 votes

---
Tags: 7
---


# Question
Title: Menu not showing for 1 server of two cloned servers
After cloning an existing server instance and pointing the new one to the same database I've modified my hosts files to load the 2nd server with the same URL as the first one.

All is well except for the fact that on the 2nd server the navigation menu is missing!

Any insight onto what may cause two otherwise identical servers to behave differently in this fashion?

update: the menu in question is generated by the superfish module.

# Answer
After a heavy duty migration like that, I would try going through the standard Drupal debugging steps first:

1. Clear caches.
2. Re-save theme settings (admin/appearance/settings/mytheme).
3. Rebuild permissions (admin/reports/status/rebuild)
4. If you are using the Features module, double check that things are identical to the old instance. You may need to revert some features components.
5. Check the status report and error log at admin/reports.

Good to cover your bases before you start digging deeper.
> 0 votes

---
Tags: routes, navigation
---


title: Body title gets displayed with content

text:
# Question
Title: Body title gets displayed with content
I have a content type of something, with title and body only as fields, body field reporting field\_body as machine name.

problem is, i create a node with content and then when it's displayed on the page, the text Body: head up the main content area, for all posts.

Tried removing the name Body from the field type name but it's a mandatory field property.

any way to rid the page of that title?

# Answer
> 2 votes
Assuming that you are using D7. Go to **/admin/structure/types** and select your content type.

Under the 'Manage display' tab, find the body field, and set the label to 'Hidden'. The field label will not display. You may have to repeat this for each display type (default, teaser etc.).

---
Tags: entities, nodes
---


# Question
Title: Multi-value checkbox within content type
I simply want to make a multivalue field within my venue content type (music venue)

funky, cool, dive, swank, disco etc.

I want to be able to select those when adding a venue, and then have it display everyone that was checked. I cannot figure this out!

# Answer
1. Add a new field choose FIELD as 'List (text)' and Widget as 'Check boxes/radio buttons'
2. Then in allowed values list, give your values eg: funky|funky cool|cool dive|dive swank|swank disco|disco
3. Choose Number of values to "Unlimited"
4. Then in DEFAULT VALUE, you can see all the options as check boxes, check every boxes if you want display all as selected.

Now you will get the desired output
> 3 votes

# Answer
First off, I think what you're describing is better suited for taxonomy functions rather than fields in a content type.

in order to display the contents of those multi-value checkboxes in a way that you want, you'll have to edit the content type template.

can you explain more about exactly where you're stuck?
> 1 votes

---
Tags: nodes, forms
---


title: Panels vs theming

text:
# Question
Title: Panels vs theming
Panels versus themes: What is the best way?

Since Panels is included in Drupal 8 core, isn't it the way forward? Do we still need to design static HTML pages and then integrate them with Drupal, or Panel everything out and directly place content there be it block, views or from some other modules as they are all readily available?

The issue of performance with Panels can be solved to an extent using the Boost module. We can't have all what we want; we have to compromise at something.

# Answer
> 2 votes
What is in Drupal 8 is not Panels -- the Panel-ish controller is still being worked on. The SCOTCH initative was definitely Panels inspired for sure but there is no UI yet, definitely no upgrade path or anything.

However, Spark is based on Panels for "better forward compatibility".

Besides Spark I am sure the Panopoly people will make sure there's an upgrade path.

With all this said, your question makes no sense. You are comparing apples to oranges. Panels vs theming, that's like asking, Views vs custom queries. It's for different skillsets and different situations.

---
Tags: theming, panels, performance, 8
---


# Question
Title: How do I create content programatically?
In WordPress I can use wp\_insert\_post() to create content programatically.

Is there any similar function available for Drupal 7, that will allow me to insert posts (and pages) into the database programatically?

# Answer
you can create a custom function to create a node.

```
function create_my_node() {
  $node = new stdClass();
  $node->type = 'your content type';
  node_object_prepare($node);

  $node->title = "your title";
  $node->language = LANGUAGE_NONE;
  global $user;

  $newnode->uid = $user->uid;
  $newnode->name = $user->name;
  $newnode->status = 1;     // 1 means published
  $newnode->promote = 0;
  node_save($node);
}

```
> 2 votes

---
Tags: 7, nodes
---


# Question
Title: Migrating SQL dump from Drupal 5 into Drupal 7
My site went recently down, and all the data were lost (PHP installation of Drupal 5). What I am left is simple SQL dump from PHPMyAdmin.

I would like to "use" this disaster and finally migrate to Drupal 7. Because of this, I do not know how to continue.

Should I install Drupal 5 first, import SQL dump, and then upgrade?

Is there any way how to save stored data from Drupal 5 (SQL dump) to Drupal 7? If the answer is *yes*, can you please point me to correct procedure?

# Answer
> 0 votes
There isn't any other way to update to Drupal 7, if not following the steps you listed. I would rather update to Drupal 6, and then to Drupal 7.
Probably, you could avoid installing Drupal 5, if you restore the database tables used from Drupal 5; you could start with updating to Drupal 6, if you have a copy of the setting.php file used from Drupal 5 (or you can *rebuild* it). I have never tried this; it could be working in theory, but have some practical problems I didn't think of.

Updating the data from Drupal 5 to Drupal 7 means to execute the update functions Drupal runs to update itself. There isn't any other method, since Drupal executes the updates in a specific order, and hook\_update\_dependencies() implementations change that order.

---
Tags: database, migrations
---


# Question
Title: How to hide a field when its value is set to zero
I want to hide a field on a node when its value is set to zero using a content type. Here is what I had done so far to achieve my goal.

```
function pay_nodeapi(&$node, $op, $a3 = NULL, $a4 = NULL) {
  global $user;

  if ($node->type=='salary_info' && $op=='presave') {
    $public_holiday = $node->field_sstru_public_holiday[0]['value']; // here I get the value that I set to 0(No) or 1(YES) using a select list.

    if ($public_holiday == 0) {
      $nid = node_load(207919); // load node where i want to unset this field
      unset($nid->field_pd_public_holiday[0]); // here iam wrong and confused
    }
    else {
      drupal_set_message("HOLIDAY");
    }
  }

```

what should I do to unset my field?

# Answer
I'm not sure why you are using **presave** operation.

If you want to hide a field on node view you should use **view** operation.

So your code should be as the following code:

```
function pay_nodeapi(&$node, $op, $a3 = NULL, $a4 = NULL) {
  if ($node->type=='salary_info' && $op=='view') {
    $public_holiday = $node->field_sstru_public_holiday[0]['value'];

    if ($public_holiday == 0) {
      // you don't need to load node again.
      unset($node->field_pd_public_holiday);
    } else {
      drupal_set_message("HOLIDAY");
    }
  }
}

```

**Edit:**

If you want to hide field on another content type or node using **presave** operation, then you need to load node and unset field value then save node again using `node_save` function

So your code should look as the following:

```
function pay_nodeapi(&$node, $op, $a3 = NULL, $a4 = NULL) {
  global $user;

  if ($node->type=='salary_info' && $op=='presave') {
    $public_holiday = $node->field_sstru_public_holiday[0]['value']; // here I get the value that I set to 0(No) or 1(YES) using a select list.

    if ($public_holiday == 0) {
      $node = node_load(207919); // load node by nid
      unset($node->field_pd_public_holiday[0]); // unset field from node object
      node_save($node); // save node after unsetting the unwanted field value.
    }
    else {
      drupal_set_message("HOLIDAY");
    }
  }
}

```
> 0 votes

---
Tags: entities, nodes
---


title: Importing JSON data

text:
# Question
Title: Importing JSON data
I have Data in JSON format, and I want to insert and update that data into Drupal. I have to update all the records which I got from an external link.

How can I achieve this?

# Answer
In Drupal 7 you can use drupal\_json\_decode() which is only a one line wrapper to json\_decode() anyway. If you structure your table smartly you can probably just write the output of `json_decode()` straight to the database (if the columns in the table agree with the data); otherwise you will have to manipulate the data a bit.
> 4 votes

# Answer
For the record. A beautiful way to do this is is with Feeds and Feed JSONPath Parser modules. Here is a great article: Easily import Tweets into Drupal using JSON and Feeds

Also Data module can be used to import data to custom tables.

Cheers, Duru.
> 3 votes

# Answer
I would give JSONData.com a try. It updates information in real time and can save you a lot of time and work. Hope that helps.
> 1 votes

---
Tags: importing-exporting
---


# Question
Title: Product color from select list in Commerce Kickstart 2
I thought it would be simple, but either I'm stupid or the commerce kickstart 2 doesn't have such functionality.

I've created a t-shirt product variation and I want to give my customers the possibility of choosing their favorite color from a color picker or from a select list. The color doesn’t affect the price.

As I see the only option for doing this in kickstart commerce is by creating each variation per color. Is there any other way to accomplish this? I just want to create t-shirt and let people choose their color.

Please help me I'm getting very frustrated.

# Answer
That's exactly what variations are for...

You have a product (a t-shirt) with a variety of different options (colours), hence you need different variations of the product to identify what colour of t-shirt has actually been sold.

Kickstart already has that exact functionality built right in; if you install the demo content and browse to "/tops/guy-short-sleeve-tee" you should see it:
> 2 votes

---
Tags: commerce
---


title: Views Content slide show- with 2 rows

text:
# Question
Title: Views Content slide show- with 2 rows
Please help me.I am searching for a content slider in Drupal 7 .

I have created a view for displaying products.A block is created for this view.

My requirement:

I need a content slider with 2 columns and two rows.All the view items should be displayed in the slider.There will be four node contents in each slider.

eg: row1 row1 row2 row2

Please find the attached screen shot .I hope this may help more.

# Answer
> 0 votes
First : download the view slideshow model ;
second : add the field you want
third :from the setting you can add controller and pager
to display the item like this you have to use it in css to display it as for item

---
Tags: views
---


# Question
Title: How do i get the type attribute when adding javascript to drupal?
i'm adding javascript with

> drupal\_add\_js()

but drupal cuts the script attribute "text/javascript" or just forgot it. It just adds the

```
<script></script>

```

tags. Can i add the script tags? Its w3c standard...;-P

# Answer
> 3 votes
The default `drupal_get_js()` includes the `type` attribute (look at the source). I suspect you have a module or theme that is implementing a `theme_html_tag()` that is stripping the `type` out.

I suggest looking through your theme and/or base theme for this theme function. You could also implement your own version in your theme, and put back in the `type`.

If you are using any of the modules that "cleanup" HTML output, then I would try disabling them. I have seen them do really weird things on pages.

# Answer
> 5 votes
On the off-chance that you're using an HTML5 `DOCTYPE`, you don't need to worry:

> The type attribute gives the language of the script or format of the data. If the attribute is present, its value must be a valid MIME type. The charset parameter must not be specified. **The default, which is used if the attribute is absent, is "text/javascript"**.

Emphasis mine

Source: HTML 5.1 Nightly - 4.3 Scripting

---
Tags: javascript
---


# Question
Title: Modify instead of add a class in classes_array for theming purposes
I am using the following preprocess in my template.php

```
function paddle_admin_preprocess_menu_block_wrapper(&$variables) {
  if ($variables['delta'] === 'management_level_2') {
    $variables['classes_array'][] = 'max-width';
  }
}

```

It works as intended, it adds a class when the delta equals this string..

I am trying to modify another other entry of the classes\_array array in order to make the classname more semantic. How would I go for that? (so replace an entry instead of add)

ps: I figured it can be as easy as:

```
$variables['classes_array'][1] = $variables['delta'];

```

but I am wondering whether the array indexes can change (from the ones I see with devel themer)

# Answer
Search for the key of the value you want to replace and then modify it. It's that simple.

```
function paddle_admin_preprocess_menu_block_wrapper(&$variables) {
  if ($variables['delta'] === 'management_level_2') {
    // Search for the key
    $key = array_search('class_to_be_replaced', $variables['classes_array']);

    // If class was found, replace it
    if ($key !== FALSE) {
        $variables['classes_array'][$key] = 'class_that_replaces';
    }
  }
}

```
> 1 votes

---
Tags: theming
---


# Question
Title: How to have different style files in multilingual website using Drupal?
I have been developing a multilingual website using Drupal 6. The languages are English and Spanish. I want to have some different backgrounds and css for them. But both use just style.css.

How can I create different style.css file for them? For example style-sp.css for Spanish one and en-style.css for English one ?

Is it possible ?

# Answer
> 2 votes
you can do this in template.php: you have to copt css file in themefolder/css.

```
    function yourtheme_preprocess_page(&$vars) {
        global $language ;
        $lang_name = $language->language ;
        if ($lang_name=='en')
        drupal_add_css(path_to_theme(). '/css/en-style.css');
        elseif ($lang_name=='sp')
        drupal_add_css(path_to_theme(). '/css/style-sp.css');
        $vars['styles'] = drupal_get_css(); //  use drupal_get_css() to add new css
}

```

so you have one of css files related to current page language.

---
Tags: i18n-l10n, theming
---


title: Drupal Master/Slave Replication

text:
# Question
Title: Drupal Master/Slave Replication
I've setup two MySQL servers with Master/Slave replication for the drupal database and I've confirmed the databases are in sync and replicating.

I am now trying to point drupal to both databases basically for failover/redundancy purposes. That is if I need to reboot our primary database server I don't want our site to go down. (Going read-only is acceptable during failure scenarios)

Based on the following article. I've modified `settings.php` as follows:

```
$databases['default']['default'] = array(
  'driver' => 'mysql',
  'database' => 'sdrupal',
  'username' => 'drupal',
  'password' => 'topsecret',
  'host' => 'masterdb.ptp.local',
);
$databases['default']['slave'][] = array(
  'driver' => 'mysql',
  'database' => 'sdrupal',
  'username' => 'drupal',
  'password' => 'topsecret',
  'host' => 'slavedb.ptp.local',
);

```

The configuration is fine until I shutdown the master (service mysqld stop) - when I do that my site pukes:

> PDOException: SQLSTATE\[HY000\] \[2013\] Lost connection to MySQL server at 'reading initial communication packet', system error: 111 in drupal\_is\_denied() (line 1895 of /www/includes/bootstrap.inc). Additional
>
> PDOException: SQLSTATE\[HY000\] \[2013\] Lost connection to MySQL server at 'reading initial communication packet', system error: 111 in dblog\_watchdog() (line 141 of /www/modules/dblog/dblog.module).

Whats the trick to make this work?

# Answer
> 6 votes
Regarding Master/Master (High availability) is possible to do load-balancing when no master is down.

The following will make all writes go to master1 and all reads go to master2. If master1 fails, all queries will go to master2. If master2 fails, all queries will go to master1.

```
'master' => array('master1', 'master2')
'slave' => array('master2', 'master1')

```

The following will make all queries go to master1. If master1 fails all queries will go to master2:

```
'master' => array('master1', 'master2')
'slave' => array('master1', 'master2')

```

# Answer
> 5 votes
For the benefit of others - as best as I've been able to find - out of the box Drupal 7 doesn't seem to have any database high availability capability built in.

You can setup two mysql servers in a master/slave configuration but the best it will do is send all writes to the master and all reads to the slave. That provides crude load distribution but ***not*** failover.

That is to say if the master mysql server goes down all bets are off – the site goes down with an ugly error message complaining that PHP can't reach the master database.

Traditionally, as I understand, the way to tackle this with other software is to either use mysql ndb clusters or mysql proxy – but after reading a bit - these technologies apparently don't play well with Drupal.

However I stumbled upon a Drupal module called auto-slave (http://drupal.org/project/autoslave). It’s not widely used (there are 12 sites actively using it according to the stats) but it does seem to be able to do what we want. It can be configured in a variety of ways:

**Master/Slave**

```
Writes go to Master
Reads go to Slave

Drawbacks:
If master is down, the durpal site displays a prominent message that the site is in "read only" mode.

```

**Master/Master (High availability)**

```
Read and Writes go to master1 (primary) unless its unavailable.
If master1 is unavailable, reads and writes go to master2 (secondary)

Drawbacks:
There is no load distribution. All load (reads and writes) go to either master1 or to master2

```

**Master/Master/Slave (High availability/High performance)**

```
Writes go to Master1 (primary) unless it’s down then they go to Master2
Reads go to the slave unless it’s down
Drawbacks:
Requires a minimum of three database servers (master/master/slave)

```

So far we've setup the first (Master/Slave) successfully. I'm going to be attempting to setup Master/Master/Slave next.

Hopefully this helps someone else out.

---
Tags: database, configuration
---


# Question
Title: Querying the database via a url and displaying the results?
*Some background context:*
I have created a custom form, which inserts data into several tables when submitted. In fact, five new records are created in the node table on submit. A new record is also created in several other other tables, which are all related to these five newly created records in node. One of these node records is the root of everything: from the nid you can access all the related records

*The aim:*
Now, I'd like to be able to enter a url, like example.com/record/1, and for the '1' to be used as the nid from which to get this root node record from the database, and all its related records, and to display it all on a page.

*The question:*
How can I do this? I have looked into node\_load and menu\_get\_object, but I can't find any documentation which describes the process of querying the database, using information in the submitted url, and displaying the results on a page.

Thanks

# Answer
> 0 votes
Direct answer to your question - you can get the parameter from the query string a number of ways:

Any of these methods would get you the nid from the query string (in your example, 1) - you could then us db\_query or node\_load to load the data for this record and output it as desired but thats too much work.

Much easier way to do this is to use the views module and add a contextual filter. Setup a basic view and then configure however you like (ex - display full node / teaser or views, etc). Set the path to

```
record/%

```

where the percent sign indicates a variable you are going to pass to the contextual filter. Next, under advanced options

* select 'contextual filters' and 'add'
* search for and add one of type 'content: nid'
* on the next screen choose 'provide a default value' of type 'raw value from url', then select the url argument you want to use which in your case is '2'

Views will handle the querying for you and take care of sanitizing the input, and dealing with the output on the way.

---
Tags: nodes
---


# Question
Title: add css class to html element based on taxonomy?
I would like to add class to the HTML element based on taxonomy. Is it possible to do it from inside template.tpl.php or do I need to create needed templates manually? If so, how will my theme know which template it should pick? Thank you

# Answer
> 3 votes
You can do this by adding a preprocess function to your template file that detects if the current node has terms associated with it and if so, populates a variable for the page.tpl.php according to your logic, ex:

```
function YOURTHEME_preprocess_page(&$variables) {
  if (!empty($variables['node'])) {
    $node = $variables['node'];
    if (!empty($node->field_tags)) {

      #your taxonomy logic here, if term matches your case then assign it to variable
      $variables["custom_taxonomy_page_class"];

    }
}

```

Then, in your page.tpl.php file in your theme, you just need to add the above variable where you want it in the HTML tag.

```
<html xmlns="http://www.w3.org/1999/xhtml" class="$custom_taxonomy_page_class">

```

If the variable is empty, no class will be output.

---
Tags: 7, theming
---


# Question
Title: Is it possible to automatically delete image files that have been uploaded when a node is not saved?
I'm using Drupal 7. On my site, users can add pictures via a content type, **Pictures**, that makes use of the core image field.

If a user uploads an image file and saves the node, then if the node is deleted the image file will be deleted as well.

**However, if a user uploads an image file and then leaves the page, the image file remains stored in the filesystem and is not deleted.** This means that if users are careless, it is possible for them to add lots of pictures that will never be seen and never be deleted, wasting lots of disk space.

Is there any way to automatically delete these "orphan" files?

# Answer
That would be difficult to accomplish automatically, since as you pointed out, these nodes / profiles are not saved and therefore the data isn't loaded into Drupal 7's file management table. Drupal 7 will automatically delete all files it is tracking in the file management table when the node is deleted.

Another way to approach this then is to try and detect any files in your target folder (ex. 'files/') that do not have a corresponding data entry in the database and then delete those. Here is a script from Caribbean New Media that does just this task (and even cleans up image styles):

> The script will scan through your chosen directory (and subdirectories), for every file found, it will endeavour to cross-reference that file within your chosen table. If the file doesn't exist in the tables, it will delete the original file and all it's generated image style files you have defined.

Definitely should be carefully configured and tested in a safe development environment before moving to your production site, but once running correctly, you can set this up in a cron job to at least have it run every few days / week to clean up orphaned uploads.
> 3 votes

---
Tags: media
---


# Question
Title: Sharing fields and their data between a user profile and a content type?
I have a content type called "Profile". This is a standalone content type and **may or may not** be associated with an actual user on the site.

I thus need to find a way of sharing profile fields between the Drupal user and the new custom content type. In other words, if you edit the "home address" field on the Drupal user's profile page, that field (and its data) should show up on the Profile page associated with the user via EntityReference or Relation or whatever.

Is this at all possible? I know you can reuse fields across content types, but in my understanding, it doesn't share their data (Such that you can use field\_something on content type A and again on content type B, but data from A will never show up on B and vice-versa).

Thanks!

(Addendum: My fallback is to just put all of the fields on the new Profile content type, keeping the actual default Drupal user profile relatively sparse. Moreover, I'm curious whether this is at all possible.)

# Answer
> 1 votes
I guess one option would be to use Rules, so that when one entity is saved, the field data is also saved int the field on the other entity.

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


# Question
Title: How to alter a form depending how it was accessed
I would like to alter the login form depending how it was accessed. As an example, if the form was access from a particular link, it would display the standard login form. If it was accessed from a different link, then the login form would be modified (ie maybe display a different title and exhibit different behaviour (redirects based on role)).

I figure I need to use hook\_form\_alter() but I am not sure how to tell which link was clicked. Any ideas how one would go about accomplishing this? I am working with Drupal 6 by the way.

Thanks

# Answer
> 1 votes
Inside your `form_alter()` hook, you can always check what page a form is on by looking at `$_GET['q']`, eg:

```
if ($form_id=='user_login' && $_GET['q']=='different/link') {
  // do form alters here
}

```

so if you are at `www.yourhost.com/different/link`, it will do whatever you tell it to do.

---
Tags: users, 6
---


# Question
Title: Page not found for a node that does exist?
I have created a module which includes a custom form. When the form is submitted the module uses `drupal_write_record` to insert the form contents into the database. The first `drupal_write_record` is to the node table. Using phpmyadmin I've looked into the node table and I can see there is a record where nid is 11. If I request `example.com/?q=node/11` I get a 'page not found' error.

Here is record 11 from the node table:

```
nid,vid,type,language,title,uid,status,created,changed,comment,promote,sticky,tnid,translate
11,NULL,game,und,Title,1,1,1365111019,1365111019,1,0,0,0,0

```

Why doesn't `example.com/?q=node/11` return the contents of this record as a page? Do I need to do something else?

# Answer
> 2 votes
You cannot write a node using a single drupal\_write\_record(). Depending on how your content type is defined you will need to write to several tables. But you don't need to know the precise details because the right way to create a node is to use node\_save() as Ahmed mentioned in his comment.

---
Tags: nodes
---


# Question
Title: How to show images uploaded only on "read more?"
How to show images uploaded only on "read more?"

drupal is so confusing...

# Answer
The 'Read more' button appears on the teaser display.

If you go to **/admin/structure/types** and select your content type, under the 'Manage display' tab you will see the display types for that content. Select 'teaser' and make the images 'Hidden' on the teaser. Then the images will only display when the full node is viewed.
> 1 votes

---
Tags: 7
---


# Question
Title: How to add a META tag in head conditionally to entity content
I need to put a meta NOINDEX tag in head conditionally to a CCK field value ("visibility=private") in one specific content type ("projects").

I read about drupal\_add\_html\_head($data = NULL, $key = NULL) but I'm not sure where to put it.

If I could put the tag in body I would just use a computed\_field, but as I need it to be in head, should I put it on my own module (but on which hook?) or should I copy/insert it in html.tpl.php ?

My problems are (a) that if html.tpl.php will change then I'll have to change also the copy I overridden; (b) then I'm also not sure I have access to $entity inside the template (I never used them) and, finally, (c) that being a matter of logic rather than presentation a module maybe is more indicated than a template. For all this reasons I would prefer a custom module. Would it be possible ?

# Answer
It's definitely possible, you could do this using `hook_entity_view()` for example:

```
function MYMODULE_entity_view($entity, $type, $view_mode, $langcode) {
  if ($type == 'my_entity_type' && $view_mode == 'some_view_mode') {
    // Check the field items.
    if ($items = field_get_items('my_entity_type', $entity, 'field_visibility')) {
      if ($items[0]['value'] == 'private') {
        $element = array(
          '#tag' => 'meta',
          '#attributes' => array(
            'name' => 'robots',
            'content' => 'noindex',
          ),
        );
        drupal_add_html_head($element, 'robots');
      }
    }
  }
}

```
> 4 votes

---
Tags: theming, meta-tags
---


# Question
Title: Filter View on Partial Term Name Across All Vocabs
Hello im sure i used to be able to do this with D6 and Views 2. Struggling to achieve it now.

I was wanting to create a content view that is filtered on partial matches of a term name across ALL my vocabs. Say i filtered on 'science' then the view will show content tagged 'science videos' from my Video Vocab and also, for example 'science chat' from my 'tags' Vocab.

Using D7 and Views 3 i dont seem to have the option to filter on name only ID and ID is limited to one vocab.

Does anyone know if i am missing something here?

Thanks

# Answer
sorted. Add relationship Taxonomy term: Name in a TERM view and viola
> 0 votes

---
Tags: views
---


# Question
Title: How to setup session sharing for language subdomains (URL language detection set to domain prefix)
I would like to use domain prefix for language selection, like en.example.com and de.example.com. I've set up language detection to `Domain` here `admin/config/regional/language/configure/url`.

In theory everything works fine, except that session data is not shared between subdomains. If I log into the main site example.com and then visit en.example.com I have to log in again. Is this behaviour by design? Can I setup drupal to share session data between subdomains? It's the same site after all - only subdomain is different.

# Answer
You need to set the variable `$cookie_domain` in your `settings.php` file to your base (default language) domain.

Just search the settings.php file for that variable, uncomment the line and replace '.example.com' with your default language domain preceded with a dot.

Source
> 1 votes

---
Tags: i18n-l10n, sessions
---


# Question
Title: How could I automatically delete accounts with a given criteria?
My drupal site has a textarea field in the new user application that asks for the new user to explain what their interest is in wanting to join the site. Some sort of machine bot is sending a dozen or so requests for accounts daily. Characteristically, this machine bot is putting two random characters into this "interest" field. Therefore, I know that any account with only 2 characters in this particular field is this computer bot since no answer to this question on the application could be acceptable with only two characters.

I would like to know if there is a way that drupal can delete such accounts with only two characters in this particular field automatically by using a set criteria (e.g. a field containing only two characters). How could I go about this? It would be ideal to have Drupal NOT send an email message at all that a new user has signed up when this occurs, but if that is not possible, then can I do something to automatically delete such an application when the length of the field is only two characters? I am looking for a Drupal method of doing this rather than a cron job method of doing this.

I realize that one could just use a field validation to start with but that won't answer the question: Can Drupal actually use some sort of specific field rule (e.g. a certain field must have more than x number of characters) to delete accounts automatically so they wouldn't have to be deleted manually and constantly by the administrator.

# Answer
You may not be able to stop the email being sent. But you can set up a rule to block the user to trigger on the event 'Before saving user account'.

You will require two conditions. First use the condiiton 'Entity has field' and check for the 'Reasons to join' field. This will make the field visible to subsequent conditions. The do a 'Data comparison' on **account-unchanged:profile-main:user:field-reasons-to-join** and check for your two charcter text. If the conditions are met use an action to 'Block a user' using **account-unchanged:profile-main:user**.

EDIT: Since your users are blocked pending admin approval, perhaps you should be looking at the Field validation module. With it you can specify a minimum length for the field (making sure you let your users know in the guidelines that the minimum length is required). You could also set up a field hidden with your css which you would require to be empty. Bots would likely fill it in with something.

You should also have a look at the Spambot module which uses the api at stopforumspam.com to catch known spammers. While it is not perfect (nothing is) it will certainly cut down on the number of bots that get through.
> 0 votes

---
Tags: users, advertising
---


# Question
Title: How to upgrade outdated Drupal 7 version
I'm using Drupal 7.10 which is an outdated version. Is it safe to just upgrade to the latest version or should I upgrade version by version from 7.11 until the latest version 7.21?

# Answer
> 3 votes
You can upgrade directly to the new version as it contains all the previous changes as well. But don't forget to follow the backup instructions...

# Answer
> 1 votes
just go to your command prompt , switch to your site folder and use the command "drush pm-update drupal" this ll help you out ..:) in an easy way..

happy coading :)

---
Tags: 7, upgrading
---


# Question
Title: how to alter main menu to add custom class
How do I add custom class to main menu. The main menu links are like **Fashion, Art, Life** and nodes being viewed category can be any one. I want to make the main menu item active as per node being viewed category. e.g if `example.com/node/44` -\> `category = fashion` then the Fashion in main menu should be selected. I tried `MYTHEME_menu_link` and `MYTHEME_menu_link_alter` but they did not work for me.

Thanks for your help.

# Answer
> -1 votes
I can't tell you how this works programatically, but with menu-position module you can achieve exactly what you're looking for. You'll just add a position-rule for your node-types (or taxonomy item used) to highlight a parent item accordingly.

---
Tags: routes, theming
---


title: Drupal Website showing only some images

text:
# Question
Title: Drupal Website showing only some images
I was told to migrate a Drupal website, but I've never worked with it before so I'm having some difficulties here. I'm trying to run the site in *localhost/myfolder*.

**The URL generated for images is:**

```
/sites/default/files/images/myFile.jpg

```

**The link is broken because it should be:**

```
myfolder/sites/default/files/images/myFile.jpg

```

***I have this on my sites/default/settings.php file:***

```
$base_url = 'http://localhost/myfolder';  // NO trailing slash!

```

***I also added this to my myfolder/.htaccess file:***

```
RewriteEngine on
RewriteBase /myFolder

```

I ran out of ideas, any help would be deeply apprecciated. Thanks.

# Answer
While migrating a site from a local instance to a staging instance there is always such problems of links of the images. we normally give **myfolder/sites/default/files/images/myFile.jpg** but while migrating to staging instance it should be **/sites/default/files/images/myFile.jpg** so that the server could trace the images.

If we use give **myfolder/sites/default/files/images/myFile.jpg** it would work fine within your local instance but while on staging it wont get loaded.

So always give **/sites/default/files/images/myFile.jpg** so that there is no problem....
> 0 votes

# Answer
You just have to use the following code.

```
$src = base_path() . path_to_theme() . 'images/myFile.jpg';

<img src= <?php echo $src; ?> />

```
> 0 votes

---
Tags: .htaccess
---


# Question
Title: The Nivo Slider library could not be found
This is the first time I use a CMS, and I'm trying to install nivo slider module into Drupal. I used the following commands

```
drush dl nivo_slider
drush en nivo_slider -y

```

Then I added some pictures to the slider but they are displayed without animation

And in the status report I have the following error message

> Nivo Slider jQuery plugin Not installed
> The Nivo Slider library could not be found.

# Answer
### Nivo Slider Requirements

You need to download the Nivo Slider Plugin and extract it to sites/all/libraries. The extracted folder must be named nivo-slider.
> 6 votes

# Answer
You have to set the field settings in the Views module; check the format settings.

This is for a view using the Views Nivo Slider module.

This is for a field formatting using the Nivo Slider module.

See https://drupal.stackexchange.com/questions/60520/nivo-slider-is-not-working-properly
> 1 votes

---
Tags: 7, drush, installation
---


title: How to add php in views?

text:
# Question
Title: How to add php in views?
I created a view, and I need to put some PHP or JavaScript in it. I would like to add some if conditions.

Is this possible?

# Answer
Yes, it is possible.

If you want to use PHP in views header, you can go to configure header, select "Global: Text area" and have to change text format to PHP code; you have to first install the PHP filter module.

If you want to use PHP in view fields, you can use the Computed field module.

If you want to use PHP in a view itself, you have to customize your views and then you can easily add PHP code to it.
> 3 votes

# Answer
It kind a depends of where in your view you want to use php. But if it is in fields there are two options:

1. Views Custom Field (d6 only)
2. Views PHP \- in dev though
> 3 votes

# Answer
in the field of view you can add Global PHP field
you can fiend this field in the header or in footer
> 0 votes

---
Tags: views
---


# Question
Title: Removing prefix for default language breaks all the link
Since I built the site I always used language prefix "en" for my site. English is my default language.

The thing is our SEO Expert said that this is content duplication for Google and we might get Panda penlty. Thus I removed "en" for English and now all my links are broken.

Thus, is there any way to do following:

**http://www.xyz.com/en/*\*business-opportunities/zimbabwean-supplier-beverage-flavourings-calls-financiers

automatically redirect it to "\**http://www.xyz.com/*\*business-opportunities/zimbabwean-supplier-beverage-flavourings-calls-financiers". So that I can save

# Answer
Google into htaccess rules if you have the apache module mod\_rewrite on the apache server (if it's an apache server you're using), you can make redirections based on REGEX patterns, so there's a little work for you there....
> 0 votes

---
Tags: uri, i18n-l10n
---


# Question
Title: Scaling image to 420px using Image Styles
I am using Image Styles to get the following effect:

width: 420px. height: no greater than 240px. Maintain aspect ratio.

To do this I have used Sale width 420 then crop 420x240, although any images which are less than 240 (height) get enlarged back to 240 using a black background.

I have also tried scale 420 then scale and crop 420x240 as this should only cut it off if it is larger, but it doesn't work, and stretches the image horizontally for any images with a height less than 240.

Any suggestions?

# Answer
If you use the ImageCache actions module, you will get some extra image effects. One is "Define Canvas." What you probably want to do is use "Scale" to make it 420px wide, and then use "Define Canvas" to put this on a canvas with the correct dimensions.
> 0 votes

---
Tags: 7, media
---


title: Display user's profile in a lightbox

text:
# Question
Title: Display user's profile in a lightbox
When a user clicks on the "My Account" link I would like the user's profile to show up in a lightbox much like the admin menu overlay works.

I am using Drupal 7.

I am not sure how to do this. My first attempt was to render $user\_profile and put it in a lightbox:

```
<div id="lightbox_this_div">
   <?php print render($user_profile); ?>
</div>

```

but $user\_profile is not available in page.tpl.php

Any thoughts?

EDIT: To be clear I just want to lightbox the content of the user's profile along with the tabs and be able to style the page. So I am not looking to lightbox the entire /user page with the site headers in an iframe style.

# Answer
> 1 votes
you need to "rel" tag in link.

```
<a href="/user" rel="lightframe[|width:400px; height:300px; scrolling: auto;]">My Account</a>

```

---

If you want show a specific region then use this.

```
<a href="/node/xxx #content-inner > *" rel="lightmodal[|width:700px;height:300px;]">Click to see only the content inside #content-inner</a>

```

---

Detailed tutorial can be found here

# Answer
> 0 votes
```
<a href="/node/[nid] .content" rel="lightmodal">
<img src="image.jpg" />
</a>

```

That's the right way... on d.org some retard edited documentation and now it messed up

---
Tags: 7, users
---


# Question
Title: How to figure which function(s) are triggered upon file download to check permissions
I am experimenting with private file system, done custom way :) .

There is file system/files/test.txt (That is, private://test.txt).

When I try to access the file, I get access denied from Drupal, **as expected** (site redirects to Access denied page, and dblog shows that accesss have been denied).

But now I want to know what module/function have blocked access to the file. I am blindly trying to check hook\_file\_download or hook\_file\_download\_access, but as far as I can see it does not go through that functions.

All that in attempt to solve this.

# Answer
If the Drupal log shows you that the access has been denied, then you have a simple way to debug this: if you have a debugger, simply set a breakpoint in drupal\_set\_message. Skip calls to that function (there shouldn't be too many) until you get the one with the access denied message - and then look at the backtrace. This should show you which function denied the access.

If you don't have a debugger, you can simply (temporarily) add some extra code in that function to test for the relevant error message, and then output a backtrace using debug\_backtrace. You can output the data on the screen, to a log file using drupal\_debug (if you have the devel module enabled), add it to the generated error message, etc.
> 3 votes

# Answer
This sounds as though its not Drupal blocking the access to this file but the filesystem. When Drupal runs it runs with the permissions of the webserver its running on. If the webserver can't access these files neither can PHP and subsequently Drupal.

A way to see if this is the problem is to set the file permissions on this test file to 777 and see what happens then.
> 0 votes

---
Tags: hooks, files
---


# Question
Title: Registration module, Rules, how to add the node-title of the registrated entity to notification mail
I have a registration form built with registration module to enable users to reserve tickets for events. Now i want to send notification mails to the site administrators to inform them about new registrations. The mails are sent via Rules "After saving a new registration" and i have all fields included except the node-title... the only "hints" of this field are the tokens \[registration:registration-id\] and \[registration:url\]. Can i transform these to human-readable items somehow? Is there a way to connect the registration-form to the specific node?

# Answer
> 1 votes
Figured it out. I had to add another action before the mail-action: "Fetch entity by id". Set the type to "Node" and the data selector to "registration:entity-id". After this all the node-specific fields were available for the mail-action.

---
Tags: 7, rules, users
---


# Question
Title: Having trouble adding a custom js file to my Drupal 7 site
I added a javascript file to my site in the theme's .info file

```
scripts[] = js/myjs.js

```

The js file loads and I can see that it's included in the head when I load the site, however the jQuery javascript doesn't work at all. I have a simple show/hide when a div on the page is clicked by it's not working.

This works fine when it is not in the Drupal site.

By clicking "Click here to start quiz" it should hide that div and show another.

I have a feeling it is because I do not have the most updated version of jQuery installed (I have 1.4.4 instead of 1.9.1), but I'm not sure how to update it for the theme I'm using.

Any ideas?

# Answer
> 0 votes
I was able to solve the problem by changing the document.ready function on the first line of my js file from: `$(document).ready(function () {` to: `jQuery(document).ready(function ($) {` I found the answer here:

---
Tags: 7, javascript
---


# Question
Title: Form Block module usage in multiple sections
While working a project i came across an issue with "Form Block" module. I used this block on a basic page in content section. Now my client also wants this same block in the right sidebar on the home page. Is there a way out to get the desired result.

# Answer
You could use the context module to achieve this. With this module you can show the same block in different regions on different pages. You can add a condition (like path is "/frontpage") and a reaction like show block xy in region xy.
> 2 votes

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


# Question
Title: How to create a contextual filter to be used as the first character for a field?
I create a view listing a field called `authors` the page path `miSite.com/authors`

Then if I load this page I get the results:

```
Bach
Vivaldi
Vaccaro
Babbitt

```

This view page has the path: `miSite.com/authors`

I need to create a contextual filter to filter the result for the first character of the author field. I should work in this way:

1) If I load:

```
miSite.com/authors/b

```

I get the results:

```
Bach
Babbitt

```

---

2) If I load:

```
miSite.com/authors/v

```

I get the results:

```
Vivaldi
Vaccaro

```

# Answer
> 3 votes
You can create a contextual filter for the node title and configure it in "glossary mode". Provide a fixed value "a" and check the glossary mode settings at the bottom of the settings page.

---
Tags: views
---


# Question
Title: How can I get the real password via hook_user_update()?
I want to change the current user password, and get the new password(the real password, not md5 encryption) when edit the account profile via user profile form(e.g.: example.com/user/1/edit) and save. would anyone can tell me how to do that? I tried using hook\_user\_update(), but it didn't succeed.

I mean I want to change the current user password, and I want to get the new password.

# Answer
Implement hook\_form\_alter() (or one of it relatives) such that it array\_unshift() a new submission handler to the user update form. The submission handler should add the password to the `$form_state['values']` array. You also have to add the same key to `$form_state['user']`, because of the way user\_profile\_form\_submit() calculates which keys from `$form_state['values']` to pass as `$edit` to your hook\_user\_update() implementation.

If you did not insist on using hook\_user\_update(), I'd suggest handling your custom additions to the password update directly in your submission handler.

By the way, Drupal 7 does not use a simple MD5 hash to store passwords.
> 3 votes

# Answer
How about reading it directly from $\_REQUEST array? I've added code like this:

```
function hook_user_presave(&$edit, $account, $category){
 echo $_REQUEST['pass']['pass1'];
}

```

and it works.
> 1 votes

---
Tags: 7, users
---


# Question
Title: Theme taxonomy term page with template override
I know this is far from duplicate but im a bit stupid. I am trying to theme the terms page for each term for a specific vocabulary i created. I 've used path auto when i was creating the terms so i have a specific path for each vocabulary term.

My website is using a subtheme that i created by copying and pasting the main theme which is ninesixty. So i have tried creating a new template for taxonomy terms like taxonomy-term--12.tpl.php added my html code and unfortunately the template wasnt overridden. I have also tried to override the template using the template.php file with no luck. I dont want to use any module so any clear answer will be helpful.

# Answer
You can use the below filename structure to create a taxonomy term template:

```
taxonomy-term--[vocabulary-machine-name|tid].tpl.php

```
> 4 votes

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


# Question
Title: Crumbs module won't display correct current page. Displays 'Anchor'
I am using the crumbs module to create a breadcrumb for my website. I have the **'Show the current page at the end of the breadcrumb trail.'** setting enabled however on one of my pages the current page is getting replaced with the word **'Anchor'**, instead of of **Home\>Products\>'Lambswool Dusters'**

Does anyone know where this is coming from? The name of the page is correct and all of my other breadcrumbs are being generated properly.

I might also add I am generating the urls using taxonomy terms and I do have page anchors on the page.

Output I am getting.

# Answer
I found the answer to my issue after using the crumbs debug tool. I had stupidly named a link **'Anchor'** when I was creating a menu and forgotten about this. This menu item was overriding the output I was looking for.

Here is my debug results if it helps anyone. Thanks to **donquixote** for pointing me in the right direction to use the debug tool.
> 0 votes

---
Tags: breadcrumbs, taxonomy-terms
---


# Question
Title: Changing a filter in a view without modifying the filter clone?
I duplicated a block from view using clone display, but when I change the language on the block cloned filter, the filter is changed in the master view also. How to avoid this? I need 3 blocks, the block to master the English language and the other 2 blocks to English and Spanish.

Thank you

# Answer
> 0 votes
When you're changing a filter, before you apply there's a dropdown box. It's probably set to "All displays (except overridden)" by default. Before you hit Save, change that All Displays to "This display only"

---
Tags: views
---


# Question
Title: Make download available after purchase of a physical good
I am running a UC Shop with Drupal which sells CDs and LPs and most of the time everything works like it should do.

Now I want to improve the service for our customers. For this reason, I want to give them the chance to download a zip-file with mp3s of every CD or LP they bought.

After we received the payment (so we set the order status to "payment received") the customers should get an encrypted link via mail or alternatively have a download button in their profile or so. It's no problem to make that possible only for authenticated users.

Any suggestions?

# Answer
Sounds like a possible job for the Commerce File module

> This module is an extension of Drupal Commerce that provides the ability to sell file access.
>
> * Ability to limit access to the file with limit settings
> * Default limits: duration, download count, IP address count
> * Limit default values can be inherited at the product level such that the product always uses the current default value
> * After purchase of a file, limits are statically recorded to the line item so that they do not reflect any changes to the product's file limits.
> * A user's limits reflect changes to an order, even after order is completed.

You can add a file field to your product entity type, and use the above module + rules to manage access to the file references by granting access licences. The licences are as liberal or as strict as you want to make them, so should be useful for your situation.

I've been using this module for a while and it works great
> 0 votes

---
Tags: ubercart, files
---


# Question
Title: Show full list of nodes that reference the node being shown
I have a content type (let's call it course) and a content type named edition (if we have a course named "English 101", we can have "English 101 - June", "English 101 - July" and so on.) For this, I used Entity Reference.

If I see the node "English 101-June", I can see the "*parent*" node being rendered (I chose that on Manage Display". What I want now, is when I see the "*parent*" node "English 101" the full list of referenced nodes to be rendered. How can I do this?

# Answer
> 1 votes
There are a number of ways to get reverse references. Probably the best option is to use the Views module. The reference module allows to create a reverse relationship in the view. You could do something like this:

* With the Views module, create a view of nodes with a page display at path 'myview' ;
* Set up your view to display only the title of each node ;
* In your view add an argument that matches your node id ;
* In your view add a reverse relationship that matches the field that is used to reference content. The name to use for the relationship would be something like `field_my_reference_field (reverse)`

Save the view, now go to 'myview/1' and you will see all the nodes that reference node 1. You could also get this displayed in a block, or as a field using the ViewField module.

If you don't want to use the Views module, then you can use the Nodereferrer module to achieve this. However in that case you can only get the list as a field - you can't get it as page or a block.

# Answer
> 0 votes
You can create a first view to list all your courses nodes.

And next, in a custom module, you display the references (with antoher view who accept an argument of the parent reference nid)

```
function custommodule_entity_view($entity, $type, $view_mode, $langcode) {

  list($id, $rev, $bundle) = entity_extract_ids($type, $entity);
  switch ($bundle){
  case 'course':
    if( $view_mode == 'full' ){
      $entity->children['children'] = array(
        '#markup' => '<h1>Childrens</h1>'. views_embed_view( 'childrens', 'default', $entity->field_course['und'][0]['nid'] ),
      );
    }
    break;
  }
}

```

---
Tags: 7, entities
---


# Question
Title: How to transfer data from views-view-fields.tpl to views-view-unformatted.tpl in D7?
I need to collect some data within views-view-fields.tpl, and then transfer it to views-view-unformatted.tpl to do some magic to the whole data-object. How could I do that? Thnx!

# Answer
I now put the following code into my template.php

```
$_SESSION['myVar'] = array();

```

but I don't know if this is the best solution...
> 0 votes

# Answer
You should use $view-\>result variable.

do dsm($view-\>result) and see if you find what you where looking for.
> 1 votes

---
Tags: 7, theming, views
---


# Question
Title: Drupal 6: integer field, how to output the value + a 3% up for a field, programmatically
I have a production website with a content type that has 3 integer fields. Now the website owner wants to raise those values in a 3%. Since there are hundreds of nodes for that content type, is there a way to modify the output in a 3% via a PHP snippet?

# Answer
The actual values can be updated. To increase the values by 3% you could use a snippet like the following and run it once, say in a hook\_cron, then remove it after the update is complete.

```
// Create a list of nodes of the required type
$result = db_query("SELECT nid FROM {node} n WHERE n.type = 'YourContentTpe'");
// Iterate through the list
foreach($result as $row) {
   // Load each node
   $node = node_load($row->nid);
   // Calculate your fields
   $node->field_1[0]['value'] = 1.03 * $node->field_1[0]['value'];
   // .. repeat for each field ..
   // Then save the node
   node_save($node);
}

```

This assumes that all the field values are set. To be rigorous, you should probably check this on each field before attempting to access them. This method uses Drupal functions to keep track of the updates, but hundreds of node\_load and node\_save functions could significantly impact your server performance while the code is being run.

To just display the altered information without changing the values in the database, You could create three computed fields, and use each to display the value in its base field incremented by 3% as suggested by Human love. This will probably lead to confusion in the future if new nodes are added and the author forgets to reduce the entered information by 3% to have it display correctly.

As much as I hate to advocate it, if this is a one-time update of the information, the most efficient method both in terms of your effort and of server resources would be direct manipulation of the database. Just make sure you back up the database before proceeding,:

```
UPDATE node n JOIN content_type_{YourContentType} f on n.nid = f.nid set f.field_field_1_value=(1.03 * f.field_field_1_value), f.field_field_2_value=(1.03 * f.field_field_2_value) WHERE n.type='YourContent_type';

```

for each of your fields. This assumes that the fields are exclusive to the content type. If the field is shared between content types, the field will appear in its own table and the above query should be modified accordingly.
> 4 votes

---
Tags: entities
---


title: add AJAX to an existing node/page path?

text:
# Question
Title: add AJAX to an existing node/page path?
I'm trying to add 'new' or 'updated' to the links in a Menu, and one of the ways is with AJAX. But to do that, I need to add AJAX to existing node/page path following the documentation and various examples, hook\_menu() successfully adds the scripts and call backs for paths that only exist in the module file

```
// The page that will run the command.
$items['my-custom-path/trigger-page'] = array(
  'title' => 'AJAX trigger page',
  'page callback' => 'my_ajax_trigger_page',
  'access arguments' => array('access content'),
  'type' => MENU_CALLBACK,
);

```

\[my\_ajax\_trigger\_page calls add\_ajax\_js and works with and without clean URLs\]

but when I add items for an existing node with a menu path, a page I created, and gave a URL path like 'my-toc-page' does not get registered for the AJAX calls. nothing happens - the scripts to not load on to the page at all, and the callbacks silently fail I have also tried this with a View, with AJAX enabled, but still it does not register

```
// register script load
$items['test-toc-page'] = array(
  'title' => 'MyTable of Contents',
  'page callback' => 'add_ajax_js',
  'access arguments' => array('access content'),
  'type' => MENU_CALLBACK,
);

```

How do you do this on a page that already exists and has content and blocks on it? No forms, but the links on the page need to be processed.

Using a page template file , I can load the JavaScript files onto an existing page, but the AJAX call backs fail.

Thanks everyone, this is a continuation of my initial question about AJAX on page load. Existing Page not getting registered by hook\_menu to trigger Drupal AJAX on page load

# Answer
> 1 votes
There are many ways to add scripts to an existing page, one option is:

```
/**
 * Implements hook_init().
 */
mymodule_init() {
  if ($some_condition) {
    drupal_add_js(drupal_get_path('module', 'mymodule') . '/mymodule.js');
  }
}

```

hook\_menu() probably isn't going to help you here, because each menu router item can only have one page callback.

---
Tags: ajax
---


title: Creating a Custom Formatter

text:
# Question
Title: Creating a Custom Formatter
I'm learning to develop for Drupal 7 and figured I'd start with something simple, like a custom formatter. I have a content type that contains several boolean fields indicating if the content type belongs to certain class of objects. When I create a view of the content types, all the boolean fields show a 1 or a 0, when I would like it to display an image instead. I created the following CheckBoxFormatter.module file

```
    <?PHP
        /**
         * @file
         * Creates a custom format for boolean fields, a checked checkbox for true
         * and unchecked for false
         */

        /**
         * Implements hook_field_formtatter_info()
         */
        function CheckBoxFormatter_field_formatter_info() {
            return array(
                'CheckBoxFormatter' => array(
                    'label' => t('Checkboxes'),
                    'field types' => array('boolean')
                ),
            );
        }

        /**
         * Implements hook_field_formatter_view()
         */
        function CheckBoxFormatter_field_formatter_view($obj_type, $object, $field, $instance, $langcode, $items, $display) {
            $elements = array();
            foreach($items as $delta => $item) {

                //Build variables array for formatter
                $element = array(
                    '#obj_type' => $obj_type,
                    '#object' => $object,
                    '#field' => $field,
                    '#instance' => $instance,
                    '#langcode' => $langcode,
                    '#items' => $items,
                    '#display' => $display
                );

                if (function_exists($function = "{$display['module']}_field_formatter_{$display['type']}")) {
                    $elements[$delta] = array(
                        '#markup' => $function($element)
                    );
                }
            }
            return $elements;
        }

        /**
         *  creates the actual checkboxes
         */
         function CheckBoxFormatter_field_formatter_CheckBoxFormatter($variables) {
             $img = array("<URL TO UNCECKED>","<URL TO CHECKED>");
             $disp = array("Unchecked","Checked");

             $element = array();
             foreach($variables['#items'] as $delta => $item) {
                 $element[$delta] = array(
                     '#markup' => '<img src="' . $img[$item['value']] . '" alt="' . $disp[$item['value']] . '" />'
                 );
             }

             return $element;
         }

```

I uploaded this to all/sites/modules/CheckBoxFormatter. I was able to activate the module in the modules section of my drupal site. Now, when I go back to the view I created, this new formatter doesn't show up. I also do not see it as an option under Manage Display for the content type. What am I doing wrong?

# Answer
Finally found it. I knew it had to be something simple. I was using the wrong field type. Turns out it should have been list\_boolean instead of simply boolean. I also simplified the code

```
    <?PHP
        /**
         * @file
         * Creates a custom format for boolean fields, a checked checkbox for true
         * and unchecked for false
         */

        /**
         * Implements hook_field_formtatter_info()
         */
        function CheckBoxFormatter_field_formatter_info() {
            return array(
                'checkboxes' => array(
                    'label' => t('Checkboxes'),
                    'field types' => array('list_boolean')
                ),
            );
        }

        /**
         * Implements hook_field_formatter_view()
         */
        function CheckBoxFormatter_field_formatter_view($obj_type, $object, $field, $instance, $langcode, $items, $display) {
            $output = array();
            $img = array("uncheck.jpg","check.jpg");
            $disp = array("Unchecked","Checked");

            if($display['type'] == "checkboxes") {
                foreach($items as $delta => $item) {
                    $output[$delta] = array(
                        '#markup' => '<img src="' . $img[$item['value']] . '" alt="' . $disp[$item['value']] . '" />'
                    );
                }
            }
            return $output;
        }

```
> 2 votes

---
Tags: entities
---


# Question
Title: Setting up regex-style rewrite rules within Drupal?
I have a couple of legacy rewrite rule redirects that I've traditionally put in .htaccess. For instance, paths are of the format:

`story/[story:title]`

And paths like:

`story/[story:nid]`

redirect to that.

Is there any way of setting up regex-matching redirects within Drupal? I could always do it in .htaccess, but that would get overwritten on the next Drupal core update. Further, it seems that Boost is nerfing any redirect I put in .htaccess -- the above hasn't worked since I installed its redirect rules.

Thanks!

# Answer
> 3 votes
Well if you are familiar with PHP and preg\_match, you could theoretically install Drupal rules module and write custom rules using PHP to redirect pages inside Drupal without touching .htaccess file.

# Answer
> 1 votes
It just dawned on me that you don't *need* to define Rewrite Rules in .htaccess — if the goal is to prevent Drush from nuking custom rewrites during Drupal core updates, it makes **way** more sense to just put them straight into the httpd.conf VirtualHost directive (If you have access to that).

See: https://serverfault.com/questions/120488/redirect-url-within-apache-virtualhost

Leaving question open in case somebody has a better solution more applicable to a broader cross-section of the community (I.e., users on shared hosting without access to .conf files).

---
Tags: 7, redirection, path-aliases, uri
---


# Question
Title: How do I find which file contains a function?
How do I find where a Drupal function is defined? For example, in which Drupal file is `db_query()` defined?

# Answer
You can find it at **includes/database/database.inc**, line 2342.

Your editor may be providing a similar feature like the one implemented in Zend studio: When you press control while you click on the function name, it will take you to the file containing the implementation of that function.
> 2 votes

# Answer
Drupal.org API shows which file contains a Drupal function, class, or method for which you are looking the documentation. In the case of db\_query(), this is what the site shows.

That is also a link that takes you to a page showing the content of that file.

Notice that the documentation for Drupal 8 is not actually complete. For some reason, Drupal 8 files are not completely parsed, and it can happen you don't find on Drupal.org API a class or method Drupal 8 defines.
> 1 votes

# Answer
For anyone reasonably comfortable with a CLI.

Find functi`on`: `grep -rn "on db_query" *`

Find cla`ss`: `grep -rn "ss Node" *`
> 1 votes

---
Tags: database
---


# Question
Title: Add a class to a field based on the page regions
I have my field tpl file which sets in a div classes 'field-item', 'odd/even' etc. I need to dynamically assign a class to it based on the regions that exist on the page. I am using bootstrap theme and the class I need to add reflects the column span count, so f I have a sidebar on the left I will have less space for that field and need a narrower column class.

Bootstrap already comes with a function doing it for page preprocess:

```
function mytheme_preprocess_page(&$variables) {
  // Add information about the number of sidebars.
  if (!empty($variables['page']['sidebar_first']) && !empty($variables['page']['sidebar_second'])) {
    $variables['columns'] = 3;
  }
  elseif (!empty($variables['page']['sidebar_first'])) {
    $variables['columns'] = 2;
  }
  elseif (!empty($variables['page']['sidebar_second'])) {
    $variables['columns'] = 2;
  }
  else {
    $variables['columns'] = 1;
  }

```

So basically what I need is to make my field aware of that page variable. How can I use this variable on my field tpl file?

# Answer
A quick look shows that the content region is wrapped in a class derived from that $columns variable, getting it from this function...

```
/**
 * Returns the correct span class for a region
 */
function _bootstrap_content_span($columns = 1) {
  $class = FALSE;

  switch($columns) {
    case 1:
      $class = 'span12';
      break;
    case 2:
      $class = 'span9';
      break;
    case 3:
      $class = 'span6';
      break;
  }

  return $class;
}

```

...so you should be able to use the cascading features of CSS to theme your field, eg...

```
.span12 .your-field-stuff {
  /* widescreen */
}

.span9 .your-field-stuff {
  /* one sidebar */
}

.span6 .your-field-stuff {
  /* two sidebars */
}

```
> 0 votes

---
Tags: entities, bootstrap-theme
---


# Question
Title: Best CSS and JS aggregation/minification strategy for D7
Drupal 6 has the awesome advagg module, which does an awesome job of *intelligently* bundling CSS and JS, but currently no D7 release.

What I am looking to achieve is:

* less CSS and JS files (5 CSS and 5 JS files is far too many)
* JS files have minification (currently core only does this for CSS)

Is there a drupal 7 solution that will help here? What are other people's experience with optimising this?

---

**Edit:** The question was originally posted in 2011. There is now a very stable D7 release of advagg.

# Answer
For D7, there's Core Library which has a learning mode that aggregates based on real-world statistics about your site.

If you want to brute-force everything into one giant aggregate, I've written an article with some sample code:

```
/**
 * Implements hook_js_alter().
 */
function mymodule_js_alter(&$javascript) {
  uasort($javascript, 'drupal_sort_css_js');
  $i = 0;
  foreach ($javascript as $name => $script) {
    $javascript[$name]['weight'] = $i++;
    $javascript[$name]['group'] = JS_DEFAULT;
    $javascript[$name]['every_page'] = FALSE;
  }
}

/**
 * Implements hook_css_alter().
 */
function mymodule_css_alter(&$css) {
  uasort($css, 'drupal_sort_css_js');
  $i = 0;
  foreach ($css as $name => $style) {
    $css[$name]['weight'] = $i++;
    $css[$name]['group'] = CSS_DEFAULT;
    $css[$name]['every_page'] = FALSE;
  }
}

```

Drupal.org issue #1034208 also proposes relaxing the strict ordering requirements slightly.
> 12 votes

# Answer
AdvAgg D7 is being developed. Other options (quotes included are from their project pages):

> ... allows on-the-fly minification of site JavaScript with uglify.js. The module relies on a web service (uglify.me) by default to do the minification so you do not need to do any pre-processing on your server to enjoy the benefits of minified JavaScript.

> ... designed to help speed up front end performance in a site. In this first release of the Speedy module it provides minified versions of core JavaScript files that are not already minified. For example, a minified version of drupal.js is provided while jquery.js (already minified) is not.
> 3 votes

---
Tags: 7, theming, performance, css-js-aggregation
---


title: Appending output to a file?

text:
# Question
Title: Appending output to a file?
I am developing a custom module and I want to write debugging output to a log file so I can monitor it in real time, and not wait to navigate to watchdog.

I was using `file_save_data()` to write to the public file system, but quickly noticed that it was making `log1.txt`, `log2.txt`, `log3.txt`, etc. I want all my log messages to go into the same file. I looked at the documentation, and saw that the only flags that exist are `FILE_EXISTS_REPLACE`, `FILE_EXISTS_RENAME`, and `FILE_EXISTS_ERROR`. Sadly for me, no `FILE_EXISTS_APPEND`.

What is the drupal way to append data to a file on the file system? Or should I just use native php functions?

# Answer
There is no existing way to append data to an existing file. Only modes you have listed in the question.

You will have to go for native PHP functions (`a` mode in `fopen()` or `FILE_APPEND` in `file_put_contents()`).

**Some pointers:**

Consider using `hook_watchdog()`. You can filter what you need to log to the file using the `type` key of the passed array.

Don't forget that there is also a module, `syslog`, to log these watchdog entries to syslog.

You can also use `dd()` function from devel module to easily log specific data to a temp file.

> dd()
>
> Logs any variable to a file named “drupal\_debug.txt” in the site’s temp directory. All output from this function is appended to the log file, making it easy to see how the contents of a variable change as you modify your code.
>
> If you’re using Mac OS X you can use the Logging Console to monitor the contents of the log file.
>
> If you’re using a flavor of Linux you can use the command “tail -f drupal\_debug.txt” to watch the data being logged to the file.
>
> dd($data, $label = NULL)
> 1 votes

---
Tags: files
---


# Question
Title: Selectively purging views from varnish cache
We are trying to optimize our site's performance with Varnish together with the Cache Expiration module to selectively purge only the updated content from varnish.

However, one problem has come up, since we are listing content with Views, the expire module has no way of knowing which pages the updated content is listed on, and can't purge these at the same time the node url gets purged.

I guess we could purge all content from Varnish at regular intervals using cron, but that would also remove lots of perfectly valid content from the cache. Has anyone manage to solve this in a nice way?

# Answer
> 1 votes
If the views are blocks you can use something like http://drupal.org/project/block\_refresh and set a short expiration for the ajax callback that module uses.

If you want to get more advanced, you could strip the JS stuff out of that module and use its ajax callback, then use edge-side includes to have varnish pull in the block content dynamically.

---
Tags: 7, views, proxies
---


# Question
Title: Custom module menu path renaming/redirection
Is it possible to create path like subdomain for custom module menu?

For example create url like xyz.example.com if path is example.com/xyz where xyz is custom module menu.

I've already tried to use .htaccess file

```
RewriteCond %{HTTP_HOST} ^(www\.)?example\.com$
RewriteRule ^xyz(.*) http://xyz.example.com/$1 [R=301,L]

```

It correctly changing url from example.com/xyz to xyz.example.com but xyz.example.com redirected me to HOME page of the site.

I just want to change the url from example.com/xyz to xyz.example.com where module result will be displayed.

Thanks.

EDIT : My requirement is similar to this

# Answer
> 3 votes
You could modify `$_GET['q']` during `hook_boot()`, something like the following.

```
function mymodule_boot() {
  $_GET['q'] = implode('.', array_slice(explode('.',$_SERVER['HTTP_HOST']), 0, -2));
}

```

There is probably a regex that could do the same as that explode/implode mess, but that does the trick to start with.

# Answer
> 0 votes
$1 will be example.com/... not the module path that you want.

Specify the path as per:

```
RewriteCond %{HTTP_HOST} ^(www\.)?example\.com$
RewriteRule ^ mymenupath [R,L]

```

Where you say the menu (mymenupath) is set up in your custom module.

Log the rewrites in your apache config to verify where the redirects are going:

```
LogLevel alert rewrite:trace3

```

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


# Question
Title: How to stop infinite loop on hook_node_grants
I am using hook\_node\_grants to provide access to a realm based on whether someone is an 'owner' of a node. The issue is that menu\_get\_object() may call hook\_node\_grants recursively.

```
function hottopics_node_grants($account, $op) {
  $grants = array();
  ...
   try {
      $node = menu_get_object();
    } catch (Exception $e) {
      // URL mustn't be the correct format.
      return $grants;
    }
   ...
    // Is the person a member of the administrator group, or the owner of the parent node?
    if (module_invoke('hottopicsresearch', 'display_moderated_research_access_callback', 'update', $node)) {
      $grants['view_hottopics_manager'] = array(1);
    }

    return $grants

```

The code recurses at $node = menu\_get\_object(). Drupal-7.

# Answer
> 0 votes
Load the node directly:

```
  // Do not use $node = menu_get_object();
  // This calls hook_access which results in a recursive loop
  $node_url = $_GET['q'];
  $nid = array_pop(explode('/', $node_url));
  if (!is_integer($nid)) {
    return $grants;
  }
  $node = node_load($nid);

```

# Answer
> 0 votes
The infinite loop you are noticing is caused from the fact that `menu_get_object()` causes Drupal to verify the currently logged-in user has access to the node, which causes your implementation of `hook_node_grants()` to be invoked again, which calls `menu_get_object()`, which causes your implementation of `hook_node_grants()` to be invoked again, which….

It is hook\_node\_access\_records() that has access to the node object; the code you are using in `hook_node_grants()` should be used in `hook_node_access_records()`.

See Node access rights for more information. In short, `hook_node_grants()` returns a `realm => GID` array, while `hook_node_access_records()` return an array containing realm, GID, priority, and three 0/1 values for the view/update/delete permissions the current user has.

---
Tags: nodes, users
---


# Question
Title: Transliteration- Is it possible to transliterate filenames (and update the DB) after files have been uploaded?
I have a website that allows users to upload pictures. To reduce the amount of space used by pictures files on my site, I attempted to use a script to remove orphaned files. However, this script chokes on Unicode file names; there are dozens of pictures with Unicode file names on my site:

> query:You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 's Adorable Kitty EDIT.jpg'' at line 1

I have enabled the Transliteration module so that new files will not have this problem. However, what can I do about the old files? Is there a way to change their names and update the Drupal DB? I am willing to do this manually if necessary, but I don't know how to approach this.

**EDIT**: Upon closer inspection, the problem is not unicode, it's the quote marks in the filename.

# Answer
> 1 votes
As far as I am able to tell, the script works OK with Unicode.

But the script doesn't sanitize the file names, and that is what invalidates the query.

It could be a a lot worse. If somebody uploads an image named `image'); DROP TABLE *;--.jpg`, and you use that script, they would erase your site (as shown in the XKCD cartoon below):

Source: xkdc - Exploits of a mom

I would strongly advice postponing the use of that script until somebody who understands database security has cleaned it up.

Suggestion: hand edit the file names with quotes in them by removing the quotes, and edit the corresponding names in table `file_managed`.

I am also puzzled that the Drupal file upload module does not sanitize file names by not permitting quotes in file names.

---
Tags: files
---


# Question
Title: User registration form change Username to name
I want to change the label of a registration form from 'Username' to name. I had used 'String overrides' module. But its not effecting. Is there any way out. please help me out.

# Answer
You can do that by implementing hook\_form\_alter() in your custom module:

```
function MODULE_form_alter(&$form, &$form_state, $form_id) {
  if($form_id == 'user_register_form') {
    $form['account']['name']['#title'] = t('Name');
  }
}

```
> 3 votes

---
Tags: users
---


# Question
Title: How to migrate from DotnetNuke to Drupal?
Currently we have DotNetNuke (= DNN) websites. We are planning to move the DNN websites into the Drupal platform.

My questions: how do I migrate the DNN content and users tables into the Drupal Mysql tables?

I have tried with Drupal Migrating Handbooks, but no luck.

# Answer
> 5 votes
There is a very good module to assist migration from other CMSs to Drupal called the Migrate module.

> The migrate module provides a flexible framework for migrating content into Drupal from other sources (e.g., when converting a web site from another CMS to Drupal). Out-of-the-box, support for creating core Drupal objects such as nodes, users, files, terms, and comments are included - it can easily be extended for migrating other kinds of content. Content is imported and rolled back using a bundled web interface (Migrate UI module) or included Drush commands (strongly recommended).

Link : Documentation.

---
Tags: migrations
---


title: Theme with tpl.php

text:
# Question
Title: Theme with tpl.php
I am trying to theme a data table with a tpl.php file. I am placing the theme-table.tpl.php file in the project. How do I call it to theme from within the code? The file contains html and php prints.

Thanks

# Answer
In your mymodule.module, you should first declare a theme:

```
/**
 * Implementation of hook_theme.
 */
function my_module_theme() {
  return array(
    'my_module_page' => array(
        'variables' => array('mydata'=>"Default value"),
        'template' => 'my_module_page',
     ),
  );
}

```

The value of template is the filename of your tpl.php file.

You can use the variables array to pass data to the template, just like I will be doing here with mydata.

Then, in any function of your module, you can create a renderable array, render it using `drupal_render` and output it, or print it, depending on your needs.

```
$renderable = array(
  '#theme' => 'my_module_page',
  '#mydata' => "Hello World!",
);

return drupal_render($renderable);

```

So, your template (my\_module\_page.tpl.php) should look like:

```
Here is my template data : <?php echo $mydata ?>

```
> 1 votes

---
Tags: theming
---


# Question
Title: Drupal 7, Ubercart, Product search by price range
I'm using Ubercart 3.x, Drupal7. Can anybody tell me how can I create a form for searching in products with price in specified interval? I.e. user should fill this form with minimum price in the interval and maximum price and after posting form he will see all suiting products.

# Answer
> 2 votes
There are two ways of doing it: One is using views and 2 price exposed filters, one with "value bigger than" and the other one with "value smaller than".

The other solution is using Search API ranges module.

> The Search API "ranges" module provides widgets for Search API range queries. Currently includes:
>
> * jQuery UI min/max slider.

To use it, you will need to use Facet API, follow a tutorial here.

I hope this helps you

---
Tags: 7, views, ubercart
---