# Question
Title: Change value of user reference based on node reference
Is there any way to refine the user reference field values based on node references value. Let me explain : I have one node reference field and user reference field in one content type and another node reference is added to user profile fields. Both node reference are of same content type with different name. Is there any way to refine the view of user reference field based on node reference field value.

Image of User Profile

Image of Content type

# Answer
If what you are asking is can you change the user reference field to something based upon a node reference field, sure, not a problem. But what do you want to change it to? If it's the user id of the creator of the node referenced, that's easy:

```
// load node in question
$node=node_load($nid);
// load node referenced in that node
$node_referenced=node_load($node->field_node_reference[$node->language][0]['nid']);
// set user referenced in node to the uid of the node referenced in it
$node->field_user_reference[$node->language][0]['uid']=$node_referenced->uid;
// save the node
node_save($node);

```

If you want to do this automagically, you can look at hook\_node\_presave() and have this done every time a node type is saved.
> 1 votes

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


title: setting the right views argument type

text:
# Question
Title: setting the right views argument type
I am using D6. I want to add another argument to a view, but it only needs to be a word ie: 'practice'. Which type of argument do I chose in the list of possible argument types ie:node, content, global...

# Answer
> 1 votes
It all depends on what that word is. For example, if 'practice' is a taxonomy term name, you would choose that and Views would filter on nodes tagged with taxonomy term 'practice.' If, however, the word was the title of a node, you would filter on node title and Views would filter on node titles equal to 'practice.'

ADDITION:

If you want to ignore the word when it comes to filtering, just use the Global Null field and it will be ignored by any queries, but will still be available as arg(#) in any script called.

ADDITION 2:

Let's say you are looking at a Views Page Display, with a path something like:

```
www.user1015214.com/all/the/best

```

that returns pictures of all the best stuff a website has to offer. Views would have that with a path of `all/the/best`. Now, let's say we wanted filter this by something, we'd change that path to `all/the/best/%` and then enter an argument (D6) or contextual filter (D7). Let's say it's a taxonomy term for this example. So now we could have something like this:

```
www.user1015214.com/all/the/best/views

```

and it would return all the best stuff the website has to offer that is tagged with the term `views`. Now, let's say you want to have an easter egg feature, where if you have polite users, they get something special, so in Views, you can add another argument to the path, eg, `all/the/best/%/%` and in this second argument you give tell Views it is a Global Null Value. Now, what this does is let Views know to look for an argument there, but not to use it in any of the sql it builds. Like a placeholder. So, now you could do something like:

```
www.user1015214.com/all/the/best/views/please

```

And Views would create the same sql statements as before, returning all the best views, but you could then access that additional argument for any custom purpose you wanted anywhere within the drupal system. The easiest is to use the system arg(#) function:

```
$foo=arg(0); // all
$bar=arg(2); // best
$baz=arg(4); // please

```

and in your example, within the your node template file, you could do something like:

```
$baz=arg(4);
if ($baz=='please') {
   print '<div class="polite">Thank\'s for being polite! Here\'s a link to something special: ';
   print l('Pee Wee\'s Playhouse', 'http://www.peeweesplayhouse.com') . '</div>';
}

```

and then whenever someone asked nicely that additional would be displayed along with your node. Pretty nonsensical I realize, but I hope it explains arg()s :)

# Answer
> 1 votes
if you want to pass view argument to theming and not use it for filtering data - add "Global: Null" argument.

---
Tags: views
---


title: more than one contact form block?

text:
# Question
Title: more than one contact form block?
I have this module enabled

http://drupal.org/project/contact\_form\_blocks

but I only have one contact form block, which is set to global. How would I make another contact form block? Thank you!

# Answer
Try Webform, to create many flexible forms. Here is a quote about it (from the module's project page):

> ... is the module for making surveys in Drupal. After a submission, users may be sent an e-mail "receipt" as well as sending a notification to administrators. Results can be exported into Excel or other spreadsheet applications. Webform also provides some basic statistical review and has and extensive API for expanding its features.
> 0 votes

---
Tags: emails
---


# Question
Title: Has anyone implemented a tablesort with ajax?
I would like to sort on a column with a round trip but no page reload. The table is very large and has to be paged in, which I am doing manually with an ajax select element. I know TableSort is available to extend the query but I've only seen examples that reload the page.

# Answer
> 0 votes
Why not to use Views module to display your data? Views already has AJAX paging, sorting and filtering.

# Answer
> 1 votes
here you go mate:

ajax table sorting

---
Tags: 7, forms, ajax
---


title: Menu links not working in Ubuntu (D7)

text:
# Question
Title: Menu links not working in Ubuntu (D7)
I had a site in Windows installed inside xampp. I copied the same `site's folder` and `database` from windows-xampp installation to Ubuntu's www folder (Lamp) . The menu links are not working now. `localhost/sitename` directs to the homepage . But when I click on any menu items , it says

> The requested URL /sitename/latest/11 was not found on this server.

I could not figure out if this is problem of localhost or menu or database?

I can't even login because `users/login` is also not working.

Any suggestion or any links to the articles that I should read to solve this problem would be great. Thank you .

# Answer
> 2 votes
My suspicion is that Drupal's .htaccess URL rewrite directives have been disallowed in your Ubuntu installation of Apache. If it were a bootstrap or database connection problem, you would not be able to see the front page either.

Ordinarily, Drupal prevents Clean URLs from being activated if not supported by the server. In this scenario, of course, that test was done in the Windows installation. Ensuring rewriting support in the target server is at the top of the migration checklist.

The quickest way to see if Clean URLs is the culprit is to try browsing to `localhost/sitename/index.php?q=user/login` ; if that page does come up, you will need to enable rewriting in your web server.

See http://drupal.org/node/1186762#comment-5424052 for some instructions on checking your Apache configuration to make sure it allows Drupal to rewrite URLs in its .htaccess file.

If you can confirm that the .htaccess file is being read, rewrite directives have been allowed in Drupal's installation directory, and that mod\_rewrite is active, and still see problems, I would check next for a corrupted menu table.

---
Tags: 7, routes, database
---


title: Assigning Organic Groups using Feeds

text:
# Question
Title: Assigning Organic Groups using Feeds
We're using Feeds (https://drupal.org/project/feeds) and things are working fine. However, we use Drupal/Acquia Commons. How might we assign Organic Groups to each new node?

# Answer
After studying up the Feeds module, I what I needed. The Feeds module, set up properly, mapped the organic group of the Feed node to the newly created \[Blog\] node.

Link: /admin/build/feeds
> 0 votes

---
Tags: 7, feeds, organic-groups
---


# Question
Title: Theming custom field directly in custom module folder?
we're trying to build a template for the custom field we developed. We don't want to put the template into our theme folder since the template should work between different themes. As far as we know we have the option of putting a custom field.tpl.php somewhere or override theme\_field() in our module. What we've been trying with naming these files/functions kind of didn't work out and now we need your help. :-)

What's best practice with building templates / templating for custom fields, where to put it and how to name it?

Thanks! :)

# Answer
> 0 votes
When you define your module's theme info in `theme_hook()`, you can use `drupal_get_path()` to find the path to your module, and the `path` array key in your theme implementation array to point to the directory your tpl is in.

A working example would be:

```
function field_collection_theme($existing, $type, $theme, $path) {

  $path = drupal_get_path('module', 'field_collection');

  return array(
    'field_collection_op_links' => array(
      'path' => $path . '/includes/theme',
      'template' => 'field-collection-op-links',
      'render element' => 'op_links',
    ),
  );
}

```

Where the field\_collection\_op\_links.tpl.php is in field\_collection/includes/theme/, no matter where field collection is installed.

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


# Question
Title: Search results showing duplicate entries
For some reason the search results show duplicate entire with the view I have, I also have distinct on under the query options so it doesn't show duplicate nodes, I cant figure out why its doing this for the life of me.

This is the view I have of it.

Any input is appreciated.

Edit: It seems to only do this when I search for only 2 words, for example "should I" "can you" "this that" "now here" ect...

# Answer
You seem to have added a field (Field: Image). If there are nodes with multiple field items (multiple images), then they will show up multiple times. To avoid that, enable aggregation in the advanced settings. It might also be possible to configure the field to only list the first value, not exactly sure.
> 2 votes

---
Tags: 7, views
---


# Question
Title: Missing edit tabs on only one content type
I have a custom node template for a particular content type, and it seems that the "view" and "edit" tabs are missing on nodes of that type. However, it doesn't appear that the node templates typically have accesss to the $tabs array; that seems to be something that goes in page.tpl.php (which I haven't overridden or altered). It still work for other node types though, so it must be something in the node template.

When I add a `dsm($tabs);` to the page.tpl.php and view a node of my custom type, it displays the arrays containing the info for the tabs, so it can't be that my user doesn't have permission, or the tabs wouldn't load any info at all, right?

What should I do to my node template to fix this?

# Answer
If you have a dsm($tabs) at the top of your page.tpl.php and it's showing it's set, nothing should be unsetting it by the time it is output later on in the template.

For example, in the default D6 page.tpl.php, it does this...

```
<?php if (!empty($tabs)): ?><div class="tabs"><?php print $tabs; ?></div><?php endif; ?>

```

and in D7 it does this...

```
<?php if ($tabs): ?><div class="tabs"><?php print render($tabs); ?></div><?php endif; ?>

```

...so, I'd take a look at the page source and see if css or something else is causing it to be hidden. For example, perhaps your theme is doing stuff like cascading a class in the body with the tabs class.
> 1 votes

---
Tags: theming, nodes, users, routes
---


# Question
Title: Adding a block to a page build with a call to theme (Drupal 7)
I have a page on Drupal site that needs to render a webGL canvas. This page is visited by hitting an end point defined in hook\_menu. Here is the code I use to render the webGL page.

```
function inflatable_icons_canvas_page() {
    $base_path = drupal_get_path('module', 'inflatable_icons') . '/Online_Inflatable_Icons/IconEditor/public/';
    drupal_add_js(array('inflatable_icons' => array('basePath' => $base_path)), 'setting');
    drupal_add_css($base_path . 'js/dojo-release-1.7.2/dijit/themes/claro/claro.css');
    drupal_add_css($base_path . 'css/shared.css');
    drupal_add_js($base_path . 'js/includes.js');
    return theme('webgl_canvas');
}
function theme_webgl_canvas() {
    $html = file_get_contents(drupal_get_path('module', 'inflatable_icons') . '/Online_Inflatable_Icons/IconEditor/public/editor.html');
    $page = new SimpleXMLElement($html);
    $table = $page->body->table;
    $div = new SimpleXMLElement("<div class='claro'></div>");
    sxml_append( $div, $table );
    return $div->asXML();
}

```

