# Question
Title: Webform file upload not working after hook_from_alter
I have used the following form alter to do some adjustments to my form but after the file upload stops working. I cant seem to find out why. This is the module code.

Any help would be much appreciated.

```
if ($form_id == 'webform_client_form_3'){
    //image btn
    $form['actions']['submit']['#type'] = 'image_button';
    $form['actions']['submit']['#src'] = drupal_get_path('theme', 'MY_THEME').'/images/submit2.png';
    $form['actions']['submit']['#attributes']['name'][] = 'op';

    //palceholders
    $form['submitted']['forename']['#attributes']['placeholder'] = t('Forename');
    $form['submitted']['surname']['#attributes']['placeholder'] = t('Surname');
    $form['submitted']['post_code']['#attributes']['placeholder'] = t('Post Code');

}

```

# Answer
I fixed this by forcing the the 'op' value to

```
 $form['actions']['op'] = array( '#type' => 'value', '#value' => 'Submit', );

```
> 1 votes

---
Tags: webforms, forms
---


# Question
Title: how to submit a text field input from a user in a views filter form to a javascript ?
I am trying to fetch the user entered text value precisely a zip code which will be taken as input in the views exposed filter form and this value should be sent to the Java script function and I have this java script function which calculates the required LAT LON based on the zipcode and gives back the result. The problem is I can use the drupal\_add\_js function to add the js file and also pass the value of zip code (I think so I am not sure though) I am wondering if I can send the zipcode value entered by the user only on form submit to the js file i.e can I send the value of zipcode to the js file only when the user submits the views exposed filter form by pressing the apply button?

I know that we can add a js file and send the values using drupal\_add\_js function but just not sure if this can be synced with the form submission button ? how can this be done? please help me in this, any pointers in this regard are appreciated.

# Answer
got it I never used Jquery before and jquery is magic it when used with drupal behaviours as magic just listens to click or any event you want it to listen to and passes the value and you can retrieve it using $(# id of the field).val()\[.val() is a function to retrieve the value\].
> 0 votes

---
Tags: views, javascript, forms
---


# Question
Title: Can't delete content type that I created?
I am running a Drupal 6 installation and created 2 content types through the admin menu (they are not programically created). Now I want to delete them but no delete link is visible in the content type screen. I do not have any pages created with those types so I don't understand why Drupal won't let me delete them.

I have searched this site and Google but I can't find an answer. Anyone here have any ideas how to get rid of them?

Thanks

# Answer
After digging around, I did find that ubercart had a reference to the content type in question in one of its configuration screens. So although I didn't create any nodes of that type, the reference to that node is what was preventing me from deleting it. Once I removed the reference, the delete link appeared again.

Thanks to everyone who proposed answers as it will help someone else who might experience this problem.
> 4 votes

# Answer
Ensure you are **user/1** and try navigating to this page

```
/admin/structure/types/manage/<content-type-name>/delete

```

replace `<content-type-name>` with the actual name of the content type
> 5 votes

# Answer
If you go to `http://my.site.com/admin/content/node-type/<your-content-type-name-machine-name>` you should have a delete button at the bottom of the page.
> 1 votes

---
Tags: nodes
---


# Question
Title: How to trigger function on vocabulary terms update?
Is there a hook that being triggered when any term in taxonomy vocabulary is edited/added/deleted?

I'v tried to use hook\_taxonomy\_vocabulary\_update but no success so far.

# Answer
> 0 votes
Oh, I probably should use term\_update for this:

```
hook_taxonomy_term_update($term){
if ($term->vid == $vid){
// Action
  }
}

```

Or Rules module

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


# Question
Title: Show block in particular nodes having some string in title
I have a block and I need to show this block only in some situations. For example if title of node includes "abc", block will be visible else it won't. From visibility settings of block I use this code snippet:

```
<?php
$match = FALSE;

$url = request_uri();
if (strpos($url, "myword")) {
  $match = TRUE;
}
?>

```

I'm sure that "myword" is included in full URL of node. I tried to debug it by adding "echo $url" but it didn't write this line into page.

How can I solve this?

edit: in last line i forgot to add "return $match;" which returned always false.

# Answer
> 1 votes
Try:

```
if (strpos($url, 'myword') !== FALSE) {
  $match = TRUE;
}

```

`strpos()` returns the zero-based index of the first occurrence of the substring.

So if "myword" is at the start of the URI string `strpos()` will return `0`, and since `0 == FALSE` in terms of a conditional, it will fail.

I've just tested your code and it works fine with the slight change.

---
Tags: 7, blocks
---


# Question
Title: What's the "Drupal" way of creating image links?
I know that the correct way to create links in Drupal is to use `l($text, $path, array $options = array())`. But that only allows for text links. Is there a similar function for creating images that link, or is it OK to just write out the HTML?

# Answer
`l()` allows for HTML too, you just need to pass it as one of the options:

```
$link = l($image_html, $path, array('html' => TRUE));

```

That'll stop the first parameter being passed through `check_plain()`, so the the full HTML you pass in will be wrapped in the `<a>` tag.

I'd advise using this method if the alternative is writing the link out manually, you get the benefit of automatic alias-translation and it's less prone to small errors in the HTML (of which I for one always make loads).
> 10 votes

---
Tags: 7, media, navigation
---


# Question
Title: views 2 - how to fetch filepath of image field for output rewriting
I'm in Drupal 6/views 2 and am rewriting the output of an image field. Is there a way to fetch the filepath of the image for the output? I have tried the filepath token for the image field, but the src for the image is not rendering, just the argument. Should I be using a preprocessor hook in a template file to do this instead?

# Answer
One trick I like to use is adding a field that contains the value I need, then hiding it from display but using it's token value for your original field's override.

So your view fields would look something like:

```
image path (hidden from display)
image (using value from the above field)

```

Keep in mind that the order is important here, so you only have access to tokens that are above the field you want to use them in.

You may need to tweak the settings of the path field to make it the style of url you need (relative, absolute, etc).
> 1 votes

---
Tags: views
---


# Question
Title: get variable indicating node preview mode (D7)?
I would like to display a specific message to users when they are previewing a node they are submitting. So I thought I would use a block with PHP code, using some info indicating that the node is being previewed. Unfortunately, I cannot get it working. I have tried these conditions:

`if ($variables['view_mode'] == 'preview')` ...

I get this error:

> Notice : Undefined variable: variables in eval() (line 4 in /.../modules/php/php.module(80) : eval()'d code).

Tried this too:
`if ($node->in_preview == TRUE)` ...

I get these errors:

> Notice : Undefined variable: node in eval() (line 5 in /.../php.module(80) : eval()'d code). Notice : Trying to get property of non-object in eval() (line 5 in /.../php.module(80) : eval()'d code).

I guess I have to declare the variable before, but how? I thought that since the node form is rendered anyway, the needed variable was available?

# Answer
The variable that inside node.tpl.php says the view mode currently used for the node is `$view_mode`, but that variable is not used when Drupal is displaying a preview of the node. To know that, you can:

* Check the value of `$node->in_preview`; when that value is `TRUE`, Drupal is displaying the preview of a node.
* Check that `$classes` contains the string `'node-preview'`, such as with the following code.

```
if (strpos($classes, 'node-preview') !== FALSE) {
  // Drupal is showing a preview of the node.
}

```

Drupal already shows a message when the user is watching the preview of a node, anyway.

> The trimmed version of your post shows what your post looks like when promoted to the main page or when exported for syndication. You can insert the delimiter "`<!--break-->`" (without the quotes) to fine-tune where your post gets split.
> 1 votes

# Answer
Blocks don't know anything about the main content that is being displayed. They have to deduce this information e.g. from the current Drupal path.

If it's OK to display the message in the main content area, implement hook\_node\_view() to display the message.

Another solution is to implement hook\_node\_view() in such a way that it lets the block know that a node is being previewed, e.g.

```
function example_node_is_in_preview($node = null) {
  static $result = null;
  if ($node !== null) {
    $result = $node;
  }
  return $result;
}

```

Call this function in your hook\_node\_view() implementation, passing the node as argument. Call this function in your block code without arguments to determine if and which node is being previewed.

This works because the main content area and its form submissions are dealt with before block content is rendered.
> 0 votes

---
Tags: nodes
---


# Question
Title: Database Abstraction Layer and 'LOAD DATA INFILE' Statements
I realize that using the database abstraction layer comes with a few caveats such as not being able to run queries that are not available in one way or another across all versions of the databases supported by Drupal7. However, I need to load data from a CSV file into the database from a user uploaded CSV file via a form built with the form API. So in the hook\_submit function, I am going to do just that. Obviously I can write my own MySQL dependent implementation, however, I was hoping there was an abstracted "Drupal way" to accomplish the same task. I have not been able to find any such method.

Typically here is how I would do this after sanitizing the data, as an example:

```
LOAD DATA INFILE 'components.csv'
INTO TABLE components
FIELDS TERMINATED BY ','
LINES TERMINATED BY '\n'
(componentId,componentName,componentDescription,componentAverageCost);

```

However, obviously this is a MySQL dependent query and even further it is dependent upon MySQL version 5 and later if my memory serves me correctly.

# Answer
> 1 votes
You can execute any query you want through db\_query(), it just isn't going to work on a different database. db\_query() doesn't care, nor does PDO. They basically just send the string passed to it to the server and allow the server to process it.\*

So, you could probably get that working through db\_query(), not sure if they LOCAL keyword would work in case your web and database server are not on the same server.

That said, I wouldn't recommend doing it. For example, you might end up having to do some processing on the data, e.g. verify that it's valid. No idea what's going to happen if your user is uploading a file that is not valid CSV.

What the DB abstraction layer of Drupal 7 *does* support are INSERT queries with multiple rows, including a fallback to doing multiple queries if the database doesn't support it. See http://drupal.org/node/310079. That's what I would recommend doing.

If the data should actually end up in Nodes or something similar, then I would recommend looking into the Feeds or Migrate modules. They're not going to be that fast but provide a nice abstraction of the actual storage.

\*There are exceptions of course, but if it's possible in PHP, then it's possible with db\_query(), pretty much. And a quick search indicated that you can do LOAD DATA INFILE from PHP.

# Answer
> 2 votes
Your question is a little vague. I assume this isn't for a Content Type you created or an Entity in D7 ?!

As you pointed out this is DBMS specific. The drupal db api basically adheres to an ANSI SQL '97 (i think) specification. So you can do basic queries, updates, etc using the Drupal API. When you start talking about DBMS specific stuff you're outta luck.

The drupal API sits atop the PHP PDO library. This is an abstraction on top of many DBMSs as well -- you can do anything dbms specific with a bare PDO\_Connection object ... called a stored procedure, or do your nifty INFILE usage above.

So you'd probably have to make your custom `MYMODULE_form_submit()` and do your custom query there from the raw pdo db connection. You can call Database::getConnection() in Drupal 7 to get the default db connection directly. Here is similar concept in calling a MySQL stored procedure from D7 asked here before on stackexchange.

Lastly, this isn't really drupal api related because you not seeking to call node\_save() with your CSV data ... node\_save() lives in the universe of the drupal API and has a succesion of function calls around it in the Drupal-verse, you're clearing asking for MySQL-verse stuff :)

---
Tags: database
---


# Question
Title: Cannot view individual article, instead the node's link displays all articles
I cannot figure out what I am doing wrong. I'm using Drupal 7 and the Omega theme. I'm using pathauto to have nice paths. I have the built-in article content type which I renamed to "news". The pattern for news articles is set to news/\[node:title\]. I created a view to list all the news and gave it the path "news".

When I went to /news I saw my view. When I clicked on an individual article, I got a file not found error with the entire web page layout embedded and repeated twice and then a third time with the individual article displayed. I also got a php "Warning: Cannot modify header information - headers already sent" error.

Thinking that using the pattern news/\[node:title\] and also creating a view with the path "news" was the problem, I changed the path of the view to "all-news". Visiting an individual article with its path "news/\[node:title\]" still gives me the file not found errors and the multiple embedded pages with the cannot modify header errors. The only way to see my individual article was to use the path all-news/\[node:title\].

Next, I disabled the view. Now I only get file not found errors for my articles when I use the url pattern "news/\[node:title\]" and no multiple embedding of the entire web page.

I think there is something I'm completely not understanding. My goal is to have a news section of the site, and to use taxonomy to organize the articles by topic. Can you tell me where I might have made a mistake?

# Answer
I suggest that you first *delete* all (if you can, else just news) path aliases (via the pathauto interface). Get your view working as you like. Then regenerate the aliases (again via the pathauto admin interface). Keep things simple first and then proceed to complicate :)

