# Question
Title: Can't use file field in custom form - gives AJAX errors
I'm building my own form for editing certain fields on a node type, and I'm using field\_attach\_form() to add the fields from that node type to my form.

Use field\_attach\_form() to get the fields added to the $form array, and then I hide the ones I don't need by setting them to `'#access' => FALSE`. For all the textual fields, selects, etc., there's no problem. But when I use a file field (for image uploads), and someone selects a file and clicks 'Upload' on that file field, I get the following two errors:

```
Notice: Undefined index: field_picture in file_ajax_upload() (line 268 of /path/to/drupal/modules/file/file.module).
Notice: Undefined index: #suffix in file_ajax_upload() (line 277 of /path/to/drupal/modules/file/file.module).

```

I noticed over on drupal.org, merlinofchaos mentioned that a user could use form\_load\_include() to include an include that needs to be loaded with the particular form (see: http://drupal.org/node/1161430#comment-4540578), but that was more because that guy additionally had something else he was loading, I think.

The form is built in mymodule.pages.inc, and is called through a menu callback at a path like /admin/config/mymodule/edit-form. What am I missing?

# Answer
> 2 votes
As it turns out, in my case, there was one place where I wasn't returning the proper form API array in the first step of the form processing, so when the file field tried refreshing/rebuilding the form via AJAX, it messed up the form state. A friend and I had to step through the entire submission process to figure out where we were losing the correct form state.

That was what happened to *me*; other people may be helped by the patch mentioned in V-A's answer, so I gave that an upvote as well.

# Answer
> 2 votes
This is a bug in Drupal. The patch in comment #6 works.

---
Tags: 7, forms, files
---


# Question
Title: How to use an aliased content title for a Views contextual filter?
I've set up a page view with a path of 'services/communication/%' the '%' being a contextual filter of 'Content: Title'.

The problem with this is that the url ends up looking something like 'services/communication/Best Practices'. In the contextual filter I have set the case to 'lower case' and checked the box to 'Transform spaces to dashes in URL', however, neither of these things are doing anything.

In most cases the link to some content works fine but if there is a dash in the content title (e.g. 'online-led reporting') the content won't display.

How can I use an aliased content title with the contextual filter?

# Answer
How I attacked the spaces/punctuation issue ( http://drupal.org/node/786612 ) in Drupal 6 was by creating a `url_safe_title` text field and putting it in any content type that needed to be looked at, searched for, etc by it, and then having nodeapi() "fill it in for me" like this:

```
function MODULE_nodeapi(&$node, $op, $teaser = NULL, $page = NULL) {
  if (isset($node->field_url_safe_title) && $op == 'presave') {
      module_load_include('inc', 'pathauto');
      $node->field_url_safe_title[0]['value']=pathauto_cleanstring($node->title);
  }
}

```

You can get fancy and hide the field with permissions, css etc so your users don't see it when creating content. I use http://drupal.org/project/nodeformcols to hide it and hide it from $content on display, too.

So, what this does is change simple titles like `Hello World` into `hello-world` but also `online-led reporting` into `online-led-reporting` with the added/needed benefit of being able to get back to "online-led reporting" from it. It also helped out with stuff like `Kukla, Fran and Ollie` that turned into `kulka-fran-ollie` :)

So now in Views I use this field instead of the node title when I needed to grab things. Just have to be aware of uniqueness, but that's another story in of itself :)
> 1 votes

---
Tags: path-aliases, views
---


# Question
Title: Removing username from personal contact form
On the personal contact form, when someone cc themselves, the username of the user they are emailing is exposed. Many users actually type their full name as username, so for them to remain anonymous, I don't want username to be exposed to others.

# Answer
You can customize the email with `hook_mail_alter(&$message)`.
> 1 votes

# Answer
The email that is send in those cases is set by contact\_mail(), which is `hook_mail()` implementation done from the Contact module, and that contains the following code:

```
  switch ($key) {
    case 'page_mail':
    case 'page_copy':
      $message['subject'] .= t('[!category] !subject', $variables, array('langcode' => $language->language));
      $message['body'][] = t("!sender-name (!sender-url) sent a message using the contact form at !form-url.", $variables, array('langcode' => $language->language));
      $message['body'][] = $params['message'];
      break;

    case 'page_autoreply':
      $message['subject'] .= t('[!category] !subject', $variables, array('langcode' => $language->language));
      $message['body'][] = $params['category']['reply'];
      break;

    case 'user_mail':
    case 'user_copy':
      $variables += array(
        '!recipient-name' => format_username($params['recipient']),
        '!recipient-edit-url' => url('user/' . $params['recipient']->uid . '/edit', array('absolute' => TRUE, 'language' => $language)),
      );
      $message['subject'] .= t('[!site-name] !subject', $variables, array('langcode' => $language->language));
      $message['body'][] = t('Hello !recipient-name,', $variables, array('langcode' => $language->language));
      $message['body'][] = t("!sender-name (!sender-url) has sent you a message via your contact form (!form-url) at !site-name.", $variables, array('langcode' => $language->language));
      $message['body'][] = t("If you don't want to receive such e-mails, you can change your settings at !recipient-edit-url.", $variables, array('langcode' => $language->language));
      $message['body'][] = t('Message:', array(), array('langcode' => $language->language));
      $message['body'][] = $params['message'];
      break;
  }

```

As visible in contact\_personal\_form\_submit(), the message identifier for the email sent when somebody contacts another user is "user\_mail."

Implementing hook\_mail\_alter() using something similar to the following code, you should achieve the task you want.

```
function mymodule_mail_alter(&$message) {
  switch ($message['key']) {
    case 'user_mail':
    case 'user_copy':
      $language = $message['language'];
      $message['body'] = array();
      $params = $message['params'];
      $variables = array(
        '!site-name' => variable_get('site_name', 'Drupal'),
        '!subject' => $params['subject'],
        '!recipient-name' => format_username($params['recipient']),
        '!recipient-edit-url' => url('user/' . $params['recipient']->uid . '/edit', array('absolute' => TRUE, 'language' => $language)),
        '!form-url' => url($_GET['q'], array('absolute' => TRUE, 'language' => $language)),
        '!sender-name' => format_username($params['sender']),
        '!sender-url' => $params['sender']->uid ? url('user/' . $params['sender']->uid, array('absolute' => TRUE, 'language' => $language)) : $params['sender']->mail,
        '!recipient-name' => format_username($params['recipient']),
      );

      $message['subject'] .= t('[!site-name] !subject', $variables, array('langcode' => $language->language));
      $message['body'][] = t('Hello !recipient-name,', $variables, array('langcode' => $language->language));
      $message['body'][] = t("A user (!sender-url) has sent you a message via your contact form (!form-url) at !site-name.", $variables, array('langcode' => $language->language));
      $message['body'][] = t("If you don't want to receive such e-mails, you can change your settings at !recipient-edit-url.", $variables, array('langcode' => $language->language));
      $message['body'][] = t('Message:', array(), array('langcode' => $language->language));
      $message['body'][] = $params['message'];
      break;
  }
}

```

I altered the message with *key* equal to *user\_reply*, which is the message returned to the user who sends the message. In this way the CC returned to the sender is the same message sent to the recipient.
> 1 votes

---
Tags: emails
---


# Question
Title: Store token replacement values in the database rather than tokens themselves
Is there a way to store the token replacement values of tokens put in a form field in the database rather than the tokens themselves?

I have a text field in a custom content type that has a token as default value (using Token Filter), \[current-user:uid\], so on node creation the replacement value is inserted into the node. In the database, it's stored as '\[current-user:uid\]', rather than as the replacement value. What is one way of storing the replacement value rather than the token string in that table?

# Answer
> 1 votes
The gist of it is to execute token\_replace in a suitable location. Here's an example.

```
hook_node_presave($node) {
  if ($node->type == 'page') {
    $replaced_text =  token_replace($node->field_with_replacements['und'][0]['value']);
    $node->field_with_replacements['und'][0]['value'] = $replaced_text;
  }
}

```

---
Tags: 7, tokens
---


# Question
Title: Change Taxonomy Page to display first node in full
By default in Drupal 7, a taxonomy page lists the titles of all the nodes that have been tagged with that term.

Is there any way to make it so the page shows just the first node that is tagged with that term?

I want it so the first node is displayed in full (Ideally, the term page should automatically take the user to the first node).

I know you can use Views to override a taxonomy and control what content is shown. However, I would like to do this without views (i.e. so the user is seeing the acutal node as opposed to a view of the node).

I also want it to happen automatically (i.e. for every term, the first node should displayed. The admin of the site should not have to manually set up this state for each individual term).

# Answer
> 1 votes
The way to do this is to enable the "Taxonomy term" view in Views: Add and offset of 1 to the page view:

And then add and Attachment display that has a pager with an Offset of 0 and an Items per page as 1. On the attachment you can switch the Format to show full nodes instead of teasers.

This will work "automatically" for all Taxonomy terms. The reason this works is that the view takes an argument of the taxonomy term in the URL.

It overrides Drupal core's url for Taxonomy terms and uses the view as a replacement.

---
Tags: taxonomy-terms
---


# Question
Title: How to enable theme on profile installation
I am creating a drupal 6 installation profile and I want to enable a specific theme on installation. How can I do that?

# Answer
In your profile\_name.info, add a new line with `theme = mytheme`.
> 4 votes

# Answer
Use Install Profile API's install\_enable\_theme() function.
> 2 votes

---
Tags: 6, theming, distributions
---


# Question
Title: Make a gmap view embeddable on another site
The website I'm building has a google map view. I want to provide a code snippet to site visitors to let them embed this gmap view on their own site. Does anyone know of a way to accomplish this in D7?

I saw this question over at the SO main site, but it appears to be D6-specific since Embed Widgets doesn't have a D7 release and Web Widgets only has an abandoned D7 release. So I'm wondering if there's another way to do this.

# Answer
You could create your own iframe: http://www.iframehtml.com/

You will most likely want to create custom page output so that you aren't including extra regions from your site. You can do so by creating a custom html.tpl.php template (might not be necessary) and page template for the map.
> 2 votes

---
Tags: 7, views, google-maps, nodes
---


# Question
Title: What is the true impact of Panels Everywhere on theming and layout duties?
From an answer on another question:

> If you have chosen Precision because it is minimalist, then you might want to consider adding the 'Panels Everywhere' module. This module works very well with Panels (same authors) and allows you to bypass the Drupal Theming process altogether. This greatly simplified my styling work.

1. Does this mean regions and blocks are completely ignored with Panels Everywhere (PE) in favor of panels only?
2. If so, does it mean one has to recreate some layout for standard pages such as node edition and publishing for example? I have an editor user profile to create specific content. Do I loose all the layout of existing Drupal screens the user could access?
3. After enabling PE, what configuration is expected regarding layout and theming (CSS) on standard pages delivered by Drupal?

Fact is, when trying PE with the Precision theme, I lost layout on all standard pages, but I want to know if this is a configuration issue or not.

# Answer
> 1 votes
From my own findings:

1. Yes. In fact, one can set a site template which (more or less) replaces the concept of regions.
2. No, one should set a site template and not forget to have a `Page Content` pane.
3. None, except for the site template itself. Eventually, some can be set on the `Page Content` too.

---
Tags: 7, panels, theming
---


title: redirect sub domain in htaccess file

text:
# Question
Title: redirect sub domain in htaccess file
I have tried a number of ways to try to redirect a sub url in my htaccess file with very little progress, and I know I am doing it correctly but for some reason it just is not working, and as far as I can tell there is no module that can do this. I am simply trying to direct a sub domain to the main domain.

This is the code I am using.

```
  RewriteBase /
  RewriteRule ^red.sitename.com$ http://sitename.com/ [R=301,L]

```

Now I have red somewhere that you have to do it this a certain way when clean urls is enabled and this is suppose to be the correct way but it is not working.

# Answer
> 4 votes
The piece you are missing is RewriteCond.

This should redirect just the subdomain

```
RewriteBase /
RewriteCond %{HTTP_HOST} ^red\.sitename\.com$ [NC]
RewriteRule ^(.*)$ http://sitename.com/$1 [L,R=301]

```

Note also that the separator needs to be escaped as `\.` to prevent it from being used as a single character match in the pattern. The `[NC]` also tells Apache to ignore case during the match.

---
Tags: 7
---


# Question
Title: Any way to convert a page of type X into page of type Y?
I inserted a webform on a Basic Page. Now, I decided I should have created a dedicated content type to hold that webform.

So now - is there an easy, non-risky way to "migrate" that page to a new content type without the need to recreate it?

I would like to save myself a couple of moments redefining the webform from scratch, but if the db dependencies are too complex, I would rather take that cost rather than risk screwing up the db.

# Answer
The Node Convert module allows you to convert individual nodes (it adds a convert tab to the node) and bulk convert. It also handles moving over values in CCK fields from one node type to another.
> 1 votes

---
Tags: nodes, webforms
---


title: Allow html tags?

text:
# Question
Title: Allow html tags?
The full html setting is only allowing certain tags to go through. How do I turn this off and allow all tags?

> Full HTML
> Allowed HTML tags: `<a> <blockquote> <br> <cite> <code> <dd> <div> <dl> <dt> <em> <li> <ol> <p> <span> <strong> <ul>`

# Answer
You just need to edit the filter.

Go to http://mysite.com/admin/config/content/formats/full\_html, un-tick the "Limit allowed HTML tags" checkbox and press "Save configuration".

**EDIT**

Note that the above is for Drupal 7. For Drupal 6 go to http://mysite.com/admin/settings/filters and click "configure" on the Full HTML format. Then un-tick the "HTML filter" checkbox and again press "Save configuration".
> 3 votes

---
Tags: nodes
---


# Question
Title: Show content that referenced to a user to him
In my site I have a content type with a **user reference field**.

I want to create a *view* to show contents to a user that are referenced by this user reference field.

How would I do this?

# Answer
> 2 votes
If you have a content type with a user reference field and you want to display a list of these content types that reference the currently logged in user, you could create a view, Filter it on published nodes of that type, and then add in an Argument, which would be the field in question, and then supply as the default argument the uid of the currently logged in user. Then just set up whatever Fields you want displayed and you should be on your way.

---
Tags: views, entities, users
---


# Question
Title: Drupal accounts with dead addresses: how to de-activate?
on my drupal website, there are a lot of users with an invalid email address. I know because, either they have never logged in or their mails bounce. But I have to check manually, which is not good.

When a user signs up with an email address, they receive a confirmation email. Is there a way to automatically disable an account if the user does not log in within the first day after receiving this confirmation mail?

Alternatively, it would be OK to keep the accounts disabled until the user clicks a link on the confirmation mail.

Are there plugins or settings in Drupal to do this?

# Answer
> 4 votes
Drupal's LoginToboggan module does this. In the settings, there is an option to "Delete unvalidated users after:" and then you select a time period. It runs with cron so you can "set it and forget it."

# Answer
> 1 votes
I think you're looking for the Inactive User module.

# Answer
> 0 votes
I'm not sure about drupal specific plugins, but I think most sites keep users inactive until they click the confirmation link if asked (otherwise why send a confirmation). Alternatively I've seen several sites with an expiration on their confirmation - IE

"you're seeing this because you signed up on example site, please confirm by clicking the link below, if this is a mistake then do nothing and the account will be closed in 24hours"

---
Tags: emails
---


title: After each View Item

text:
# Question
Title: After each View Item
I made a block using the Views module, that displays 3 blog posts. It only displays the title and the teaser, and I want to add a "Read More" after each blog post teaser. I can only see how to add a footer to the end of the whole block, not after each listed item. Is this possible? thanks

# Answer
> 1 votes
Sure, add a Node: Link field, turn off the label, and set the Text To Display to "Read More" and you should be set.

---
Tags: views
---


# Question
Title: How can I manage a users collection of products?
I am pretty new to Drupal, and I am tasked with creating a Drupal 7 site that has a lot of products; I need to enable users to maintain a list of the products that they own/have.

Basically I need the ability to take a list of products and allow a user to check off the ones they have and the ability to save this data associated with the user. Is there a module that I should take a look at, or can someone point me in the right direction?

# Answer
Check out the Flag module. You could create a product content type and then your users could flag which individual products they have.
> 1 votes

---
Tags: 7
---


# Question
Title: How to show a view of content types on another content type
I have one content type 'class' and I have another content type 'lesson' and I want to easily display all lessons that belong to a class on the view of a 'class.' Is this possible and if so, how?

# Answer
> 5 votes
I would take a look at the "Panels" module, which allows you to create custom pages that can display multiple Views displays in one page.

-

Alternatively, instead of creating multiple content types, consider utilizing taxonomy terms to differentiate your classes and lessons.

For instance, create a list of terms for a new vocabulary "Class", which differentiates the different types of class.

Then, for each of your "Lesson" content type nodes, apply the specific class taxonomy term which applies.

Finally, you can create a View which displays Lessons content nodes, and have it filter the results to those Lessons which are tagged with a specific "Class" taxonomy term.

# Answer
> -1 votes
Good question. This requires a trick which is not easy to discover unless you've seen it before!

I'm assuming your Lesson type has a 'node reference' linking each Lesson to its appropriate Class? If not, that's a good place to start.

(I'm going to refer to Drupal 6 here: If you're using D7, I think you need the 'Entity Reference' module, and some things may be different.)

Then, create a View which lists all the nodes of type Lesson that are also Published.

Add an argument, which links to the node reference field mentioned above. You should then be able to enter, say, '2' in the Preview box at the bottom of the view-editing screen and get just a list of all the lessons for *the class represented by node 2*.

As an aside, let's assume you'd like to have a separate page listing those. Create a page display for the view, give it a URL path (say 'classlessons') and then you can add the node number to the URL to get your page:

mysite.com/classlessons/2

I think a different URL format is nicer, though, something that indicates this is class 2 that we're talking about, not lesson 2. If you set the path of the view to be 'class/%/lessons', then the argument is taken from the location of the % sign, ie:

mysite.com/class/2/lessons

Isn't that nice?

OK, now in your case, you want this to appear on the class page itself. Create another display for your view, but this time a Block display rather than a Page display. This will give you a block that you can include on the page, but it has a problem: blocks don't have URLs, so how can they have arguments? There's a way to deal with this.

In your block display, click on the argument, and you'll see a section called 'Action to take if argument is not present'. One option is 'Provide Default Argument', and you can select 'Node ID from URL'. This basically says, "I know this block doesn't have a URL, but I want to take the argument from the node id of the page that it's in".

Finally, add this block to the relevant pages - the easiest way is probably to do this by URL: if your class pages have consistent URLs you can choose 'Show only on the listed pages' and enter, for example,

class/\*

If they don't have consistent pretty URLs, take a look at the Pathauto module.

This should, I think, do what you want. Note that the 'Node ID from URL' default argument thing will work even if the URL you use doesn't actually have the node id in it but has an equivalent alias:

mysite.com/class/geography

The system knows which node is being referred to and substitutes the appropriate ID.

---
Tags: 7, views, nodes
---


# Question
Title: Create views field template override for table style
I have a view named studies that displays title, status. The status field should be "Active" or "Completed". This value is the result of comparing the timestamp of the date field that my content type has with the today timestamp. So I added the date field to my view as well, but choose to have it excluded from display. Then I created a global text field with the label "Status".

Then i tried taking my first steps into theming. What I need is to override the content of the Status field with either "Active" or "Completed" based on my code. I created a template called **views-view-field--studies--nothing.tpl** based on the suggestions of the Views theme information. The problem is that it doesn't matter what I write inside nothing gets displayed, not even just a simple `<?php print $output."Hello World"; ?>` (I did rescan the template files and Views sees my template, plus I flushed all caches)

My view right now has table style. I changed the style to unformatted list and voila the Hello World showed up! So am I messing around with the wrong template? Do I need to create a template for the table style of my view? Seems too excessive when I only need to override the content of one field.

# Answer
> 0 votes
Not really sure what could have fixed the problem, but after many cache flushes I can now see the template working correctly. So there was nothing wrong with my workflow.

# Answer
> 0 votes
What you are trying works fine for me under drupal6, so, I'd look at your theme information again and be perfecting sure that it is looking at the right theme when you switch styles from table to unformatted and so forth. I did that once and had my views template file sitting in one theme and couldn't figure out why views wasn't picking it up in another :)

---
Tags: views, theming
---


# Question
Title: Why does Drupal jump back to the calling function after submitting a form?
Dear Drupal community,

I am pretty much lost with the form listed below. When calling the form funnyform via the function funny\_function (via the menu link 'Funny'), the form appears, and the word 'Fun' is displayed as I programmed. Now, when I click on the 'Resume' button, the word 'Submitted' is obviously displayed. However, the word 'Fun' appears as well. Apparently, Drupal goes back into this function once again! Now, this is very bad news because in my "real-life" this function contains additional programming code which is then run twice...

Can anybody please help me how to stop Drupal from going back there? And explain to me why it even does so??

Thanks and best wishes, Tobias

```
$items['funny'] = array(
  'title' => t('Funny'),
  'page callback' => 'funny_function',
  'access callback' => TRUE,
  'type' => MENU_NORMAL_ITEM,
);

function funny_function() {
  drupal_set_message('Fun');
  return drupal_get_form('funnyform');
}

function funnyform($form, &$form_state) {
  $form['information'] = array(
    '#markup' => t('Nothing'),
  );

  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Resume'),
    '#weight' => '100',
  );
  return $form;
}

function funnyform_submit($form, &$form_state) {
  drupal_set_message('Submitted');
  $form_state['redirect'] = 'another_funny_page';
}

```

# Answer
Where else would you expect the form to lead?

You can add ?destination=somepath to the URL, or a #redirect to the submit array, or a drupal\_goto in the funnyform\_submit() function, but if you don't tell Drupal where to go, it's just going to reload the current page.
> 2 votes

---
Tags: 7, forms
---


# Question
Title: Commerce product programatically with price
How do I get the correct price in the site's default currency to work like the the add product form does?

This function gives a product with a price of $0.01 I want $1.00.

I am sure this has to do with calculated price?

```
function generate_products () {

    $product_type = 'product';

    $values = array (
        'price' => 1.00 ,
        'currency_code' => commerce_default_currency() ,
    );

    $extras = array(
        'status' => 1,
        'uid' => 1,
        'sku' => randomName ( 10 ),
        'title' => randomName ( 10 ),
    );

    commerce_installments_create_product ($product_type,$values,$extras);
}

function commerce_installments_create_product ( $product_type , $values , $extras ) {
    $form_state = array ();
    $form_state[ 'values' ] = $values;
    $form = array ();
    $form[ '#parents' ] = array ();

    // Generate a new product object
    $new_product = commerce_product_new ( $product_type );

    $new_product->status = $extras[ 'status' ];
    $new_product->uid = $extras[ 'uid' ];

    $new_product->sku = $extras[ 'sku' ];
    $new_product->title = $extras[ 'title' ];
    $new_product->created = $new_product->changed = time ();

    if ( ! empty( $values[ 'original_order' ] ) ) {
        // field_original_order[und][0][target_id]
        $order = array ( LANGUAGE_NONE => array ( 0 => array ( 'target_id' => $values[ 'original_order' ] ) ) );
        $form_state[ 'values' ][ 'field_original_order' ] = $order;
    }

    if ( ! empty( $values[ 'original_line_item' ] ) ) {
        // field_original_line_item[und][0][target_id]
        $line_item = array ( LANGUAGE_NONE => array ( 0 => array ( 'target_id' => $values[ 'original_line_item' ] ) ) );
        $form_state[ 'values' ][ 'field_original_line_item' ] = $line_item;
    }

    if ( ! empty( $values[ 'original_product' ] ) ) {
        $product = array ( LANGUAGE_NONE => array ( 0 => array ( 'target_id' => $values[ 'original_product' ] ) ) );
        $form_state[ 'values' ][ 'field_original_product' ] = $product;
    }

    //commerce_price[und][0][amount]
    $price = array ( LANGUAGE_NONE => array ( 0 => array (
        'amount' => $values[ 'price' ] ,
        'currency_code' => $values[ 'currency_code' ],
    ) ) );
    $form_state[ 'values' ][ 'commerce_price' ] = $price;

    // Notify field widgets to save their field data
    field_attach_submit ( 'commerce_product' , $new_product , $form , $form_state );

    commerce_product_save ( $new_product );
    return $new_product->product_id;
}

```

//function based on answer here How do I programmatically create an entity with its fields?

# Answer
Prices are stocked as integer in database.

Try replacing 1.00 by 100 in your price array :

```
$values = array (
        'price' => 100 ,
        'currency_code' => commerce_default_currency() ,
    );

```

Cf : http://drupal.org/node/1124416
> 4 votes

# Answer
The number that's stored in a commerce price field is the `price * 100`.

So $1.00 is 100, $10 is 1000, $7.50 is 750, etc.

You could do `'amount' => $values[ 'price' ] * 100 ,` in `commerce_installments_create_product` and that would correct it.
> 1 votes

---
Tags: entities, commerce
---


title: How to avoid round problem in tax?

text:
# Question
Title: How to avoid round problem in tax?
I have to deal with order with high quantities by product.

Tax (VAT) is calculated by rule for unit price, rounded, then multiplied by quantity. With high quantity this kind of rounding cause problem.

How to deal with that?

# Answer
> 3 votes
You can specify the round mode you want in the tax type configuration page.

/admin/commerce/config/taxes/types/vat/edit

(It should be configure to no round by default)

---
Tags: commerce
---


# Question
Title: Drupal Commerce assign role on account create on checkout
When a checkout is completed by an anonymous user on a Drupal Commerce website, a Drupal account will be created. I would look to auto-assign a role like 'customer' to the newly created Commerce user. How can I do that programmatically? It has to be in Drupal 7 code so I can use it for my custom module.

# Answer
> 3 votes
```
$account = new stdClass;
$account->is_new = TRUE; //indicate the account is new
$account->name = 'account_name';
$account->pass = user_hash_password('password'); // make a function to create random passwords
$account->mail = 'email';
$account->init = 'email';
$account->status = TRUE; //set the user to activated at creation
$account->roles = array(DRUPAL_AUTHENTICATED_RID => TRUE); //set user as authenticated user
$account->timezone = variable_get('date_default_timezone', '');
$new_user = user_save($account); //create user (user_save() returns a fully loaded $user object)

$role_name = 'ROLE_NAME'; // The name of the role to add.
if ($role = user_role_load_by_name($role_name)) {
  user_multiple_role_edit(array($new_user->uid), 'add_role', $role->rid);
}

```

You can use the hook: hook\_user\_insert. And apply the last piece of code from above to update the role.

---
Tags: commerce
---


# Question
Title: Dragboxes in a page (Dashboard kind of display which is clickable)
I'm creating a new site and is fairly new to Drupal. I had some research into sites and liked "http://churchofengland.org/" front page.

They have aligned the front-page with dragboxes. How can I do similar in Drupal?

# Answer
You're looking for the jQuery UI Sortable plugin used in the "grid" display mode (this is how the C of E website does it).

As Drupal 7 includes jQuery UI you can add the required libraries like this:

```
drupal_add_library('system', 'ui.sortable');

```

And then simlpy add a Javascript file to the required pages with your code in to attach the sortable behaviour to the correct elements. There are plenty of examples on the documentation page to show you how to do this.
> 0 votes

# Answer
I would check into jQuery UI/Drag & Drop. http://jqueryui.com/demos/

After you get the hang of this, create a template file for your homepage. Create blocks with different content and render them in your homepage template file. Apply the drag and drop interface to the blocks you rendered on your homepage.

This is just a quick look on your question, but it should get you in the right direction.
> 1 votes

---
Tags: blocks
---


# Question
Title: How to know if jQuery UI is being included
Is there a good way of checking for if jQuery UI is being included on the current page request?

Found drupal\_get\_library(), and drupal\_add\_library(), but neither of them allows me to check if it is being included.

I am trying to do this from the theme, and then load a jquery.ui.touch-punch library to enable iPad/iPhone support.

# Answer
There's no built in way but as `drupal_add_library()` uses Drupal's static pattern you can find out by doing this:

```
function ui_is_included() {
  // Get the list of libraries included in this page load
  $libs = drupal_static('drupal_add_library');

  // The system library will pretty much always exist as it includes jQuery,
  // but it's just good sense to check just in case.
  if (isset($libs['system'])) {
    // If the system library array includes UI then make sure it's enbabled
    return isset($libs['system']['ui']) && $libs['system']['ui'] === TRUE;
  }

  // UI is not loaded if we've got to this point
  return FALSE;
}

```

You can even compress that down a bit:

```
function ui_is_included() {
  $libs = drupal_static('drupal_add_library');
  return isset($libs['system']['ui']) && $libs['system']['ui'];
}

```

I'd advise calling this function as late on in the page build process as possible, to ensure that all modules have had a chance to request that UI is added. `hook_preprocess_html()` in your theme's `template.php` file might be a good place to put it.
> 2 votes

---
Tags: javascript
---


title: Using VBO to change users passwords

text:
# Question
Title: Using VBO to change users passwords
I need a method of changing users passwords which doesn't require email, as such the best solution I can come up with is providing "manager" roles the ability to reset passwords. However we do not want to provide these users with "administer users" permission.

I am thinking the best way of doing this is a view which displays "my team" (uses a user reference on that managers direct reports.) and uses views bulk operations however I can not find anywhere documentation on how to reset users passwords.

Ideally the VBO action would allow managers to select members on their team and reset passwords to a string, then update the user in person.

# Answer
Userplus has an action which changes a users password, I was able to use the below:

```
/**
 * Implementation of hook_action_info().
 */
function userplus_actions_action_info() {
  $actions = array(
    'userplus_change_password_action' => array(
      'type' => 'user',
      'description' => t('Change user\'s password'),
      'configurable' => TRUE,
      'hooks' => array(),
    ),
  );
  return $actions;
}

/**
 * Action to change a user's password
 */
function userplus_change_password_action_form($context) {
  _user_password_dynamic_validation();
  $form['pass'] = array(
    '#title' => t('New password'),
    '#type' => 'password_confirm',
    '#description' => t('Provide a password for the selected users in both fields.'),
    '#required' => TRUE,
    '#size' => 25,
  );

  return $form;
}

function userplus_change_password_action_submit($form, $form_state) {
  return array('pass' => $form_state['values']['pass']);
}

function userplus_change_password_action(&$user, $context) {
  user_save($user, array('pass' => $context['pass']));
}

```
> 2 votes

# Answer
Another method, for Drupal 7, is to create a rules action, and save it in the file MODULENAME.rules.inc. Change "MODULENAME" by your module name.

```
/**
 * Implements hook_rules_action_info().
 */
function MODULENAME_rules_action_info() {
 return array(
   'of_client_change_password' => array(
     'label' => t('Change user\'s password'),
     'parameter' => array(
       'account' => array(
         'type' => 'user',
         'label' => t('User'),
        ),
       'password' => array(
         'type' => 'text',
         'label' => t('Password'),
       ),
     ),
     'group' => t('MODULENAME'),
   ),
 );
}

function MODULENAME_change_password($account, $password) {
  // If we pass the password in the $edit array, it will be properly hashed
  $edit['pass'] = $password;
  user_save($account, $edit);
}

```
> 2 votes

---
Tags: users, views
---


# Question
Title: 'Page not found' but hook_menu() is correct!
This is my `hook_menu`:

```
$items['events/%event'] = array(
  'title' => 'Event',
  'title callback' => 'entity_label',
  'title arguments' => array('event', 1),
  'page callback' => 'events_view',
  'page arguments' => array(1),
  'access callback' => 'entity_access',
  'access arguments' => array('view', 'event', 1),
  'file' => 'events.pages.inc',
);

return $items;

```

But when I navigate to `events/2` there's a 404 error waiting! Here's the page:

As you can see, my `Event` has been successfully created (it exists in database and its `id` is definitely `2`) but the requested page could not be found and `Shortcuts` menu and `Navigation` block has disappeared.
What possibly could I mistaken?
Feel free to ask for more information.
Thanks.

EDIT:
I'm using Drupal 7.12

# Answer
> 5 votes
If you're getting a 404 it's due to one of the following:

* You haven't cleared Drupal's cache since you implemented the menu item, OR
* Your `event_load()` function is returning FALSE/NULL for the provided ID, OR
* The function `event_load()` doesn't actually exist

Judging from the rest of your function/file names (`events_view`, `events.pages.inc`) your module is called `events` so your router load function will probably be called `events_load()` (note the additional `s`).

If that's true then you need to change your menu item to match that:

```
$items['events/%events'] = array(
  // ...

```

And clear Drupal's cache to pick up the change.

---
Tags: 7, hooks, uri
---


# Question
Title: How to split content over different regions... views?
I have a client who wants to allow some editorial staff to create and edit 'main pages' on their site. These are things like 'about us', 'our clients', 'breaking news' and so on; they want these 'main pages' to follow a house style (one main image, relevant links here, block quote there, content in the middle, etc.)

The site is built with Drupal 7.

I'm thinking that the way to go is probably using a custom content type, 'main\_article' and then using views to display various fields from that content type in the relevant blocks - so, for example, having a 'main content' block that sits in the content region and displays the title and main content, 'picture' and 'links' blocks that both go in the left column, and 'citation' and 'blah' blocks over in the right column.

I guess I would use the 'Content: NID' contextual filter to make sure that I only get content from the relevant 'main\_article'.

1. This seems like a standard enough design issue: Am I going about it in the right way?
Is there a better solution? (I've seen similar questions here and elsewhere that led me to follow this way of doing it.)
2. How would I go about getting the 'main\_article' content type to put a link in the main navigation menu?
Using the menu option in the content creation page would link to the default content, not the view (if you see what I mean). Could it be done using a field?
3. If the user creates a URL Path for the content they create using this content type, that's going to break the 'content: NID' contextual filter. Is there a way of 'contextual filtering' on the URL (which should then work for standard node URLs and for 'nice' URL paths)?

# Answer
An simple solution is to use the Panels module and Page Manager from ctools module to override the default node page for your content type. That way you also do not have to worry about menus, sitemaps etc.

The downside is that you cannot easily use the blocks defined in the template to position parts of the nodes content.
> 1 votes

# Answer
If the display needs are pretty simple, then you can enable the CCK Blocks module.

Then if you got to 'Manage fields' for a particular CCK field, you can specify 'Provide block for this field', and, sure enough, you'll get a new block which you can include on the relevant pages.
> 0 votes

---
Tags: views, blocks
---


title: Form alter hook in Drupal 6

text:
# Question
Title: Form alter hook in Drupal 6
I have created a content type in which I have a field that is a select box.
Now I want to change all the default values of that select box.

I know `hook_form_alter()` will work this, but I have no idea on how to change this.
Is anybody able to give me an idea?

# Answer
Just adjust the values of the form element to your needs. Check this http://api.drupal.org/api/drupal/developer!topics!forms\_api\_reference.html/6#select to see how selects ar build using FAPI.
> 2 votes

---
Tags: 6, hooks
---


title: Views multiple entities output

text:
# Question
Title: Views multiple entities output
*I am new to Drupal 7, so I hope I am using the word **entity** in the right context.*

I am using the profile2 module to collect additional information when yours signup. Of course, the users are required to provide an email address and they can also upload a photo of themselves.

My issue is how to use the same view to return a users user information (email, username, photo) and all the profile2 collected information.

# Answer
When you create a view for users or the profile nodes, you should be able to add a relation to the other one. Not shure thou whether this works in both directions.
> 1 votes

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


# Question
Title: Article automation solutions for Drupal?
Does anyone know of any article automation services that allows easy creation of content into Drupal 6?

Something like Article Marketing Automation would be great if their promised integration worked as advertised.

# Answer
It all depends on the type of content you want to create.

If you're looking for test content then devel will create dummy content for your site.

If you're looking for more spam (not judging) content then you'd have to go down the custom route. Here's a sample workflow:

1. Use Feeds to aggregate a few different sites to a content type that isn't published.
2. Use Open Calais to scan the content and auto create taxonomies.
3. Use a custom module to create new nodes based on a term, this would bring in x amount of automatically scraped nodes aggregate them into one, you can then publish the newly created node.

I don't agree with the outcome but I find it an interesting challenge coming up with a solution.
> 1 votes

---
Tags: 6
---


# Question
Title: Can you set the Media module to only show specific images?
I'm looking to use the media module on a site. Very impressed so far with it but there is one thing I need of it for it to be perfect.

I need it to only show certain images in the library, not every single image that has been uploaded. Is there any way of doing this that any one knows?

Thanks

# Answer
I've been looking for the same functionality for a while, I've been through the media browser code and there's nothing I'm afraid.

The best you can do is download the **dev** version of Media Browser Plus which now has support for a hierarchical folder structure for the media library.

It doesn't have any access control by default (that I can see) but you might be able to hook in and add some.
> 1 votes

# Answer
Media module 2.x uses views in its media browser. You can edit the standard view, or create new ones, and use relationships and (exposed) filters.
> 3 votes

# Answer
What I did for that was to create a view of my files, and give it the appropriate relationship.

Then I re-wrote the output of the field linking it to the fid/edit page of the file.

Also assigned the view as a menu in my admin bar. Was a pretty nifty solution.
> 2 votes

---
Tags: 7, media
---


title: How to print block from template?

text:
# Question
Title: How to print block from template?
I have block template. How do I output this block on front page just by calling `render($page[region_name])`, where region\_name is the name of a region to which the block is assigned.

**Edit:** I want to print the whole region assuming it contains only this block.

# Answer
You'd be better off handling this in a custom module and declaring the block in there, then you don't need to worry about trying to inject the output from a template file into a custom block (using PHP in block bodies should be discouraged as it uses the evil `eval()` function).

The following is a generic example:

```
// Implements hook_theme()
function MYMODULE_theme() {
  return array(
    'MYMODULE_block_template' => array(
      'template' => 'MYMODULE_block_template',
      'variables' => array()
    )
  );
}

// Implements hook_block_info()
function MYMODULE_block_info() {
  return array(
    'my_block' => array(
      'info' => t('My Block')
    )
  );
}

// Implements hook_block_view()
function MYMODULE_block_view($delta = '') {
  $block = array();

  if ($delta == 'my_block') {
    $block['subject'] = t('Block Title');
    $block['content'] = theme('MYMODULE_block_template');
  }

  return $block;
}

```

In the above code you declare a theme functino called `MYMODULE_block_template` which is attached to a template file in the root of your module folder (`MYMODULE_block_template.tpl.php`).

Once you install the module you'll have a block called 'My Block' in the blocks admin page that you will be able to assign to any region. The content of the block will be exactly what's contained in the `MYMODULE_block_template.tpl.php` file.
> 1 votes

# Answer
```
<?php print render(block_get_blocks_by_region('region_name')); ?>

```
> 2 votes

---
Tags: blocks, theming
---


# Question
Title: Create a user friendly workflow to create banners
I'm looking for an easy way where my users can add banners on a page. There are many options here (View Slideshows, Rotating Banners,...) but what I want is a user to be able to do this as simple as possible.

The ideal scenario would be:
Create content - upload image - type a title and select the pages on which it should be displayed.

Basically, my (absolute n00b users) must be able to add a banner to any page available without any knowledge of views, panels,...

I've experimented with node references and templates, but no luck so far.

Is their anyone with the same situation and found out a great solution?

# Answer
The simplest would be a content type with an image field and a text field. The image field would be the banner and the text field would be the path on your website where it should be displayed.

Create a view that filters on that content type and has the image as the field it displays. Put the path field as an argument. Configure it to return only 1 item.

In a block, call that view using $\_GET\['q'\] as the argument.

Image is displayed in the block. Display this block on your page where you want your banner.

Don't like blocks? Put this in a page\_preprocess() hook and assign the view output to a variable and put this in your page where ever you want it.

Get fancy? Randomize the sort so if more than one of these content types has the same path a different image is displayed on each page load/reload.

Get fancier. Use the views\_nivo\_slider module ( http://drupal.org/project/views\_nivo\_slider )
> 1 votes

---
Tags: 7
---


# Question
Title: how to send $user variable from drupal to another php non-drupal page under same root?
I have drupal cms and another php site with each own session and db etc on same root.

What I want is to pass somehow the drupal $user variable with all the login details of the user to the other non-drupal php site in order to bypass the login and make the user logged in there too.

The non-drupal site has its own login/register and sessions etc. I want to override this by getting the user info from drupal registration.

```
require_once './includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);

```

I tried to use the above code on the index of the non-drupal site, but I get errors about session and headers that already sent.

Any help?

# Answer
I have a similar setup running; what I did was sending the session ID as a URL parameter, including the "bootstrap.inc" file, bootstrapping the database, and then looking up the info I needed.

Example where I've stored some info in the session:

```
require_once './includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_DATABASE);

if (@$_GET["sid"]) {
  $_SESSION["sid"] = @$_GET["sid"];
}

if (@$_SESSION["sid"]) {
  //Get the get username/role from the database
  $result = db_query("SELECT session FROM {sessions}
    WHERE uid > 0 and sid = '%s'", array(
      $_SESSION["sid"],
    )
  );

  while ($row = db_fetch_object($result)) {
    $_SESSION += unserializesession($row->session);
  }
}

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

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

  $returnArray = array();
  $lastOffset = null;
  $currentKey = '';

  foreach ($matchesarray[2] as $value) {
    $offset = $value[1];

    if (!is_null($lastOffset)) {
      $valueText = substr($data, $lastOffset, $offset - $lastOffset);
      $returnArray[$currentKey] = unserialize($valueText);
    }

    $currentKey = $value[0];
    $lastOffset = $offset + strlen($currentKey) + 1;
  }

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

  return $returnArray;
}

```
> 1 votes

# Answer
If you call `drupal_bootstrap()` for the `DRUPAL_BOOTSTRAP_SESSION` or later phase, Drupal will override PHP session handling and starts a session in `drupal_session_initialize()`. When starting a session, Drupal will invoke `session_start()` which has already been invoked from your own separated non-drupal code.

If you only need to retrieve whether or not the user is logged in in Drupal, you can bootstrap the Drupal database only (ie. `drupal_bootstrap(DRUPAL_BOOTSTRAP_DATABASE)`) and query the `sessions` table with the session id returned by session\_id(). If the returned row has a non-zero `uid`m then you should have a logged in user. Session handling in Drupal is more complex than that, so obviously it won't be as robust.
> 0 votes

---
Tags: users
---


title: How to add CSS to menu_callback page?

text:
# Question
Title: How to add CSS to menu_callback page?
I have implemented hook\_menu in my module and created a page. Now how to add CSS to this page? I have the below code inside my page\_callback function, but still the css is not applied.

```
$css = "table,tr,th,td {padding: 10 !important; }";
drupal_add_css($css, 'inline');

```

Any help is appreciated.

# Answer
> 3 votes
Unless you've hacked D6, 'inline' only works with `drupal_add_js()`, not `drupal_add_css()`. So, to do what you want, you need to put that line of css in a file and include that file instead.

---
Tags: theming, 7
---


# Question
Title: Changing output format of displayed body text
I imported node and comment body fields as "Full HTML" (they are coming from a trusted site).

Now I want to display those body fields differently, for example strip certain HTML tags. Do I just change the filters for "Full HTML" and use "Full HTML" as my "custom" input format? I could change the name of it, just want to make sure it have special significance in Drupal.

Or do I have to manually change them in the DB

# Answer
> 2 votes
You can safely make changes to the regular "Full HTML" filter. It has no special significance in the system. It is simply created by the "Standard" install profile because it is convenient for end users. If you install a minimal profile you won't have it at all.

Obviously changing the full html filter will affect other nodes as well that use this filter.

# Answer
> 1 votes
You shouldn't redo the "Full HTML" filter to actually be filtered, you should add your own filter.

Try adding your custom filter, check off all the roles that can edit the content, and then disallowing the "Full HTML" for all roles. Log in as something other than an admin role. If you resave an existing node, it should use the new filter.

---
Tags: 7, input-formats
---


# Question
Title: hook_block and rendering a form in content section
Basically, I have tabs on my modules admin page, I need to show a different form per page. The node type and forms have been created and the first form on `block[0]` shows correctly, while the first part of `block[1]` shows correctly, it also icludes some fields from `block[0]` and this shouldn't be so.

Here is my `hook_block`, maybe someone can spot my mistake and point it out to me.

```
function svm_mail_block($op = 'list', $delta = 0, $edit = array()) {

switch ($op) {
  case 'list':
    $blocks = array(
      0 => array(
        'info' => t('Add New Account'),
        'status' => 1,
        'region' => 'content',
        'visibility' => 1,
        'pages' => array('admin/settings/svm-mail/add-account'),
        ),
      1 => array(
        'info' => t('Update Mail Statistics'),
        'status' => 1,
        'region' => 'content',
        'visibility' => 1,
        'pages' => array('admin/settings/svm-mail/ymlp/update'),
        )
      );
    return $blocks;
    break;

  case 'view':
    if(user_access('create mail account')) {
    switch ($delta) {
      case 0:
        //render node form from http://api.drupal.org/api/drupal/includes!form.inc/function/drupal_get_form/6
        module_load_include('inc', 'node', 'node.pages');
        $node_type = 'svm_mail_account';
        $form_id = $node_type . '_node_form';
        global $user;
        $node = new stdClass();
        $node ->uid = $user->uid;
        $node ->name = (isset($user->name) ? $user ->name: '');
        $node ->type = $node_type;
        $block['subject'] = t('Add New Account');
        $block['content'] = drupal_get_form($form_id,$node);
        dvm($block);
        return $block;
        break;
      case 1:
        module_load_include('inc', 'node', 'node.pages');
        $node_type = 'svm_mail_groups';
        $form_id = $node_type . '_node_form';
        global $user;
        $node = new stdClass();
        $node ->uid = $user->uid;
        $node ->name = (isset($user->name) ? $user ->name: '');
        $node ->type = $node_type;
        $block['subject'] = t('Update Mail Statistics');
        $block['content'] = drupal_get_form($form_id,$node);
        dvm($block);
        return $block;
        break;
    }
    break;
}
 }
}

```

# Answer
> 1 votes
When using my case statements for my form entities, I forgot to add in a break;

It all works nicely now!!

---
Tags: blocks, forms
---


# Question
Title: Possible side effects when changing node type?
I sometimes have uses cases where I want to be able to change the type of a node. There is a nodetype module that comes with a big disclaimer: "only use if you know what you are doing".

Of course I would lose any fields if they have a different name with the other type. What else could go wrong?

Would it be save to use node\_load(), modify the type and then use node\_save()?

# Answer
> 2 votes
I've changed the content type of nodes directly in the database plenty of times and the only thing I've had to deal with is orphaned field data for nodes.

I think that this orphaned data might cause some false-positive results for certain query types (`EntityFieldQuery` springs to mind) but I can't be absolutely sure.

Instead of risk this I've always written a small script to go through the field tables in question and clear up any stagnant data after I've made the content type change.

I don't think you'll encounter any errors using `node_load()` and `node_save()` as you suggest; it would probably be wise to clear Drupal's cache once you've made the change in case anything needs to be updated there.

---
Tags: 7, nodes
---


title: Joins and looking for NULL values

text:
# Question
Title: Joins and looking for NULL values
I'm using the flag module to let users mark their questions as solved, similar to how it works on this site. I therefore want to let users filter posts to show only unsolved questions. Additionally, some posts might not be questions at all. Therefore, they can't have a "solved" flag, but they also should NOT appear in the results when filtering only by unsolved questions. Therefore, I need to join the node table with two others: `flag_content` and `field_data_field_question` (this latter table is what tells whether or not a post is a question).

Here's the current code I'm trying:

```
$query->join('flag_content', 'f', 'f.content_id = n.nid AND f.content_type = "node" AND f.fid = 5');
$query->join('field_data_field_question', 'q', 'q.entity_id = n.nid AND q.field_question_value = 1');
$query->condition('f.fid', 'NULL', 'IS');
$query->condition('q.field_question_value', 'NULL', 'IS NOT');

```

However, this results in the following error:

```
PDOException: SQLSTATE[42000]: Syntax error or access violation: 1064 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 ''NULL') AND (q.field_question_value IS NOT 'NULL')
LIMIT 21 OFFSET 0' at line 4: SELECT n.nid AS nid
FROM
{node} n
INNER JOIN {field_data_field_category} t ON t.entity_id = n.nid
INNER JOIN {flag_content} f ON f.content_id = n.nid AND f.content_type = "node" AND f.fid = 5
INNER JOIN {field_data_field_question} q ON q.entity_id = n.nid AND q.field_question_value = 1
WHERE (t.field_category_tid = :db_condition_placeholder_0) AND (f.fid IS :db_condition_placeholder_1) AND (q.field_question_value IS NOT :db_condition_placeholder_2)
LIMIT 21 OFFSET 0; Array
( [:db_condition_placeholder_0] => 464 [:db_condition_placeholder_1] => NULL [:db_condition_placeholder_2] => NULL
)
in queryExecuteRender_recentActivity() (line 57 of someFile.php).

```

Is this not the correct way to pass `NULL` values into a query?

# Answer
> 34 votes
The database API actually has a preferred way to add expressions of this type, namely the `SelectQuery::isNull()` and `SelectQuery::isNotNull()` functions. You can use them like this:

```
$query->isNull('f.fid');

$query->isNotNull('q.field_question_value');

```

---
Tags: 7, database
---


title: FAQ in Drupal, using vocabularies?

text:
# Question
Title: FAQ in Drupal, using vocabularies?
## Hi Drupal enthusiasts!

I am trying to design way of organizing FAQ on Drupal page.

Does anyone know about module that implements following use case?

2 vocabularies: faq categories, faq items grouping.

## Example:

Faq Categories:

* Application
* + Calculator
* + Paint
* + Notepad

Faq Grouping:

* Using cursor
* Printing
* Saving

Now I create question, I may choose Paint and Notepad tags for categories, to show a question in both categories. Then I choose printing term to show this question next to other one, which is also printing group.

Do you think I should struggle with Views? I don't think it's gonna fulfil following use case. Probably I need to write code by myself.. Question can be assigned to as many grouping and category terms as wanted, as some questions are referring to multiple..

# Answer
It turned out you can do this with Views. You list all content with some category tags, then you sort them with grouping tag and remove not needed headers (duplicates).
> 1 votes

# Answer
Have you tried the Faq module? You might be able to achieve what you trying to do. If am not mistaken it uses views :)
> 0 votes

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


# Question
Title: Can I create a node that acts as a pointer to another node of the same type?
For example:

There are two types, "contest" and "recipe". A recipe can reference any number of contests, and a contest can be referenced by any number of recipes. There is a recipe View that lists all the details of each recipe matching the criteria. I want to filter the recipes listed only to those in the most recent contest. I can add the contest relationship. The problem is that I have to choose from one of the existing contests. Can I create a contest called "mostrecent" that will refer to a different contest depending on which of all contests was created most recently?

# Answer
> 0 votes
You can create a view that lists contests in newest/descending order and limit it to 1 item, and use that to return the nid of the lastest contest, or if you are comfortable with SQL, do something like `select nid from {node} where type="contest" and status=1 ORDER BY created DESC limit 1` to get it.

You can then use that as an argument to another view that returns recipes based upon what contest they reference, eg, all recipes with a contest node reference of nid.

You can do that all inside the views UI with default arguments and so forth, or create a module to do it.

MORE SPECIFICS--the easy part:

1. create a view, filter it on published recipes
2. put in the fields area whatever you want to see, eg, the title linked to the recipe, a node teaser, etc.

MORE SPECIFICS--the hard part:

1. add an argument to the view:

a. select the field in recipe that is the node reference to contest

b. in action to be taken if argument is not present, select php code and enter:

`$nid=db_result(db_query('select nid from {node} where type="contest" and status=1 ORDER BY created DESC limit 1'));
 return $nid;`
2. save everything :)
3. Preview the view. What should be happening now is the view will be returning all recipes that have the latest contest nid (aka node reference) in the field you entered in the argument above.

---
Tags: views, nodes
---


title: Insert (Google ad) token in a template

text:
# Question
Title: Insert (Google ad) token in a template
I want to insert a token from the Google Ad Manager module in a view.

But how do you insert a token like the ad\_slot token in this module in a views template?

# Answer
> 1 votes
The Google Ad Manager module uses a filter for the tokens, not the Token module. You could call its internal function `$content=_google_admanager_substitute_tags($text);` to do the substitution for you, where you replace $text with `[google_ad:ad_slot]` but I am not sure if it will know enough to put all the google js in your page. Try it out, I guess.

Otherwise, you can do something like `$content=theme('google_admanager_block', $gid, $google_ad);` where `$gid=variable_get('google_admanager_account','');` and `$google_ad` is your ad slot. That I've done all over the place myself with reasonable success.

---
Tags: views, theming, tokens
---


# Question
Title: Filtered html with class attribute not being stripped?
How to extend "filtered html" by ability of using class attribute? I can't let user have full html, but classes seem to be useful.

# Answer
> 0 votes
I use the Wysiwyg filter module in combination with the wysiwyg module for this. The module allows you to define exactly what properties to allow, what elements, classes etc. It takes a little time to set up, but the added control is well worth it imo.

# Answer
> 0 votes
I found way of implementing of filtering system: http://definitivedrupal.org/node/90

but I still hope there's easier way like just a checkbox \[x\] don't filter class attribute.

---
Tags: 7, input-formats
---


title: Custom view format, parse a text value

text:
# Question
Title: Custom view format, parse a text value
I think this is a pretty easy thing to do once you figure it out once, but I'm struggling to do the following:

I have a content type called YouTube video. It accepts a text field "URL" that is the full video URL (or alternatively just the ending video ID)

I want the displayed content to be an embedded video. How can I set the default embed code and then have a variable to swap for the ID?

Edit: Been poking all day, still can't figure this one out. I'm from a Wordpress background and this would be a simple ~3 minute addition to functions.php. Can someone point me in the right direction?

# Answer
If you want the fields approach, try looking at the module http://drupal.org/project/emfield If you want to do it yourself in code, there are different approaches, the most basic one being adding a node template for your content type and adding your embed code there. Look at drupal.org for basic information about addding templates.
> 1 votes

---
Tags: views
---


# Question
Title: how to start fresh and add custom backgrounds
I am completely new to Drupal 7 and have searched the web hard for a good tutorial that teaches me how to add a custom background to Drupal sites, but to no avail.

I have a Drupal 7 multi-site set-up and I am just trying to change the background image of the Bartik theme to a custom image.

In my project directory I have the following folders:

```
mysite/files
mysite/modules
mysite/themes
mysite/tmp
mysite/settings.php
mysite/default.settings.php

```

Could someone please tell me a way to create a custom background, exclusively, for the site "mysite" without editing any of the core files?

Thanks.

# Answer
1. Create a folder called "myTheme" in `sites/all/themes`
2. Create a file in that new folder called "myTheme.info"
3. Copy the sample .info from below into the info file
4. Now create a folder in your theme called "css"
5. Now copy `style.css` from Bartik's css folder into your css folder
6. Now change the background using CSS
7. Any other changes you want to make? Copy from bartik into your theme folder, make the change

**Sample info file:**

```
name = My Theme
description = My theme is amazing
core = 7.x
engine = phptemplate
base theme = bartik

```
> 2 votes

---
Tags: media, theming
---


# Question
Title: field_get_items('user', $user, 'field_name') empty?
I have a added data to the user using:

```
taxonomy_term_reference

```

when creating the

```
field_create_instance($instance)

```

and everything is working fine, I can add and store values and these are added to the specified vocabulary.

The problem is, I cannot extract the value added as a term to the $user object using field\_get\_items and field\_view\_value since field\_get\_items('user', $user, 'field\_name') is empty.

Is field\_get\_items and field\_view\_value not applicable to $user?

# Answer
> 3 votes
I was experiencing the same issue. field\_get\_items was always empty when trying to get a field attached to a user. The problem was that the $user object you get when you do a

`global $user`

isn't the full entity. So when you pass it into the field\_get\_items function, it doesn't match anything.

Do a full user\_load on the $user-\>uid and THEN pass the resulting object to field\_get\_items, and everything should work.

---
Tags: 7, taxonomy-terms, entities, users
---


# Question
Title: Views Template Suggestions When There are Duplicate Filenames
What does Drupal 6 / Views 2 do when there are two templates with the same filename in different directories?

I just ran into a situation where a row template was accidentally uploaded twice. Typically, I make `views` subdirectory in my theme, and then a subdirectory per view inside that. Due to a bad copy/paste, I ended up with

```
site/all/themes/mytheme/views/myview/views-view-unformatted--myview.tpl.php
site/all/themes/mytheme/views/myview2/views-view-unformatted--myview.tpl.php

```

My dev server was picking up the first template. My live server was picking up the second template, despite being the same set of files as the dev server. I didn't do the actual live deployment, but as far as I know, the rollout was an exact clone of the files.

I haven't been able to unravel how this actually happened, and would appreciate some insight.

Thanks.

# Answer
> 0 votes
I think I got to the bottom of this.

It looks like when you rebuild the theme registry, `_theme_build_registry` invokes `phptemplate_theme` via a hook.

`phptemplate_theme` calls `drupal_find_theme_templates`, which calls `drupal_system_listing`, which calls `file_scan_directory`.

`file_scan_directory` uses the PHP functions `opendir` and `readdir` to build the list.

No sorting takes place anywhere, so `file_scan_directory` returns in the order which `readdir` returns, which is typically in the order that the files were written to the filesystem.

So, for my problem, the issue boiled down to the dev server and live server writing out the template files in different orders, so the choice as to which to use was different.

# Answer
> 0 votes
You could look and see in your theme registry by dpm-ing in theme\_registry\_alter() or by turning on devel and visiting /devel/theme/registry and seeing what entry is pointing to what file.

If you don't want to do that on production you could do it locally first and then grab the production database locally.

I would imagine that the registry was rebuilt between the two sites and the first time it picked up one of the files and the second time the other since I don't know of a designed hierarchy for two files in the same level directories in a theme folder.

Don't upvote - this is a speculative answer.

---
Tags: views, 6
---


# Question
Title: How do I make a user profile field a link
I've created a custom field for users on a site I'm working on that is for their website url. I want to make this field actually link to the website the users enter upon signing up.

Using Drupal 7, customized Bartik theme. The field is a standard text field.

I've tried doing a custom field template for that field, and I've tried editing the page-user.tpl.php file, neither worked.

# Answer
If I'm understanding the question correctly it sounds like you need an additional module that will correctly validate/display the link in the user profile. Overview of the steps needed:

1. Download the Link module:
2. Add a new field to the user profile of type "Link" (found in confifuration --\> people --\> account settings --\> manage fields)
3. Set any other config options you need
> 2 votes

---
Tags: entities, users
---


title: db_query to drupal variable

text:
# Question
Title: db_query to drupal variable
I have a the following query:

```
function background_audio_file_query($path) {
  $result = db_query("SELECT uri
    FROM `file_managed`
    WHERE `filemime` = 'audio/mpeg'
    LIMIT 1 , 30",
    array(':uri'=>$path))->fetch();

return $result;
}

```

How can I pass this to a Drupal variable? I am assuming `variable_set()` but I am having trouble with the syntax. Could anyone lend a hand?

# Answer
> 3 votes
If you want to set a variable with the URI returned from the query, you just execute code similar to the following one:

```
variable_set('variable name', $result->uri);

```

Replace "variable name" with the name you want to give to the Drupal variable, which is the same one you pass to `variable_get()`.

# Answer
> 1 votes
Once you have your result, variable\_set syntax is simply name, value:

```
variable_set('background_audio', 'meep.au');

```

Does that answer your question?

---
Tags: database, configuration
---


# Question
Title: How to access the functionality in two different modules?
Hai I have modules called `sites/all/module/dashboard` and `sites/all/module/userpoints`

I need to display userpoints in inside the dashboard. There is a hook in `sites/all/module/userpoints/userpoints.module` called userpoints\_block() to display the userpoints . Can i access this hook `userpoints_block()` in `sites/all/module/dashboard/dashboard.module` . How to do this?

# Answer
> 1 votes
Use module\_invoke() to call the functions in other module

# Answer
> 1 votes
module\_invoke seems to be a very handy option for this

(ex) To get content of the Most Recent Poll (core module's block) content

```
module_invoke('poll', 'block', 'view', '0');

```

The first argument is the name of the module, second being hook, third and fourth are the params for the hook namely condition ('view') and block delta value (0). The return value is an array of block subject and content.

---
Tags: 6, hooks
---


title: Jump menu and conditional links

text:
# Question
Title: Jump menu and conditional links
I am looking for a way to add some logic to a view's (styled as Jump Menu) selection options. The View's UI allows me to "output this field as a link" but I need to do something like this:

```
if (current_url == 'something') {
  link_here();
}
else {
  link_there();
}

```

Basically all I want to do is to figure out where to theme (a template or other files) the following part:

```
<option value="6ee3dbb066bb38cb7fb90872a6f0144e::/Cakes/AllCakes/[tid]">Chocolate</option>

```

# Answer
> 1 votes
After "manually" producing the link by rewriting fields, I was able to theme that field and complete my task.

Instead of Using the views' "Link the output of this field" functionality, I created an extra "Custom Text" field in the view in which I created the links manually ("AllCakes/\[tid\]").

By theming this field with views' template files, I was able to add an if statement based on the current URL

```
<?php
  if (arg(1) == 'AllCakesList') {
$output = str_replace("/AllCakes/", "/AllCakesList/", $output);
  }
?>
<?php print $output; ?>

```

Thus I successfully linked to where I wanted.

# Answer
> 0 votes
In the Views UI, when you edit the View, open up the "Advanced" options. The penultimate option (one up from the bottom) is "Theme: Information." Here's an example:

If you click on "Information" you'll be given a list of template suggestions like this one:

And if you then click on one of the output types (i.e. "Display output," "Style output," etc), you'll be shown the boilerplate code for a template that should be named with one of the names to the right of the style type, which you can cut and paste into a file you save with the appropriate name. Like so:

Once you've got the template name to use, and some code to go in it, create your template in your theme directory and modify to rewrite the links as you require. I happened to choose the "Display output" template as my example, but you'll most likely want to use the "Field Content" template/associated template name.

Note that this is an information-only option in Views - it won't create the template for you. You'll have to do that yourself. You can cut'n'paste from the boilerplate to get started.

I hope that helps...

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


title: Views - Filters - weird scenario

text:
# Question
Title: Views - Filters - weird scenario
Ok, I'll try to describe the scenario I am facing since I can't narrow it down to sub-questions to see what feedback I can get.

Say I am constructing an e-commerce site that sells cakes (I love that example as it seems).

I have already created a view that shows all my cakes sorted alphabetically as thumbnails and also one view that shows all my cakes at a themed alphabetical 'catalogue' style (as this question shows) and both views link to eachother.

All nice and nifty.

Now what's come up is that the cakes are tagged with taxonomy terms that mark their... ehh.. flavor, their size, and say their... use (party - wedding - just a normal cake). I know the example is stupid but you get the idea.

The tricky part comes when I need a **global** (global as in available in all pages throughout the site) dropdown list menu that lists those taxonomy terms and upon selection takes the user to the first view (the thumbnail one) which is filtered only with the cakes that match the selected taxonomy.

I hear you mumbling that that's easy and that contextual filters is all I need. And I agree, and I've done that.

The tricky part comes now: If the user was lead to the view by this route and he clicks to go to the 'catalogue' view, the cakes that match, should be **higlighted** and if the user *is* in the 'catalogue' view and selects another taxonomy term from the menu he should *remain* in the current view and the appropriate cakes should be highlighted. Also if he should go back to the 'thumbnail' view, it should be also be filtered accordingly.

So, recap:

**~~1) clicking a taxonomy term leads to a filtered 'thumbnail' view.~~
~~2) clicking the 'catalogue' view link while on the filtered 'thumbnail' view leads to a highlighted 'catalogue' view and vice versa.
~~ ~~3) clicking on taxonomy while on either 'thumbnail' or 'catalogue' view should perform the aforementioned mentioned actions.
~~ ~~4) if the user navigates away from either of the pages the whole process resets until a taxonomy is selected again.
~~**