I also need to be able to add some blocks to this page (either programmatically created or created through interface builder), how would I add these blocks to my page which is created through loading the html file editor.html and calling theme.

# Answer
inflatable\_icons\_canvas\_page() is the callback function for your hook\_menu page, therefore in your hook\_menu you will define a route as:

```
  function inflatable_icons_menu() {
    $items['abc/def'] = array(
      'page callback' => 'inflatable_icons_canvas_page',
    );
    return $items;
  }

```

Then you can use the route 'abc/def' to determine the visibility of your blocks either in the admin blocks UI or in your module code. In later case it will be something like:

```
$blocks['example_empty'] = array(
    'info' => t('Example: empty block'),
    'status' => TRUE,
    'region' => 'sidebar_first', // Not usually provided.
    'visibility' => BLOCK_VISIBILITY_LISTED, // Not usually provided.
    'pages' => 'abc/def', // Not usually provided here.
  );

```

Then configure the block as usual from blocks admin UI. If you go to configure the block you will find the configuration of visibility settings to "show block in specific pages" option "only the listed pages" and your hook\_menu route in text area. You could change it now if desired, as you will with a block created through UI.
> 3 votes

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


title: User session and https

text:
# Question
Title: User session and https
I've got a few pages on my site that need to be accessed via https. I need to pull some information about the current logged user on those pages. The problem is, users log using http mode and the session is not kept when switching from http to https. I've looked into secure login module but it brings some other issues (with facebook connect...)

Is there any way we can tell the cookie to persist ? Thanks in advance

# Answer
Add `$conf['https'] = TRUE;` to `settings.php`.

from here: http://drupal.org/node/1037542 and http://drupal.org/https-information

however, why not just run the whole site securely?
> 1 votes

---
Tags: users, sessions, cookies, ssl
---


# Question
Title: Is there a way to setup a site monitor on drupal?
I have the current question: https://drupal.stackexchange.com/questions/37712/ubercart-items-wont-add-to-cart-unless-cache-is-cleared. In order to try and narrow down what the issue is. I'm curious if there is a way to setup a sort of monitor or logs to be able to get some more insight as to what is going wrong. I know of the typical status reports, Log messages & server logs. But is there anything that might be able to give me more drupal related details?

# Answer
> -1 votes
mysql and httpd logging on your server should help a bit. turn them on (and adjust reporting levels) but make sure you don't fill up your disk with logs. turn the logging level back down to something normal once you've looked for a while.

---
Tags: 7
---


# Question
Title: How to print number of blocks in a region in Drupal 6
I use Drupal 6 and I'm trying to get number of blocks in a region. How is that possible?

# Answer
The following query returns the number of blocks in the *left* region of the current theme. Replace *left* with your region name.

```
$current_theme = variable_get('theme_default', '');
$number_of_blocks = db_result(db_query("SELECT COUNT(*) FROM {blocks} WHERE theme='%s' AND region='%s'", $current_theme, 'left'));

```
> 2 votes

---
Tags: 6, blocks, media, theming
---


# Question
Title: How to create custom page with user images in grid and with pagination, not using views
As I guess I need to override node.tpl.php or page.tpl.php?

# Answer
> 0 votes
use hook\_menu() to create a path to your page. Then use db\_select() with the tableSort extender to supply pagination in the hook\_menu `page callback`. Select the uid, username, user image(s) ? in your database query.

Then just loop over your resultset and output a div with your user images per cell. Simply float all the divs to the left so your output appears as a grid instead of a single long column of rows.

---
Tags: hooks, theming
---


# Question
Title: Is Organic Groups 7.x ready for production?
I am about to build a community and planned on using organic groups. I was using drupalmodules.com to download modules, and I noticed that that the reviews for organic groups 7.x are terrible. http://drupalmodules.com/module/organic-groups. Is anyone using organic groups 7.x, and what are your experiences with it?

# Answer
I've used OG6 in the past and am starting to use OG7 now for a website. I'd say in general, both with the 6 and 7 versions that the learning curve in figuring out how to use Organic Groups can be steep for a newbie, since it's a complicated module with a lot of features, and a lot of related, supporting modules like OG menu, OG Extras, etc.

Give yourself time to play with all of those. Don't expect to setup your perfect site in a day if you've never used it before. It may be that the 6 folks who reviewed the module on the site you referenced had such expectations. Also, those are **6 reviews out of over 24,000 sites currently using OG**. :-)

My recommendation: do your own testing and make up your own mind before believing a review 100%. Some of those reviews are probably quite valid, but OG is a useful module and may be able to do everything you want for your site.
> 1 votes

---
Tags: 7, organic-groups
---


# Question
Title: installed drupal site locally but not working (XAMPP)
I want to install the site from the server locally so I can test changes before performing them.

So:

1. I exported the database and installed it locally
2. I downloaded all the files that were inside the site root folder and put them in a root folder locally (but with another name)
3. I changed the parameter `$db_url` and `$base_url`

The problem is that the front page is shown correctly but when I click to go to another page from the menu it says:

\[an error occurred while processing this directive\] The requested URL was not found on this server. The link on the referring page seems to be wrong or outdated. Please inform the author of that page about the error. \[an error occurred while processing this directive\]

Anyone have any idea?

NOTE: I just noticed that the url is something like this: `http://localhost/root//articles/article-one`

Thank you

# Answer
> 1 votes
are there any custom rewrite rules in your htaccess file? when something similar happened in my case, I had `RewriteBase /` set in my *.htaccess* file from the actual deployment environment that had to be commented. Identified this by enabling a log in my local httpd.conf on how the URLs were translated with

```
RewriteLog "custom/folder/path"
RewriteLogLevel 9

```

to have a better idea of how the rules translated the URLs and where i messed up, hope this has some significance in solving the issue you are facing.

# Answer
> 2 votes
One reason for this can be 'the apache server's rewrite mod is not enabled'.

See if

> localhost/sitename/index.php?q=user/login

is working.

If that is working then try enabling Clean URL (`sudo a2enmod rewrite for LAMP`).

Few links that can be related to the problems.

http://drupal.org/node/1186762

http://drupal.org/node/333675

# Answer
> 1 votes
Looks like you need to clear the menu cache but after an import I always clear all cache to be safe. Also try a search in your imported db for your online url..?

Also for Drupal Local dev, have a look at Dev Desktop, I used to use XAMPP then moved to WAMP and now use Dev Desktop as I pretty much soley develop Drupal now.

# Answer
> 1 votes
The problem may be with the links in your site.

```
<a href="/awesome_page">Awesome Page</a>

```

If absolute links are used then this will work fine in your live site. `www.mysite.com/awesome_page` is valid but when you try to work with your local i.e `http://localhost/drupal/front_page` the link Awesome page will now actually point to `http://localhost/awesome_page`.
Quick work around will be to set up your local like live site. Add an entry in your hosts file like `127.0.0.1 www.mysite.local` Add a virtual host entry(httpd-vhosts.conf)

```
<VirtualHost *:80>
    ServerName www.mysite.local
    DocumentRoot "C:/apache2.2.8/htdocs/drupal"
</VirtualHost>

```

restart apache server and you will be able to access http://www.mysite.local from your local server and all links will work.

# Answer
> 1 votes
Check if .htaccess file is exists in site root folder.

---
Tags: migrations
---


# Question
Title: EntityFieldQuery select entity if at least one tid is in the array?
This seems like it would be a common need but I don't see how it can be done with the operators available. I have a taxonomy reference field that allows multiple values. I would like to construct an EntityFieldQuery that selects the entity if at least one of the tid's is in the given array.

```
$query->fieldCondition('field_tags', 'tid', $tid_array, 'CONTAINS_ONE');

```

# Answer
> 7 votes
All you need is:

`$query->fieldCondition('field_tags', 'tid', $tid_array);`

From `EntityFieldQuery::addFieldCondition()`: "The operator can be omitted, and will default to 'IN' if the value is an array, or to '=' otherwise."

---
Tags: entities, database
---


# Question
Title: drush extension installation directory location
Where is the recommended location to install drush extensions?

I've downloaded drush\_sup and have drush 5.4 installed.

drush\_sup/README.txt says to look in the drush README.txt file for the recommended location:

> See the Drush README.txt for locations where Drush extensions may be placed.

drush/README.txt does not discuss extensions.

# Answer
This (the incorrect contents in the drush\_sup README file) is a drush\_sup bug report, and should go in the drush\_sup issue queue. I am the drush\_sup maintainer, though, and can make this correction.

If you use Drush to download drush sup (i.e. `drush dl drush_sup`), then it will automatically be placed in the .drush folder in your home directory. Drush automatically finds extensions stored in this location.
> 2 votes

---
Tags: drush
---


# Question
Title: How to pre-populate a field with the current users name?
I want to pre-populate a form field with the value from another cck field from a different content type. I have been looking into using the prepopulate module and pathauto to get the correct url, but I am not sure that these will work. I am new to drupal and kinda lost in the storm with this problem.

# Answer
> 1 votes
To answer the question posed in the title of this question, you could in a custom module do something along the lines of...

```
function MYMODULE_form_alter(&$form, $form_state, $form_id) {
  global $user;

  if ($form_id=='NODETYPE_node_form') {
     $form['field_FIELD'][0]['#default_value']['value']=$user->name;
  }

  // any other form alters you need

}

```

where MYMODULE is the name of your custom module, NODETYPE is the content type in question and FIELD is the field name in question without the field\_ prefix. Now, whenever you are editing or creating a content type of NODETYPE, the FIELD in question will have a prefilled default value of the current user's name.

Now, if this is a different form, you'll just need to adjust the $form\_id== construct to point to that form, the field in that form, etc, but the rest of the logic should be the same.

# Answer
> 0 votes
I'm not sure how it would apply to your situation, and I'm sorry I don't really have time to check it out completely at the moment, but you could try using Entity Reference and Entity Reference Prepopulate. By using Entity Reference, the new content type will be related back to the user in a way that can be utilized by views and many other modules. I just realized, though, that it looks like you tagged this as Drupal 6, so this solution may not work for you if you cannot move to Drupal 7.

---
Tags: 6, entities
---


# Question
Title: Getting book pages in same level like getting child pages
I have a book called `courses` with several subpages, I want to show the list of ot other subpages when one subpage is open.

Example:

```
-Courses
---Course1
---Course2
---Course3
---course4

```

I want to show course1, course2 & course3 when course4 is open. I know to get childpages, but have no idea how to get pages in same level. I am using Drupal 7.

# Answer
If book module is enabled, it also creates a block called "Book navigation". You can display the block in any of the "Region" defined in your theme (e.g. "Sidebar first" in Bartik theme), by visiting `http://your-site-url/admin/structure/block`.