If things persist, try with a test node type.
> 0 votes

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


title: Rewrite photo field URLs

text:
# Question
Title: Rewrite photo field URLs
Every time I download a new copy of the live database to my local site I also have to download the photos (several GB). Is there an easy way to write the URL for one "photo" field (type image) to always use the live site urls?

I'm using S3 but haven't found a good way to batch move images and image styles to S3.

# Answer
`theme_image()` by default looks like this:

```
function theme_image($variables) {
  $attributes = $variables['attributes'];
  $attributes['src'] = file_create_url($variables['path']);

  foreach (array('width', 'height', 'alt', 'title') as $key) {

    if (isset($variables[$key])) {
      $attributes[$key] = $variables[$key];
    }
  }

  return '<img' . drupal_attributes($attributes) . ' />';
}

```

so, if you are storing the images in this field in an identifiable place, eg, you can look at `$variables['path']` and figure out they are the ones you want to always look for on a specific host, you should be able to do something like this in your theme:

```
function MOTOTHEME_image($variables) {
  $attributes = $variables['attributes'];

  if (dirname($variables['path'])==WHEREIKEEPTHISFIELDSIMAGES) { // on d7 this might be a uri so you might need to get fancier than dirname() :)
    $attributes['src'] = // http://.....
  } else {
    $attributes['src'] = file_create_url($variables['path']);
  }

  foreach (array('width', 'height', 'alt', 'title') as $key) {

    if (isset($variables[$key])) {
      $attributes[$key] = $variables[$key];
    }
  }

  return '<img' . drupal_attributes($attributes) . ' />';
}

```
> 3 votes

---
Tags: 7, uri
---


# Question
Title: What is the purpose of _field_sql_storage_columnname()?
While reviewing a patch, I came across an interesting function, \_field\_sql\_storage\_columnname(). And I couldn't help but wondering, why on earth do we have this function?

git blame unfortunately wasn't helpful, as it only lead me to a commit that cleanup up windows line-endings.

# Answer
I think it's clear what the function is doing, the question was more why a function is required for that.

My guess is that the function was there from very first day field API existed where it might have made sense to change it. Nowadays, it's not going to be as easy as "just" changing that function, because it will obviously completely break all existing field tables.

I think the function is still useful for consistency reasons as there is one for the table name as well and I think it's also easier to read because it implies the string is the column name, which might not be that obvious if you e.g have a line like this:

```
$sql_field = "$table_alias." . _field_sql_storage_columnname($field['field_name'], $specifier['column']);
// vs.
$sql_field = "$table_alias." . $field['field_name'] . '_' . $specifier['column'];

```
> 2 votes

# Answer
The reason to have a function that returns the column name is that a field could save more than one value. For example, an image field saves the following values:

* fid
* alt
* title
* width
* height

When the field data are saved in the database table, the column name must be unique, to avoid conflicts with other fields.

The reason why the fields are not saved as serialized data is to make searching for a field with specific values faster. For example, you could search for an image with a specific weight with an SQL query, rather than executing a generic query, getting the data, passing the data to `unserialize()`, and verifying the data contain what you are looking for.

The reason to have a single function that returns the column name is to make easier to change that code, if there is the need to change it: It is enough to change the code of a single function, rather than searching for the code used in the module, and changing it.
> 1 votes

---
Tags: entities
---


title: Ajax views (watch) table

text:
# Question
Title: Ajax views (watch) table
I want to have a table view that remains on a particular page, but once someone anywhere on that site creates a node that is a part of that view, the view updates through AJAX and I see the new entry. Like a live twitter feed but for nodes.

# Answer
> 1 votes
Found it!: module Views Auto-Refresh, which used to be part of the Views Hacks module (but is now considered a "Graduated module", as mentioned on the project page). \`Here are some details about it, i.e. a quote from its project page:

> ... to refresh a view after a specified time interval. Includes advanced options to avoid reloading the whole view, and to avoid causing a full Drupal bootstrap at each refresh.
>
> Suitable for usage on liveblogs, activity streams, comment lists, and any other view where new items are frequently added.

---
Tags: views, ajax
---


# Question
Title: The link of "Pdf version" on node page does not appear in chrome
I have installed the the print module on my drupal 7 site. I configured the the print module pdf settings.

Now the link "pdf version" is displaying with each node on the content area at bottom. When I click on the link, it save the node in pdf format.

But this only works in firefox. In chrome the "pdf version" link in not displaying.

What is the problem?

# Answer
> 0 votes
It was the permission issue. I granted the permission to the authenticated and anonymous users and it works for me.

---
Tags: 7, files
---


title: Clean up Unused Tables

text:
# Question
Title: Clean up Unused Tables
I have installed some analytics module for my drupal sites. Because it's on company's internal network, I couldn't use it. Now I have the tables created by the module sitting in my database (after I just forcefully removed the module folder from drupal installation).

Is there a way to clean unused tables in Drupal 7?

Note: I tried Schema, but it doesn't seem doing anything but displaying tables are in use and not used

# Answer
Most Drupal modules that installed their own database tables also remove them upon **uninstall**. I have bolded uninstall due to the fact that modules can have two states when they are turned off namely *disabled* and *uninstalled*.

Disabled implies that you have simply turned the module off, but have chosen to keep the module's settings and database tables intact in the event that you turn it back on again at some point. Disabling is done by simply unchecking the module on the module administration page and clicking on "Save configuration".

Uninstalled on the other hand indicates that you have decided that a previously *disabled* module will never be used again. Consequently, you are happy to remove all the settings and database tables created. This is done by clicking on the "Uninstall" *tab* on the module administration page, checking the module that you want to uninstall and then clicking on "Uninstall".

If for some reason the module does not have an uninstallation script in its `.install` file, then you will need to remove the tables manually. You can also try creating an issue in the module's issue queue asking for this oversight to be remedied.

If you have removed the module's files from the server, then you will (obviously) be unable to run the uninstallation script (as the module will no longer be listed under the uninstall tab). To fix this, simply download/restore the module again to the file system (you do not need to install it). This should list it again under the uninstall tab and you can proceed to run its uninstallation script as above.
> 6 votes

# Answer
If the module does not provide the usual .install hooks which should remove the tables automatically up on uninstall, you can examine what's in .install to add the tables to find what you have to remove manually.
> 1 votes

---
Tags: 7, database, installation
---


# Question
Title: term field permission for authenticated user
I have installed the tern\_fields module.

I have added a term field to the taxonomy vocabulary. The specification of that field is.

type: File widget: image

Now when I try to upload an image for a taxonomy term, it works fine for the admin but when I try to upload an image for a taxonomy term as a site manager then it gives me the following error.

```
The selected file test.jpeg could not be uploaded. Only files with the following extensions are allowed: png|gif|jpg|jpeg.

```

Where the site manager is a user role. and in the permissions for the site manager against the term\_fields module, both check boxes are checked. administer term\_fields and upload term files.

what is the problem now?

# Answer
> 0 votes
I have found the answer of my own.

I edit the field there in the file extension I had entered like this "png, gif, jpg".

I changed it to "png gif jpg". insert the space instead of the comma and it solved my problem.

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


title: Multiple nodes within a node

text:
# Question
Title: Multiple nodes within a node
Does anyone know if there's a module out that would provide the functionality for displaying multiple nodes within a node i.e. similar to how a blog looks with its articles, simply a page that displays a number of teasers that link directly to other nodes.

The big thing would be the CMS part and the ability to add existing nodes within a node. By this I mean like the way you would with a field, except in this case it would be a list of existing nodes.

So far my attempt at such as set-up has been to use the field collections module to put a few fields together like title, image, long text, etc, then use this field collection as part of a basic page. This does exactly what I'm after except all we are doing here is giving the content manager the ability to supply a path to an existing node so there is not relationship here at all.

A content manager could delete the node and forget to delete the teaser on another page that was linking to it.

Please could I stress that 'Node embed' is not an option or anything similar because its just not practical for clients to use such methods. It needs to be very simple that almost requires them not to think.

Any suggestions please?

# Answer
Sounds like you need to use entity reference module and have it render the teaser view mode.

This field can have unlimited values so you can keep "adding more". This will allow you to specify nodes to embed in another node.

Alternately you can use field collection if you do not require these embedded nodes to be a node on their own.

Furthermore you could even add a view which shows teasers as a block to bottom of the node, however the filters / contextual filters will be more dynamic in nature rather than manually selecting specific nodes. You could argue that node queue would allow you to do this but I would say thats a lengthy way of resolving you question.
> 2 votes

---
Tags: 7, nodes
---


title: Ajaxify Menu Links

text:
# Question
Title: Ajaxify Menu Links
I have menu on left column, When we click menu-link I need to post data in right column without page refresh. I am looking to ajaxify menu.

Could you please give me an example how to ajaxify menu links?

# Answer
> 0 votes
This is really simple by using Drupal ajax framework.

First, define your menu callback page.

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

  $items['yourmodule/callback-page'] = array(
    'title' => 'AJAX callback - refresh the elements on the right hand',
    'page callback' => 'yourmodule_refresh',
    'page arguments' => array(1),
    'access arguments' => array('access content'),
    'type' => MENU_CALLBACK,
  );

  return $items;
}

```