P.S. on the 'catalogue' view the cakes' divs have their taxonomy tags as classes to make highlighting easier.

Thanks for your time in advance.

~~EDIT: I managed using arg(x) to make the links from one view to another dynamic, i.e:~~

~~if the user is in www.cakes.com/Cakes/AllCakes/\[tid\] and clicks the link to the 'catalogue' view, the link instead leads to www.cakes.com/Cakes/AllCakesList/\[tid\] which is **filtered**, which leads to the following question too:~~

~~**5) is there a way to use contextual filters NOT for filtering but for other functions like adding a CSS class for instance?**~~

EDIT #2: Marking with strikethrough the tasks already completed.

EDIT #3: First EDIT marked since filtering is (obviously) not the way to go. But since I have the \[tid\] on the URL and thus on arg(x) I could somehow use it to highlight the appropriate divs.

EDIT #4: Managed via inline javascript and using the arg(x) argument to highlight the cakes in the 'catalogue' view!

# Answer
> 1 votes
It's funny how some times after you ask someone or a community for some solution you actually see the problem more clearly.

I was able to complete all of the mentioned tasks and I will summarize here just in case someone bizarrely stumbles upon a similar scenario in the future - although I really doubt it.

So, the views linking to each other dynamically was accomplished using the \[tid\] argument from the URL and passing it accordingly:

```
<a href="/Cakes/AllCakes/<?php echo arg(2);?>"></a>
<a href="/Cakes/AllCakesList/<?php echo arg(2);?>"></a>

```

The jump menu itself is set to Link to the thumbnail view by default unless the url is that of the 'catalogue' view. If so, via theming:

```
<?php if (arg(1) == 'AllCakesList'){
  $output=  str_replace("/AllCakes/" , "/AllCakesList/",$output);
}?>
<?php print $output; ?>

```

It leads to the 'catalogue' view.

And if the user is on none of those pages, the jump menu will lead him to the thumbnail view thus also fulfilling the 4th task in my question. That's all folks, sorry for the monstrous post!

---
Tags: 7, views
---


title: Using hook_form_alter() only on loading

text:
# Question
Title: Using hook_form_alter() only on loading
I am using hook\_form\_alter() in Drupal 6, which successfully works. As for now, when I submit the form, it again runs the same hook. I want to run it only on load and edit.

Do you have any idea on how I do this?

# Answer
Use the following code for the load operation of existing forms

```
hook_form_alter(&$form, &$form_state, $form_id) {

  if(empty($form_state['post'])) {
    //do you load operation
  }

}

```
> 1 votes

---
Tags: forms, hooks
---


# Question
Title: Change CCK Nodereference View at runtime
I have a CCK nodereference field, displayed as a dropdown, and populated by a view.