The block will be displayed(in the selected region) whenever you open the book page. And by default it will show the the book pages at the same level(sibling) pages.
> 0 votes

---
Tags: 7, nodes
---


# Question
Title: Programmatically showing the summary of a post
What's the PHP code to call summary of a post (teaser) in a custom page?

I use Drupal 6 and I want to show a small part of a specific post in a custom page.

# Answer
> 2 votes
You can use teasers from node. In node.tpl.php you can use `$teaser` variable to print it.
In other templates, you need to use node\_load().

```
$node = node_load(211); // 211 is the Node ID
print $node->teaser;

```

# Answer
> 2 votes
Apart from the $teaser variable, you can also use the `node_teaser()` function (http://api.drupal.org/api/drupal/modules%21node%21node.module/function/node\_teaser/6). This allows you to create a custom teaser, in case $teaser is not present.

# Answer
> 1 votes
The function that creates the teaser of a node is node\_teaser(), which is called from node\_submit(), the function called from the form submission handler for the node edit form, and from node\_preview(), the function used to create a preview of the node being saved.

It can happen a node doesn't have a teaser, for example when a module saves the node using node\_save(). in such cases, you can use code similar to the following one.

```
$node = node_load($nid);
if (!isset($node->teaser)) {
  if (isset($node->body)) {
    $node->teaser = node_teaser($node->body, isset($node->format) ? $node->format : NULL);
  }
  else {
    $node->teaser = '';
    $node->format = 0;
  }
}

```

To notice that Drupal 7 doesn't have the `node_teaser()` function anymore, as the body of a node is a field.

---
Tags: 6, nodes
---


title: Filter view by passing a date via URL

text:
# Question
Title: Filter view by passing a date via URL
I have created a view and I want to show filtered posts passing arguments via the URL. Example:

http://mysite.com/press/2012-01

I want to show all press posts created in January'2012.

How can I do that ?

# Answer
Take a look at the core Views example *Archive* (`admin/structure/views/view/archive/edit`) which is disabled by default.
> 1 votes

# Answer
You need to use Contextual Filters in order to pass arguments to the view.
> 0 votes

---
Tags: views
---


title: Can't get SQL query results

text:
# Question
Title: Can't get SQL query results
I used a PHP code to show results of this query:

```
SELECT COUNT(*) FROM mytable

```

I want to get the number of rows in a specific table. This query works fine in phpMyAdmin, but it doesn't work when I place it in a template file.

I mean it doesn't return the number of rows.

Do you have any idea?

# Answer
> 2 votes
A template file should never contain code that executes a query; that should be done in a preprocess function, eventually.

The code to get the number of rows in a table is similar to the following one.

```
$count = db_result(db_query("SELECT COUNT(*) FROM {mytable}"));

```

The table name should always be put between curly brackets, which will be replaced with the prefix currently set for database tables.

---
Tags: 6, database
---


# Question
Title: Elysia cron module does not execute cron job automatically
I have installed the elysia cron module and setup the cron job. My module has a cron function `test_cron()` which inserts some data into a table.

This function lists in the elysia cron status page. I have setup the the default scheduled rule to `*/1 * * * *` to run the cron after every minute.

When I click on the **run** infront of the `test_cron()` the cron runs and some data inserts into the database.

But this the manual method, I want to execute the cron after every minute therefore I defined the scheduled time for the `test_cron()`, but it does not executed automatically after every minute.

What should I do? Is there any other configuration which I should do to run the cron automatically?

# Answer
As I mentioned before *Elysia Cron can only schedule the cron jobs not control it* when to run. If system crontabs are set to run every minute elysia cron module can control it from there on. Check out the drupal page for that module.

> Elysia Cron
> However to get the full potential out of elysia cron and have the full control over you tasks a further step is needed: you need to configure the system crontab to execute drupal cron every minute.
> 6 votes

---
Tags: 7, cron
---


title: Get total revenue for special product

text:
# Question
Title: Get total revenue for special product
I want to get total revenue from a productId on Drupal commerce. How can I do that? I found in drupal commerce's table but didn't see any relationship to get that info.

# Answer
> 1 votes
After some research here is the result. I think it work fine

```
$totalRevenueQuery = db_select('commerce_payment_transaction', 'cpt')
    ->fields('cpt', array('currency_code'));
  $totalRevenueQuery->addExpression('SUM(amount)', 'amount');
    $totalRevenueQuery->leftJoin('commerce_order', 'commerce_order', 'cpt.order_id = commerce_order.order_id');
    $totalRevenueQuery->leftJoin('field_data_commerce_line_items', 'field_data_commerce_line_items', 'cpt.order_id = field_data_commerce_line_items.entity_id');
    $totalRevenueQuery->innerJoin('commerce_line_item', 'commerce_line_item_field_data_commerce_line_items', 'field_data_commerce_line_items.commerce_line_items_line_item_id = commerce_line_item_field_data_commerce_line_items.line_item_id');
    $totalRevenueQuery->leftJoin('field_data_commerce_product', 'commerce_line_item_field_data_commerce_line_items__field_data_commerce_product', 'commerce_line_item_field_data_commerce_line_items.line_item_id = commerce_line_item_field_data_commerce_line_items__field_data_commerce_product.entity_id');
    $totalRevenueQuery->innerJoin('commerce_product', 'commerce_product_field_data_commerce_product', 'commerce_line_item_field_data_commerce_line_items__field_data_commerce_product.commerce_product_product_id = commerce_product_field_data_commerce_product.product_id');
    $totalRevenueQuery->condition('commerce_product_field_data_commerce_product.product_id', $product_id);
    $totalRevenueQuery->condition('field_data_commerce_line_items.entity_type', 'commerce_order');
    $totalRevenueQuery->condition('field_data_commerce_line_items.deleted', 0);
    $totalRevenueQuery->condition('commerce_line_item_field_data_commerce_line_items__field_data_commerce_product.entity_type', 'commerce_line_item');
    $totalRevenueQuery->condition('commerce_line_item_field_data_commerce_line_items__field_data_commerce_product.deleted', 0);
    $totalRevenueQuery->condition('commerce_order.type', 'commerce_order');
  $totalRevenue = $totalRevenueQuery->execute();

```

---
Tags: commerce
---


# Question
Title: Custom Pricing based on anonymous customer input
Hi gurus and fellows,

I am a newbie at DrupalCommerce, though I have been designing website for a while using Drupal.

For our new project, we need to provide some custom pricing rules, based on user input. **Anomymous** user fills in a form, and, based on his input, we compute some special 'discount' (sort of). Let me emphasize that user is not connected (registered), and its data is kept in session only.

As far as I know, we need to set up some "Pricing Rules", but to tackle my problem, I can only see "User has role" / "User is blocked" in the possible conditions, which address only logged-on users.

How you would you do that ? Do I need to write up a custom rule ?

Any hints much appreciated.

Thank you.

# Answer
> 0 votes
User has role can indeed be used to setup a rule for Anomymous user, see the image:

---
Tags: commerce
---


# Question
Title: Possible conflict with multiple jquery plugins
I have a custom module that uses the jCarousel jquery plugin (not the Drupal module). The module code up to this point works correctly, and looks like this (only the main function included for brevity.)

```
function speaker_carousel_block_view($delta = '') {
 switch($delta){
    case 'speaker_carousel':
      drupal_add_js('sites/all/libraries/jcarousel/lib/jquery.jcarousel.min.js');
      drupal_add_css('sites/all/libraries/jcarousel/skins/speakers/jcarousel-speakers.css');

     drupal_add_js(
       'jQuery.noConflict();
            (function($) {
              $(document).ready(function() {
                 jQuery("#mycarousel").jcarousel({wrap: "circular"});
                });
            })(jQuery);',
       'inline'

     );

        $block_content = "";
        //Use our custom function to retrieve data.
        $result = speaker_carousel_get_data();

        //parse into html
        $block_content .= '<ul id="mycarousel" class="jcarousel-skin-speakers">';
        $block_content .= speaker_carousel_create_html($result);
        $block_content .= '</ul>';

        $block['content'] = $block_content;
  }
  return $block;
}

```

I'm now trying to incorporate a second plugin (\[jquery tools tooltip\]) to handle a mouseover popup of some text. This is what the function looks like after additions:

```
function speaker_carousel_block_view($delta = '') {
 switch($delta){
    case 'speaker_carousel':
      drupal_add_js('sites/all/libraries/jcarousel/lib/jquery.jcarousel.min.js');
      drupal_add_css('sites/all/libraries/jcarousel/skins/speakers/jcarousel-speakers.css');
      drupal_add_js('http://cdn.jquerytools.org/1.2.7/full/jquery.tools.min.js', 'external');

     drupal_add_js(
       'jQuery.noConflict();
            (function($) {
              $(document).ready(function() {
                 jQuery("#mycarousel").jcarousel({wrap: "circular"});
                 jQuery("#mycarousel img").tooltip();
                });
            })(jQuery);',
       'inline'

     );
        $block_content = "";
        //Use our custom function to retrieve data.
        $result = speaker_carousel_get_data();

        //parse into html
        $block_content .= '<ul id="mycarousel" class="jcarousel-skin-speakers">';
        $block_content .= speaker_carousel_create_html($result);
        $block_content .= '</ul>';

        $block['content'] = $block_content;

  }
  return $block;
}

```

As soon as I add the second `drupal_add_js()` call in (to the cdn.jquerytools.org site), everything blows up. The carousel no longer displays correctly; it just shows a single item instead of the horizontally scrolling strip of images that was there before. Any idea how I can get the two to play nicely together?

---

I found the JQuery Multi module, which I really thought would help. I installed and configured, and now the carousel no longer blows up, but I get an error in Firebug console:

> jQuery("#mycarousel a.speaker\_trigger").tooltip is not a function
> jQuery("#mycarousel a.speaker\_trigger").tooltip();

I know it's not an issue with the two plugins working together, because I copied the rendered source into a static HTML file and put it here. It works fine, but it's only using a single version of jquery.

Do you have any idea?

# Answer
> 3 votes
You can run two separate versions of jQuery, which is what your situation seems to require.

This module offers hope to an easy resolution . https://drupal.org/project/jqmulti

Otherwise this document offers more clarity: https://drupal.org/node/1058168

Generally speaking, you only need a single instance of jQuery installed on the server, which might be called from many different scripts scattered all over the place. However sometimes you'll have a requirement for jQuery more recent than your current stock-Drupal installation. This is when you want to run multiple jQuery versions (because you don't want to simply upgrade your single instance, which would break standard Drupal jQuery stuff like the admin-menu).