Secondly, do ajax deliver on callback page.

```
/**
 * Menu callback.
 */
function yourmodule_refresh($action, $type) {
  if ($type != 'ajax') {
    // This is js only.
    return 'Oh well';
  }

  $content = t('What ever you want');

  $commands = array();
  $commands[] = ajax_command_replace('.right-hand-wrapper-class', $content);
  $page = array('#type' => 'ajax', '#commands' => $commands);
  ajax_deliver($page);
}

```

---
Tags: hooks, routes
---


title: Text After Comment Form

text:
# Question
Title: Text After Comment Form
How I could put a block of text after my comment form (kinda like politics), I put comments separated from the content (different pages).

# Answer
As megadesk mentioned its `hook_form_alter` you're after.

Depending on what your more comfortable with you can either add this to your theme in template.php or you can add it to a module. I'm going to assume from now on that you'r putting it into template.php. An infact rather than hook\_form\_alter we'll use hook\_form\_FORM\_ID\_alter.

```
/*
* Implementation of hook_form_FORM_ID_alter
*
* Adding text after the comment form
*/

function YOUR_MODULE_NAME_form_comment_form_alter(&$form, &$form_state) {

    //add an I agree to house rules checkbox to the form
    $form['markup'] = array(
                 //This is the text you want to add to the form, using the t() function allows it to be translatable
                '#markup' => t('You can leave us a message using the contact form below.'),
                //By making the weight 20 we insure that it appears at the bottom of the form
                '#weight' => 20,
        );
}

```

I havnt tested this but that should be what your after... Let me know if you need more.
> 3 votes

# Answer
You could simply use hook\_form\_alter. http://api.drupal.org/api/drupal/modules!system!system.api.php/function/hook\_form\_alter/7

Here is a little Tutorial for that: http://www.digett.com/blog/05/26/2011/how-theme-comment-form-drupal-7
> 0 votes

---
Tags: 7, comments
---


# Question
Title: Is Drupal suitable for that kind of ecommerce?
I have to do website that sells webinars and I want to use D7 to this job. Unfortunately I have never done any Drupal ecommerce before.

I'll have to kind of users:

* Teacher
* Student

Payment method: PayPal only

Webinar content type:

* Title
* Description
* Start date (every webinar length is 60 minutes)
* Places
* Price is the same of all webinars and is specified by Admin
* Webinar booked at least 7 days before start costa less (discount and days limit configurated via admin area)
* If a webinar is cancelled need option to move the participants/users into a new webinar

User of role Teacher can add/edit/list his Webinars.

In addition Teacher can create group with fields:

* Topic
* Description When Teacher is creating new webinar, he can specify group for this webinar (select list) (not mandatory)

Student (auth user) can buy single webinar or group. When buying group discount is bigger.

Every webinar can repeat and has multiple start date. Setting next start date must generate different ID for webinar for invoice

If do it by plain PHP database structure will look something like:

* groups

+ id
    + topic
    + title
* webinar

+ id
    + group\_id
    + title
    + description
    + etc
* webinar\_date

+ id
    + invoice\_id (maybe webinar id + webinar\_date id)
    + webinar\_id
    + date

Teacher can see list of his webinar with dates, so if webinar has two dates it must be visible in two times in list. Also info about free places of webinar must be and income from bookings of webinar. After choosing webinar Teacher can see list of all users that buy webinar 'ticket'.

The same is for admin but he can see all webinars of course.

Is this possible to create in Drupal without a lot of pain?

Which module are most suitable for this: Commerce or Ubercart?

Thanks in advance

# Answer
Yes it is possible, most of which using Rules, Fields, Date and Views. I'd say that, due to the specificity around some features, Commerce would be best as it fully taps into the Entity API which makes developing a breeze.
> 1 votes

# Answer
Yes it is possible, but I'd say to go with Ubercart.

Commerce is promising but it lacks in additional modules, maturity and resources. Ubercart has been around for quite a long time so you can virtually find anything you need to do with it.

Also Ubercart is much less intimidating than Commerce for first-time users.

Just my 2 cents, hope this helps :)
> 1 votes

---
Tags: 7, commerce, ubercart
---


# Question
Title: Using Views to add comments to user profiles
My goal is to create an additional "ratings/comments" tab to user profiles in drupal 7 to allow authenticated users to leave comments/ratings for other users. I've created a "ratings" content type (which naturally has comments enabled) and created a view around this type and added it as a user menu tab.

The problem is, since it is one content type, all the comments that have been left by any authenticated user show up on every single user's "ratings/comments" tab. Of course I only want the comments that were meant for that particular user to show up.

Is this possible using filters? I've been playing around with it but haven't been able to find the right setting just yet. I know there is a guestbook module but I don't really want to go this route.

Thanks.

# Answer
Some hints which might push you in the right direction:

* Ratings can be handled with the five star module.
* I didn't test this, but the profile 2 module gives you the ability to tye a content type to a drupal user. Enabling comments for this content type could get you going.
> 1 votes

---
Tags: views, users, comments
---


title: Changing the Login block HTML for D7

text:
# Question
Title: Changing the Login block HTML for D7
I want to change the form elements a bit in the login block for D7 to add the following to the input elements:

```
onblur="if(this.value=='') this.value='Username'" onfocus="if(this.value =='Username' ) this.value=''"

```

I would prefer not to create a new module just for this via hook form alter, and I did not see a user block to override in the User module.

Is there a template.php function that could be used?

# Answer
You dont need to do access the form elements directly like that. You can use some unobtrusive JavaScript with jQuery to do the same thing.

```
;(function ($){
    Drupal.behaviors.YOUR_FUNCTION = {
        attach: function (context, settings) {
                    // your script goes here...
               };
    };
})(jQuery);

```

Create a scripts file and add the above. Add a reference to that file in your .info file.

Then add your script.

Some references if your not familiar with jQuery.
> 0 votes

---
Tags: 7, users
---


# Question
Title: how to hide text format tips for text field in a module, not theme?
I need to hide the text format tips for body field, depending on user role, in a module. After some research, I found this kind of code:

```
function mymodule_form_node_form_alter(&$form, &$form_state) {
  if (isset($form['body'][LANGUAGE_NONE][0]['#after_build'])) {
    $form['body'][LANGUAGE_NONE][0]['#after_build'][] = 'mymodule_node_after_build';
  } else {
     $form['body'][LANGUAGE_NONE][0]['#after_build'] = array('mymodule_node_after_build');
  }
}
function mymodule_node_after_build(&$form, &$form_state) {
  /*if (!user_access('administer filters')) {
    $form['LANGUAGE_NONE']['0']['format']['#attributes']['class'][] = 'invisible';
  }*/
}

```

\*I know the mymodule\_node\_after\_build function is all commented, so it's doing nothing, but it's here only for illustration. Just adding `#after_build` to the form or field makes it all invisible - and this is the issue here.\*

The above code results in field body not displayed at all, instead of just hiding text format info. More precisely, the html contains this code in place of the body field (just an empty div):

```
<div class="field-type-text-with-summary field-name-body field-widget-text-textarea-with-summary form-wrapper" id="edit-body"></div>

```

I tried setting this also for:

```
$form['body'][LANGUAGE_NONE]['#after_build']
$form['body']['#after_build']
$form['#after_build']

```

(the last one displays white space instead of the whole form)

Unless there is another much simpler solution to this problem, I'd like to use the above approach or something similar in a module, but it's not working!! So what's wrong with it?

# Answer
> 0 votes
Here is the simple code you can write your role base logic in hidetips\_test\_node\_form\_after\_build() fuction.

```

function hidetips_form_node_form_alter(&$form, &$form_state) {
  $form['#after_build'][] = 'hidetips_test_node_form_after_build';
}

function hidetips_test_node_form_after_build($form) {
  // Here you can write your logic for role based hide and display.
  $form['body']['und']['0']['format']['#access'] = FALSE;
    return $form;
}

```

---
Tags: 7, forms
---


# Question
Title: Rules help: After updating existing content
First time using Rules to make a complicated rule. Would appreciate some help. I'm making rules to send an e-mail, to a pre-defined e-mail address, after an existing node is updated. This node is of a certain type, and this type has a taxonomy term reference field. When any node of this type gets updated, by a user with certain role, Drupal should send an e-mail, and in the e-mail it should attach the **name** of the taxonomy term.

tl;dr/problem: What I'm having trouble is, when creating a condition to check the user's role (the user who updated the content, not the author). There seems to be only the "Author" of the node available on the Data selector (see attached image). Is `node:author` the correct one to check for the user who updated the content?

# Answer
For your task you need `site:current-user` token which corresponds to `$GLOBALS['user']` (`global $user`) object.

> I'm not sure how reliable this is when multiple users are logged in to the system?

Webserver creates new PHP thread (or process) for each request so there are no sharing variables between requests.`global $user` variable is initialized by Drupal on every request.

When you have just updated a node you can use `global $user` to know who updated this node. At any time after updating you can get that user id from revision (`$node->revision_uid`).
> 1 votes

---
Tags: 7, rules
---


title: Force trailing slash on every URL?

text:
# Question
Title: Force trailing slash on every URL?
The Global Redirect module has a "deslash" feature. It forces all URLs to not have a trailing slash at the end. If you add a slash at the end of a URL it will redirect you to the correct page.

I'm looking for the opposite of this and would like to have a trailing slash on every URL.

I tried the Trailing Slash module for Drupal 7 but just got a lot of errors. Are there any other methods?

Any help would be greatly appreciated!

Thank you.

# Answer
Rather than using a module, you can accomplish this via httpd's mod\_rewrite as detailed here, here and elsewhere. The appropriate rules can be incorporated into the .htaccess file in Drupal's root. Once you are done, make sure that you check all the various components of the site - CSS & JS files, images, directories, clean URLs on/off, path aliases on/off and so on.
> 1 votes