I'd like to change that view depending on user permissions. Can I change the view programmatically before it gets rendered?

I can't do it in `hook_form_alter()` because CCK isn't available here. So I set up an `#after_build`, and inspect here. But this seems to late. The `#options` have already been rendered and there's no `view` property to change.

# Answer
> 1 votes
Thanks for the sugs. I prefer to do everything in code so this was my solution. I just manually loaded the view given some argument, and parsed the results.

```
function module_form_nodetype_node_form_alter(&$form, &$form_state)
{
    // Manipulate form after build so we have access to CCK
    $form['#after_build'][] = '_form_afterbuild';
}

function _form_afterbuild($form, &$form_state)
{
    // Custom options list for this nodereference
    $arg = user_access('administer nodes') ? false : true;
    $form['field_fieldname']['nid']['nid']['#options'] = _GetOptions($arg);
}

function _GetOptions($arg=false)
{
    $viewResults = views_get_view_result('view_name', '', $arg);

    $options = array();
    foreach ($viewResults as $row) {
        $optionTitle = $row->title;
        $options[$row->nid] = $optionTitle;
    }

    // Sort options by alpha
    asort($options);

    return $options;
}

```

# Answer
> 0 votes
If you want to change the argument at run time, you can specify the argument in the view, and then in the argument "definition," you can select supply default argument if not present (which it won't be unless you specify it in your CCK definitions) and select PHP code, and there you can program the argument however you want. You can also do the same thing with argument validation.

# Answer
> 0 votes
You can utilize Advanced View to filter the display depending on user roles. And use Views UI Permissions to implement that. Essentially, you will create a new view, and use that view as an advanced view option in your the field referencing.

---
Tags: views, 6, entities
---


title: Switch Site Name depending on URL

text:
# Question
Title: Switch Site Name depending on URL
I'm looking to switch my Site Name (admin/config/system/site-information) depending on what url I'm at. So if I was at www.example.com/cat I could have the site name be Cats and if I was at www.example.com/dog I could have the site name be Dogs.

Doe anyone know of a module that has this functionality?

I know that this is similar to a multisite, but I just need to create a bunch of tiny blogs and a multisite seems like overkill.

# Answer
> 1 votes
One approach would be to use the Domain Access module. Not sure if you can use it with subdirectories, but you can use it with subdomains. Basically, you would create an "affiliate" (module's term for a site) for dogs and one for cats, and configure as needed.

---
Tags: 7, multi-sites
---


title: Multiple Active Themes

text:
# Question
Title: Multiple Active Themes
is it possible to have more than one active theme? Basically what I'm trying to achieve is another theme that has none of the extra CSS/JS output by Drupal modules -- this would only be used for E-Newsletter display. I see the "default" setting for a theme, but how would I apply certain content types, etc to a specific theme? I've searched a bit and am stuck in the mud at the moment. Any help would be greatly appreciated. Thanks!

# Answer
> 1 votes
The Themekey module has that functionality built in:

> ThemeKey allows you to define simple or sophisticated theme-switching rules which allow automatic selection of a theme depending on current path, taxonomy terms, language, **node-type**, and many, many other properties

# Answer
> 1 votes
1. For this requirement you can use the only one tpl to the active theme folder page-your\_content\_type\_name.tpl.php.Here you can copy the page.tpl.php and paste.then remove the unwanted variable print over that page.(Remove print $styles for remove all css adding by your module).
2. To alter the rendering of that particular content type use node-content\_type\_name.tpl.php in themes folder

# Answer
> 1 votes
Page theme module works very well for me.

Simply add the desired themes and specify theme's pages.

Let's say your content type is name "cars" and your node urls all start with `http://www.yousite.com/cars/something`, simply add `cars/*` to your theme's page list.

---
Tags: theming
---


# Question
Title: Module for cropping user picture immediately
I'd like users to be able to crop their user pictures immediately. That means:

After selecting the image file, it gets uploaded immediately (as opposed to waiting for the user to submit the entire profile edit form) and some kind of overlay, div, etc. appears that allows the cropping to be done.

As far as I can tell, a module does not exist that provides this functionality. If I'm wrong, please direct me to the module I'm looking for. If I'm right that it doesn't exist, what tips would you offer? Is there a module that will help get me part of the way, i.e. immediate upload, and then I can implement the rest (like just the cropping)?

# Answer
The best solution I found is to use the Imagefield Crop module. This does NOT work on profile pictures, so simply disable user pictures and then add an image field to the user account fields. It will work with that.
> 2 votes

# Answer
The Image JavaScript Crop module should get you a good part of the way there.

It has support for the user profile picture built in so in fact it might be exactly what you're looking for.
> 1 votes

# Answer
Assuming Drupal 7 here...

Not sure about a module that does this, but as a starting point I would add a submit handler for the image upload. You could also try one of the hooks that the file module fires.

Inside that, you can call `theme('image_style')` which will give you the URL of the image w/ the selected style. You can then call `image_style_create_derivative`, which does what it says.

Check out `image_style_deliver`, which is the menu callback when a browser requests a styled image, for inspiration.
> 1 votes

---
Tags: forms, users, media
---


# Question
Title: How to allow users have only alphabetical "username"?
I suddenly realized that username can be any character after seeing someone just made his or her account in Japanese characters. I don't really have a problem with that but just would like to let them register only with alphabetical characters to keep the things tidy. Is there anyway to do this?

# Answer
> 6 votes
Check out the Custom Username Validation module, it seems like it should do exactly what you like.

If not, (In Drupal 6) you can set up "Access Rules" in the administration pages. Set up multiple access rules to deny usernames that contain undesired symbols. Access Rules Docs. Unfortunately that would take a lot of time to deny all non-alphabetical characters.

Finally, you could also create a custom module and use `hook_form_alter()` (or `hook_form_FORM_ID_alter()`) to change the validation on the username field. Here's a related question on SO: Hook into Drupal registration and validate user info against business logic

# Answer
> 6 votes
Using hook\_form\_alter

You can do like this,

```
function hook_form_alter(&$form, &$form_state, $form_id) {
  if($form_id == 'user_register'){
    $form['#validate'][] = 'user_name_validate';
  }
}

function user_name_validate($form, &$form_state) {
  $name = $form_state['values']['name'];
  if(preg_match('/[^A-Za-z]/', $name)) {
    form_set_error('name', 'username contains non alphapetic');
  }
}

```

# Answer
> 0 votes
In addition to the module or hook\_form\_alter() you can also use the username originality AJAX check module to show a message to your user before they submit the form.

I was able to modify the code in that module to do my custom validation - I don't like special characters in usernames either ;-)

---
Tags: 6, users
---


title: Drupal with lazy developers

text:
# Question
Title: Drupal with lazy developers
I inherited a Drupal website from previous "developers". After my initial sweep of the website, I found out they did a very very "interesting" job when creating the website.

As you can see, for reason beyond my understanding, they coded INTO the php files, instead of implementing through the drupal system.

**My question is, what do you recommend in this situation?: Re-write the whole page from scratch, or should I try implement these "stray codes" into proper blocks, code them into php etc.**

(The thing is there are several other different node files, each of them have the menu system coded into them as html. As result of that, to change the order of the menus I would need to change the code in 17 different php files. Way too many chances to screw up...)

Your thoughts and advices are appriciated!

Code:

```
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="hu" lang="hu">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link rel="home" href="http://www.htconsulting.hu/" title="Home" />
<title><?php print $head_title ?></title>
<?php print $head ?>
<?php print $styles ?>
<?php print $scripts ?>
<link rel="stylesheet" href="<?php print base_path() . path_to_theme(); ?>/zoli.css" type="text/css" media="screen" charset="utf-8">
<script src="http://ajax.googleapis.com/ajax/libs/swfobject/2/swfobject.js" type="text/javascript"></script>
<script src="<?php print base_path() . path_to_theme(); ?>/javascripts/main.js" type="text/javascript"></script>
<!--[if lt IE 7]>
<script src="http://ie7-js.googlecode.com/svn/version/2.0(beta3)/IE7.js" type="text/javascript"></script>
<![endif]-->
</head>
<body>
<div id="container_outer">
<div id="container">
<div id="header">
<div id="lang-selector-container">
<div id="lang-selector">
<span class="lang-active">HUN</span>
<span id="lang-sep">|</span>
<a href="/en" class="lang-link">ENG</a>
</div><!-- lang-selector -->
</div><!-- lang-selector-container -->
<!--<a href="#" id="header-search"><span></span>keresÃ©s</a>  -->
</div> <!-- header -->
<div id="content">
<div id="top-menu">
<ul class="top-menu-left">
<li><a href="/elerhetoseg" class="first">ElÃ©rhetÅ‘sÃ©g</a></li>
<li><a href="/search">KeresÃ©s </a></li>
</ul>
<ul>
<li><a href="/magunkrol" class="first">MagunkrÃ³l</a></li>
<li><a href="/referenciak">ReferenciÃ¡k</a></li>
<li><a href="/partnereink">Partnereink</a></li>
</ul>
</div> <!-- top-menu -->
<div class="clear"></div>
<div id="left-menu">
<ul>
<li class="org-dev"><span id="org-dev"><img src="<?php print base_path() . path_to_theme(); ?>/images/fogaskerekek.png" /></span>
<?php print l("SzervezetfejlesztÃ©s", 'node/6', array('attributes' => array('class' => 'org-dev'))) ?> </li>
<li class="training"><span id="training"><img src="<?php print base_path() . path_to_theme(); ?>/images/figurak.png" /></span>
<?php print l("TrÃ©ningek", 'node/7', array('attributes' => array('class' => 'training'))) ?> </li>
<li class="training-tools"><span id="training-tools"><img src="<?php print base_path() . path_to_theme(); ?>/images/disk.png" /></span>
<?php print l("KÃ©pzÃ©si eszkÃ¶zÃ¶k", 'node/8', array('attributes' => array('class' => 'training-tools'))) ?> </li>
<li class="methodology"><span id="methodology"><img src="<?php print base_path() . path_to_theme(); ?>/images/page.png" /></span>
<?php print l("MÃ³dszertan", 'node/80', array('attributes' => array('class' => 'methodology'))) ?> </li>
</ul>
<a href="http://flowcsoport.hu/" target="_blank">
<img id="flowlogo" src="/sites/all/themes/htc/pictures/flowlogo_120px.png" border="0">
</a>
<?php include "randomimage.php"; ?>
<br />
<br />
<div id="intro-video" style="visibility: visible">
<script type="text/javascript" style="visibility: visible">
            jwplayer("container").setup({
            flashplayer: "/flash/jw_html5/player.swf",
            file: "/videok/ian.mp4",
            height: 260,
            width: 195
        });
</script>
</div>
<br />
<br />
<!-- <?php print $left; ?> -->
</div> <!-- left-menu -->
<div id="content-main">
<?php if ($tabs): print '<div id="tabs-wrapper" class="clear-block">'; endif; ?>
<?php if ($tabs): print '<ul class="tabs primary">'. $tabs .'</ul></div>'; endif; ?>
<?php if ($tabs2): print '<ul class="tabs secondary">'. $tabs2 .'</ul>'; endif; ?>
<?php if ($show_messages && $messages): print $messages; endif; ?>
<?php print $help; ?>
<div id="content-inner" class="front">
<?php print $content ?>
<?php print $footer ?>
</div>
<div id="content-banner">
<?php print $right; ?>
</div>
</div> <!-- content-main -->
<div class="clear"></div>
<!-- <a href="http://flowcsoport.hu/" target="_blank">
<img id="flowlogo_old" src="/sites/all/themes/htc/pictures/flowlogo_120px.png" border="0">
</a> -->
</div> <!-- content -->
<div id="footer">
<ul>
<li class="company-name">Human Telex Consulting Kft.</li>
<li class="company-address">1015 Budapest, Toldy F. u. 16/c.</li>
<li class="company-tel">Tel.: 214-0204, 225-1576</li>
<li class="right">KMRMK: 01-0122-04; FAT: AL-1416</li>
<!-- <li class="customer-gate"><a href="#">ÃœgyfÃ©lkapu</a></li> -->
</ul>
</div><!--  footer -->
</div><!-- container -->
</div><!-- container outer -->
<?php print $closure ?>
</body>
</html>

```

# Answer
> 6 votes
Providing they haven't changed the core you should be fine to just add a new theme and do things properly in there.

If it were up to me I would install a clean version of Drupal somewhere (to make sure the core hasn't been messed with), then start a new theme from scratch. You can probably reuse the CSS file but I would completely gut it.

Either way it's a bit of work now to avoid a potential lot of pain later on.

# Answer
> 4 votes
I cannot see any big problems in the posted code. Moving the menu entries into a custom block might be a good thing if it's reused in multiple places.

If you want to check whether core or contrib modules have been changed, you can use the Hacked! module.

# Answer
> 0 votes
You should re-implement everything using the Drupal system. It is a lot of work, but you must consider future updates of the website, etc. You put a bit of effort now, but then you'll look back and congratulate yourself for the good decision.

---
Tags: theming
---


# Question
Title: Drupal base_url incorrectly writing extra subdomain
We have a basic drupal multi-site installation on a RHEL (RedHat) server. For some reason when viewing the site, the asset URLs (CSS/JS) all point to the wrong subdomain.

Our site URL: `http://drupal.sandbox.domain.com` the drupal index page loads up with asset URLs being written as: `http://drupal.sandbox.sandbox.domain.com`. Why would drupal add in the extra `.sandbox` subdomain?

The `.htaccess` file has been left as the default, also attempted to set RewriteBase to `/`, but there was no change. The `sites/default/settings.php` file has the base\_url set to: `$base_url = 'http://drupal.sandbox.domain.com'` but Drupal is overwriting this somewhere. Setting the `$base_url` to the IP of the server causes the assets to be linked to the correct location (using the IP rather than the actual domain), but this is not ideal.

I've tested using the same configuration on an Ubuntu Server without any problems. I'm not sure exactly how to track down the cause of this problem.

How would I go about debugging this and discovering what is causing the overwritten URLs?

# Answer
This is not a Drupal-specific problem. This can easily be checked by creating a standalone PHP page and using the same code to test. Being that the variable is overwritten immediately after it is set shows that PHP/Apache is the one doing the overwriting.

It is possible for Apache to overwrite input and output. See: What would cause PHP variables to be rewritten by the server?
> 1 votes

---
Tags: 7, uri
---


# Question
Title: Getting the user picture URL when Gravatar is installed
I'm trying to print a user's picture without the link to the user's profile which is what `theme('user_picture', array('account' =>$user_item))` will render. If I use `image_style_url('thumbnail', $user->picture->uri)` the Gravatar hook will not be called.

So far the only way I have found to do this is:

```
if (function_exists('_gravatar_get_account_user_picture')) {
    $picture = _gravatar_get_account_user_picture($user);
} else {
    $picture = $user->picture->uri;
}
if (file_valid_uri($picture)) {
    $picture = image_style_url('thumbnail', $picture);
}

```

But this isn't very elegant, especially since I am developing a module and I'd rather not have to explicitly call the Gravatar module.

Any suggestions?

Thanks!

# Answer
> 3 votes
The reason calling `theme('user_picture')` returns the user picture as a link is because it's hard coded into the `gravatar_preprocess_user_picture()` function (see lines 148 and 156 of the `gravatar.module` file).

This function uses `_gravatar_get_account_user_picture()` itself so your options are:

* Use that function directly as you're doing at the moment
* Hack the `gravatar_preprocess_user_picture()` function to return the `<img>` tag without the link
* Perform some sort of hideous regex on the rendered HTML in your own preprocess function to extract the `<img>` tag

Personally I'd say the first option is the most desirable.

A slightly more 'Drupal' way to do it might be to use `module_exists()` instead of checking for the existence of the function itself. It returns `TRUE`:

> if the module is both installed and enabled

While that's not ideal it's a tiny bit more elegant, and if you're worried about the length of code you could shorten it a bit:

```
$uri = module_exists('gravatar') ? _gravatar_get_account_user_picture($user) : $user->picture->uri

if (file_valid_uri($uri)) {
  $options = array('style_name' => 'thumbnail', 'uri' => $uri, 'alt' => 'Alt');
  $img_html = theme('image_style', $options);
}

```

The above code generates the HTML for the `<img>` tag directly using `theme_image_style()` without having to get the URI directly which I think is what you're after.

# Answer
> 4 votes
Obviously, handling directly in the Gravatar module would be best, but another option (though slightly hackish) would be to simply

```
$img = strip_tags(theme("user_picture", array('account' => $user_item)), "<img>");

```

---
Tags: 7, uri, media
---