```
(function($){
    // your code here, using jQuery 1.7.1 setup w/ jqmulti module
    alert("jQuery version = " + $().jquery); //proves jquery version being used
})(jq171)

```

# Answer
> 2 votes
jquerytools includes jquery so you are calling jquery 2 times (if i'm not wrong you are calling the full jquerytools file).

You should download a version without jquery and link that one.

Beware: Drupal jquery is version 1.4.4 (1.5.2 with jquery update). I remember jquerytools depending on jquery 1.6.x (not sure) so check for jquerytools requirements.

---
Tags: javascript
---


title: Crossdomain.xml on a multisite setup

text:
# Question
Title: Crossdomain.xml on a multisite setup
I can't figure out where I need to place the crossdomain.xml (to let Flash communicate).

If I place it on the root of my Drupal installation, the cross-domain-policy is not working because the symlink redirects the user-agent to the multisite folder.

If I place the crossdomain.xml in the multisite folder, it doesn't work either.

What should I try?

# Answer
I would make up a module with a `hook_menu` in it with a path of "crossdomain.xml". In the menu callback, figure out your domain and serve up the proper file with the proper MIME type. Install the module in "sites/all" and enable for each site that needs it.

I also suspect you could handle it in .htaccess with something like

```
RewriteCond %{HTTP_HOST} ^www\.host1\.com [NC]
RewriteRule crossdomain.xml crossdomain.host1.xml [L]
RewriteCond %{HTTP_HOST} ^www\.host2\.com [NC]
RewriteRule crossdomain.xml crossdomain.host2.xml [L]
RewriteCond %{HTTP_HOST} ^www\.host3\.com [NC]
RewriteRule crossdomain.xml crossdomain.host3.xml [L]

```
> 3 votes

# Answer
The docroot is the correct place for it to go. You should not have any symlinks either.
> -1 votes

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


title: D7 Webform tokens for user fields

text:
# Question
Title: D7 Webform tokens for user fields
In D6 we could configure a webform field to pull profile data by using a token like %profile\[key\] and assigning the user field to the form (Details here). How can we to something similar in D7 using the user fields instead of the profile fields?

# Answer
It appears that this can't be done using the standard webform module. It defines a limited list of tokens that hasn't been updated for the new user fields. They are included as tokens (if you use field\_nnn) but they will be an empty value.

After initially looking at building a custom module, it seems that the Tokens module does make user fields available in the form \[user:field\_nnn\].
> 3 votes

# Answer
The new Webform 4.x uses the token system. The ongoing process can be followed here
> 2 votes

---
Tags: 7, webforms, tokens, users
---


# Question
Title: LDAP Role Mapping - Working, but not Assigning
I have setup the ldap module for Drupal 7 - everything is working as it should, apart from when a user logs into the site the role defined for that person isn't been assigned to their profile, they remain just an authenticated user.

When I run a test on their username it shows that the user should be part of the correct role.

In the error log I can see it is failing when granting a single authorisation with the following error:

```
LdapAuthorizationConsumerDrupalRole.grantSingleAuthorization() failed to grant xxx the role Delegate because role does not exist

```

However the Delegate role is setup and present.

Has anyone else come across this problem?

--

Just to note that I found the solution - don't use capitals in your roles. Changing Delegate to delegate fixed it. I will put this as the answer when my 8 hour self answer delay lapses.

# Answer
> 1 votes
Ok so I found the solution - which made me kick myself :p

In order to get the role mapping working the role names have to start with a lower case letter - so in my example I changed the role name from Delegate to delegate and it is all working now.

---
Tags: users, authentication-authorization
---


title: Programmatically assign new users to OG

text:
# Question
Title: Programmatically assign new users to OG
My site is sub-divided into organic groups.

Group administrators are allowed to create new users, but I need a way to auto-assign the new user to the same organic group the creating group administrator belongs to.

Can anyone tell me how I can accomplish this auto-assignment either programmatically or with a module?

# Answer
> 4 votes
You should write a custom module that implements **hook\_form\_alter()**.

* Get the `$form_id` of the 'create new user' form that you want to alter.

( `drupal_set_message($form_id);` is an easy way to do this. )
* Add a custom submit handler to the 'create user' form that uses the respective details and the **og\_group()** function to add the new user to the group.

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

    if (isset($form_id) && $form_id == 'YOUROG_USERCREATION_FORMID') {
        $form['#submit'][] = 'MODULENAME_submit_handler';
    }

}

function MODULENAME_submit_handler($form, &$form_state) {

    $gid = $form_state['values']['groupID'];
    $uid = $form_state['values']['userID'];

    $account = user_load($uid);
    $values = array(
        'entity_type' => 'user',
        'entity' => $account,
        'state' => OG_STATE_ACTIVE,
       );

    og_group('node', $gid, $values);

    return $form;
}

```

Just as a point of information, this code sample is geared towards **OG 7.2.x**.

If you're using **OG 7.1.x**, you drop the first argument in og\_group, so it would be `og_group($gid, $values);`

Also, the possible `$values` you can use, and defaults, are as follows:

```
# taken directly from og.module

$values += array(
     'entity type' => 'user',
     'entity' => FALSE,
     'state' => OG_STATE_ACTIVE,
     'save' => TRUE,
     'force reload' => TRUE,
     'membership type' => OG_MEMBERSHIP_TYPE_DEFAULT,
     'membership fields' => array(),
     'created' => time(),
    );

```

# Answer
> 0 votes
Try the Rules module: http://drupal.org/project/rules

You could react on "User created" and assign the new user the group of the currently logged in user, which is the creator.

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


# Question
Title: Creating a page.tpl.php template for a group of pages (Drupal 7)
I have a special part of my site that needs a very different kind of layout from the rest of my site. I have created a template file called page--special.tpl.php that implements the kinds of themeing I need. This page works fine as the long as the page that is being viewed is at the endpoint ?q=special but I do not want to have to make a different template for each page in this special section (all of which would have the same theme code). Is there anyway to have all pages that have endpoints starting with ?q=special use this template?

Is there some other better way to do this?

# Answer
If the pages `www.yoursite.com/special`, `www.yoursite.com/special/anotherpage`, etc are the actual paths to the content and not aliases, then `page--special.tpl.php` should work for all of them. If, however, they are aliases to node content, eg, `www.yoursite.com/special/anotherpage` is really something like `www.yoursite.com/node/123`, then you could do something like this in your theme's template.php file...

```
function YOURTHEME_preprocess_page(&$vars) {

  $alias=drupal_get_path_alias($_GET['q']);
  $args=explode('/', $alias);
  if ($args[0]=='special') {
    $vars['theme_hook_suggestions'][] = 'page__special';
  }

  // any other page preprocessing here

}

```

...which takes a dull ax to the url and chops it apart and if the first part is `special` then it tells drupal to use your page template for it. If, however, you know that all of the nodes there are of a certain type, you could do it this way instead...

```
function YOURTHEME_preprocess_page(&$vars) {

  if (!empty($vars['node']->type) && $vars['node']->type == 'SPECIAL_TYPE') {
    $vars['theme_hook_suggestions'][] = 'page__special';
  }

  // any other page preprocessing here

}

```

...which would tell drupal to use your template file whenever it displays a SPECIAL\_TYPE node on a full page.
> 2 votes

---
Tags: 7, theming
---


title: Google can not connect to the server?

text:
# Question
Title: Google can not connect to the server?
Google Webmaster's tool tells me on a site that "Request timed out or site is blocking Google". On that site. I am wondering how to fix this.

Probably relevant info: I'm using Varnish in front of nginx and also user use iptables and DDoS deflate. The site is large but works pretty smoothly, with load less than 2 most of the times. The standard Pressflow 6 robots.txt is there and accessible through browser.

I am not quite sure how to figure out what blocks googlebots and how to fix the problem. So appreciate your hints.

# Answer
Check the settings in the `nodewords` (or another meta tags) module look for `noindex`
> 1 votes

---
Tags: 6
---


title: Where are the main menu links created?

text:
# Question
Title: Where are the main menu links created?
I've been doing some w3 validation but I find that my menu's are missing a `<ul>` for the `<li>`'s. I have read Where is links\__system\_main\_menu defined? but this doesn't really answer my question. I understand that

> links\__system\_main\_menu is a theme hook pattern of the form \[base hook\]\__\[context\]. When links are themed with theme('links\__system\_main\_menu', $vars), theme() will search for and use theme\_links\__system\_main\_menu() if it has been defined. If not, it will use theme\_links().

The theme i'm using doesn't do much as far as modify the menu system at first glance. In the theme.php file, it contains:

```
$variables['main_menu_themed'] = theme(
    'links__system_main_menu',
    array(
      'links' => $variables['main_menu'],
      'attributes' => array(
        'id' => '',
        'class' => array('links', 'clearfix'),
      ),
      'heading' => array(
        'text' => t('Main menu'),
        'level' => 'h2',
        'class' => array('element-invisible'),
      ),
    )
  );

```

How can I modify the actual output of the menu?

# Answer
> 2 votes
You can override `theme_links__system_main_menu()` by declaring a function in your theme's template.php file:

```
function MYTHEME_links__system_main_menu($vars) {
  $links = $vars['links'];

  $items = array();
  foreach ($links as $link) {
    $items[] = l($link['title'], $link['href']);
  }

  return theme('item_list', array('items' => $items));
}

```

The above is a very basic example, you'll probably want to take a look at the original code for `theme_links()` to make that a bit more bulletproof.

---
Tags: 7, routes
---


title: Right way to include nusoap in D7

text:
# Question
Title: Right way to include nusoap in D7
I should include nusoap library in my module, there is two way:

1- Download and extract it in my module directory and simply include it.

2- Writing another module to provide nusoap wrapper for other modules need it including mine.

I searched for existing module but I didn't find any. so which way is better?

# Answer
It depends what you need really.

If you only need nusoap once, for a single project, then just download the library and include it using `include` (or even better, `module_load_include()`, that way it's still a 'Drupal' method!) There's no point writing a whole new module just to include a few files.

If you think you can provide useful wrappers for nusoap functionality though (as in ones not intrinsically provided by the library itself), or if you're likely to want to use nusoap again in a future project, it will probably save you some time later on to write a new module.

If you did this then you also have the added benefit of being able to contribute the module back to the community; a lightweight Drupal-capable soap library would probably be useful to a lot of people.

If I could offer any advice it would be to plan out what functionality you'd want your new module to have (what entities it could interface with, view/rules integration etc) before you dive in and write it. It's a lot more difficult to make a module generic halfway through writing it than it is at the beginning :)
> 1 votes

---
Tags: 7
---


title: Remove cck field from nodes body

text:
# Question
Title: Remove cck field from nodes body
I have defined a cck field but I don't want it to be printed out in posts body.

I print body in this way:

```
<?php print $node->body; ?>