# Answer
I would look at the code that applies these functions in both of the modules you mentioned. You should be able to determine what elements of the code would be helpful in recreating them but to do the vice versa...
> 0 votes

---
Tags: uri
---


# Question
Title: Error in validation of managed_file field with Form API
To begin I worked with this solution but a wild error appear: Image Upload in a Custom Module

Here is my code :

```
function module_top_content_equipe_admin_form(){
  $default = get_variable_value(variable_get('module_top_content_equipe_display', ''));
  $default_image = variable_get('module_top_content_equipe_image', '');
  $form['module_top_content_equipe_display'] = array(
    '#type' => 'text_format',
    '#name' => 'module_top_content_equipe_display',
    '#title' => t('Content of the block'),
    '#description' => t("Text to display"),
    '#format' => 'filtered_html',
    '#default_value' => $default,
  );
  $form['module_top_content_equipe_image'] = array(
    '#type' => 'managed_file',
    '#name' => 'module_top_content_equipe_image',
    '#title' => t('Top Content page l equipe Image'),
    '#description' => t("Image should be less than 400 pixels wide and in JPG format."),
    '#default_value' => $default_image,
    '#upload_location' => 'public://',
  );
  return system_settings_form($form);
}

function module_top_content_equipe_admin_form_submit($form, &$form_state){
  if (isset($form_state['values']['module_top_content_equipe_image'])) {
    $file = file_load($form_state['values']['module_top_content_equipe_image']);

    $file->status = FILE_STATUS_PERMANENT;

    file_save($file);
  }
}

```

and my error when I submit the form

> Fatal error: Cannot unset string offsets in /includes/form.inc on line 2157

Thank you with advance