```

but cck filed still exists. I want to use value of that field for some other purpose.

any ideas?

# Answer
> 2 votes
If you look at the Display Fields in CCK, eg `www.yourhost.com/admin/content/node-type/NODETYPE/display`, you can exclude fields from the `$content` variable that is passed to the node template. I'd look into that and use `$content` instead of `$node->body` if it isn't excluded from there as well.

---
Tags: 6, nodes, entities
---


title: clear form fields after submit

text:
# Question
Title: clear form fields after submit
im trying to clear the form fields after submitting (with ajax) right now after submitting the fields remain filled, how can I do this?

at the bottom of the script you can see my attempt. I think I should be able to do this with unset form, another option would be jquery. Been trying this for a while now, any ideas?

```
<?php

function social_links_form($form, &$form_state) {
$form['#suffix'] = '<script type="text/javascript">'
                 . 'jQuery(\'input#edit-url\').focus();'
                 . '</script>';

$form['box'] = array(
    '#type'         => 'markup',
    '#prefix'       => '<div id="box">',
    '#suffix'       => '</div>',
);
$form['url'] = array(
    '#type'         => 'textfield',
    '#required'     => TRUE,
    '#description'  => "Please enter your url name.",
    '#ajax'         => array(
    'wrapper'       => 'box',
    'name'          => 'url',
    ),
);
$form['title'] = array(
    '#type'         => 'textfield',
    '#required'     => TRUE,
    '#description'  => "Please enter your title.",
    '#ajax'         => array(
    'wrapper'       => 'box',
    'name'          => 'title',
    ),
);
$form['icon'] = array(
    '#type'         => 'hidden',
    '#required'     => TRUE,
    '#description'  => "Icon path",
    '#ajax'         => array(
    'wrapper'       => 'box',
    'name'          => 'icon1',
    ),
);

$form['file'] = array(
    '#title'        => t('Upload image'),
    '#type'         => 'file',
    '#description'  => t('Images must be one of jpg, bmp, gif or png formats.'),
    '#ajax'         => array(
    'wrapper'       => 'box',
    'name'          => 'icon2',
    ),
);

$form['submit'] = array(
    '#type'         => 'submit',
    '#ajax'         => array(
    'callback'      => 'social_links_insert',
    'wrapper'       => 'box',
    'name'          => 'submit1',
    'effect'        => 'fade',
    ),
    '#value' => t('Submit'),
);

return $form;
}

// save form values to database
function social_links_insert($form, $form_state){

  // first handle the image upload
  $file = file_save_upload('file', array(
  'file_validate_is_image' => array(),
  'file_validate_extensions' => array('png gif jpg jpeg'),
  ));

  if ($file) {
    if ($file = file_move($file, 'public://')){
      $form_state['storage']['file'] = $file;
    }
    else {
      form_set_error('file', t('Failed to write the uploaded file the site\'s file folder.'));
    }
  }
  else {
    form_set_error('file', t('No file was uploaded.'));
  }
  $file = $form_state['storage']['file'];
  unset($form_state['storage']['file']);
  $file->status = FILE_STATUS_PERMANENT;
  file_save($file);

  // display success message
  $element = $form['box'];
  $element['#markup'] = "
  <p style='font-weight: 700; color: green;'>Social link succesfully submitted</p>
  <b>URL:</b> {$form_state['values']['url']} &
  <b>Title:</b> {$form_state['values']['title']} &
  <b>Icon:</b> {$file->filename}
  ";

  // save form values
  db_insert('social_links') ->fields(array(
  'url' => $form_state['input']['url'],
  'title' => $form_state['input']['title'],
  'icon' => $file->filename,
  'created' => date('c'),
  ))
  ->execute();

    return $element;

  // reset the form
  $form_state = form_state_defaults();
}

```

**EDIT** I've got this on top of my admin.inc file. I think I should continue in this fashion. (because that piece of code does work)

```
 $form['#suffix'] = '<script type="text/javascript">'
                 . 'jQuery(\'input#edit-url\').focus(); '
                 . '</script>';

```

Can anyone assist me with implementing a form clear function inside the above piece of code? To be honest im quite disappointed drupal made using jquery so hard :(

**EDIT II**

second attempt:

```
$form['#suffix'] = '<script type="text/javascript">'
             . 'jQuery(\'input#edit-url\').focus(); '
             . 'jQuery(\'input[type=text]\' , "form#social-links-form").each(function(){jQuery(this).val("")});'
             . '</script>';

```

# Answer
> 1 votes
```
(function ($) {
Drupal.behaviors.yourmodulename = {
    attach: function(context) {

     setTimeout(function (){
$(".button").click(function(){
    $("input[type=text]" , context).each(
        function(){$(this).val("")});
        }
        )}, 1000);
}
}
})(jQuery);

```

# Answer
> 3 votes
Try add this code to you submit callback:

```
function social_links_insert($form, $form_state){
  /*your code goes here*/

  $form_state['input'] = array();
  $form_state['rebuild'] = TRUE;
}

```

Also remove "return $element;" from submit callback.

# Answer
> 0 votes
You can bind a simple jquery callback to ajax response. So if your response is successful then, do this

```
jQuery("input[type=text]" , "form#yourformid").each(function(){jQuery(this).val("")});

```

---
Tags: 7, forms
---


# Question
Title: #ajax elements added in hook_form_alter miss after first ajax call
I am modifying elements from the multiselect module to add ajax functionality. I wanted to use hook\_field\_widget\_WIDGET\_TYPE\_form\_alter() but I'm stuck in 7.14 and it requires 7.8.

So, I'm traversing the $form in hook\_form\_alter() to find the modify the 'multiselect' elements:

```
/*
 * Implements hook_form_alter()
 */
function ajax_multiselect_form_alter(&$form, &$form_state, $form_id) {
  _ajax_multiselect_search_children($form, $form);
}

/*
 * Look for multiselect elements
 */
function _ajax_multiselect_search_children(&$form, &$element) {

  if (isset($element['#type']) && $element['#type'] == 'multiselect') {
    _ajax_multiselect_modify_multiselect($form, $element);
  }

  $children = element_children($element);

  if (is_array($children)) {
    foreach ($children as $child) {
      _ajax_multiselect_search_children($form, $element[$child]);
    }
  }
}

```

When I find a 'multiselect' element, I add a new 'select' element to the form with the #ajax property copied from the original 'multiselect'.

```
/*
 * Modify the multiselect for ajax processing
 */
function _ajax_multiselect_modify_multiselect(&$form, &$element) {

  $element['#attached']['js'] = array(
    array(
      'data' => drupal_get_path('module', 'ajax_multiselect') . '/js/ajax_multiselect.js',
    ),
  );

  if (isset($element['#ajax'])) {

    $ajax_element_id = drupal_html_id('ajax_multiselect_element');

    // tell jquery where to find the id of the dummy select
    $element['#attributes']['class'][] = 'multiselect-element-id-holder';
    // transmit the id of the dummy select to jquery
    $element['#attributes']['data-ajax-multiselect-element-id'] = $ajax_element_id;

    $form[$ajax_element_id] = array(

      '#id' => $ajax_element_id,
      '#type' => 'select',
      '#ajax' => $element['#ajax'],
      '#options' => array(0,1),

//      '#prefix' => '<div style="display:none">',
//      '#suffix' => '</div>',
    );

  }

}

```

Then, in Javascript, I trigger a 'change' event on the new (dummy) 'select' whenever the items in the 'multiselect' are altered.

```
  // create a new function that incorporates the old function to add/remove options in multiselect
  $.fn.oldAddOption = $.fn.addOption;
  $.fn.addOption = function(arguments) {
    this.oldAddOption(arguments);

    // find the tag that holds the id of the ajax multiselect element
    var tag_with_id = $(this).parent().parent().find('.multiselect-element-id-holder');
    // find the id of the ajax multiselect element
    var ajax_element_id = tag_with_id.data('ajax-multiselect-element-id');

    $('#'+ajax_element_id).trigger('change');
  }

```

This works for the first #ajax round trip, but after the first #ajax call anywhere on the page, my new (dummy) 'select' elements don't fire the correct #ajax. In my Drupal Recent Logs, I get

```
Undefined index: #ajax in ajax_form_callback()

```

when I use the dummy select elements.

In network activity, I can see that the first #ajax response includes the correct array of commands for the replace action. But, after the first #ajax anywhere on the form, my new 'select' elements only receive a default #ajax settings response with no replace commands.

I think there is something about the way I am building in hook\_form\_alter that is not adding the #ajax property correctly after the first ajax call, but I can't figure out what it is.

# Answer
The problem was relying on the IDs created by drupal\_html\_id() to match after ajax rebuild of the form. I fixed it by having jQuery find the dummy select elements by 'name' attribute.

```
  $.fn.oldAddOption = $.fn.addOption;
  $.fn.addOption = function(arguments) {
    this.oldAddOption(arguments);

    // find the tag that holds the id of the ajax multiselect element
    var tag_with_name = $(this).parent().parent().find('.multiselect-element-name-holder');
    // find the id of the ajax multiselect element
    var ajax_element_name = tag_with_name.data('ajax-multiselect-element-name');

    $('select[name="'+ajax_element_name+'"]').trigger('change');
  }

```

This code now sets unique element names instead of trying to set unique ids:

```
$ajax_element_name = drupal_html_id('ajax-multiselect-element');

// tell jquery where to find the id of the dummy select
$element['#attributes']['class'][] = 'multiselect-element-name-holder';
// transmit the id of the dummy select to jquery
$element['#attributes']['data-ajax-multiselect-element-name'] = $ajax_element_name;

$form[$ajax_element_name] = array(
  '#type' => 'select',
  '#ajax' => $element['#ajax'],
  '#options' => array(0,1),
);

```
> 1 votes

---
Tags: 7, forms
---


# Question
Title: How to change field_tags in hook_form_alter?
I have the field\_tags set to be a select box (not auto-complete). Inside hook\_form\_alter, how can I change the default value of the field\_tags select box? So far, I have:

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

    if($form_id == 'article_node_form'){
      //change default value here
    }

}

```

But I don't know how to access the field\_tags element and then change the default value. Please help! Thanks.

# Answer
The `field_tags` element is likely a widget from the Field API. You can surely alter it from a form alter hook, but be aware that it would not be your average Form API element. The Field API adds post-processor, pre-rendered, etc. functions of its own. These functions may expect things you may want to alter.

You can however, change the default value of the field from the configuration interface of your content type (you need to enable the Field UI module for this). You should also be able to select a different widget (ie. a select box) from there.
> 1 votes

---
Tags: entities, taxonomy-terms
---


# Question
Title: How to reference a content-region block in node template?
Scenario:

I have a basic node content type that has some fields. I also have a custom block that will appear in the content-region of this node content type.

How can I (is it possible) reference the rendering of the block from within the theme node--mycontenttype.tpl.php file?

# Answer
> 1 votes
In Drupal 6, you can do something like this:

```
$block=module_invoke(MODULE_NAME, 'block', 'view', BLOCK_NAME);

```

and now `$block['content']` will contain the html content of BLOCK\_NAME defined within MODULE\_NAME.

I just noticed the -- in your template name, so in Drupal 7 it would be:

```
$block=module_invoke(MODULE_NAME, 'block_view', BLOCK_NAME);

```

and more details can be found here.

---
Tags: 6, theming, blocks
---


# Question
Title: How to handle private file uploads and downloads?
For a project I'm working on, I need to be able to:

* Upload a file as Admin, assigning it to a user (this is working using the "author" field at the moment), attaching it to a node (ie. using the "FileField" field type)
* Store the file in a private directory (not accessible by public users)
* Allow the Admin and "author" users to download the files

We've setup a test project using Drupal 7 with a FileField on a custom content type. The FileField is set to use "Private" uploads.

What seems to happen is that the files are not accessible by their path on the disk (e.g. http://sitename.com/sites/default/files/filename.pdf) but are accessible by the Drupal private file download path (e.g. http://sitename.com/system/files/filename.pdf) - even when users aren't logged in, the private file download path still allows the file to be downloaded.

**What we need to do is:**
Stop users who aren't logged in, and aren't the author or admin of the node, from downloading the file from the private path.

We've already got a hook\_node\_view() in a custom module which stops people looking at the node if they don't have permission (i.e. the $user-\>uid matches the $node-\>uid) - it's just the private file path we need to hook and validate (check the user is accurate).

Any ideas what we're doing wrong?

# Answer
> 4 votes
If the whole node should only be visible to the author, then you should either implement hook\_node\_access() yourself and correctly deny view access or use a content access module (e.g. Content access) to do that for you. Note that hook\_node\_access() won't prevent that now to show up in listings, for that you need a content access module (or implement one on your own).

Alternatively, if you just want to hide the field, you could use the Field permission module and configure it accordingly.

Both ways should be able to to this because it is something that Drupal can check, it can't know that you prevent access in hook\_node\_view().

# Answer
> 0 votes
Either you are missing an .htaccess file in the system/files directory, or .htaccess has been disabled there. Without it, that directory is no different from any other publicly available part of the site.

If it is missing, try creating one containing just the line `Deny from all`.

If such a file does exist, your server configuration is ignoring it.

Personally, I never store private files below the public webroot. If my Drupal site is at `/usr/local/www/mysite`, I'll put the private files in `/usr/local/www/mysite-files` or some such.

See also http://drupal.org/documentation/modules/file .

---
Tags: users, files
---


title: Do Fields Slow Down Drupal

text:
# Question
Title: Do Fields Slow Down Drupal
Whenever I'm trying to edit or create a content type, it always takes quite a while to load the page. Is it because I have too many existing fields and `Node Autotitle` is pulling all of them and slow Drupal down?

# Answer
> 1 votes
If you have Tokens module enabled and also if you have a lot of fields, then it'll take a lot of time for the token ui to load up. This was the problem in my site. It took me a long time to figure this out. If there is a performance hit, only when you try to edit or create a content type then it might be caused by the tokens module. It's worth checking it out.

---
Tags: entities, nodes, performance
---


# Question
Title: How to handle complex redirection requirement?
I have a content type defined with a field storing the URL for accessing an external web resource and am looking for a way to have my Drupal 7 instance manage the redirection to this external site based on the nid contained in the incoming request path (ie. mysite.com/resource/123 redirects to the location stored in field\_data\_field\_url where nid = 123).

The driver for this requirement is that our partner sites need to publish links to these resources that will not be subject to change. Drupal will house the database of resources and I am hoping to provide an endpoint that handles the redirect without further action from the user.

I have begun exploring the Services module in attempting to solve this problem but am not making headway in figuring out how to ultimately perform a redirection. I would appreciate input on whether this is an appropriate case for this web service approach or should I be looking at another way to tackle this problem within the Drupal framework?

# Answer
You could use Services, you dont have to.

1) To have remote resources you need to create a url in drupal to consume data sent to it (Services can indeed do this). eg, `mysite.com/secret/submit-a-resource-location`. You could make this in a custom module with `hook_menu`, it could store values in a table with NID, and RESOURCE\_URL as the columns.

2) If you goto some path on your site like `mysite.com/passthrough/NID` you could look at the NID passed in and in the hook\_menu page\_callback function and use drupal\_goto to go to your remote url.

Eg:

```
function mymodule_menu() {
  $items['secret/submit-a-resource-location'] = array ( /* ... */ );
  $items['passthrough/%'] = array( /* ... */ );
  return $items;
}

function mymodule_passthrough_page_content($arg) {
  $result = db_query("SELECT resource_url FROM {external_resources} er WHERE er.nid = :nid", array(':nid' => $arg))->fetchCol();
  drupal_goto($result['resource_url'], 302);
  // implicit exit here by drupal goto.
}

```
> 0 votes

# Answer
Here is the working code for those interested (accessed via mysite.com/api/redirect/123):

```
/**
* Implements hook_menu()
*/
function resource_redirect_menu() {
  $items['api/redirect'] = array(
    'page callback' => 'resource_redirect',
    'access arguments' => array('access content'),
  );
  return $items;
}

function resource_redirect($arg = 0) {
  $result = db_query("SELECT field_url_url FROM field_data_field_url fd WHERE fd.entity_id = :nid", array(':nid' => $arg))->fetchCol();
  drupal_goto($result[0]);
}

```
> 0 votes

---
Tags: services
---


# Question
Title: Alternative, more secure user registration process wanted
I don't like that Drupal 7 exposes at the registration page whether the provided e-mail is known by displaying a "The e-mail address xx@xx.xx is already registered. Have you forgotten your password?" message.

I would prefer if it only lets the user know that the process has been initialized, and depending on the status of the e-mail it either sends out a normal registration e-mail or a password reset.