# Answer
There's a bug in the way `system_settings_form()` handles managed\_file types. It's to do with the upload/remove buttons and parent elements (if you read the whole issue you hould get a good take on what's going on).

I don't know if it's the same error as I was having, but adding code like the following to the top of the form's submit handler fixed it for me:

```
foreach($form_state['buttons'] as $delta => &$button) {
  if (preg_match('/module_top_content_equipe_image_(upload|remove)_button/i', $button['#name'])) {
      $button['#parents'] = array();
    }
  }

```

Not ideal by any means, but it does work.

On another note, the `#process` property attached to the managed\_file item is unnecessary. That code should be run in the form's submit handler, and since your submit handler is named in the right convention it will be run when the form is submitted, which is when you need it to.

Try removing the `#process` line altogether and see what happens.
> 1 votes

# Answer
I success to submit my form only by adding this :

```
$form['#submit'][] = 'module_top_content_equipe_admin_form_submit';

```

before

```
return system_settings_form($form);

```

So as Clive say in it's first comment it's a bug between the managed\_file #type and the system\_settings\_form() function. Just have to submit manually before this function and it works like a charm !
> 0 votes

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


# Question
Title: Module similar to module filter to filter content and users?
I use Module filter module to filter the long list of modules. It comes very handy to find a module rather than using CTRL+F always. I was wondering if there is a module which can filter the content (at admin/content) and/or users (at admin/people) as well.

# Answer
> 0 votes
Contentment (along with VBO) looks like a winning combination.

---
Tags: 7
---


title: Separate page.tpl file for URL

text:
# Question
Title: Separate page.tpl file for URL
I have created a custom module with page URL like `$items['testpage/get']`. How can I create a separate page.tpl file for this URL? Link is like: `http://199.x.x.x/mysitename/testpage/get`.

# Answer
It's based upon the path. In D6:

`page-testpage-get.tpl.php`

In D7:

`page--testpage-get.tpl.php`

(Although D7 might want `page--testpage--get.tpl.php` due to its love of double dashes :)

All about templates and their suggestions can be found here:

D6: http://drupal.org/node/1089642

D7: http://drupal.org/node/1089656
> 3 votes

---
Tags: theming, 7
---


# Question
Title: Workbench moderation allowing a role to unpublish content?
I'm using Workbench Moderation on a new D7 site build. All is great in terms of workflow and I think I have the permissions near perfect, but I can't for the life of me seem to grant my 'content approver' roles the ability to unpublish content.

If I log in as a administrator (Drupal default role) I can see the option to 'unpublish' appearing, but I can't spot a particular Workbench / Drupal permission to grant to allow this permission for lower roles.

Anyone have a suggestion?

# Answer
> 5 votes
You need to make transitions for the backward states through moderation (eg, Published -\> Needs Review, and Published -\> Draft) on **admin/config/workbench/moderation/transitions**

Then, on on **admin/people/permissions#module-workbench\_moderation**, assign the permissions appropriately to the roles you want to allow to push things backwards

---
Tags: users, workflows, workbench
---


title: drupal commerce no. sold per product

text:
# Question
Title: drupal commerce no. sold per product
I want to create a rule based on the number of sales per product. Is there a data selector to get the number of sales per product? If anyone can point me in the right direction, I will be very grateful!

# Answer
> 1 votes
I don't think you'll find that particular condition out of the box. Conditions for rules are pretty easy to write though, check Commerce Conditions for some easy to follow examples.

# Answer
> 0 votes
Exactly what kind of rule you want to create? What do you want to accomplish with it? You could do a database query that returns you "the number of sales per product" and then perform an action based on that number, and run this on a cron job. But since we don't know how sales or products are represented in your site, not what exactly your rule will try to accomplish, we cannot point you in the right direction.

# Answer
> 0 votes
You could use Commerce Product Popularity, which uses a Radioactivity field that increases with each purchase. If you switch off decay and configure the rule with an energy of 1, then the field will contain the total units sold for that product since the field was last cleared.

---
Tags: commerce, rules
---


title: Views slideshow pager as menu tabs

text:
# Question
Title: Views slideshow pager as menu tabs
I wondering if this is possible.
I can not find any information on this topic, but I am trying to make my pager that is in a Views slideshow into the menu tabs of my navigation, so that if I scroll over the "home" menu button, the image would change, or if I scroll over "about us," the image would change to the "about us" image. Can anyone give me some suggestions on what I can do to achieve this?

# Answer
> 0 votes
I was able to achieve this using views and and a contextual filter, the module has since then been updated to enable the hover function on each field.

# Answer
> 0 votes
Views Slideshow Menu. Only works with 2.x at the moment.

# Answer
> 0 votes
Views slideshow use cycle plugin (a jquery plugin) to change the slides and other activities.

This code navigates your slideshow to next slide when you scroll over a menu item:

```
$('YOUR MENU ITEM').hover(function () {
  $('YOUR VIEWS SLIDESHOW BLOCK ID').cycle('next');
});

```

To see list of all the functions and methods of jquery cycle plugin visit: http://jquery.malsup.com/cycle/options.html

---
Tags: 7, views
---


# Question
Title: Multilingual front page- redirect anonymous users based on browser language
I have a Drupal 7 site that is available in both English and Japanese. I am using i18n and entity translation; I have configured the **User interface text language detection** at /admin/config/regional/language/configure as follows:

* User
* URL
* Browser
* Default

This is great for authenticated users and for all pages of the site except the front page, which is the most important.

I would like users with Japanese browsers to be taken to the Japanese version and all other users to be taken to the English version. However, since the site default language is English, it appears that all users are by default taken to the English version.

If it matters, my front page is actually a panel.

How can I configure it so that users with Japanese browsers are redirected to the Japanese language version? I don't want to move browser to the top of the list because I want to respect user preferences for authenticated users, and I also need URL to precede browser because I want people to be able to use the language switcher block to change the language if for some reason they are using a browser in a language they are not comfortable with.

# Answer
> 0 votes
This is inspired by a deleted answer, but my first approach would be to have the whole site built with Panels, and then have an English variant and Japanese variant for each.

For each variant, you would use the **PHP Code** selection rule, and then add your logic.

For unauthenticated users, you could examine `$_SERVER["HTTP_ACCEPT_LANGUAGE"]` and return the proper thing. For authenticated users, would would use your normal method.

Preferably, you would put the logic in a module function that you would call from the **PHP Code** selection rule, so you only need to change things in one place. You could also do a ctools plugin to make your own selection rule, too, using the same logic.

---
Tags: i18n-l10n
---


title: Multiblock Module D7 $edit

text:
# Question
Title: Multiblock Module D7 $edit
Using the multiblock module, I haven't been able to retrieve the $edit variable my custom `hook_block_configure()` or `hook_block_view()`. According to the readme:

`add an optional $edit
argument to your hook_block_view and hook_block_configure functions.`

I have, like so:

`function donation_form_block_configure($delta = '', $edit = array()) { ... }`

But alas, $edit is all ways null. I'm simply looking for the multiblock id during the configuration and viewing.

# Answer
the module aint workin.

hacked it to fix.

```
$block = module_invoke($block_info->module, 'block_'. $op, $block_info->orig_delta, $edit);

```
> 0 votes

---
Tags: 7, blocks
---


title: Show block on /user profile page only

text:
# Question
Title: Show block on /user profile page only
I want to show a block when a user visits his/her own profile page at /user. The public user profiles have paths of "/member/\[username\]".

When I limit the block to "user" it won't show up. When I limit it to "member/\*" it will show up both on the own profile and on the public profiles.

Is the "user" url something special?

# Answer
> 2 votes
What @clive has mentioned is great if you want to use `/user` for this, but from a number of angles, I really don't like using it at all for this kind of thing. I would like to say mostly from a style perspective, but actually more from a linking perspective, eg, an email or post that includes `check out my cool profile on mototribe: www.mototribe.com/user` bollixing things up.

So, when I've done stuff like this, I include php logic in my block view along the lines of:

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

if ($node->type==THENODETYPEWEARELOOKINGFOR && $node->uid==$user->uid) {
  // generate the block here
} else {
  // don't generate anything (or put something else in it's place)
}

return $block;

```

so the block is only generated when the currently logged in user looks at a certain node type that s/he owns. Obviously I've not fleshed out all the isset()s or empty()s needed in prime time for the above but I am sure you get the jist.

Of course, I could also be talking total smack here if D7 user profiles aren't nodes, but this works great in D6 with content profiles :)

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


# Question
Title: Why do modules run multiple times on a single page load?
In Drupal 7 created a module which implemented `hook_init()`.

I put an error log message as the first line of the function.

```
function my_module_init() {
  error_log('running init');
}

```

On each page load of the site I see the error message multiple times. I was expecting `hook_init()` to be ran exactly once per page load. Why is it running multiple times?

# Answer
`hook_init()` is invoked by Drupal only once for each requested page; it is the last step done in \_drupal\_bootstrap\_full().

```
  // Drupal 6
  //
  // Let all modules take action before menu system handles the request
  // We do not want this while running update.php.
  if (!defined('MAINTENANCE_MODE') || MAINTENANCE_MODE != 'update') {
    module_invoke_all('init');
  }

```

```
  // Drupal 7
  //
  // Let all modules take action before the menu system handles the request.
  // We do not want this while running update.php.
  if (!defined('MAINTENANCE_MODE') || MAINTENANCE_MODE != 'update') {
    // Prior to invoking hook_init(), initialize the theme (potentially a custom
    // one for this page), so that:
    // - Modules with hook_init() implementations that call theme() or
//   theme_get_registry() don't initialize the incorrect theme.
    // - The theme can have hook_*_alter() implementations affect page building
//   (e.g., hook_form_alter(), hook_node_view_alter(), hook_page_alter()),
//   ahead of when rendering starts.
    menu_set_custom_theme();
    drupal_theme_initialize();
    module_invoke_all('init');
  }

```

If `hook_init()` is being executed more than once per each page request, there could be a module that calls module\_invoke\_all('init'). It could also happens that a module calls drupal\_goto(), and redirects the user to another page; this would cause a new page request, and a new invocation of `hook_init()`, if the page is not served from the cache.

In Drupal 7, there is just a way to check if `hook_init()` is invoked twice per page request, and it is to implement `hook_init()` using the following code.

```
function mymodule_init() {
  watchdog('mymodule', 'Request time: !timestamp', array('!timestamp' => REQUEST_TIME), WATCHDOG_DEBUG);
}

```

As REQUEST\_TIME is a constant that Drupal defines each times it bootstraps (which means each times a page is requested), if you see two consecutive `watchdog()` entries showing the same value, then `hook_init()` is being invoked twice, or it is invoked in two different page requests done in less than a second. If the difference is 2 seconds, for example, then `hook_init()` is invoked in two different page requests.
> 6 votes

# Answer
`hook_init()` runs once per page request on all non-cached pages.

Keep in mind that when you load a page in your browser, it loads the page and all assets on that page (CSS, JS, images, etc).

Also keep in mind that Drupal handles 404 errors by default1, so if there is a bad URL on the page (say /favicon.ico), then Drupal may handle that asset, depending on how you have Apache configured.

Image styles used on a page that don't have derivatives on the filesystem will also get handled by Drupal and go through the whole bootstrap process.

My advice is to try to match up the timestamps in the error log with the Apache access\_log and see what is going on.

So, it is very likely that your multiple entries in the error log from `hook_init()` are from individual URLs that Drupal has handled in quick succession, but potentially from starting from a single browser page load.

1 This bahavior can be refined in more recent versions of Drupal 7.
> 2 votes

---
Tags: hooks
---


# Question
Title: Overcoming 255 character URI limit for files_managed
I recently stumbled upon an interesting limitation of Drupal. It seems that in the table files\_managed there is a field called "uri" which represents the path to the files being managed by Drupal. This field is defined as a VARCHAR(255). I was blissfully ignorant of this fact/limitation until one of our users initiated a chain of events that lead to Drupal trying to manage a file with a 261 character path, at this point Drupal gave a nasty database error which lead me to this issue.

Is there anyway to configure Drupal to allow file paths longer then 255 characters?

# Answer
You can alter the database defined from another module, but this is generally a bad idea. As said from Letharion, it is probable you are going to cause issues with other modules that take assumptions.

If you really need to do it, then you should implement code that (at least):

* Alters the database table defined from the other module
* Implements hook\_schema\_alter() to make other functions know the new schema used for the database table

The latter step is necessary because there are functions, such as drupal\_write\_record(), that use drupal\_get\_schema(), which invokes `hook_schema()`, and `hook_schema_alter()` to know the schema used for a table.

Your code should be at least the following one.

### mymodule.install

```
function mymodule_install() {
  if (db_table_exists('file_managed') && db_field_exists('file_managed', 'uri')) {
    $schema = drupal_get_schema_unprocessed('system');
    $schema['file_managed']['uri']['type'] = 'varchar';
    $schema['file_managed']['uri']['length'] = 12288;
    db_drop_unique_key('file_managed', 'uri');
    db_change_field('file_managed', 'uri', 'uri', $schema['file_managed']['uri']);
    db_add_unique_key('file_managed', 'uri', array('uri'));
  }
}

function mymodule_schema_alter(&$schema) {
  if (isset($schema['file_managed']['uri'])) {
    $schema['file_managed']['uri']['type'] = 'varchar';
    $schema['file_managed']['uri']['length'] = 12288;
  }
}

```

What is missing in the code I shown is the code to unistall the module. It should change the database table as it was before the module was installed, but what happens if another module installed after yours alters the same field in that table?

Notice that, generally, managed files have a URI that is similar to public://field/image/100\_0140.JPG. If the problem is the path being too long, then you should use less directories, or a shorter filename.
> 4 votes

# Answer
You can't configure Drupal to allow longer file names because the schema is hardcoded.

However, trying to upload a file with a longer file name shouldn't lead to a database error, you should report that as a bug report against the module that allowed to upload/create such a file.
> 1 votes

# Answer
I would consider Berdirs answer the correct one, but I want to add that there *is* a hook\_schema\_alter, which *can* allow you to make this change.

Most of the time though, it's not a good idea, simply because it's so rare that you are likely to hit other issues from modules making assumptions you've rendered false.
> 0 votes

---
Tags: 7, files, uri
---


title: Forms in a table won't show

text:
# Question
Title: Forms in a table won't show
I am trying to display a form in a table, but it is showing an empty result, while the header is displayed. I can't understand what I am doing wrong.

```
/*
 * cart form and page display
 */
function cart_page_form() {
  $form=array();
  $form['#tree'] = TRUE;

  $checkboxes=array();

  foreach($_SESSION['cart'] as $key => $qty) {
    $checkboxes[$key] = '';

    $form['checkboxes'][$key] = array(
      '#type' => 'checkbox',
      '#default_value' =>check_plain($key),
    );

    $form['quantinty'][$key] = array(
      '#type' => 'textfield',
      '#size' => 4,
      '#maxlength' => 4,
      '#id' => 'prod_qty',
      '#default_value' => check_plain($qty),
    );

    $form['price'][$key]['#value'] = t('244p');
  }

  $form['remove'] = array(
      '#type'           => 'button',
      '#name'           => 'remove_selected',
      '#value'          => t('Remove selected'),
  );

  $form['submit'] = array(
    '#type'           => 'button',
    '#name'           => 'update_quantity',
    '#value'          => t('Update'),
  );

  $form['checkout'] = array(
    '#type'           => 'submit',
    '#name'           => 'checkout',
    '#value'          => t('Зделать заказы'),
  );

   return $form;
}

/**
 *Implementation of hook_theme().
 *
 */
function yalublurudn_theme() {
  return array(
    'cart_page_form' => array('variables' => array('form' => NULL)),
  );
}

/**
 * display cart page
 */
function theme_cart_page_form($form) {
  $rows = array();

  foreach(element_children($form) as $key) {
    if (isset($form['checkboxes'][$key])) { //// make sure this is one of our table rows
      $row = array();
      $row[] = array('data' => drupal_render($form['checkboxes'][$key]));
      $row[] = array('data' =>drupal_render($form['quantinty'][$key]));
      $row[] = array('data' =>drupal_render($form['price'][$key]));
      $rows[] = $row;
    }
  }

  $header = array(
    'Checkboxes',
    'Title',
    'Quantity',
  );

  $output = theme('table', array('header' => $header, 'rows' => $rows));
  $output .= drupal_render($form); // Render rest of form components.

  return $output;
}

```

# Answer
In Drupal 7, a theme function like yours receives an array containing the variables declared in `hook_theme()`. If you execute `element_children($form)` with the form you defined, you get an array containing the following values:

* checkboxes
* quantinty
* price
* remove
* submit
* checkout

The control statement `if (isset($form['checkboxes'][$key])) {` will not be executed, if not in the case you have `$form['checkboxes']['checkboxes']`, etc.

Your theme function should use the following code.

```
function theme_cart_page_form($variables) {
  $form = $variables['form'];
  $rows = array();

  foreach(element_children($form['checkboxes']) as $key) {
    $row = array();
    $row[] = array('data' => drupal_render($form['checkboxes'][$key]));
    $row[] = array('data' =>drupal_render($form['quantinty'][$key]));
    $row[] = array('data' =>drupal_render($form['price'][$key]));
    $rows[] = $row;
  }

  $header = array(
    'Checkboxes',
    'Title',
    'Quantity',
  );

  $output = theme('table', array('header' => $header, 'rows' => $rows));
  $output .= drupal_render_children($form); // Render rest of form components.

  return $output;
}

```

Actually, you should declare the theme function using the following code.

```
function yalublurudn_theme() {
  return array(
    'cart_page_form' => array('render element' => 'form'),
  );
}

```
> 4 votes

---
Tags: forms, theming
---


title: drush site-alias array

text:
# Question
Title: drush site-alias array
I'm trying to script something up to completely automate synching sites around, and I want to be able to get a value out of the site alias which is an array.

If I do a

```
root@dev-drupal-www:~# drush sa @www.mysite.org.au
$aliases['www.mysite.org.au'] = array (
  'remote-host' => 'prod-drupalsites',
  'remote-user' => 'root',
  'uri' => 'www.mysite.org.au',
  'root' => '/vhost/www.mysite.org.au',
  'path-aliases' =>
  array (
    '%site' => 'sites/default/',
    '%files' => 'sites/default/files',
    '%dump' => '/tmp/drush_www.mysite.org.au.sql',
  ),
);
root@dev-drupal-www:~# drush sa @www.mysite.org.au --component="path-aliases"
Array
root@dev-drupal-www:~# drush sa @www.mysite.org.au --component="path-aliases:%dump"
The element path-aliases:%dump was not found in the alias record for @www.mysite.org.au.                                                                                [error]
root@dev-drupal-www:~#

```

How can I extract an item from the path-aliases?

Thanks!

# Answer
> 2 votes
Unfortunately, (as you discovered), the site-alias command is not flexible enough to do what you want. There are other ways, though. For your specific example above, which happens to involve paths, you can use the drupal-directory (dd) command:

```
$ drush dd @www.mysite.org.au:%dump
/tmp/drush_www.mysite.org.au.sql
$ drush dd @www.mysite.org.au:%files
/vhost/www.mysite.org.au/sites/default/files

```

For a more general-purpose solution, you could use the php-eval (ev) command:

```
$ drush ev '$a = drush_sitealias_get_record("@gk.dev"); print_r($a["path-aliases"]);'
Array
(
    [%boo] => /usr/local/boo
    [%root] => /srv/www/dev.greenknowe.org
)

```

This can, of course, be customized to suit, as the ev command will evaluate any arbitrary php you care to throw at it (as long as you escape special characters correctly). This is more complicated to use than the dd command, but it will also work for elements other than paths in the path-aliases element.

---
Tags: drush
---


# Question
Title: How to create additional drupal sites with a drush script
I'm using **drush site-install** for my initial site, and everything works great, but when I go to try create another site (using table prefixes so I can use the same database), drush attempts to drop and recreate the database, so I loose all the table from my first site. I know how to target drush to a particular subsite, but I'm not sure how to tell the drush site-install command not to drop the database tables.

Is there a better way to do this if I want to setup a initial site with 2 additional sites?

# Answer
Drush has very limited support for table prefixes; site-install is just one of the ways that Drush can fail. sql-sync has similar problems. It would take a lot of work to fully support table prefixes everywhere; it is best and safest to just use multiple databases when using Drush.
> 1 votes

---
Tags: drush
---


title: pager query with join

text:
# Question
Title: pager query with join
I plan to list all polls in the most recent order where I need to join my "poll" table with the "node" table and display them with pager. Here is what I do:

```
$polls_query = db_select('poll', 'p')
              ->extend('PagerDefault')
              ->limit(3);
$polls_query->join('node', 'n', 'n.nid = p.nid')
            ->fields('p', array('nid'))
            ->condition('p.active', 1, '=')
            ->orderBy('n.created', 'DESC');
$result = $polls_query->execute();
foreach ($result AS $poll) {
  $polls[] = array('data' => drupal_render(node_view(node_load($poll->nid), 'teaser')));
}
$content['pager_list'] = array(
  '#theme' => 'item_list',
  '#items' => $polls,
  '#title' => t('Listing Consensus'),
  '#type' => 'ul',
);
$content['pager_pager'] = array('#theme' => 'pager');
return drupal_render($content);

```

Unfortunately I see a white screen of death and the php error log says "PHP Fatal error: Call to a member function fields() on a non-object in .. " and thats the line where I mention after fields. If I dont use join, everything works fine.

If anyone else has had similar problems, please share the solution.

# Answer
The `join()` method doesn't return the query object to isn't chainable.

If you change your code to this you should be fine:

```
$polls_query = db_select('poll', 'p')
  ->extend('PagerDefault')
  ->limit(3);

$polls_query->join('node', 'n', 'n.nid = p.nid');

$polls_query->fields('p', array('nid'))
  ->condition('p.active', 1, '=')
  ->orderBy('n.created', 'DESC');

// etc...

```
> 2 votes

---
Tags: database
---


title: Send unique code to user email

text:
# Question
Title: Send unique code to user email
I want to send a unique code to the user after registration. I know how to do custom modules. Also in the mail text send to the user I can see there are variables such as \[user:name\]. Should I define a variable and send it to the user?

Any help will be appreciated.

Thanks

# Answer
> 1 votes
I assume you will have to store that unique code somewhere because the user is going to use it and you will have to verify it against something?

I'd suggest to define a field for that unique code, you can use the field permissions module or a custom hook\_field\_access() to hide from the user. Then you generate that unique code in hook\_user\_presave() for new users and save in that field. The advantage of this is that you can then enable the token.module and you get tokens for all fields for free.

Alternatively, you can also store it in a custom table or $user-\>data and define hook\_token\_info() and hook\_tokens() yourself. Instead of directly defining it as a token, you can also define it as a property (hook\_entity\_property\_info()) to entity.module and it will automatically be available as a token as well if the entity\_token module is enabled.

So yes, whichever way you chose, in the end it will be a token and you can use it in the mail.

# Answer
> 0 votes
> Should I define a variable and send it to the user?

If you allow the users with the right permission to set the content of the email your module sends to the user, and which contains the unique code, then you can define a token for that purpose. If that code needs to be used only for that email, I would implement code similar to the following one, which what Drupal uses when sending an email to the users to recover their password.

```
function mymodule_mail($key, &$message, $params) {
  $language = $message['language'];
  $variables = array('user' => $params['account']);
  $message['subject'] .= _mymodule_mail_text($key . '_subject', $language, $variables);
  $message['body'][] = _mymodule_mail_text($key . '_body', $language, $variables);
}

function _mymodule_mail_text($key, $language = NULL, $variables = array(), $replace = TRUE) {
  $langcode = isset($language) ? $language->language : NULL;

  switch ($key) {
    case 'user_unique_code_subject':
      $text = t('Your subject', array(), array('langcode' => $langcode));
      break;

    case 'user_unique_code_body':
      $text = t("Your body", array(), array('langcode' => $langcode));
      break;
  }

  if ($replace) {
    return token_replace($text, $variables, array('language' => $language, 'callback' => 'mymodule_mail_tokens', 'sanitize' => FALSE, 'clear' => TRUE));
  }

  return $text;
}

function mymodule_mail_tokens(&$replacements, $data, $options) {
  if (isset($data['user'])) {
    $replacements['[user:unique-code]'] = mymodule_unique_code($data['user']);
  }
}

```

When your module wants to send the email to the user, it uses drupal\_mail().

---
Tags: 7, users, emails
---


# Question
Title: How do I know which products have seen other customers when they took a look at the product that I am currently looking?
I am developing a website with the Drupal Commerce module, and my customer wants me to implement a functionality to allow the purchaser to know which products have seen other purchasers/customers when they saw the same product he is currently watching.

Do you know if any specific module for Drupal Commerce is available, or can I use a combination of modules that have nothing to do with the Drupal Commerce module?

# Answer
Yes the feature you are asking after is this module. Commerce Recommender

:: Updated, Here is a tutorial on how you can achieve what you are looking for

Drupal Commerce recommender tutorial
> 3 votes

---
Tags: 7, commerce
---


# Question
Title: Install custom module into modules/custom folder
I've just made a facebook module, it's working nicely, the only thing is that it doesn't install into the modules/custom folder. The module installs into the modules folder (the custom folder is located inside this modules folder).

How can I make sure the module installs into modules/custom?

This is my .install file.

```
/**
 * @file
 * Install, update and uninstall functions for the facebooklikebox module.
 */

/**
 * Implements hook_uninstall().
 */
function facebooklikebox_uninstall() {
  db_query("DELETE FROM {variable} WHERE name LIKE '%facebooklikebox%'");
  cache_clear_all('variables', 'cache');
}

function facebooklikebox_update_6101() {
  // Get the default settings
  drupal_load('module', 'facebooklikebox');
  $defaults = _facebooklikebox_get_settings(TRUE);

  // Define a settings array based on the variables already set (or their defaults)
  $settings = array(
    'facebooklikebox_pageurl' => variable_get('facebooklikebox_pageurl', 0),
    'facebooklikebox_height' => variable_get('facebooklikebox_height', 0),
    'facebooklikebox_width' => variable_get('facebooklikebox_width', 0),
    'facebooklikebox_bordercolor' => variable_get('facebooklikebox_bordercolor', 0),
    'facebooklikebox_showfaces' => variable_get('facebooklikebox_showfaces', 0),
    'facebooklikebox_showstream' => variable_get('facebooklikebox_showstream', 0),
    'facebooklikebox_showheader' => variable_get('facebooklikebox_showheader', 0),

  );

  // If a setting matches the default value, unset it (we wont need to store it)
  foreach ($settings as $key => $value) {
    // We used to use -1 for disabled, convert this to 0 for the new diabled
    if ($value == -1) {
      $settings[$key] = 0;
    }
    // Now compare the value to the defaults. Only store if an "override".
    if ($value == $defaults[$key]) {
      unset($settings[$key]);
    }
  }

  // Save the settings in a single array rather than individual keys
  if (!empty($settings)) {
    variable_set('facebooklikebox_settings', $settings);
  }

  // Remove all the old settings
  variable_del('facebooklikebox_pageurl');
  variable_del('facebooklikebox_height');
  variable_del('facebooklikebox_width');
  variable_del('facebooklikebox_bordercolor');
  variable_del('facebooklikebox_showfaces');
  variable_del('facebooklikebox_showstream');
  variable_del('facebooklikebox_showheader');
}

```

# Answer
As I know Drupal web interface will always install modules to sites/all/modules.
Placing modules in subfolders like sites/all/modules/contrib, sites/all/modules/custom, or sites/all/modules/dev is a task for Drush and Drush Make; you can manually place the module in the right folder.

You can move your module folder with the PHP `rename()` function, or implement your own Updater instead of core `ModuleUpdater`. In your case, these solutions look improper.
> 4 votes

---
Tags: 7, installation
---


# Question
Title: If end date is empty show "Now" or "Current" or something else
In some of the content type I have a field date with collects start date and end date. The end date is not required and is empty as default value.

When I show date in teaser or node or view it will show start and end date but I want a condition

```
if (empty($end_date)) {
 print "current";
} else {
print $end_date;
}

```

of course I can set it in the node.tpl.php, for the teaser and the node, and with alternative text if empty in the views with field setting.

Now would like to know if there is any way to do it with the API. Something I can do in the template.php and not in every single node--CONTENT-TYPE.tpl.php and in every single view.

I'm looking for something like

```
function my_module_date_api ($something) {
if (empty($end_date)) {
     print "current";
    } else {
    print $end_date;
    }
}

```

Thanks in advance

# Answer
Have a look at Custom Formatters module.

"The Custom Formatters module allows users to easily create custom CCK/Field Formatters without the need to write a custom module."
> 2 votes

---
Tags: 7, theming, datetime
---


title: Reset node form after AJAX submit

text:
# Question
Title: Reset node form after AJAX submit
I have a node form in a block, that is submitted using AJAX.

I've created my own callback, because I'm adding the created node to the page if the submission was successful.

Now, I want to reset the node form to the default values. Any ideas on how to accomplish that?

Update: I've managed to replace the form, by looking at the way node\_add() works.

```
$new_node = (object) array(
  'uid' => $user->uid,
  'name' => (isset($user->name) ? $user->name : ''),
  'type' => 'node_type',
  'language' => LANGUAGE_NONE,
);

```

And then, I'm replacing the entire form with the return value from `drupal_render(drupal_get_form('node_form', $new_node));`

The form gets replaced as it should be, apart from some ids being different. However, when I submit the new form, I'll get a javascript alert window, with the entire contents of a new page. I can see from the HTML, that it's the page for the node that has been created. I suppose the AJAX callback gets redirected to the new node, but I don't know why.

Any clues?

# Answer
Got it!

The main problem was that the new form was loaded from a cached version of the previous submitted form.

This is what I've got in my AJAX callback:

```
$new_form_state = array();
$new_form_state['build_info']['args'][] = (object) array(
  'uid' => $user->uid,
  'name' => (isset($user->name) ? $user->name : ''),
  'type' => 'node_type',
  'language' => LANGUAGE_NONE,
);
$new_form_state['no_redirect'] = TRUE;
$new_form_state['input'] = array();
$new_form = drupal_build_form('node_type_node_form', $new_form_state);
$commands[] = ajax_command_replace('#node-type-node-form', drupal_render($new_form));

```

The `$new_form_state['no_redirect'] = TRUE;` prevents the redirect, and the empty array in `$new_form_state['input']` prevents the form from being loaded from a cached version.

@googletorp, thanks for the help!
> 7 votes

# Answer
If you are are using Drupal 7 you can unset `form_state['values']` and rebuild the form which should work (untested).

An alternative solution would be to issue ajax commands and update the form with the default values fetched from the form definition.
> 3 votes

# Answer
I have the same task. Node add form must be posted via AJAX. After node is successfully created - form must be ready to add next node (i.e. all form fields must be empty). If form is not validated - it must be shown to user again to allow him fix errors.

This is my solution

```
function MY_MODULE_form_CONTENT_TYPE_node_form_alter(&$form, &$form_state, $form_id) {

  $form['actions']['submit']['#ajax'] = array(
    'wrapper' => $form_state['node']->type . '-node-form',
    'callback' => 'MY_MODULE_node_add_callback',
    'method' => 'replace',
    'effect' => 'fade',
  );

  // We can have several forms on one page.
  // This id must be unique, because ajax behavior is attached using it.
  $form['actions']['submit']['#id'] = 'edit-submit-' . $form_state['node']->type . '-ajax';
}

function MY_MODULE_node_add_callback($form, &$form_state) {

  $node = $form_state['node'];

  if (!empty($node->nid)) {

    // Node is created successfully.
    // Return the same from but with empty fields.
    $new_node = (object) array(
      'uid' => $node->uid,
      'name' => $node->name,
      'type' => $node->type,
      'language' => $node->language,
    );

    $new_form_state = array();
    $new_form_state['build_info']['args'] = array($new_node);
    $new_form_state['values'] = array();
    $new_form_state['method'] = $form_state['method'];

    form_load_include($new_form_state, 'inc', 'node', 'node.pages');

    return drupal_rebuild_form($node->type . '_node_form', $new_form_state);
  }
  else {

    // Node is not created because of validation fail.
    // Return current form so user can continue editing and fix errors.
    return $form;
  }
}

```
> 2 votes

# Answer
Use drupal\_rebuild\_form() function. http://api.drupal.org/api/drupal/includes%21form.inc/function/drupal\_rebuild\_form/7
> 0 votes

---
Tags: forms, ajax
---


# Question
Title: Can I run a site on AWS Elastic Beanstalk for PHP?
I'm looking at AWS Elastic Beanstalk.

Does Drupal 7 run on AWS Elastic Beanstalk for PHP?

Any extra info regarding caching and performance (e.g. comparison with PressFlow, or Memcache) is welcome.

# Answer
> 3 votes
Yes, we are currently running site build on Drupal 7 on AWS Elastic Beanstalk for PHP.

I am strongly recommend to install and configure memcache for best performance. PressFlow is not required replacement for standard Drupal 7 core (but for Drupal 6 is).

Also sites/default/files folder must be mounted from S3 bucket (read here how to manage it https://sites.google.com/site/truthkos/home/tutorials/amazon-web-services/working-with-ec2-instances/setup-a-s3-connection-to-ec2-instance-via-fuse)

For anonymous user Varnish will dramatically increase site performance.

---
Tags: 7
---


# Question
Title: Theming a node reference field in a template file
I have two content types:

* Course
* Subject

The Course nodes have a field reference field which references a Subject node.

In the Course node display, I want to have access to the variables from the corresponding Subject node. I've set the field to render as 'rendered node', but I need to rearrange the fields from both nodes to construct a tabbed interface out of all of the fields available.

What's the best way to proceed?

# Answer
Using a template, as suggested above, you force your drupal to use subject-node.tpl.php to display "subject" nodes, no? To display fields or data from the referenced node you could create a view that returns fields and everything you want, setting a "nid" contextual filter. So, in your "course template" you have to include the view, in this way:

```
print views_embed_view('view_name', 'views_display', $node->nid);

```

You can also use Context module to display this view.
> 1 votes

# Answer
Hi you can use theme\_render\_template() function like below.

```

$subject_node_object = node_load('node/' . $node_id_from_ref_filed);// Pass your node ref here.
// Use below code in your course node template.
print theme_render_template(drupal_get_path('theme', 'YOUR_THEME_NAME') . 'PATH_TO_TEMPLATE/subject-node.tpl.php', $subject_node_object);

```

You need to create a template for you subject content type fields.
> 1 votes

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


# Question
Title: views exposed filter on non existent field
I have a content type which has the following fields:

* month: List (integer) \[jan, feb, ..., dec\] (non mandatory)
* year: Date (only collects year - mandatory)

I can normally create two exposed views filters, one for the month and one for the year.

What I'd like to do though is have a single exposed filter which, internally, would operate on the two fields above at once.

For example if the operator is "Is Between" and the user selects `Oct 2011` to `Feb 2012` I'd like the filter to return only nodes which have:

* 2011, Oct
* 2011, Nov
* 2011, Dec
* 2012, NULL month
* 2012, Jan
* 2012, Feb

Note that I've used two fields (month and year) instead of one so I can have the possibility of a monthless node.

What approach should I take? I've thought of the following:

* use a third field which, on `hook_node_presave` will store the calculated (filter specific) date on the node. I wouldn't like this field to be visible on the edit node screen though
* somehow (using a hook) calculate and rewrite the view filtering query. My problem here is how to display an exposed filter for a field which does not exist

# Answer
The most obvious solution to me would be to get the month data into the date field, since you are treating the date to be 1/1 when no month is given, this would fit just fine; there is no reason to create a new field for this.

You should be able to do this in a form submission handler for the node edit form.
> 1 votes

---
Tags: 7, views
---


title: $ is not a function in drupal 7 theme

text:
# Question
Title: $ is not a function in drupal 7 theme
```
$(function(){
  $('.slider').mobilyslider({
    content: '.sliderContent',
    children: 'div',
    transition: 'horizontal',
    animationSpeed: 500,
    autoplay: true,
    autoplaySpeed: 9000,
    pauseOnHover: true,
    bullets: true,
    arrows: true,
    arrowsHide: true,
    prev: 'prev',
    next: 'next',
    animationStart: function(){},
    animationComplete: function(){}
  });
});

```

I am integrating the above JavaScript file in a Drupal theme, but it is giving me the "$ is not function" error. I googled it, and changed the code bro the below, but it doesn't work either.

```
(function($) {
  $('.slider').mobilyslider({
    content: '.sliderContent',
    children: 'div',
    transition: 'horizontal',
    animationSpeed: 500,
    autoplay: true,
    autoplaySpeed: 9000,
    pauseOnHover: true,
    bullets: true,
    arrows: true,
    arrowsHide: true,
    prev: 'prev',
    next: 'next',
    animationStart: function(){},
    animationComplete: function(){}
  });
})(jQuery);

```

The above code gives me following error:

> `$('.slider').mobilyslider` is not a function

# Answer
> 9 votes
The first error you were getting was because `$` isn't defined as `jQuery` in Drupal 7, to avoid conflicts with other libraries. Adding the closure fixed that, as in your second code example.

As long as the mobilyslider library is definitely loaded into the page, the problem is probably that you're attaching the event before the DOM is ready...so the elements you're trying to attach to don't exist yet.

You could use the standard `$(document).ready()` method to solve this if you want to, or else use Drupal JS behaviours. For Drupal 7 that code would look like this:

```
(function($){
  Drupal.behaviors.mymodule = {
    attach: function(context, settings) {
      $('.slider', context).mobilyslider({
        content: '.sliderContent',
        children: 'div',
        transition: 'horizontal',
        animationSpeed: 500,
        autoplay: true,
        autoplaySpeed: 9000,
        pauseOnHover: true,
        bullets: true,
        arrows: true,
        arrowsHide: true,
        prev: 'prev',
        next: 'next',
        animationStart: function(){},
        animationComplete: function(){}
      });
    }
  };
})(jQuery);

```

Be sure to pass in `context` to your jQuery selector for reusability.

See Managing JavaScript in Drupal 7 for more info.

# Answer
> 3 votes
check this out

I think you must store your js as drupal behavior:

```
(function($){
  Drupal.behaviors.some_name = {
    attach: function (context) {
      $('.slider').mobilyslider({
        content: '.sliderContent',
        children: 'div',
        transition: 'horizontal',
        animationSpeed: 500,
        autoplay: true,
        autoplaySpeed: 9000,
        pauseOnHover: true,
        bullets: true,
        arrows: true,
        arrowsHide: true,
        prev: 'prev',
        next: 'next',
        animationStart: function(){},
        animationComplete: function(){}
      });
    }
  };
})(jQuery);

```

Updated the code after @clives tip

# Answer
> 0 votes
The way you include your jQuers code is fine. There's a problem with the `mobilyslider` function. My guess is that you are relying on a jQuery plugin which isn't included.

---
Tags: theming, javascript
---


# Question
Title: How do I create a Machine Name type of field?
I need to add a **Machine Name** type of field to Nodes of a certain Content Type. It's the same Machine Name field that Drupal is using when creating Content Types.

> Example: If I enter "My Title" in the title field, the Machine Name field will be populated with "my\_title" via javascript.

Why do I need it? I am referencing nodes to other nodes and want to generate an URI, based on a node referenced, i.e. example.com/node-referenced/node-content

# Answer
Just found a module that does that: Safeword

> Safeword adds a new Field type to Drupal 7: the "Name/Machine Name" combination. This field type can be useful for storing public-facint text and an internal "short" name, similar to the way that Content Type labels and machine names are used in the Drupal administration UI.
>
> Safeword also uses the new 'Machine Name' FormAPI element in Drupal 7 to automatically suggest a machine name based on the text entered into the human-readable field.
>
> Why bother using it? Using Token, Pathauto, and Auto NodeTitles, Safeword can be used as a replacement for Drupal's standard "Title" field, allowing content editors to create a visitor-friendly title with a customizable URL-safe "short" version that's used to build path aliases. The short URL-friendly machine name can also be used as a Views argument. Finally, it makes your Content Type administration page just a tiny bit cooler.
> 1 votes

# Answer
There is a machine\_name element type for the Form API, but it appears there is no machine name field type in core or in a contrib module. From there, I see three code-driven solutions:

* It should be possible to crudely alter your node form to replace a text-field widget with a machine name element,
* but the proper way would be to define a new Field API widget type based on the machine name Form API element type.
* You can also not use the Field API for, directly add a machine name element in your node edit form through a form alter hook and handle storing it's value yourself.
> 1 votes

# Answer
And here is the machine name field:

http://drupal.org/project/machine\_name

Courtesy beejeebus, hunmonk, and C\_Logemann working on Drupal.org's own project module.
> 1 votes

# Answer
It sounds like you just need a new field on a certain content type, and want the field to be called machine name.

If that is the case do this:

1. Goto: \[yoursite.com\]/admin/structure/types
2. Click Manage fields for the content type you want to add this field
3. Fill in the details in the add new field row, and hit save

That should add your field, but you may also want to edit the order it is displayed, and you can do that by dragging it up or down, and hitting save.

If you want to change how it is displayed then you need to look at the Manage Display tab, and you can re-order it and change the way it is displayed as well.
> 0 votes

---
Tags: 7, entities
---


# Question
Title: How can I apply node template file only to node view page but not revision page?
I have a node template named `node-"content-type-name".tpl.php` which overrides the default node.tpl.php for this content type.

But this template file is applied to also node revision pages. Is there anyway I can apply the node template file to just node view/edit page without revision page?

# Answer
> 1 votes
I don't have a D6 site around with revisions enabled so I can't test this, but the following code should disable the custom template for the revision pages:

```
function MYTHEME_preprocess_node(&$vars) {
  $template_name = 'node-content-type-name';

  // Work out if we're on a revision page
  $on_revision_page = arg(0) == 'node' && is_numeric(arg(1)) && arg(2) == 'revisions';

  // See if the rogue template file is available as one of the suggestions.
  $template_index = array_search($template_name, $vars['template_files']);

  if ($on_revision_page && $template_index !== FALSE) {
    // Remove the rogue template file from the suggestions.
    unset($vars['template_files'][$template_index]);
  }
}

```

---
Tags: 6, theming, nodes
---


# Question
Title: How can i create a user without role authenticated user role
I am creating some users programaticaly with role "staff". I don't want them as my authenticated user. I created them for a particular purpose. I don't want any permissions which are assigned to authenticated users for this role.

```
 $userinfo = array(
            'name' => $name,
            'init' => $mail,
            'mail' => $mail,
            'pass' => $pass,
            'status' => 1,
            'roles' => array(
             9 => 'staff',
            ),
            );
            $account = user_save(null, $userinfo);

```

This is my code. It creates user but assigns authenticated user role also by default . How can i achive my target? I want a) New role staff b) staff is not an authenticated user or no permission of an authenticated user Pls help me. I am using drupal 6

# Answer
> 9 votes
I think you are using the autenticated user role for something specific. You should create a new role which is taking the rights of autenticated user. Once done, you can take away all rights from the autenticated user role.

To make things more clear: You are using the *autenticated user* role for *assembly members*. You should create a new role *assembly members* which is taking the rights of *autenticated user*. Once done, you can take away all rights from the *autenticated user* role.

---
Tags: users
---


title: Webform redirect

text:
# Question
Title: Webform redirect
I'd like to do something pretty straightforward: After user fills out a webform, I'd like a button that simply redirects them to a URL (in this case it's to a demo sandbox). Of course I'd want the user to fill in their info to capture for lead-generation purposes. My Webform is set up correctly in that it correctly captures all the user fields and submits them to me via email. However, upon completion "click" I'd like to have the user redirected to a determined internal URL www.mysite.com/foo

I can't figure out how this is done with the vanilla webform settings. Am I missing something obvious?

# Answer
If i had to redirect the users after submission than i would go to the already created webfrom, click on

* **Webform**(on top of the form)-\>**Form settings**

After scrolling down a bit you will see **Redirection location**

Choose **Custom URL** and enter your Internal URL ***www.mysite.com/foo***

Thats it you are done.
> 8 votes

# Answer
You don't need code for this.

Install this modules:

Now add a rule that redirects the user to your URL after a webform submission.
> 2 votes

# Answer
Edit your webform and go to Form Settings. In Redirection location select Custom URL. That's all.

I usually use the rule method that BetaRide suggested. If you are using any rule logic with your webform go with that solution.
> 1 votes

# Answer
You can try native idea `drupal_redirect_form`

> Redirects the user to a URL after a form has been processed.

```
$form_state['redirect'] = 'node';

```

Or to redirect to 'node/123?foo=bar#baz':

```
$form_state['redirect'] = array(
  'node/123',
  array(
    'query' => array(
      'foo' => 'bar',
    ),
    'fragment' => 'baz',
  ),
);

```

You can use it in `hook_form_alter`

```
function hook_form_alter(&$form, &$form_state, $form_id) {
 if($form_id == 'YORWEBFORMID') {
   $form_state['redirect'] = 'node';
 }
}

```
> 0 votes

---
Tags: webforms
---


# Question
Title: create multilingual node programmatically
i'm trying to create a multilingual node using a php script.

I'm doing this:

```
 $node = new stdClass();
 $node->title = "Test ".mktime();
 $node->type = "job";
 $node->language = 'de'; // Or e.g. 'en' if locale is enabled
 $node->uid = $user->uid;
 $node->status = 1; //(1 or 0): published or not
 $node->promote = 0; //(1 or 0): promoted to front page
 $node->comment = 1; //2 = comments on, 1 = comments off
 $node->path = array('alias' => 'das-ist-ein-test-'.mktime());
 $node->body[$node->language][0]['value']   = "Body Body Body";
 $node->body[$node->language] = text_summary("Body Body Body");
 $node->body[$node->language]  = 'filtered_html';
 node_save($node);

```

As long as i set $node-\>language to 'und' everything is working fine. But as soon as I set the language to 'de' or 'en' (both languages are activated in my Drupal installation) the body text doesn't get saved.

So my question is: can anybody provide me with a working example of how to store a multlingual node (de,en) into Drupal using program code.

Thank you

# Answer
> 9 votes
It depends on is your body field translatable or not. Please, look at this explanation about translatable fields: https://drupal.stackexchange.com/a/31639/2466

```
$node_lang = 'ru'; // I am a Russian girl

$node = new stdClass();
$node->title = "Test ".mktime();
$node->type = 'article'; // Your type
$node->language = $node_lang;
$node->uid = 1;
$node->status = 1;

// Get proper langcode
$body_field_info = field_info_field('body');
if (field_is_translatable('node', $body_field_info)) {
  $body_language = field_valid_language($node_lang);
} else {
  $body_language = LANGUAGE_NONE;
}

// Some lorem ipsum.
// You can add custom summary:
// $node->body[$body_language][0]['summary'] = 'Summary';
$node->body[$body_language][0]['value']   = 'Lorem monotonectally iterate resource-leveling innovation before timely core competencies. Globally coordinate sustainable strategic theme areas and intermandated infomediaries. Monotonectally brand customer directed solutions and high-quality bandwidth.';

node_save($node);

```

There is an issue for Drupal 8 to make Field Language API more usable.

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


title: view and Content:user issue

text:
# Question
Title: view and Content:user issue
while customizing front page i can not find 'Content: User' to add author name field in views. but i can find something like `Content: Author uid` how to show author name in front page? another question i cant add new fields while selecting grid view, how to fix it too.

# Answer
If you are using the Unformatted list format used by default from the front page view, you would see the author of the node. This happens if you selected *Display author and date information* on the settings page for the content type (admin/structure/types/manage/\[content type\]).

Supposing that you change the format to, for example, *Table* (which allows you to add fields), when you add the new fields you will notice that *Content: Author uid* field has the following description:

> The user authoring the content. If you need more fields than the uid add the content: author relationship.

So, you just add a relationship.

Once you do that, you will find the author name between the fields you can add.

As for the *Grid* format, it doesn't uses fields; that is why you cannot select them.
> 1 votes

---
Tags: views, users
---


title: Facebook Connect module

text:
# Question
Title: Facebook Connect module
I'm using Drupal 6 and FB Connect module, but I can't change Facebook login button design.

What it looks like, now.

What I want it to be.

# Answer
A quick look at the code shows that this is being created via:

```
function theme_fbconnect_login_button($text, $attr) {
  return '<fb:login-button ' . drupal_attributes($attr) . '>' . $text . '</fb:login-button>';
}

```

which shows that Facebook is creating the button, and thus suggesting you are stuck with what you got. Now, there may be some hidden attribute incantation to change the button, but given how brand conscious Facebook is, I doubt they will allow you to change it up using their SDK.
> 1 votes

---
Tags: social-network
---


# Question
Title: PDOStatement::execute takes 11s, what to do?
Our Drupal site is sslllooooowwwww, at best taking 3s for static-content pages, at worst 11s for shopping cart pages. Above is the profile for visiting the shopping cart. Profiling reveals that PDOStatement::execute is the #1 time consumer. Any advice why or what to do about it?

Not sure if indicator that my connection has problems, Drupal is inefficiently sending data, or if it's time to learn how to tweak MySql.

# Answer
I suggest that you use the Devel module to debug this. You can turn on query logging in its option to list all the queries used in the display of the page and go from there. I would also try running the site on a different server - perhaps a dev server with plenty of resources - and see how it performs there. I would also check your syslog and mysql logs to see if there are any warnings there for you to consider or if your server is running out of resources.
> 2 votes

# Answer
It could mean any of a bunch of things. `PDOStatement::execute()` is just the final method that gets called for each and every database query Drupal makes (which can be quite a few).

First, make sure you Apache is configured properly, and that APC is installed and has enough memory.

Then, I would make sure your MySQL instance has a decent starting point. Download, run, and follow the advice of mysqltuner.

Then, download/install/enable the Performance Logging and Monitoring module and play around with the reports.

Figure out what is slow, and fix it.

There are also bunches of posts with other profiling advice, too, as well as advice for performance improvements beyond basic configuration (eg, advanced caching strategies).
> 4 votes

---
Tags: database, debugging
---