What would be the best way (the closest to Drupal's philosophy) to implement such a feature?

Is this a module?

Could it be accomplished by reconfiguring the fields of the user account?

# Answer
> 4 votes
If you want to change the way a user can register on a Drupal site, I would rather implement hook\_menu\_alter() to alter the menu callback called when a user access user/register.

```
function mymodule_menu_alter(&$items) {
  if (isset($items['user/register'])) {
    $items['user/register']['page arguments'] = array('mymodule_register_form');
  }
}

```

If you are going to allow users to enter an email that is already used from another account, then you should alter also the menu callback associated with user/register, as Drupal allows users to reset a password by entering their username or their email address.

```
function mymodule_menu_alter(&$items) {
  if (isset($items['user/register'])) {
    $items['user/register']['page arguments'] = array('mymodule_register_form');
  }
  if (isset($items['user/password'])) {
    $items['user/password']['page arguments'] = array('mymodule_user_pass');
  }
}

```

The functions Drupal uses as form builders for those menus are user\_register\_form(), and user\_pass(). You can use them as guideline for the code you implement.

Keep in mind the following points, though:

* The unique email is necessary because Drupal allows users to request a new password by entering the email associated with their account. This is also helpful for who simply forgot their username, as the email sent from Drupal contains a link that redirects them to their account, where they will eventually change their password (or just enter their previous password to keep it).
* There isn't any security involved, as that doesn't allow a user to know all the emails used in a Drupal site, nor any email matching a partial email address. The users need to enter a complete email, and at that point there is few they can do; even in the case they try resetting a password, Drupal would sent an email to that email address, to which that user needs to have access. If that user can change the password of that email address, or can obtain it, that is not a Drupal security issue, but eventually with how that email address is handled, or who knows the password used for an email address.
If there is a security issue with allowing to use an email address to reset a password, then there would be a security issue even in the case the user is able to enter a username to request a new password, because somebody could find out a username already in use on a Drupal site.
* Allowing to have not unique emails can create problems with modules such as the LoginToboggan module that allows users to log in entering their email address when logging in. There are probably other modules that assume there aren't two user accounts using the same email.
* Enforce unique email addresses for users is a Drupal issue report related to what you are trying to achieve. If this patch is going to be applied, it will be possible to allow users not to have unique emails by setting the user\_mail\_unique Drupal variable.

# Answer
> 3 votes
Yes, you can alter the form and replace the validate and submit functions with your own. You want to alter user\_register\_form(), which uses user\_account\_form\_validate() as the validate and user\_register\_submit() as the submit callbacks.

You have to copy these two functions and then adjust them as you want. Basically, in the validate function, remove the form\_set\_error() and add the same check in submit instead, where you use the functionality of user\_pass\_submit() to send the mail.

# Answer
> 0 votes
I would look at function yourtheme\_form\_user\_register\_form\_alter(&$form, &$form\_state, $form\_id)

and the associated functions.

---
Tags: 7, users, security
---


title: Associating Nodes with Anonymous User

text:
# Question
Title: Associating Nodes with Anonymous User
I created a new content type which anonymous users are allowed to create. However, they can only do so if they are authenticated into Facebook. What is a good way of associating the particular node with the user? Right now Drupal is assigning a uid of 0 to these anonymous users. Is it possible to overwrite that uid with the id of my Facebook login table? How else can i create a relationship?

# Answer
The user ID Drupal uses is contained in the uid field of the {users} table. On that table, the user ID for the anonymous users is 0.

You cannot alter the user ID to be a different value, especially if that value is not even contained in the {users} table. If you alter the user ID associated with a node, you are changing the author of that node.

I don't think it is even possible to associate an anonymous user with a Facebook account. What for Drupal is an anonymous user is not really a single user but a multitude of users that access a Drupal site without logging in; also the Google bot is an anonymous user, and associating it with a Facebook account would not make sense.
> 1 votes

---
Tags: 7, nodes, users, social-network
---


# Question
Title: Imported blogs not showing up under proper tab
In using Acquia/Drupal Commons and the Feeds module, we have successfully pulled in a few WordPress feeds. While the Organic Group is assigned and the newly created feeds appear in the OG's Home tab, they do not show up under the blog tag until I visit each one, click the edit tab, and then click save.

Given that, I assume I haven't mapped something that the `group_tab_blogs` View is searching on.

Additionally, if I copy the Query produced from `group_tab_blogs` live preview, copy it into a mysql client, and run, the results **do** show up. So that leads me to believe that it's something in the view filters.

Current Mapping between Source (Feed node) and Target (Blog node):

Current `group_tab_blogs` settings:

**Update:**

I can fix this by a manual running the query below. Once we set the field `field_group_sticky_value` of from table `content_field_group_sticky` to 'Not Sticky' it is now showing up.

```
 update content_field_group_sticky set field_group_sticky_value='Not Sticky';

```

However, I can't just map target fields Sticky and Group Sticky to just any value. I've already tried Published Date. So now I either need to run the above query on a trigger or adjust the view.

# Answer
Well, that query list above was the key. So I just threw it into a module cron. When feeds are imported on each cron run, this query runs and corrects the null value in the table.

```
function hook_cron() {
      db_query("update content_field_group_sticky set field_group_sticky_value='Not Sticky' where field_group_sticky_value is null");
}

```
> 0 votes

---
Tags: views, organic-groups, feeds, 7, nodes
---


# Question
Title: Taxonomy term missing as type of data to store in new field for content type
I have Drupal 6.2. I added a taxonomy term and I am trying to to add it as a new field to a content type. However, I don't see "taxonomy term" as a "type of data to store" when I try to select a field type.

# Answer
> 0 votes
Use the Content taxonomy module. It provides a CCK field type for referencing taxonomy terms.

# Answer
> 0 votes
Visit the Taxonomy administrative page (admin/content/taxonomy), and click on the "edit vocabulary" link for the vocabulary you want to associate with a content type.

On that page, you find the "Content types" field set that allows you to associate the content type for which a vocabulary should be used.

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


title: Unhelpful error message

text:
# Question
Title: Unhelpful error message
When I try to upload an image to a content type that has an image field, I get this very non-specific error:

`The file could not be uploaded.`

I have checked that the file is within the allowed size constraints, the proper format, and has no spaces or strange characters in the name. Saving the content works fine except for that one field.

I have other fields accepting uploads and images on this and other content types and they work fine.

I have no idea how to troubleshoot this issue. Where do I begin?

# Answer
> 5 votes
That error comes from `file_managed_file_save_upload()` (around line 638 of the core file.module file).

Just before that error is a call to `watchdog()` with a much more descriptive error message:

> The upload directory %directory for the file field !name could not be created or is not accessible. A newly uploaded file could not be saved in this directory as a consequence, and the upload was canceled.

So it looks like it might be a permissions issue (does your web server own the sites/default/files folder?)

In case you haven't come across it before you can see you "Recent log messages" at http://mysite.com/admin/reports/dblog, it's often the best place to look when the front-end messages are unclear.

# Answer
> 1 votes
You should find some more detailed information in the Drupal log. From memory, in Drupal 7, you access this from the Reports menu then choose Recent log messages

---
Tags: media, files
---


# Question
Title: Content region not visible in blocks setup page in Sky Adaptive Theme
I checked the 'content' region, being one of the prerequisite regions and it is present and referenced in the sky.info file as well as in the page.tpl.php.

That is: (in sky.info file)

```
regions[content] = Main content

```

(in page.tpl.php file)

```
        <div id="content"><?php print render($page['content']); ?></div>

```

However, when I go into the 'block' setup GUI page, from the regions dropdown, I can not see the 'content' region option.

Any idea as to why its not visible would be great. Cheers

# Answer
Which version of Sky theme are you using? In 7.x-2.3, I can see the "Main content" region in the drop down list. If you have made custom changes to theme, try clearing the cache.
> 0 votes

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


# Question
Title: If parent feeds (import) node is unpublished, how do I not include it in the import schedule?
If the parent feed imports a node (the form/node to input the feed URL, not the feeds importer) that is unpublished, I'd like to have it (the feed URL) not be included in the cron schedule to update/import the feed items. How is this done? For example, a user submits a feed, but the administrator needs to verify it before publishing, and importing it.

See also Don't import items if parent feed is unpublished.

# Answer
> 1 votes
It looks like, when a node is saved, Feeds module starts importing the feed from that node.

```
function feeds_node_insert($node) {
  // Source attached to node.
  feeds_node_update($node);
  if (isset($node->feeds) && $importer_id = feeds_get_importer_id($node->type)) {
    $source = feeds_source($importer_id, $node->nid);
    // Start import if requested.
    if (feeds_importer($importer_id)->config['import_on_create'] && !isset($node->feeds['suppress_import'])) {
      $source->startImport();
    }
    // Schedule source and importer.
    $source->schedule();
    feeds_importer($importer_id)->schedule();
  }
}

```

There is an option in the importer's setting page called **Import on submission**. If you uncheck this box, hopefully your feed won't be imported. Feeds maintainer still need to make changes in feed\_cron() so that it won't fetch the unpublished nodes.

While you wait for a better fix from module maintainers, you can quickly fix this code by changing the first if statement to add **$node-\>status==1** condition as follows:

```
if ($node->status==1 && isset($node->feeds) && $importer_id = feeds_get_importer_id($node->type))

```

---
Tags: 7, feeds
---


title: drupal files directory

text:
# Question
Title: drupal files directory
I have a Drupal site and I am unsure of how the files directory works.

It seems at the moment all files uploaded to the site go to the files directory. If I create a new node and upload fish.png which goes to the files directory another user also uploading a file called fish.png will overwrite my file.

Have I missed something here???

# Answer
You can see the how to set the file system settings on File system settings. You can also change it, and specify the other folder for the files as per your requirement.
> 1 votes

# Answer
> If I create a new node and upload fish.png which goes to the files directory another user also uploading a file called fish.png will overwrite my file.

The file is renamed, and an number is added to make the filename unique. When an uploaded file is saved, file\_save\_upload() indirectly calls file\_create\_filename(), which contains the following code.

```
  if (file_exists($destination)) {
    // Destination file already exists, generate an alternative.
    $pos = strrpos($basename, '.');
    if ($pos !== FALSE) {
      $name = substr($basename, 0, $pos);
      $ext = substr($basename, $pos);
    }
    else {
      $name = $basename;
      $ext = '';
    }

    $counter = 0;
    do {
      $destination = $directory . $separator . $name . '_' . $counter++ . $ext;
    } while (file_exists($destination));
  }

```
> 0 votes

---
Tags: files
---


# Question
Title: force block module to load admin panel theme
I use diffident themes for admin panel and content pages. when I want to use block module, it loads my content page theme (made by me) and doesn't work correctly.

how can I force block module to display admin panel theme?

or maybe force it to display a specific theme?

# Answer
If what you are asking is if, when you go to `admin/build/block`, is there a way to make drupal use your admin theme instead of your custom theme, then the answer to that question is no, because it needs your theme to figure out what regions are available and what blocks are in them. But it will allow you to pick different active themes so you can put different blocks in different regions in different themes if desired once your custom theme has the needed regions and other logic required to work with the block admin pages.
> 1 votes

---
Tags: 6, blocks, theming
---


# Question
Title: How do I change the capitalization formatting of my Taxonomy terms programatically?
I am using taxonomy terms with the formatting where the first Letter of the phrase (if there is more than one word in the taxonomy) is capitalized, and then the others are not. So, for examples 'Cars and trucks'

In house we have made the decision to change these so that every major word is capitalized, so, 'Cars and Trucks,' excluding minor words like and, it, but, etc - basically the word list that is in the Path auto terms to exclude.

I have thousands of terms. More over, there was a point when the community contributed them so there is no consistency.

Thoughts on how to tackle this without having to edit them one by one?

Thanks

# Answer
It's fairly easy to cobble some (admittedly inefficient) code together that will convert a string to title case while ignoring certain words (you'll have to choose the words yourself though):

```
function _MYMODULE_custom_title_case($string, $blacklist = array()) {
  // Split the words into an array
  $words = explode(' ', $string);

  $new_words = array();
  foreach ($words as $word) {
    // If the word isn't in the blacklist, capitalise it.
    if (!in_array($word, $blacklist)) {
      $word = ucfirst($word);
    }

    $new_words[] = $word;
  }

  // Join the string back up and return it.
  return implode(' ', $new_words);
}

```

Then you can simply load all of the terms in your vocabulary, change the title, and save them:

```
$vid = 1; // Vocabulary ID
$terms = taxonomy_get_tree($vid); // Get the terms

// User the pathauto blacklist
$blacklist = variable_get('pathauto_ignore_words', array());
foreach ($terms as $term) {
  // Update
  $term->name = _MYMODULE_custom_title_case($term->name, $blacklist);

  // And save
  taxonomy_term_save($term);
}

```

I confess to not having tested that so use a bit of caution! If you've got a lot of terms you might want to split it up into batches to avoid hitting a PHP timeout.
> 1 votes

# Answer
The term that you are looking for is title case. I should note that you're going to have to deal with edge cases such as abbreviations etc. For example, USA, U.A.E, usa will very likely all be handled incorrectly. I recommend that you adapt this JavaScript for your needs as it works reasonably well.

I believe that you can *add* revision support to taxonomy term fields. If this is reasonably straightforward to achieve, it might be worth considering to ensure that your script is not destructive. Moreover, revisions will make the handling of the aforementioned edge cases a lot easier.

I'm unsure if the Unitag module handles such functions for user *input*. But it might be worth checking out.
> 0 votes

# Answer
If it is for display only, thus not in your database, use this CSS property:

```
text-transform: capitalize;

```

Works in all browsers.
> 0 votes

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


# Question
Title: Custom widget field only saves first letter, disappears on edit
I'm trying to create a custom module for Drupal 7 that makes two widgets available for Text fields. They autocomplete from a database table using #autocomplete\_path. The autocomplete works fine and when a match is selected it is made the value for the field, but when the node is saved only the first letter from that field is shown. Then when the node is edited, the field comes up blank in the edit form.

Here's my module code:

```
<?php
/**
 * Implements hook_menu().
 */
function autocomplete_jsb_users_menu() {
    $items['jsbu/speaker/autocomplete'] = array(
        'page callback' => 'jsbu_speaker_autocomplete',
        'access callback' => TRUE,
        'weight' => 1,
    );
    $items['jsbu/venue/autocomplete'] = array(
        'page callback' => 'jsbu_venue_autocomplete',
        'access callback' => TRUE,
        'weight' => 2,
    );
    return $items;
}

/**
 * Implements hook_field_widget_info().
 *
 * Two widgets are provided.
 * - A textfield Speaker name autocomplete widget.
 * - A textfield Venue name autocomplete widget.
 */
function autocomplete_jsb_users_field_widget_info() {
    return array(
        'autocomplete_speaker_name' => array(
            'label' => t('Autocomplete Speaker Name'),
            'field types' => array('text'),
        ),
        'autocomplete_venue_name' => array(
            'label' => t('Autocomplete Venue Name'),
            'field types' => array('text'),
        ),
    );
}

/**
 * Implements hook_field_widget_form().
 */
function autocomplete_jsb_users_field_widget_form(&$form, &$form_state, $field, $instance, $langcode, $items, $delta, $element) {
    // set the default text instance
    $element += array(
        '#type' => 'textfield',
        '#size' => $instance['widget']['settings']['size'],
        '#maxlength' => $field['settings']['max_length'],
        '#attributes' => array('class' => array('text-full')),
    );

    if ($instance['widget']['type'] == 'autocomplete_speaker_name') {
        $element['#autocomplete_path' ] = 'jsbu/speaker/autocomplete';
    } else if($instance['widget']['type'] == 'autocomplete_venue_name') {
        $element['#autocomplete_path' ] = 'jsbu/venue/autocomplete';
    }

    return $element;
}

/**
 * Implements the autocomplete_jsbu_speaker() callback.
 */
function jsbu_speaker_autocomplete() {
    $matches = array();

    // Query the database
    $query = db_select('field_data_field_speaker_name', 'sn');

    // Select rows that match the string
    $query
        ->fields('sn', array('field_speaker_name_value'))
        ->orderBy('field_speaker_name_value', 'DESC')
        ->distinct();

    $result = $query->execute();

    // add matches to $matches
    foreach ($result as $row) {
        $matches[$row->field_speaker_name_value] = check_plain($row->field_speaker_name_value);
    }

    // return for JS
    drupal_json_output($matches);
}

/**
 * Implements the autocomplete_jsbu_venue() callback.
 */
function jsbu_venue_autocomplete() {
    $matches = array();

    // Query the database
    $query = db_select('field_data_field_venue_name', 'vn');

    // Select rows that match the string
    $query
        ->fields('vn', array('field_venue_name_value'))
        ->orderBy('field_venue_name_value', 'DESC')
        ->distinct();

    $result = $query->execute();

    // add matches to $matches
    foreach ($result as $row) {
        $matches[$row->field_venue_name_value] = check_plain($row->field_venue_name_value);
    }

    // return for JS
    drupal_json_output($matches);
}

```

Any ideas? Thanks!

# Answer
It may help to just wrap the returned array from the \_field\_widget\_form in yet another array

```
return array('anything' => $element);

```

Worked for me ;)
> 3 votes

---
Tags: 7, entities, ajax
---


# Question
Title: Webform - Mandatory text field depending on select option state
I was hoping to get some direction on how to make a textfield in my webfrom mandatory but only if a particular select option was not checked.

So the textfield is mandatory by default but if the select option is checked, the text filed is no longer mandatory. I have tried to do this via jquery but have then read that validation is server side so I'm not sure what best practice is for this.

Does this type of behavior need custom validation via hook\_form\_alter() - or is there another way to achieve this? I am running Drupal 7.

Thank you in advanced.

# Answer
> 1 votes
I found a module called Webform Validation that lets you achieve this without any custom code.

To accomplish the above, add the 'Require at least one of two fields' validator under 'form validation' and then select both components that you want to validate against.

---
Tags: webforms, forms
---


title: Node delete doesn't delete from DB

text:
# Question
Title: Node delete doesn't delete from DB
I'm trying to delete a node knowing it's nid.

I've implemented hook\_cron in order to do this:

```
function my_module_cron() {
  node_delete(5446);
  print "deleting node 5446";
}

```

The print message it's shown when executing the hook\_cron, so I assume it also executes node\_delete.

But the node it's still there in the website and also in the DB.

Other alternative would be manually deleting the node from the DB using the queries that appear in the node\_delete code

Would this be enough?

Could it broke something doing this manually instead of using node\_delete?

I call the hook\_cron using drush:

```
drush --uri="www.myurl.com" php-eval 'my_module_cron();'

```

# Answer
How is cron being called? (drush, wget, manually run).

node\_delete requires the permission delete to actually execute the delete queries.

Depending on how you run cron will depend on the result, for example if cron is run from wget then it's run as an anonymous user therefore nothing will happen as hopefully anonymous user can't delete content.

If you try calling cron from status report while logged in as uid 1 then it should delete fine.
> 2 votes

---
Tags: 6, nodes
---


title: integrate php login page to drupal

text:
# Question
Title: integrate php login page to drupal
I have a login page in php , I want to convert in drupal in the login page it directly access to the admin, is it possible? If its possible then what is the code for this to convert the user login in login page.

```
<td valign="top" class="rht_td">
    <form method="post" action="">
        <table width="100%" border="0" cellspacing="0" cellpadding="0">
      <tr>
        <td><h3>SIGN IN</h3></td>
      </tr>
      <tr>
        <td>User Name : <span title="This field is required.">*</span></td>
      </tr>
      <tr>
        <td><input type="text" name="uname" class="wid100" /></td>
      </tr>
      <tr>
        <td> </td>
      </tr>
      <tr>
        <td>Password: <span title="This field is required.">*</span></td>
      </tr>
      <tr>
        <td><input type="password" name="password" class="wid100" /></td>
      </tr>
      <tr>
        <td> </td>
      </tr>
      <tr>
        <td><input type="submit" name="button2" id="button2" value="Login" /></td>
      </tr>
    </table></form></td>
  </tr>
</table> </div>
    </div>
    </div>

```

# Answer
Integrating your login page with drupal is not as easy as copy pasting the code. Also creating a new module from scratch to attain your functionality is not worth your time, except as a learning exercise. You should be able to use existing, well-tested modules for what you're trying to do, although you may need to customize them from time to time to match your specific use case. Some modules that can help you in login are :

1. Login Destination \- Redirect users to custom page after login based on their roles.
2. LoginToboggan \- Provides a slick Twitter like login box and several other functionality.

These are very general suggestions but it sounds like you're in the very early stages of your planning; if you have specific questions, you're welcome to post those later.
> 1 votes

---
Tags: 6, hooks
---


# Question
Title: Disable language code in URL for default language
I'm using drupal 7 and i18n module.

I select the user language with the language code in the URL like this: mysite.com/fr/node/1 mysite.com/en/node/1 etc

The default language is French.

How could I manage to get only "mysite.com/node/1" when selected language is French? For now, I only get "mysite.com/fr/node/1". If I go to the root of my website "mysite.com", and I overlay the links, they're all pointing to "mysite.com/fr/...".

Is there anyway I could disable the `/fr/` as the default language?

I tried playing around with the selection's rule weight, without success.

# Answer
Under "admin/config/regional/language" you will see the list of languages. Click the edit link to edit the languages. In the edit screen, change the "Path prefix language code". If French is your default language, then keep this value blank for French.
> 15 votes

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


# Question
Title: In defining a hook_block_info() is it possible to define the region per theme?
I'm trying to avoid this error and it seems I should be able to define the blocks region on a per theme basis. I've checked the API documentation but it's not covered. Has anyone pulled this off yet?

A for instance would be how do I additionally define the `sidebar_first` region in `Bartik` in the following example?

Here is my current `_block_info()`:

```
  $blocks['find_activities_large'] = array(
  'info' => t('Find Activities Widget (large)'),
  'status' => TRUE,
  'theme' => 'MY_CUSTOM_THEME',
  'region' => 'inner_sidebar',
  'weight' => 0,
  'visibility' => BLOCK_VISIBILITY_LISTED,
  'pages' => '<front>',

```

);

# Answer
I can't say for sure but I would be surprised if that works.

You could try to define the region using the Context module and Context Conditional Theme module if you only want certain blocks to show up in certain regions for certain themes. Context module configuration is exportable so you could commit those settings to code.
> 1 votes

# Answer
You can implement hook\_block\_info\_alter(), which gets `$theme` as parameter. The visibility, and the region the hook sets are valid for that specific theme.

As example of implementation, you can look at dashboard\_block\_info\_alter().

```
function dashboard_block_info_alter(&$blocks, $theme, $code_blocks) {
  $admin_theme = variable_get('admin_theme');
  if (($admin_theme && $theme == $admin_theme) || (!$admin_theme && $theme == variable_get('theme_default', 'bartik'))) {
    foreach ($blocks as $module => &$module_blocks) {
      foreach ($module_blocks as $delta => &$block) {
        // Make administrative blocks that are not already in use elsewhere
        // available for the dashboard.
        if (empty($block['status']) && (empty($block['region']) || $block['region'] == BLOCK_REGION_NONE) && !empty($code_blocks[$module][$delta]['properties']['administrative'])) {
          $block['status'] = 1;
          $block['region'] = 'dashboard_inactive';
        }
      }
    }
  }
}

```
> 1 votes

---
Tags: blocks
---


title: Adding validator to a number of fields

text:
# Question
Title: Adding validator to a number of fields
I have a number of fields added to multiple content types. Using the Field validation module takes much time, so I decided to validate them programmatically. Which hook should I use to validate fields?

# Answer
You'll need to add a `hook_form_alter()`, check the form ID matches one of those that you're interested in, then add a validation handler to the form. The validation handler will perform your validation against the form fields. Something like

```
function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  $form_ids = array(
    'article_node_form',
    'page_node_form'
  );

  if (in_array($form_id, $form_ids)) {
    $form['#validate'][] = 'MYMODULE_field_validate_callback';
  }
}

function MYMODULE_field_validate_callback($form, &$form_state) {
  if (empty($form_state['values']['field_x'][LANGUAGE_NONE][0]['value'])) {
    form_set_error('', 'Field X cannot be empty.');
  }
}

```

I don't know of another way to do this as `hook_field_validate()` is only called for the module that implements the field type.
> 2 votes

---
Tags: 7, forms
---


title: Views taxonomy page by content type

text:
# Question
Title: Views taxonomy page by content type
I've got two content types: "job" and "job description".

Both of these types are categorized by using ONE taxonomy vocabulary "category".

I've enabled the default "taxonomy term view" for views.

No when I navigate to the site /category/entertainment (for example) all jobs and job descriptions which are tagged with the category "Entertainment" will be displayed. But I want to extend this view like:

* /category/entertainment/job =\> show all nodes of type "job" with the category Entertainment
* /category/entertainment/job\_description =\> show all nodes of type "job\_description" with the category Entertainment

# Answer
Basically you have to add a second parameter to your views page path so it looks somthing like this: `taxonomy/term/%/%`. The first % will be the category, the second will be the node type.

Now you have to add a contextual filter. Choose the filter "Content: Type". The default filter setting should work fine. You can try rewriting the title under "When value IN URL" to something like `node type %2` to see if the value is correct.

You can test it in the preview at the bottom by setting the parameters to "entertainment/job" or "entertainment/job\_description".
> 2 votes

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