# Question
Title: How can I change the precision in the decimal field of CCK?
I have a decimal field. The field has a minimum precision of 10. Can I change this precision? I need that the numbers allowed have the next format: 19.1, 20.3. In other words that the number be of 2 integers and one decimal.

I select one decimal in the configuration of the decimal field , however the field accepts big numbers. How can I change this, the solution can be with form\_alter.

Thanks.

# Answer
> 0 votes
I don't think this is possible via form alter however I would implement these verifications in a `hook_nodeapi()` to check that your number is between 10 and 99.9 (2 decimals) and a precision of just one digit.
Put this code in a `custom.module`:

```
function mymodule_nodeapi($node, $op, $a3, $a4) {
  if ($op == 'validate') {
    $number = $node->field_mynumber[0]['value'];
    if ($number < 10 || $number > 100) {
      form_set_error('field_mynumber', t('Please select a number between 10 and 99.9.'));
    }
    if (round($number, 1) != $number) {
      form_set_error('field_mynumber', t('Please select a number with a precision of 1 digit.'));
    }
  }
}

```

Of course you can also add a test on `$node->type` to restrict this on some of your content types. PS: answer updated to use D6

# Answer
> 2 votes
yeah, \_node\_validate is a flexible way. an alternative to a custom module, can be use a **Rules** module and integration with **Rules Forms support** module. Also will be useful use a more flexible CCK field, then, this will allow to validate whatever number with the model that you want.

.1. install the modules.

.2. then we need now is indicate to rules in what form must work. You must go to **Rules \> Form events** and enable the option Enable event activation messages on forms. then go to the respective form and click in the **Activate events for.. (the name of the form)**

.3. go to rules and add a new rule and select in the **Event:** the respective event on which you want to evaluate this rule. (to this case **Rules Forms** modules will include the name of your form in the **Rules Forms** section on the **Event** select list.

.4. In a condition of rule add a **numeric comparison** (or whatever other condition that you want, for example a custom php code):

example with numeric comparison:

**field Number 1 (php code):** `$number= $form_state['values']['number'][0]['value']; if ($number < 10 || $number > 100) { echo 1; }`

**Field Comparison:** Equal to

**Field Number 2:** 1

.5. in the action option, of your rule, add an action like a form error message to warn about change the syntax of the number. in **Form element ID** add the ID of the field, for example field\_color (you can review the name in the list of fields CCK of the content/node type).

.6. Create a new rule if is necessary, like `$number= $form_state['values']['number'][0]['value']; if (...) { echo 1; }` and add the respective error message.

do not forget enable the rule, to see working your rule!.

(I hope that this information be useful)

---
Tags: entities
---


# Question
Title: maintain password value after failed login attempt
I'm working on a custom login page for users. I have some special elements on the page, which might cause authentication to fail even though a user enters a valid username and password combination.

After a failed authentication attempt, the username field still keeps the username they entered, but the password field is blank. I would like the password field to keep its value, like the username field does.

I'm starting the form with `user_login()`. I added a check to add in the password:

```
if (isset($form_state['input']['pass']) ) {
// user has submitted the login form once.

 // maintain their entered password
  $form['pass']['#default_value'] = $form_state['input']['pass'];
}

```

Yet it doesn't survive.

How can I re-populate the password field after a failed login?

# Answer
> 4 votes
The password field doesn't use the "#default\_value" property. This means that is not possible to pre fill the field with a default value as it is possible with a textfield field. As it is not possible to set a default value for the field, a password field is always shown empty.

It is what I would expect, especially when a validation handler returns an error for the entered password. If the password is wrong, I don't see any reason to pre fill the field with what previously entered, considering that what the user sees is something similar to "•••••" (or a group of asterisks).

# Answer
> 0 votes
IMO it should be:

```
$form_state['values']['pass']

```

# Answer
> 0 votes
Anything goes, even though #default\_value is really not supported for the password element.

To make it work you'll have to override the default `<input type="password">` theming. Then, use hook\_form\_alter to pass the value from `$form_state` back to `$form`.

I got it to work on my side with code like this:

```
sites/all/themes/YOUR_THEME/template.php:

function YOUR_THEME_theme($existing, $type, $theme, $path) {
  return array(
    'password' => array(
      'variables' => array('element' => NULL)
    )
  );
}

function YOUR_THEME_password($element) {
  $size = $element['#size'] ? ' size="'. $element['#size'] .'" ' : '';
  $maxlength = $element['#maxlength'] ? ' maxlength="'. $element['#maxlength'] .'" ' : '';
  $default_value = $element['#default_value'] ? ' value="'. $element['#default_value'] .'" ' : '';

  _form_set_class($element, array('form-text'));
  $output = '<input type="password" name="'. $element['#name'] .'" id="'. $element['#id'] .'" '. $default_value . $maxlength . $size . drupal_attributes($element['#attributes']) .' />';
  return theme('form_element', $element, $output);
}

sites/all/modules/YOUR_MODULE/YOUR_MODULE.module:

function YOUR_MODULE_form_user_login_alter(&$form, &$form_state) {
  $form['pass']['#default_value'] = $form_state['post']['pass'];
}

```

Now I'm not quite sure about the last one, though. I was expecting `$form_state['values']` like IMO suggested, but I only have `$form_state['post']`. While that works, somebody may want to clarify.

---
Tags: forms, users
---


# Question
Title: Form select option results in "Illegal Choice has been detected"
I have a form where a user picks a date for their submission(s) to appear on the website. I am populating a 'date' field like so:

```
function mymodule_get_date_options($type = 'start') {
  $options = array();

  $start_week = time();

  if (date('w', $start_week) == 3) {
    $start_week = strtotime('+1 week', $start_week);
  }

  while (date('w', $start_week) != 3) {
    $start_week = strtotime('+1 day', $start_week);
  }

  if ($type == 'end') {
    $start_week = strtotime('+1 week', $start_week);
  }

  for ($x = 0; $x < 24; $x++) {
    $options[date('U', $start_week)] = date('M d, Y', $start_week);
    $start_week = strtotime('+1 week', $start_week);
  }

  return $options;
}

```

And the element:

```
$form['start_date'] = array(
    '#title' => t('Start Date'),
    '#type' => 'select',
    '#options' => mymodule_get_date_options('start'),
    '#default_value' => $mymodule_form_object->start_date,
  );

```

The generated HTML:

```
// a chunk of the option elements
<option value="1313615248">Aug 17, 2011</option>
<option value="1314220048">Aug 24, 2011</option>
<option value="1314824848">Aug 31, 2011</option>
<option value="1315429648">Sep 07, 2011</option>
<option value="1316034448">Sep 14, 2011</option>
<option value="1316639248">Sep 21, 2011</option>
<option value="1317244048">Sep 28, 2011</option>
<option value="1317848848">Oct 05, 2011</option>
<option value="1318453648">Oct 12, 2011</option>

```

So, everything looks okay, except when the form is submitted it says 'An Illegal Choice has been detected" with the date selects highlighted.

# Answer
That's because the form gets generated both upon output and submission, and you're using form values that are time-dependent. When you first output the form it generates options like this:

```
1313615248
1314220048
1314824848
1315429648

```

And when a user submits the form, it will generate new values, with a few second difference:

```
1313615268
1314220068
1314824868
1315429668
(+20 second difference)

```

So none of the previous options are present here. Drupal's validator by default checks if the submitted option is among generated options.
> 6 votes

---
Tags: 7, forms
---


title: IMCE image upload and permissions issue

text:
# Question
Title: IMCE image upload and permissions issue
I've implemented the IMCE module and added it to the CKEditor. When we upload files though, the resized images come out fine, but the uploaded file itself is saved in the same directory with incorrect file permissions, which causes the file to not be viewable in the browser.

Upon inspection, the uploaded file has no effective permissions for the IUSR account, but the resized images have the needed permissions for IUSR.

Does anyone know how I can resolve this issue?

We are running IIS7 with Drupal 6.

# Answer
The real issue is file permissions. When PHP uploads a file, it saves it in the temp directory. When that file then gets moved it retains the file permissions from the temp directory and does not inherit the destination folder permissions.

So check folder permissions of both your temp folder and the destination folder.
> 2 votes

---
Tags: 6, media, wysiwyg, files
---


title: Confused about installing Apache Solr

text:
# Question
Title: Confused about installing Apache Solr
This is pretty embarrassing but I gotta start somewhere, right? This concerns about installing Apache Solr.

I've seen the instructions when trying to install *Apache Solr* and each one starts off with installing Java. I'm confused since I'm using Bluehost for webhosting (http://drupal.org/hosting). Does that mean I need to install Java on my server? There's also the thing about the terminal but I've never seen the terminal in my hosting's Cpanel. Help.

**Edit**: By terminal does that mean *SSH?* Because I can have that enabled in cPanel. It would be nice if there were a simple tutorial for cPanel's users like me. :-)

# Answer
> 1 votes
Yet that's true. If you want to use apachesolr for your own you have to run a java server.

Alternative there are some services which you can pay to host apachesolr for you. Some examples:

* acquia
* drupalconcept

---
Tags: 7, search
---


title: Clearing theme cache

text:
# Question
Title: Clearing theme cache
I added new code to the template.php and tried clearing the cache but it does not seem like the cache is being cleared. I tried the Admin -\>settings-\>performance and drush (not sure if I installed it properly). Would there be any suggestions?

Drupal 6.

# Answer
> 4 votes
What's the new code that you've added to the template.php file? When I run into problems like this, in the 95% of cases I make a mistake and the cache clearing works, but my new code won't be recognized because of errors.

Basically, if you're able to run

```
drush cc all

```

without any warnings or errors, the cache clearing succeed and it should tell you that

```
'all' cache was cleared [success]

```

---
Tags: caching
---


# Question
Title: nginx sets content-type text/html on redirect
I set up nginx as a reverse proxy for Drupal. Static files are served from a different domain. It works well, imagecache files are generated well, too. But the problem is: when the derivated image does not exist, the request for this image returns a redirect with the content-type:text/html, and Facebook or jQueryMobile (only when running in an iPhone, not in desktop browser) does not like it.

The context: when a file is requested from mycdn.com, if it does not exist, it is redirect to mysite.com which is a site that does the reverse proxy. So, it can be seen that imagecache does nothing here, just a use case. The question here: why nginx adds a text/html when it does a redirect?

Here is the scenario:

```
GET http://mycdn.com/sites/default/files/imagecache/gallery/myfile.jpg

Server  nginx
Date    Tue, 26 Jul 2011 05:28:09 GMT
Content-Type    text/html
Content-Length  154
Connection  keep-alive
Location    http://mysite.com/sites/default/files/imagecache/gallery/myfile.jpg
Expires Thu, 25 Aug 2011 05:28:09 GMT
Cache-Control   max-age=2592000

```

then the result of the redirect

```
GET http://mysite.com/sites/default/files/imagecache/gallery/myfile.jpg
Server  nginx
Date    Tue, 26 Jul 2011 05:28:10 GMT
Content-Type    image/jpeg
Connection  keep-alive
X-Powered-By    PHP/5.2.17
Expires Tue, 09 Aug 2011 05:28:10 GMT
Cache-Control   max-age=1209600, private, must-revalidate
Etag    "58a657c2ee47424f202387000c191b7e"
Set-Cookie  DRUPAL_UID=64; expires=Thu, 18-Aug-2011 09:01:29 GMT; path=/; domain=.thongtincongnghe.com
Vary    Cookie,Accept-Encoding,User-Agent
Last-Modified   Tue, 26 Jul 2011 05:28:10 GMT
Content-Encoding    gzip
Content-Length  1400

```

nginx configuration on mycdn.com (I removed unrelated info):

```
server {
    listen       80;
    server_name mycdn.com;
    root   /home/ttcn/public_html;
    expires 30d;

    location / {
        try_files $uri @redirect;
    }

    location @redirect {
        rewrite ^(.*)$ http://mysite.com$1;
    }
}

```

Brief, with a desktop browser, there is no difference. Everything works flawlessly. But jQueryMobile on a mobile does not work (until the derivated image is generated, through a desktop browsing), Facebook OpenGraph does not work (I put the derivated image url in the og:image value) - it does not take that image until it exists on the server.

# Answer
> 3 votes
There is nothing wrong with the redirect having a content type of `text/html`. On the contrary, it is actually mandated by the HTTP/1.1 specification itself:

> The temporary URI SHOULD be given by the Location field in the response. Unless the request method was HEAD, the entity of the response SHOULD contain a short hypertext note with a hyperlink to the new URI(s).

The cache control header might be confusing Webkit mobile. Have you tried add `expires off;` inside the `location @redirect` block?

---
Tags: nodes, redirection
---


# Question
Title: Show clrcle overlay instead of marker in google map?
I'm using gmap module on Drupal 6. I create a view and select gmap as style for my display. Everything works fine but the map shows a Marker and I need to show a circle overlay instead of the marker so that the map hide the exact address location.

I tried all setting within gmap module but...nope.

Where is the right place for this setting?

Thanks

# Answer
> 2 votes
The view settings should allow you to choose the marker style. Don't have the module installed to check but a comment on the "Provide Gmap marker field for use in Views listing" feature request illustrates how I remember it:

> Under style: GMap in your view try clicking on the setting icon next to where it says GMap. An option box should appear below the view with some options:
>
> * Marker handling: By content type (for node views)
> * By term (for node views)
> * Use single marker type

---
Tags: google-maps
---


title: Force block page to use admin theme?

text:
# Question
Title: Force block page to use admin theme?
I'm trying to use this snippet I found, but it throws this error:

```
function mytheme_init() {
  // Hardcode the administration theme onto the blocks page
  if ($_GET['q'] == 'admin/build/block') {
    global $theme;
    $theme = 'rubik';
  }
}

```

Fatal error: Unsupported operand types in /var/www/clients/client4/web39/web/modules/block/block.admin.inc on line 39

The $theme = 'rubik'; line appears to be the culprit in some way, as it doesn't throw the error if I comment it.

# Answer
> 3 votes
You have to use the global variable `$custom_theme`.
The implementation of your `hook_init()` is good.

# Answer
> 2 votes
There is a good module for this: Administration theme.

> Drupal allows you to define a different theme for administration pages (Administer -\> Site configuration -\> Administration theme). By default this only applies to pages with a path starting with 'admin' and content editing pages.
> The Administration theme module allows you to use this theme on more pages like:
>
> * batch processing pages
> * devel node load and render pages
> * coder code review pages
> * pages you define yourself in the provided textarea

---
Tags: 6, theming
---


title: table component for webform

text:
# Question
Title: table component for webform
is there any module to add "table component" to webform? I want to have a button to add a row to that table.it means that the rows count not limited and is added number of user want.

sorry,my English not good ;)

# Answer
There's now a table component module for webform, take a look to it.
> 2 votes

---
Tags: 6, entities, webforms
---


# Question
Title: In a custom module how do I get all the nodes of a certain type?
Do I just do a direct `db_query()` on node/node\_revision, or is there a function?

# Answer
> 5 votes
You use `db_query()` to get the node IDs for all the nodes of a content type, and then node\_load() to load the single nodes one by one.

```
$query = db_query("SELECT nid FROM {node} WHERE type = '%s'", $type);

while ($result = db_fetch_object($query)) {
  $node = node_load($result->nid);
  // Use $node or store it in an array;
}

```

As the query is fetching a single field, `db_fetch_object()` could probably be replaced with db\_result(); I have never checked if it works for all the database engines, and I didn't find a Drupal core module that uses `db_result()` in a loop (e.g., `while ($nid = db_result($query))`).

The reason you should use `node_load()` is that:

* It allows the module that define the content type for the loaded node, and third-party modules to add extra fields in the node object. This is because the function uses the following code:

```
// Call the node specific callback (if any) and piggy-back the
// results to the node or overwrite some values.
if ($extra = node_invoke($node, 'load')) {
  foreach ($extra as $key => $value) {
    $node->$key = $value;
  }
}

if ($extra = node_invoke_nodeapi($node, 'load')) {
  foreach ($extra as $key => $value) {
    $node->$key = $value;
  }
}

```
* It loads the correct node revision, when revisions are enabled for the content type.
* It caches the result; if two calls to the functions are requiring the same node, the function simply return the previous result. This happens if the call to the function doesn't require a specific revision of the module, and if the last parameter passed to the function (`$reset`) is not equal to `TRUE`.

If you are interested to get only the node ID, then the call to `db_query()` is sufficient.

In Drupal 7, there is a class that allows to load multiple entities (Drupal 7 nodes are entities) that match some criteria in once: EntityFieldQuery.

# Answer
> 3 votes
You do a query with `db_query()`

```
db_query("SELECT nid FROM {node} WHERE type = 'type';");

```

---
Tags: nodes, database
---


# Question
Title: How do I add Google +1 to Addthis Button?
I am using the Addthis Module version 6.x-3.0-beta2, the problem is that google +1 doesn't appear as one of the services. Anyone knows how to fix this ? Thanks !

# Answer
There is a tutorial http://www.addthis.com/features/google-plus1-button

Anyway, +1 is not a sharing service, I'm not sure that Addthis will add this (like there is no Facebook Like button). You can use the Customize service that addthis.module supports to add code described here.
> 1 votes

---
Tags: 7
---


title: Conditionally switch jquery version

text:
# Question
Title: Conditionally switch jquery version
In order to get a necessary jQuery plugin to work I had to upgrade my jQuery version to 1.4.

To do this I installed jquery\_update and manually put 1.4 in the module directory.

That's working just fine for the public facing side of my site, but now various AHAH elements (like Views UI or FileField uploads) no longer work on the admin side.

I'd like to use Drupal's jQuery for admin/edit pages, and jquery\_update's jQuery for everything else. What's the *least* hacky way of doing this? Or is there a totally different solution for this?

# Answer
I had to do this recently also. Revert your jquery\_update to 1.3.2 (or whatever it provides by default) and follow the instructions at http://drupal.org/node/1058168.

They key is to notice that you load the newer version of jQuery **before** the `<?php print $scripts; ?>` in your page.tpl.php.

The final thing you need to do, which is not mentioned there, is to load your jquery plugin in between the new jQuery and the `jQuery.noConflict()`. This will make it so you don't have to modify the plugin (That pages tells you how to modify the plugin if you can't do this final step).
> 2 votes

# Answer
You can still use jQuery Update if you want, you just need to apply the patch outlined in http://drupal.org/node/775924#comment-3010750. When you do this, you can also change the version of jQuery that is loaded for non-admin pages, or even use a variable\_get.

This solution also plays nicely with Javascript Aggregator.
> 0 votes

---
Tags: 6, javascript
---


# Question
Title: importing XML file to create/update nodes, relation nodes/users, and taxonomy terms (to several vocabularies)
Thanks for take time to read this question.

I want to import a XML file. XML content will create/update: nodes, relations nodes/users, and taxonomy terms (to several vocabularies) and his relation with nodes. I want to know, if is possible, your experiences and suggestions about this kind of requirements, or modules to resolve this, or if is best a custom code.

thanks in advance.

# Answer
@rocketeerbkw's answer is good, but personally I find that a custom import script is the way to go. The source for the Wordpress Import module is a good starting point for how to do things, and there are lots of other articles on the web about creating nodes with code.

Based on experience doing this on several projects, I find that I get things done quicker with a custom import script, and that I can fine tune things better.

Make sure you also install Backup and Migrate so you can quickly backup/restore your database as you work on the data import.
> 2 votes

# Answer
The migrate and migrate extras modules are your best friend for this (for Drupal 6 and 7).

The downside is all configuration is done in PHP Classes so you must have a reasonable amount of knowledge about them.

The upside is the documentation. The migrate module comes with an excellent example module that has examples for importing taxonomy, users, nodes + comments, files and roles from a SQL database and XML (it can also import from CSV, JSON and more but is not part of example module)

If you're looking for a nice UI to handle all this, migrate is not for you. You won't find anything else as flexible and full featured though.
> 2 votes

---
Tags: nodes, users, taxonomy-terms, importing-exporting
---


title: How get path between two point on map?

text:
# Question
Title: How get path between two point on map?
I want to use an API that gives me the path between two points. I know the value of latitude and longitude.

How do I get path, latitude and longitude of points of in between path?

# Answer
I believe you can use the Google Maps Directions API, although I don't know any Drupal module that handles this API out of the box.
> 1 votes

---
Tags: 7
---


# Question
Title: How to send an email to the node author when a date is approaching?
The user has created a node and has set a future date to be alerted of the approach of this date.

I want the user receive an email when the set date is approaching.

Making the user able to change the approaching time would be great. Any sugestions?

# Answer
> 4 votes
Have you tested Rules, this is the module to do such actions based on events.
Here is a tutorial to help you with this: Publish content based on a CCK date field.

Also don't forget to enable the debugging feature of rules under `admin/rules/settings`.

---
Tags: 6, datetime, emails
---


title: Cleaning up the node edit URL

text:
# Question
Title: Cleaning up the node edit URL
Say I have node/111/edit, and that node's path is my-node. I want the edit page to be at my-node/edit, instead of node/nid/edit.

Is there an existing solution for cleaning up the node edit URL, e.g. a custom module or the Pathauto module? All I see for the Pathauto module is a place for page patterns, but that would only handle page views, not edits.

# Answer
> 7 votes
This issue in pathauto Replacing node/XXX/edit to mypage/edit lead to this module: Sub-path URL Aliases give it a shot.

> The Drupal Path module matches only full URLs when creating SEO-friendly aliases. This module extends that behavior by also matching known sub-paths and replacing them with their respective alias. For example, if node/1 is aliased to content/alias, this module rewrites the link to the node edit page node/1/edit to use the aliased URL content/alias/edit instead. This also includes Views URLs taking a node as argument (node/%/yourview), in short, every URL that is based on, or extends, an existing alias. In combination with the Pathauto module it is possible to get rid of all remaining exposed internal URLs.

---
Tags: 7, path-aliases
---


# Question
Title: A view only shows if a certain filter criteria does not exist?
I have a view that I am using to list events, specifically "today's events." I used a filter criteria to allow me to only display events that were happening "today" (as asked by an earlier question. I have recently realized that there will not necessarily be an event "Today", and if there isn't, I have a problem, because nothing is displaying. what I want is to have either a separate view (or do it in the current view if it is possible) that only displays if there are no events "today" what I want it to display instead is "upcoming events." that way, if there are no events on the day that you are looking at the site, than ou will see future events instead.

# Answer
Under the advanced tab you can define "No Results Behavior". This will allow you to add a view or html instead. This will be in the same view.
> 3 votes

---
Tags: 7, views, datetime
---


title: how to update a module-defined view?

text:
# Question
Title: how to update a module-defined view?
In D6, I have a custom module that I've developed. It has a view.

I've made some changes to the view in the module code, and I wanted those changes to go live on the site. I've clear the cache, but I don't see my changes. What should I do, disable, revert, delete?

# Answer
1 - if its a default view, you should not be able to delete it. You should only have the option to *Enable* or *Disable* it. If the enabled view is alter then you only have the option to *Revert*.

2 - An unaltered default views are not stored in the views\_view table of the database (however they are stored in the cache\_views table). If you alter the view, they are *now* stored in the views\_view table.

So, if you have a unaltered default view and you make changes to it in the code, then the changes will be visible once you clear the cache. If you have an alter default view, you must revert it for it to match the code in your module.
> 1 votes

---
Tags: views, 7
---


# Question
Title: Ubercart - Manual Credit Card Processing
This has ALWAYS been the reason why I haven't used Ubercart...the lack of a module that allows for offline (manual) credit card information.

It has been a few years now since I looked last and I am wondering if this is STILL not an option with Ubercart. I did some searches and it still looks like there is nothing.

Anyone?

# Answer
> 4 votes
I believe this is more of a workflow question than, a lack of module(s) question. You can setup Ubercart so that you accept an order without accepting a payment. You can set the status of the order as non-processed. You then process their payment manually (via phone, online, inperson, etc), then, manually, change the status of their order to process.

---
Tags: ubercart
---


# Question
Title: Set a different home page for each role?
The Front Page module only appears to work with anon\auth users and I need it for other roles. Any ideas on how to accomplish this?

# Answer
Ok nevermind, the Front Page description is poor. It apparently does possess the functionality I need.
> 0 votes

# Answer
I haven't tried this exact scenario, but I just did a quick check user roles and permissions are options in the selection rule when making pages with the Panels module.
> 1 votes

---
Tags: 6, users
---


# Question
Title: How to add radio button in drupal profile page
I want to get more info from my users when they register. With the standard profile.module I have the following options:

* single-line textfield
* multi-line textfield
* checkbox
* list selection
* freeform list
* URL
* date

But I want radio buttons to select 1 option from multiple options. This can be done with list selection, but I prefer radio buttons.

Can anyone help me with this?

# Answer
> 5 votes
By using the Profile Checkboxes module, you can be able to add radio buttons in the Drupal profile page.

1. Download the Profile Checkboxes module, and install it.
2. If you need to create a radio buttons field, click "List selection" in "Add new field."
3. In that page, you will find the "Selection options" option with a text area field. Enter the radio button details here. For example, if you are adding the gender, enter "Male" and in next line enter "Female."
4. Now, at the bottom of the page you will find the "Profile checkboxes" tab.
5. There you select the "Radio buttons (single choice)" and save.

# Answer
> 2 votes
If you really want to customise the user profile / registration pages I recommend using the Content Profile module. Some more details about it (from its project page):

> This module builds user profiles as content (aka nodes), which opens the opportunity to use all the powerful modules for content for user profiles too, e.g. the Content Construction Kit (CCK). It's intended to be simple and useful, but extensible by further modules.
>
> Content profiles can be restricted to certain roles; the module also supports separate content profiles for different roles.

It allows you to use CCK fields on both user profiles and registration pages. You can use Radio boxes easily along with all the other great features provided by CCK.

# Answer
> 2 votes
In Drupal 7 you must enable the Option module, which is a separate core module that will enable these fields. It's a change in the way things were done in drupal 6.

---
Tags: 7, users
---


# Question
Title: IMCE: Prevent deletion if file is in use
Does any one know of a way to prevent a file from being deleted through IMCE if the file is in use? I saw this feature requested http://drupal.org/node/628246 and there is a comment to state that this feature is already in dev but I'm not finding that this is the case.

# Answer
I'm not familiar with IMCE but Drupal core provides a file\_usage table that is for locking/unlocking files. These are the functions used to interact with it:

```
file_usage_add()
file_usage_delete()
file_usage_list()

```

Drupal's file\_delete() then checks the usage table before deleting a file.
> 1 votes

---
Tags: 7, files
---


# Question
Title: Set URL Fragment based on which Vertical Tab clicked?
Would it be possible for me to have the URL of a given page change depending on what Vertical Tab the user clicks on the page?

For example, when a user is on a complex node form on my site, there are many tabs, each one providing a separate group of information about the node. I'd like for the user to be able to click on a link inside one of the fieldsets, and be able to click the back button to jump straight back into the fieldset he was viewing previously.

Right now, since the fragment isn't in the URL, the user is always brought back to the first vertical tab, regardless of which was open when a link was opened.

If I manually enter the fragment of the #id of the vertical tab that should be opened (like `example.com/node/200/edit#my-vertical-tab-id`), that works. Is there a simple way to make it so that when a user clicks on a vertical tab, it's anchor fragment is appended to the end of the URL?

# Answer
> 1 votes
You could use JavaScript to change the URL fragment each time a tab is opened (click listener on the tab changes the fragment to that tab's ID). But that would only allow the user to go back and have whatever the last tab they opened before following a link remain open.

If you want to save the state of many opened/closed vertical tabs I can't think of a solution that doesn't involve reading/writing constantly to a DB. Maybe you could get away with using cookies instead? Either way its gonna be messy.

---
Tags: javascript, forms
---


# Question
Title: Is it possible to filter content  displayed by the  Views module using a regular expression?
Is there a way to filter content displayed by Views 3 using a regular expression?

I have a large list (10K items) of content of a custom type on my site and I want to create preset views for my users. The default views filter is not selective enough. I need to select with a regular expression such as /M \[0-9\]\[0-9\]?\[0-9\]?/ in one of the fields.

Is this possible in some other way, not using a regular expression?

I'm using Drupal 7. Thanks!

# Answer
Set up a `Contextual Filter` (previously know as `Arguments` in D6), they're hiding under the "Advanced" menu of you view. There you can put some PHP code to return a list of arguments.

Here is an example from one of my views, my PHP code return ID for a field regarding the roles of a user, it returns a string separated by "+" like `1+2+3` which is the separator for "OR" so I can select various node which have these values in this field.

This is the configuration to provide multiple arguments.
> 1 votes

---
Tags: views
---


# Question
Title: User organic groups for paid elearning courses?
I don't know very much about the Organic Groups module.

I have a client that is interested in a course learning system and have that content restricted by groups. Each paid user would checkout and purchase this course.

Would organic groups be good for this particular feature?

# Answer
You can set Organic Groups to be visible only to users of certain roles. And with the uc\_roles module in Ubercart, you can create products which grant users a certain role.

There's also a module that makes it possible to sell Organic Group membership to one or more groups when a user purchases a particular product: UC OG Subscribe

Depending on what exactly the course learning system would be about, the og could be a good fit. Even without it, though, you can always restrict access to content through core roles, or ACL and the likes.
> 1 votes

---
Tags: organic-groups
---


# Question
Title: How do I add a field to a view that shows the user that published the node?
I am using Drupal 6.22 and the module Revisioning to create an approval process for the creation of new nodes. An "Author" user role can create the initial draft of the content and the "Moderator" user role must sign in to review and approve. Once a Moderator approves the content, they may publish it.

Revisioning does not allow an easy mechanism to display the particular user (of user role "Moderator") that published the content. According to this issue, the maintainer of the module will not build that feature: http://drupal.org/node/611586

I am attempting to create this feature myself. I have installed and configured the Workflow module, as referenced in the thread above. Each node now has a "Workflow" tab that shows the history of the Workflow states and it is possible there to see the username of the user that published the node (along with all other state changes, which my client does not care about). I have not been able to find a way to pull this information into a View field in order to display it in a View.

Is this possible?

I am happy to provide any additional information that may be useful in providing a solution. Thanks!

# Answer
> 2 votes
You may want to have a look at the `revisioning_content_summary` view which comes with the Revisioning module. You'll find it at `admin/build/views/edit/revisioning_content_summary`.

It lists both the *User: Name* for the author and the *Node: Last edited by* for the moderator -- the information used in the *Revisions* tab, too.

Additionaly, have a look at creating views of type *Node revision*, which enable you to list all revisions of nodes, along with the revisioning information.

---
Tags: views, workflows, nodes
---


# Question
Title: Making a username/password syncronization scheme - D7
I need to register my users to a 3rd party service upon registration in Drupal. I have toyed around a bit with hooks, and tried to catch the password upon registration so I can insert it into another database, but to no avail. The 3rd party DB encrypts the password in a different way, so I need to get the users password in clear text, crypt it and then save it to the database.

Can anyone give me some pointers to where I should look? `hook_user_insert (&$edit, $account, $category)`, both `$edit` and `$account` contains the users encrypted drupal passwords.

# Answer
> 4 votes
When a form is submitted, its values are validated by the functions listed in `$form['#validate']` then processed by the functions in `$form['#submit']`. If there is no `$form['#validate']`, then the function `FORM_NAME_validate` will run (if any). Same for submit.

See user\_register\_submit. The plain text password is in `$form_state['values']['pass']`. Write a hook\_form\_alter and add a new submit function to `$form['#submit']`. Declare that function and put the logic you need in it.

---
Tags: database, users
---


# Question
Title: Link a Drupal 7 site with a Facebook account
I would like to know if there is a Facebook App that can automatically post content from the feed generated by a Drupal 7 site to one's Facebook Wall. I would like something that does what My Blog Posts Facebook App promises to do but more efficiently (since that works only by manually refreshing the state).

Thanks a lot !

# Answer
> 4 votes
You might want to check out Drupal for Facebook.

A quote from the project page: `If you already have content in Drupal, you can expose it on Facebook.`

Documentation can be found on http://drupal.org/node/195035

# Answer
> 1 votes
Even an easier method could be using the RSS feed of your website and the Notes application in your Facebook page. Notes can publish RSS feed items automaticly.

# Answer
> 1 votes
Try the RSS Graffiti application in facebook.

---
Tags: 7, feeds, social-network
---


title: Timezone Dropdown List in User Account

text:
# Question
Title: Timezone Dropdown List in User Account
Doe anyone know how to change the timezone dropdown list in the user account/registration? So which file is the menu/settings located in? (Assuming I am using Garland theme if that matters, and the variables will still be stored as a string, ie America/Chicago). Alternatively, how to change the user registration/account settings page so I can key in my own dropdown form.

Thanks!

\[The reason is that it is quite difficult to find some locations in the US on it (It would make sense to make the American cities easier to find in their own section rather than in a collective North & South & Central America). So I want to be able to set in some choices manually or at least make it more intuitive (such as sorting by GMT +/-, I understand the issues with timezone, unix time, etc ...meaning they depend on the political area and jurisdiction, along with DST in some states and not so in others, ie Indiana, Arizona etc...)\]

I was thinking of changing the format to this:

'America/Denver' =\> '(GMT-07:00) Mountain Time (US & Canada)', 'America/Chihuahua' =\> '(GMT-07:00) Mexico/Chihuahua', 'America/Phoenix' =\> '(GMT-07:00) USA/Arizona', 'America/Regina' =\> '(GMT-06:00) Canada/Saskatchewan', 'America/Tegucigalpa' =\> '(GMT-06:00) Central America', 'America/Chicago' =\> '(GMT-06:00) Central Time (US & Canada)',

# Answer
> 2 votes
User register forms are built by the User module, but the timezone widget is added by the Locale module through locale\_form\_alter() (an implementation of `hook_form_alter()`).

The Drupal community suggests leaving the core files alone (see Do not hack core). If you want to change the form, just write your own implementation of `hook_form_alter()`, and add/edit the available values using the form API and the "select" form field.

There is a nice tutorial at Brenda Boggs blog.

# Answer
> 0 votes
You can not configure those options in menu management interface. System module alter the user editing form: http://api.drupal.org/api/drupal/modules--system--system.module/function/system\_form\_user\_profile\_form\_alter/7 \> then add timezone widget, options returned by this function system\_time\_zones().

---
Tags: datetime
---


# Question
Title: Module for requiring some authors' texts to be approved by admin
I am developing a site for a client that wishes to have two levels of content administrators, editor and admin. The editor is supposed to be able to edit their own content but an admin has to approve it before it is published. All content is versioned on the site so one version would be displayed to the site visitor while a newer version is in review mode. Once it is approved by an admin it can be published.

Is there any module available for this kind of setup?

# Answer
I suggest the Workbench module. You will need to dig deeper to have a revision show up while the next one is being moderated, but I'm sure it can be done with hook\_menu\_alter.
> 3 votes

---
Tags: 7
---


# Question
Title: Taxonomy Menu Associated with a single content type
I have a single Taxonomy used for all Content Types in the site. I have one Content Type called "Books" for which I'd like to build a Taxonomy Menu for just this content type. As I looked through Taxonomy Menu for Drupal 6, I saw a note that indicated it had some association with views.

Is it possible to use a view to let Taxonomy Menu build a view of terms from with the count of "Books" in each?

# Answer
Please take a look at https://drupal.org/project/views\_groupby. You should be able to:

* Create a new view that has a filter of 'books' content type
* Add a filter to ensure the node is published
* Add a views group by to group on taxonomy term
* Use the SQL count funtion built into views group by

Hope this helps
> 0 votes

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


title: How should I use hook_init()?

text:
# Question
Title: How should I use hook_init()?
I'm trying to disable the LabJS module from running on certain pages by following the maintainers instructions at Compatibility issue with Slickgrid.

This is what I have, so far. I tried putting it directly in the page and my themes template.php with the theme's name appended to the function name, but neither work.

```
/**
 * Disable LabJS on certain pages
 */
function versatile_hook_init() {
  if (current_path() == "private/members/search") {
    define('LABJS_DISABLE', TRUE);
  }
}

```

Can you help pointing me in the right direction?

# Answer
> 7 votes
`hook_init()` must be implemented in a custom module. In your example, the function `mymodule_init()` would go into a file named mymodule.module in a custom module named *mymodule*. You would also supply a simple mymodule.info file and put both files in the sites/sitename/modules/mymodule directory.

The custom module must be enabled like any other. Also, when creating a hook implementation, it is usually necessary to clear the cache for Drupal to recognize it. Finally, note that *mymodule* needs to be a unique name different from other modules or themes.

As a minor usage point, current\_path() returns the current URL which may not be the current alias (e.g., node/5). Using drupal\_get\_path\_alias() is recommended to always return a friendly alias.

---
Tags: hooks
---


title: Drupal path prefix based node content

text:
# Question
Title: Drupal path prefix based node content
I'm new to Drupal and have a basic question which I cannot find a good answer to. I have already posted this at Stack Overflow but still am hopeless. I am trying to dynamicly determine the contents of my website based on a selection made by the user and keep the selection displayed in the routing for SEO purposes.

In other words I want to a path prefix which I can use as a variable to display nodes specifically for that franchise. My content types have multiple CCK references to content types Franchise and I want to base my selection on the location inside my content type franchise.

**It's a website for a Restaurant with multiple franchises.**

What i'm trying to do is the following:

1. The user visits my website and gets a splash screen presented with the available franchises or a textbox to enter his postalcode
2. Upon selecting he enters the main website with the navigational structure adapted to that particular franchise only. The selected Franchise city should remain inside of the url structure. Nodes should not be made available without the city inside of the url. For example: *domain.com/city/*, *domain.com/city/menu*, *domain.com/city/menu/dishes*, *domain.com/city/contact*, ...
3. The contents of all nodes are based upon the city the user selected. Some franchises have extra nodes which should be displayed in the main navigation aswell. The contents of the views and panels should automaticly be adjusted to that particular Franchise aswell.
4. Users can change the selected franchise by clicking on a main link which links back to the splash page.

What I have found so far which might be part of the solution is:

* Purl
* Context
* Spaces

Parts of the nodes will be the same for all franchises other parts will be different. Menu item prices will also be different.

This is the first website i'm building using Drupal so any advice is welcome.

**Thanks!**

# Answer
What you want, is not (simple) with only views and CCK. That is because both lack a system for persistence in filters and arguments.

I can advise you to add a new module to your stack: Domain Access. This is a large module, which is not simple to configure right, but it sounds like it is the exact solution to your problem. **It will allow you filter content, based on the domain (franchise) it is posted into**.

The mayor concern with this module is its complexity. The second concern would be its use of Drupal's *content access hooks and system*. Modules like Domain Access, i18n, Organic Groups all use this system, which has very severe penalties for performance. IOW: Domain Access, or any access-module, will make your site notably slower and less performant.
> 1 votes

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


# Question
Title: Create a View of Group Posts Who's Group has a Specific Tax Term?
Hi i hope someone can help me get my head about this. I dont know if im just having a blonde moment though.

I have tax terms added to my 'groups' (blog, betting, diary etc) I was wanting to create a view showing just posts in Groups that have the term 'blog' attached to the Group. The posts in Groups tagged with 'blog' do not have the term 'blog' in the posts so thus they will not show in any views i create. I hope im making sense here as i think im just confusing the issue.

I think i would need some sort of Relationship to create the View Ill try explain again. I only have one Group content type 'Groups'. Each group has a term (blog, betting etc) I want to...bah im just saying the same thing again arent i?...How can i show just my 'Group Posts' whos parent Group is tagged with 'betting' in a view?

# Answer
In addition to your view configuration, you need to set up a group node relationship and filter out group nodes by taxonomy term. This should do it for you:

**Add relationship:** Organic groups: Group node (post)
**Require this relationship:** checked

**Add filter:** Taxonomy: Term
**Vocabulary:** Your Vocabulary
**Selection type:** Dropdown
**Relationship:** Group node (post)
**Operator:** Is one of
**Select terms from vocabulary Your Vocabulary:** blog
> 1 votes

---
Tags: views, organic-groups
---


title: Getting QueryString from with a module

text:
# Question
Title: Getting QueryString from with a module
I've trying to get the querystring from within a module.

I've tried the following. However the following always returns A

exporter/directory?l=o

```
$l = "A";
if ( !empty($_SERVER['l']) ) {
    $l = $_SERVER['l'];
}

```

/\* edit \*/

```
    $l = "A";
if ( !empty($_GET ['l']) ) {
  $l = $_GET ['l'];

}

```

# Answer
> 3 votes
The query string is stored in `$_SERVER['QUERY_STRING']`, the same way as when not using Drupal. You can access the individual variables of the query string using the `$_GET` array, the same way as when not using Drupal (with one exception: `$_GET['q']` is the canonical Drupal path, not the one assigned using the Path module).

# Answer
> 10 votes
Oswald is correct. Alternatively, in Drupal 7, you can use drupal\_get\_query\_parameters():

```
$query_parameters = drupal_get_query_parameters();
if (!empty($query_parameters['l'])) {
  $l = $query_parameters['l']
}

```

---
Tags: 7
---


# Question
Title: htaccess settings to allow access to special non-drupal page
I have a properly working Drupal 6 site, at the webroot of my server, which can be accessed by www.mysite.com or by mysite.com. I have some special html files (not part of Drupal) that can be currently accessed by going to mysite.com/special and that works fine.

I would prefer that people just go to special.mysite.com to get to the html files in that directory (instead of mysite.com/special). I just had the DNS set up so that special.mysite.com now points to the webroot, and Drupal currently handles it the same as www.mysite.com.

However, I would like it if people coming to special.mysite.com arrive at the index file within the "special" folder on mysite.com. I bet I can do something to the .htaccess file that Drupal uses in the webroot directory - but I don't know what? Any advice? Thanks a ton.

# Answer
> 1 votes
add in your .htaccess.

```
RewriteCond %{HTTP_HOST} ^special.mysite.com$
RewriteRule ^/?$ "http\:\/\/mysite\.com\/special" [R=301,L]

```

---
Tags: redirection, .htaccess
---


# Question
Title: How should I add ID or classes to secondary tabs?
I'm developing a site in drupal 7. I see that the function theme\_menu\_local\_tasks() in includes/menu.inc is responsible for generating the secondary tabs. However the `<li>` elements do not have any IDs or classes. How do I start adding IDs and classes to the list elements?

# Answer
The theme function that render the single menu local tasks is theme\_menu\_local\_task(), which is the function that output the `<li>` tags.

```
return '<li' . (!empty($variables['element']['#active']) ? ' class="active"' : '') . '>' . l($link_text, $link['href'], $link['localized_options']) . "</li>\n";

```

In a theme, you can implement an alternative of that theme function, using the code of that function as base; you then can add more CSS classes.

Supposing that your theme is "my\_beautiful\_theme," you need to create a "template.php" file (if it doesn't exist), and add the function `my_beautiful_theme_menu_local_task()` with the code for your theme function.

From a module is more complicated, but it has the pro of being applied for every theme you set in your site. If users are allowed to set a theme for themselves, you don't need to add that theme function in all the themes you enable, which also means not altering the code provided by other users. If you alter a theme you install, you then would lose your customizations every time the theme is update, and you install the update in your site.

With a module, you just need to implement something similar to the following code:

```
function mymodule_theme_registry_alter(&$theme_registry) {
  if (isset($theme_registry['menu_local_task'])) {
    $theme_registry['menu_local_task']['function'] = 'theme_mymodule_local_task'; // The new theme function.
  }
}

function theme_mymodule_local_task(&$variables) {
  // Add here your code for the theme function.
}

```

For more information, you can look at hook\_theme(), and hook\_theme\_registry\_alter().
> 6 votes

---
Tags: 7, routes
---


# Question
Title: Cache page based on cookie value and URL
I am working on a site that is multi-lingual as well as multi-country. This means that pages will show content differently depending on a country cookie that is set when the user first visits the site. I used taxonomy tid's for the cookie's value, so there was no issue with case sensitivity, etc.

The problem is that Drupal's cache\_page table indexes content by URL only, so users with different countries but the same URL all get the same content. I was able to get the effect I wanted just by modifying the mod\_rewrite implementation:

```
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{QUERY_STRING} !(cid)
RewriteCond %{HTTP_COOKIE} (?:^|;\s*)country=([^;]*)
RewriteRule ^(.*)$ $1?cid=%1&%{QUERY_STRING} [L,R=302]

RewriteCond %{QUERY_STRING} ^$
RewriteCond %{HTTP_COOKIE} (?:^|;\s*)country=([^;]*)
RewriteRule ^$ /?cid=%1 [L,R=302]

# Rewrite URLs of the form 'x' to the form 'index.php?q=x'.
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !=/favicon.ico
RewriteRule ^(.*)$ index.php?q=$1 [L,QSA]

```

I did have to disable the ExpiresDefault directive, as it was causing the browser to remember old content when the user switches countries.

The resulting cid's in the cache\_page table look like this:

```
http://example.com/pagename?cid=98
http://example.com/pagename?cid=256

```

This post isn't so much of a "help me I'm stuck" but a "I had this problem, and here's how I solved it. Can you think of a better way to do this?"

# Answer
> 1 votes
You can do it without .htaccess rules.

Drupal core cache; modify in your settings.php file (apache only). From http://drupal.org/node/361832#comment-4204294

```
<?php
// Check if cookie is set.
if (!empty($_COOKIE['my_cookie'])) {
  // Add cookie value to page cache id.
  $_SERVER['REQUEST_URI'] .= '#' . $_COOKIE['my_cookie'];

}
// Disable page cache if cookie not set so your magic code can set the cookie.
else {
  $conf['cache'] = CACHE_DISABLED;
}
?>

```

Memcache http://drupal.org/node/942914#comment-4477150

---
Tags: caching, i18n-l10n, cookies, uri
---


# Question
Title: How i can popuplate user's facebook data into my built-in drupal register form?
How can I populate an authorized user's Facebook data into my Drupal registration form? Note: user is authorized from my Facebook application and allowed my Facebook app to access his data.

**Update:** I am using Drupal for Facebook, and to populate the user info I am implementing `fb_form_alter` inside fb.module. My code is

```
function fb_form__alter(&$form, &$form_state, $form_id) {
if(!($form_id == 'user_register_form')) {
return;
}
if ($GLOBALS['_fb'] && $fbu = fb_get_fbu($account)) { // @TODO - is fb_get_fbu() a performance hit here?
    try {
      $data = fb_fql_query($GLOBALS['_fb'], "SELECT name FROM user WHERE uid=$fbu", array(
                             'access_token' => fb_get_token($GLOBALS['_fb']),
                           ));
      if (count($data) && isset($data[0]['name'])) {
        $form['account']['name']['#default_value'] = $data[0]['name'];
      }
    }
    catch (Exception $e) {
      fb_log_exception($e, t('Failed to alter username for facebook user %fbu', array(
                               '%fbu' => $fbu)));
    }
}
}

```

I put the above code after the `form_username_alter()` function but with no success :(

# Answer
If you're using Drupal for Facebook, it should be doing that for you already. Make sure to enable the FB User module and configure the *Form Alters* at `admin/build/fb/fb_user`. Once you've got that configured, visitors to the *Create new account* page will have the form prepopulated, including the profile picture.

To see how it's done, have a look at fb\_user.module's `hook_form_alter()`. To see if it's all working, you can create a simple PHP block to display the Facebook data collected for the current visitor:

```
$data = _fb_user_facebook_data($GLOBALS['_fb']);
print '<pre>' . print_r($data, TRUE) . '</pre>';

```
> 1 votes

# Answer
The Dupal for Facebook module kind of does the trick.

The problem is that it uses soon to be deprecated FB APIs, and it isn't exactly Drupal 7 ready yet (though it's very well maintained and I am sure it'll catch up soon), so you might as well want to write your own module from scratch. These are the basic info you should check if you want to get into this

1. Get user Authentication and Permissions. (You will probably need to also look into offline\_access permissions.)
2. Access to the FB user object using the PHP SDK for Basic profile informations. It is session based, so you can access it from anywhere in your site, for instance to pre-populate you registration form. (Don't forget to include the PHP SDK to your script.)
3. Access or write other user data (e.g., activities, picture, wall feed) via the Graph API.
> 1 votes

---
Tags: forms, social-network
---


# Question
Title: How can I create correct breadcrumbs when using Views arguments?
I have a custom CCK content type for blog posts and I’m using Views to display the posts in an archived list. I use two arguments—Node: Created year and Node: Created month—to generate the monthly and yearly archive pages, which allows me to build URLs like http://example.com/blog/2011 and http://example.com/blog/2011/08. This is pretty standard stuff and really easy to do with Views.

While the actual archive list pages are working just fine, the breadcrumbs that views generates are not. With the URL http://example.com/blog/2011/08, instead of creating this kind of trail (which seems correct):

```
Titles = Home > Blog  > 2011       > August
URLs   = /      /blog   /blog/2011   /blog/2011/08

```

… Views generates this incorrect breadcrumb trail:

```
Titles = Home > Blog  > 2011  > August
URLs   = /      /blog   /blog   /blog/2011

```

The URL generated for the year argument points to `/blog` rather than `/blog/[yyyy]`, and the generated URL for the month argument only points to the year, not the month.

Going down one level (to http://example.com/blog/2011) creates a similar problem:

```
Titles = Home > Blog  > 2011
URLs   = /      /blog   /blog

```

In both cases, none of the arguments' URLs are output correctly, while their titles are.

My settings for each of the arguments in Views are pretty standard: Month settings and Year settings. The path for the page display is just "blog".

What is causing this strange breadcrumb behavior and how can I fix it?

Thanks!

# Answer
> 2 votes
The title and breadcrumb settings are often very confusing. Drupal usually does not display current page as part of breadcrumbs and that is how Views' settings work, too.

You need to keep in mind you're setting the title for the current page, but breadcrumb for the previous one in the hierarchy. That means: "what do I want to be added to breadcrumbs when this page is displayed".

**Node: Created year**
**Title:** Blog archive for %1
**Breadcrumb:** Blog

**Node: Created month**
**Title:** Blog archive for %2 %1
**Breadcrumb:** %1

This should fix the label-link matching for you. If you're using a theme that adds current page to breadcrumbs, or want current page's link in breadcrumbs anyway, let me know more about the theme you're using and if it's okay to have the current page's title there. Cheers!

# Answer
> 5 votes
Check out the Custom Breadcrumbs module which has support for Views. Here is a quote about it (from the module's project page):

> **Custom Breadcrumbs 1**:
>
> Allows administrators to set up parametrized breadcrumb trails for any node type. This allows CCK-style node types to have "Home \> User Blog \> 2005 \> January" style breadcrumbs on the node view page itself, synchronizing cleanly with custom views or pathauto aliases. Breadcrumb visibility can be customized via a php snippet.
>
> **Custom Breadcrumbs 2**:
>
> Many new features have been added including support for Views, Panels, Taxonomy vocabularies and terms, paths, and a simple API that allows contributed modules to enable custom breadcrumbs for module pages and theme templates. These are implemented using optional, independent submodules that depend on the main Custom Breadcrumbs module.
>
> In addition to breadcrumb visibility, this version provides an option permitting PHP code snippets to be used in forming the breadcrumb titles and paths. Multiple languages are also supported.

---
Tags: views, 6, breadcrumbs
---


# Question
Title: How to change the title of the button in the user profile form in Drupal 7?
How do I change the name of the button in the user\_profile\_form in Drupal 7? I alter the user profile using `hook_form_alter()`.

```
function userform_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'user_profile_form' ) {
    // I define a submit button like:
    $form['submit'] = array(
      '#type' => 'submit',
      '#value' => t('Continue'),
    );

    //Then I can change it with this code:
    // Change 'Continue' to 'Sign in'.
    $form['submit']['#value'] = t('Sign in');
  }
}

```

It works for all elements (buttons) I define myself, but it doesn't work for the default button in the user profile form.
This the rendered HTML for the "Save" button:

```
<input id="edit-submit" class="form-submit" type="submit" value="Save" name="op">

```

# Answer
> 1 votes
Try using profile\_form\_alter

---
Tags: 7, forms, users
---


title: Drupal Theming 'Add Content' Page

text:
# Question
Title: Drupal Theming 'Add Content' Page
Is there any module that can help me theming the "add content" page?

I'm also looking for a way to allow the use of the "add content" menu only to the users who paid.

When I talk about "add content" page, I'm actually talking about the template used when creating for example a new article page.

I don't want to give access to other users to the following fields, and basically change the whole look of that page.

* Menu settings
* Revision information
* URL path settings
* Comment settings
* Authoring information
* Publishing options

# Answer
I found and article explaining how to theme the node form here (http://batayneh.me/post/theming-node-forms-drupal-7). To solve the other part of your question - Only people who pay can use the "create content" you can create a new role and specify that only users with the new role can create content.
> 1 votes

---
Tags: theming, users
---


# Question
Title: Is it correct to make queries to DB in preprocess functions?
I've just started using Drupal after long experience of using other framework. When I do something new, I'm scaring to crash performance because of my incomprehension. So, my problem: I want to add dynamically some data from database to some existing page region. For example, I want to add list of child terms to taxonomy term page. And I don't need to change any other things on this page, so I don't want to turn on View. Is it normal to query data in preprocess functions? My solution for D7 was like this:

```
function mymodule_taxonomy_term_view_alter(&$build) {
  if ($build['#view_mode'] == 'full') {
    $children = taxonomy_get_tree($build['#term']->vid, $build['#term']->tid, 1);
    foreach($children as $term) {
      $build['children'][] = (array)$term;
    }
  }
}

function mymodule_preprocess_taxonomy_term(&$variables) {
  if($variables['vocabulary_machine_name'] == 'catalog') {

    if(count($variables['elements']['children'])) {
      $items = array();
      foreach($variables['elements']['children'] as $term) {
        $items[] = array(
          'data' => l($term['name'], 'taxonomy/term/' . $term['tid'])
        );
      }

      $variables['content']['children']['#markup'] = theme('item_list', array('items' => $items, 'title' => 'Text terms list', 'type' => 'ul', 'attributes' => array()));
    }
  }
}

```

Any comment are welcome.

# Answer
> 7 votes
No, it's not incorrect to query the database in a preprocess function. If the information is required to render the page, putting a query in a preprocess function is an acceptable choice. Plus, in this particular case taxonomy\_get\_tree() caches results, so there is very little cost associated with repeated fetches.

Regarding Views, yes there is some overhead associated with it, but it employs a sophisticated caching strategy, and is ultimately just so powerful and useful that most sites use it. You could probably solve this current problem with no custom code by using a Viewfield.

These questions provide a lot of interesting background on Drupal performance.

---
Tags: nodes, performance, theming
---


title: /video/nid returns a 404 error

text:
# Question
Title: /video/nid returns a 404 error
I am trying to create a module in Drupal 6.22, using the following code.

```
function example_video_perm() {
  return array("video access");
}

function example_video_menu() {
  $items = array();

  $items['video/%nid'] = array(
    'title' => '',
    'page callback' => 'video_load',
    'access arguments' => array('video access'),
    'type' => MENU_CALLBACK,
  );

  return $items;
}

function video_load($nid) {
  print_r($nid);
}

```

Whenever I am trying to access http://example.com/video/nid, I get a 404 error. Please help.

# Answer
```
function example_video_menu() {
    $items = array();
    $items['video/%'] = array(
        'title' => '',
        'page callback' => 'video_load',
        'page arguments' => array(1),
        'access callback' => TRUE,
        'type' => MENU_CALLBACK,
    );
    return $items;
}

function video_load($nid) {
    print_r($nid);
}

```
> 0 votes

# Answer
The problem is that the path associated to your menu item is using a wildcard ("%nid"), but your code is not defining an auto-loader for that wildcard.

* For a wildcard such as "%nid" Drupal is looking for a function called `nid_load()`, which doesn't exist; if you want to use `video_load()`, then the placeholder should be "%video" and not the one you are using. If that part of the path is a node ID, then you should use "%node" that would cause Drupal to use `node_load()`, which is a function defined from the Node object and that returns a node object for the node ID passed as argument.
* The auto-loader function should return an object or an array. If the auto-loader function is not returning a value, then Drupal would act as if the returned value is `FALSE`, which is the value that causes Drupal to return to the user the "page not found" error, as it understands the value as meaning "I didn't found what the user is looking for." Return an object (which is what node\_load() does), or an array, and the user will not see the "page not found" error anymore.

In your case, the URL for the menu item defined from the module is something similar to http://example.com/video/1, or http://example.com/video/2, where 1 and 2 are (I presume from your code, as you use "%nid" as wildcard, which should mean "node ID") the node IDs of existing nodes.
Take as example the URL for the menu item associated with the node view page, which is "node/%node"; you invoke that page with, e.g., http://example.com/node/1, and Drupal shows you the content of the node with node ID equal to 1.

If you don't want to use an auto-loader, then your menu item should use a path such as "video/%" and Drupal would not look for an auto-loader function. What I reported about the URL to use to invoke the page served from your module is still valid, except that the URL could be http://example.com/video/asdfsdfwer, http://example.com/video/2, http://example.com/video/azder54gfg because the *%* in "video/%" matches any string.

Bart is correct in saying that using "%nid" as placeholder in the path, when the page callback, the access callback, or the title callback doesn't get any argument derived from that placeholder, doesn't make sense.

For more information, you can look at the documentation for hook\_menu(); Wildcard Loader Arguments, Wildcard usage and core's wildcards, Dynamic argument replacement (wildcard), Wildcard, ancestors and fitness; and, as general information on how Drupal menu system work, Drupal menu system (Drupal 6.x).
> 2 votes

# Answer
The page callback should return the content of the page as a string. See `menu_execute_active_handler` about how the page callback is invoked and index.php about what is done with the result of `menu_execute_active_handler`.

This doe not explain the 404, but it's the next trap you will fall into.
> 1 votes

# Answer
You forgot page arguments!

> "page arguments": An array of arguments to pass to the page callback function, with path component substitution as described above.
> 0 votes

---
Tags: 6, hooks
---


# Question
Title: Custom content types and fields: how do I set it up properly?
I'm looking for a check-list style explanation of how I create this custom content type if possible.

I'm scraping data from an external website (it works flawlessly), I store it in my own database table (`hook_schema()`, etc.), and I display it in my config page as a table. The data gets re-scraped on cron using the queue API built into Drupal.

All this works fine. Now, my next step is to have this data turned into nodes as a custom content type. I will never need to create nodes of this content type by hand through the 'Add Content' menu because all the nodes should be generated by my module's scraping/parsing function, but the content should be searchable with Drupal's built in search. This is a bit more of a challenge. I have multiple fields (10-ish) I want to sort my data into, all different sections of the pages I'm scraping and I want to keep them separated properly so I can theme the content with a tpl file. The fields are all text, mostly HTML, some are titles/subtitles with no HTML, and a few Unix timestamps.

This has to all be done programmatically because this module might be deployed to other websites in the future, and this should not require configuring to work.

# Answer
> 1 votes
The first step is to create the content type and fields with the built-in UI of Drupal core. There are then several ways to export the configurations into code, but the simplest is probably Features, which will export a fully-functional module for you including all fields and content types you select.

To get your content into nodes of your content type, I'd suggest you create one node with the UI, use devel to look at the structure, then create the same object structure in code, which would look something like this:

```
$node = new StdClass;
$node->type = 'content_type;
$node->field_something = array(
  'und' => array(
    array(
      'value' => 'some value',
    ),
  ),
);
node_save($node);

```

Drupal's search defaults to searching nodes of all types, so that part should just work. Same with theming. You can use permissions (also exportable via Features) to remove the content type from the "Add content" list.

---
Tags: 7, entities, database, nodes
---


title: Expose filter like google

text:
# Question
Title: Expose filter like google
I create a views and filter node title , with expose filter. how to change it to work like Google . don't have apply button and filter on time. is it possible ?

# Answer
The closest I know you can get by doing just site buiding is by using the views autocomplete filters module which gives the possibility of using an autocomplete widget for the exposed filter by simply checking an option in the exposed filter options in the view.
> 2 votes

---
Tags: 6, views
---


# Question
Title: Radioactivity module. "how-to" most popular article in one day questions
thanks for the time to read this question.

to me not is clear the concept of Radiactivity measures. how to get the most popular article in one day? I must use the half-life in 43200 seconds (12 hours)? when change this results? (each day in this case?), what's happen if I Cut-off energy to 0?. where is stored this results if I want a report per days?

thanks in advance.

# Answer
> 2 votes
According comparison of the Radioactivity results and a Analytics service, seems that 12 hours (in seconds) is the time needed to track 1 day.

---
Tags: 7, nodes
---


# Question
Title: How can I change the style of a specific CCK field?
I need to change the position to fields of content types. How can I modify the style of a specific field?

When I check the code for knowing the class, I see this:

```
<input id="edit-field-first-name-0-value" class="form-text text" type="text" value="" size="60" name="field_first_name[0][value]">

```

# Answer
you can review the style in the source code, detecting the 'id' of the specific field.

for example add this rule (according the specific id):

```
#edit-field-color-value {
color:#00FF00;
}

```
> 1 votes

---
Tags: entities
---


# Question
Title: Add "- Please Select -" to a required CCK field
In Drupal 6, by default, a required CCK field will display the first allowed value.
I want it displays "- Please Select -": Is there an easy way to do this?

I do not want to save "- Please Select -" in the database.

# Answer
Use the key|label format for allowed values:

```
|-Please Select -
1|option1
2|option2
3|option3

```

By making the key for "-Please Select -" an empty string, the form can't be submitted with this value.
> 7 votes

# Answer
In the list of options of *global settings* of field you can put in first place the option - Please Select - :

-Please Select -
option1
option2
option3

Save the field.

After in the *field settings* you choose - Please Select - in default value of the field.

Finally you save the configuration of field.
> 0 votes

# Answer
seems like AHAH can do the job to populate select list or add items: AHAH - populating a select (list) with a select (drop-down).
> 0 votes

# Answer
Put your field as not required and then in a `hook_nodeapi()` check that the user has effectively selected a value:

```
function custom_nodeapi(&$node, $op, $a3 = NULL, $a4 = NULL) {
  if ($op == 'validate') {
      if ($node->field_select[0]['value'] == '') {
        form_set_error('field_select', t('Please select a value.'));
      }
  }
}

```
> 0 votes

---
Tags: entities
---


title: Heading for comment section

text:
# Question
Title: Heading for comment section
I would like to have a heading over my comments that only appears after a comment has been left... I tried the code below but it doesn't seem to be the answer:

```
<?php if ($comment): ?>
    <h2>Comments</h2>
<?php endif; ?>

```

# Answer
> 1 votes
This is the default behavior of Garland. Have a look in the `themes/garland/template.php` file:

```
function garland_preprocess_comment_wrapper(&$vars) {
  if ($vars['content'] && $vars['node']->type != 'forum') {
    $vars['content'] = '<h2 class="comments">'. t('Comments') .'</h2>'.  $vars['content'];
  }
}

```

Where did you put your code? Depending on your theme, you most probably want to theme comment-wrapper.tpl.php, which only gets output when there are comments to be displayed. Which what you want. :-)

# Answer
> 0 votes
seems that you can add your conditional in a preprocess function, please see "Altering the 'Post new comment' heading" part in: http://www.systemseed.com/blog/how-customise-comment-form-drupal-6

---
Tags: 6, theming, comments
---


# Question
Title: Why is my validate function not receiving the value of my form element?
```
function mymodule_email_reviewers_action_form($context) {
  $form = array();
    $form['email_text'] = array(
        '#type' => 'textarea',
        '#name' => 'message'
    );
    $form['submit'] = array(
        '#name' => '',
        '#type' => 'submit',
        '#value' => 'Apply'
    );
  return $form;
}

function mymodule_email_reviewers_action_validate($form, $form_state) {
    $text = $form_state['values']['email_text'];
    dsm($form_state);
    dsm($text);
    dsm($form);
    if ($text == 'Email body' || empty($text)) {
        form_set_error('email_text', t('Please enter a message'));
    }
}

```

I'm not sure what might be wrong here. Neither the `$form` nor `$form_state` contain the text I enter into my textarea.

# Answer
> 2 votes
In the description for the "#name" attribute is reported the following text:

> INTERNAL, except for buttons. All button and submit elements on a form should have the same name, which is set to 'op' by default in Drupal. This does not apply to image buttons. For non-button elements, Drupal sets the name by using 'foo' in $form\['foo'\] as well as any parents of the element.

You should not set that attribute, which is considered internal.

# Answer
> 0 votes
Apparently setting `#name` is the problem. Taking that out fixed it.

---
Tags: 6, forms
---


# Question
Title: Popup w/overlay for content (Lightbox-esque)
Is there a module/technique that allows for a popup of a node content? I'm looking for a lightbox-esque affect that displays specifically content (node?), not an image.

# Answer
> 1 votes
See this question: Display node as a popup window

"There are a lot of solutions for this kind of stuff. I would do it in the theme layer to have something really light. You can also use the variety of popup modules for this. One simple way to do this, is use the Lightbox2 module, checkout this documentation page: http://drupal.org/node/252260"

---
Tags: modal-dialogs, javascript
---


title: Make a page unsearchable

text:
# Question
Title: Make a page unsearchable
I made an AJAX email page that allows the user to send a short email, and it loads a separate page showing a message similar to"Your email has been sent." Can I make that last page (the one that shows the message) unsearchable? It's just a success page, and I think it shouldn't come out in any search result.

# Answer
> 1 votes
There is a good article by Lullabot that covers this: Hiding content from Drupal's search system.

# Answer
> 1 votes
If the page is not a node, then Drupal doesn't index it, and the page isn't shown in the search results.

The Drupal core modules have support for the search module for nodes, and user profiles. This means that, for example, a setting page of a module is not included in the search, because it's not a node.

---
Tags: search
---


title: Questions about the imagefield of CCK

text:
# Question
Title: Questions about the imagefield of CCK
1. How can I include the text between the label of image field and the upload button?
2. How can I remove the text "maximum file size" of the image field in some content types? I want to remove the text "maximum file size" but I want to keep "allowed extensions."

# Answer
assuming that you are talking about the 'edit form', you can use css to control the visibility of these fields in this way:

```
/*---------------------------
this rule is to hide the text
"maximum file size"
and "allowed extensions"*/

div#edit-field-cl-namefiled-upload-wrapper div#edit-field-namefiled-upload-wrapper div.description{
display:none;
}

/*---------------------------
this rule is to move your description
near to the field to upload.
here you can add the "allowed extensions.." text*/

div#edit-field-namefiled-upload-wrapper > div.description{
margin-top:-70px;
position:absolute;
}

```
> 1 votes

---
Tags: entities
---


# Question
Title: More specific way to override THEME_process_page() function?
I'm going to explain my problem through the use of pseudo code. Right now, i have in template.php the following code

```
function THEME_process_page(&$variables)
{
    if($variables->view == 'calendar')
    {
        // do something
    }
    else if ($variables->view == 'google_maps')
    {
        // do something
    }
    else if($variables->content_type == 'news')
    {
        // do something
    }
    else if($variables->content_type == 'event')
    {
        // do something
    }
}

```

Instead of writing a whole bunch of if statements for each view and content\_type, can I do something like

```
function THEME_process_view_calendar()
{
    // do something
}
function THEME_process_view_google_maps()
{
    // do something
}
function THEME_process_content_type_news()
{
    // do something
}
function THEME_process_content_type_event()
{
    // do something
}

```

If this is possible, what's the correct way of naming functions to do this?

# Answer
In the case of the content types, Drupal invokes only the preprocess and process functions for the page; it doesn't invoke a different preprocess function basing on the content type of the node being shown. Drupal invokes the following functions (the same order is followed for the process functions):

* template\_preprocess(&$variables, $hook)
* template\_preprocess\_page(&$variables)
* MODULE\_preprocess(&$variables, $hook)
* MODULE\_preprocess\_page(&$variables)
* ENGINE\_engine\_preprocess(&$variables, $hook)
* ENGINE\_engine\_preprocess\_page(&$variables)
* ENGINE\_preprocess(&$variables, $hook)
* ENGINE\_preprocess\_page(&$variables)
* THEME\_preprocess(&$variables, $hook)
* THEME\_preprocess\_page(&$variables)

"MODULE" is the short name of a module, "ENGINE" is the short name of the theme engine used for the currently used theme, and "THEME" is the short name for the currently set theme.

You could say to Drupal to call different preprocess functions, but the hook that would add them doesn't have information about the content type of the node being shown. hook\_theme\_registry\_alter() could be used to add new preprocess functions to a theme function, but all the preprocess function added would be all executed.

```
function mymodule_theme_registry_alter(&$theme_registry) {
  if (isset($theme_registry['page']) {
    $theme_registry['page']['preprocess functions'][] = 'template_mymodule_additional_preprocess_handler';
    $theme_registry['page']['preprocess functions'][] = 'template_mymodule_last_preprocess_handler';
  }
}

```

This is only necessary if the preprocess function is not one of the functions that Drupal would invoke.

If you need to use a different template file basing on the content type, then a preprocess function can suggest the template files to use; in Drupal 7, this means to use code similar to the following one:

```
function mymodule_preprocess_page(&variables) {
  if (!empty($variables['node']) {
    $variables['theme_hook_suggestions'][] = "page__" . str_replace(array("/", "\\", "\0", '-'), array('', '', '', '_'), $variables['node']->type);
  }
}

```
> 2 votes

---
Tags: views, theming
---


title: Control Views Bulk Operation messages?

text:
# Question
Title: Control Views Bulk Operation messages?
For my purposes I don't need these types of messages:

```
2 rows processed in about 261 ms:
Performed Email Reviewers on user joren1.
Performed Email Reviewers on user joren5.

```

I don't want to hide messages in general. Is there a way to specifically target messages from this module, or specific messages at all?

# Answer
You can uncheck "Display processing result" in the VBO settings (in the edit view UI).

VBO for D7 stopped generating that many messages in latest -devs (after beta1). It now only shows one message: "Performed $operation on $count items."

That is something that should be backported to D6, there's an open issue for it. In general, you can't affect those, the module is just calling `drupal_set_message` (usually in `_views_bulk_operations_execute_finished()`).
> 2 votes

# Answer
As general solution that works independently from the module that writes the messages you want to see, you can override theme\_status\_messages(), and filter out the messages you don't want appearing.

You need to implement hook\_theme\_registry\_alter() in a module, using code similar to the following one:

```
function mymodule_theme_registry_alter(&$theme_registry) {
  if (isset($theme_registry['status_messages'])) {
    $theme_registry['status_messages']['function'] = 'theme_mymodule_status_messages';
  }
}

```

`theme_mymodule_status_messages()` is the function that the module implements to filter out the messages that would appear to the user, and that modules add through `drupal_set_message()`.

In the case of the Views Bulk Operations, it is enough to update the module to the latest version, but if you need to control the messages output from modules, you can implement the functions I described here.
> 2 votes

---
Tags: views
---


title: custom script to migrate d5 to d7

text:
# Question
Title: custom script to migrate d5 to d7
can any one suggest the custom script to migrate the contents,views and content types from D5 to D7. We already tried with normal conversion process like d5=\>d6=\>d7 but we facing many errors and contents and views are not imported correctly.

# Answer
> 2 votes
This should help: Direct Drupal 5 to Drupal 7 Migration in 24hrs.

So, rebuild the views and content types on the Drupal 7 site, then use a custom script (like the one provided in the article, or one you write yourself), or the Migrate module to move the data.

---
Tags: migrations
---


# Question
Title: How can I get the name of the currently logged in user in Drupal 7 in the external file?
In an external file I use the following code:

```
$path = $_SERVER['DOCUMENT_ROOT'];
chdir($path."/drupal");
define('DRUPAL_ROOT', getcwd());
require_once './includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);

global $user;
print $user->name;

```

The code doesn't print anything, but this code works:

```
$account = user_load(2);
print $account->name;

```

How can I get the name of the current user in Drupal 7?

# Answer
`drupal_session_initialize()` is run as part of the full bootstrap. This will give you a $user object.

If you are not getting a user object that would be a good place to start looking. I would suggest that something with your setup is not quite right.

But I would re-iterate the suggestions that creating a module and learning the framework is the way to go.
> 3 votes

# Answer
I advice you to:

* create a module
* put your script in that module (inside one or more functions)
* implement hook\_menu() to define the url you can call (eg. example.com/mytuff/ajax) and set your script's (main) function as the 'page callback'
* instead of returning stuff (like page callbacks normally do) `print` your output and `exit()` at the end
> 3 votes

# Answer
If there are no sessions open for any authenticated user, then the current user is the anonymous user; in that case, `print $user->name` doesn't print anything because `$user->name` is not set.

This is evident in the drupal\_anonymous\_user() code:

```
function drupal_anonymous_user() {
  $user = new stdClass();
  $user->uid = 0;
  $user->hostname = ip_address();
  $user->roles = array();
  $user->roles[DRUPAL_ANONYMOUS_RID] = 'anonymous user';
  $user->cache = 0;
  return $user;
}

```

I agree with the other users that using an external file in this case is not necessary; to understand when an external file is used instead of a module, see Are there cases where a third-party module would need to use its own file similar to xmlrp.php, cron.php, or authenticate.php?
> 1 votes

# Answer
In Drupal 6 I found this issue to be related to how the session was being saved. By default the session was saved to the path /. I was able to fix this by uncommenting and configuring the $base\_url variable in the settings.php file. My exact issue was that the external file was not in the root of the drupal install and was in a subfolder like www.example.com/mycustomcode/test.php. Therefore the sessions were not set for that path. If you move your code to the root of the install you may find that it works just fine when you call bootstrap full, global $user and print\_r $user. I assume this fix may also apply to Drupal 7 but I have not needed this functionality as of yet.

Hope this helps.
> 1 votes

---
Tags: users
---


# Question
Title: How can I display a view's count in a navigation item?
How can I display a view's count in a navigation item?

I have a view the displays a list of stories (a content type) and I have an item in a menu that links to that view. I need to display the number of items returned by that view next to the menu item that links to it on all pages of the site.

The solutions I've thought of so far have been:

1. Add a block to the view and have that blocked displayed in a hidden area on all pages and then use the `total_rows` or `num_rows` property of the view's object. The disadvantage of this is that this view then runs on every page possibly causing performance issues.
2. Add a block (or some other type) to the view that calculates the count and have that displayed by the menu item some how. But I haven't been able to figure out how to do this. I tried using the "Use aggregation" setting but I get a "broken/missing handler" error when using an "Aggregation type" other than "Group results together" in Sort or Filter criteria.

Any help with this would be much appreciated.

This is running on Drupal 7.7.

# Answer
I know only how to get it with codding.
You can define in your module function, which gets total rows count from your view. And you can use drupal cache system for result, but actually you can use Views cache for it.
Something like that:

```
/**
 * Executes View to know rows count
 */
function testm_get_view_items_count($view_name, $display_id, $args) {
    $count = &drupal_static(__FUNCTION__);
    if(!isset($count)) {
        if($view = views_get_view($view_name)) {
            $view->set_arguments($args);
            $view->get_total_rows = true;
            $view->execute($display_id);
            if(isset($view->total_rows)) {
                $count = $view->total_rows;
            }
        }
    }
    return $count;
}

```

You can add cache\_set/cache\_get as Lulabots showed, but then you need to think about when to do flushing you cache.
You can use this function in `THEMEORMODULE_preprocess_menu_link()` function in Drupal 7. Here I showed example. This code works on D7.
> 4 votes

---
Tags: 7, views
---


title: Console style syntax highlighting

text:
# Question
Title: Console style syntax highlighting
I am using the syntax highlighter, which is convenient. I was wondering if there is a module for a console style rendering. For example, in a wordpress site, I saw

I highlighted it just to show that it is not an image of an actual terminal.

# Answer
The GeshiFilter module may help you.

> At the time of this writing the GeSHi library supports highlighting for more than 130 programming languages and configuration syntaxes, including: ActionScript, Ada, Apache Log, AppleScript, ASM, ASP, **Bash**, C, ColdFusion, C++, QT, C#, CSS, D, Delphi, Diff, DOS, dot, Eiffel, Fortran, Groovy, Haskell, HTML, INI, Inno, Java, Javascript, LaTeX, Lisp, Lua, Motorola 68000 Assembler, Matlab, mIRC Scripting, MySQL, Objective C, OCaml, OpenOffice.org Basic, Oracle 8 SQL, Pascal, Perl, PHP, PL/SQL, Python, QBasic/QuickBASIC, Rails, Microsoft Registry, robots.txt, Ruby, SAS, Scheme, Smalltalk, Smarty, SQL, TCL, Text, Visual Basic, vb.net, VHDL, XML, X++.
> 2 votes

---
Tags: input-formats
---


# Question
Title: Connecting different content types/tables in Drupal with primary/foreign keys
I am using Drupal 7 and I want to create tables which have primary key and foreign keys using content types. Each table would be created using content types. Let's say, when I create Fruit content type, it should create a table for it, right? Then, I may have Price table, hence, I create a Price content type. Now, the Fruit id(primary key) should be connected with Fruit id in the Price table (content type). How's this possible? I don't know how to code the tables/content type schema.

Thanks for your help.

# Answer
Following link has a long discussion about foreign key in Groups.Drupal

=\> Add join/foreign key info to schema
> 2 votes

# Answer
I think this is what you want: References Module
> 1 votes

---
Tags: database
---


# Question
Title: Complex view based off of Node Reference
Drupal 7

1. Is it possible to get the current pages Node name and dynamically use it for a view using node reference? I have a content type called product and I am going to add a view to this content type that will show a list of image content types that have a node reference field set to the product content type.

For example:

```
"Furniture" page - content type "Product"
"Clothing" page - content type "Product"

"Image" content type - "Image 1" w/ a node reference field of "Furniture"
"Image" content type - "Image 2" w/ a node reference field of "Clothing"
"Image" content type - "Image 3" w/ a node reference field of "Clothing"
"Image" content type - "Image 4" w/ a node reference field of "Furniture"

```

So when I go to the Furniture product page my view will have Image 1 and Image 4 in the list and if I got to Clothing product page it will show Image 2 and Image 3.

If this needs more explanation please let me know.

# Answer
First add the node reference field as a relationship. That will enable the node reference field to be added as a contextual filter.

You can use EVA module to attach the view to your node page, which will automatically pass the node ID to the view (which your contextual filter should pick up and show only images referencing that node).

You can checkout Is there a good tutorial for "Entity Views Attach Module"? for more info on EVA
> 2 votes

---
Tags: views, nodes
---


# Question
Title: Nesting views with a node reference field
I am creating a Drupal site that is used as a task manager; each task node has the ability to reference another task node as a parent.
In the task list view, I would like to nest the same or similar view within each row, displaying that tasks children.

I've done something similar before by theming; however, I'm wondering if is there a standard, or emerging way of accomplishing this within the Views interface with a third-party module.

# Answer
You can solve it with Viewfield.

> View arguments are supplied through tokens.

So, what you should do:

1. Add new type of your view (new Block, for example) and add contextual filter by node reference field.
You can modify display format etc.
2. Create for your tasks new field "View Reference" and set your new display type of view. Check «Always use default value».
3. Set `[node:nid]` in Arguments input.

Tested on D7.
> 3 votes

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


# Question
Title: How to integrate with the jQuery Mobile framework?
I saw that Wordpress integrates a special plugin to transform Wordpress themes in mobile themes with an integration of the jQuery Mobile framework.

Is it possible to make for Drupal 7? Exist a module that can change or integrate with jQuery Mobile?

# Answer
> 7 votes
There are currently people working on an integration of jQuery Mobile and Drupal.

Take a look at the jQuery Mobile module and the jQM Theme. They are both currently only in dev, but I don't think there is much else out there yet. If you prefer you could always do the integration yourself and use the basic Mobile theme.

The creators of this module and theme also have a video from Drupalcon Chicago that was very interesting: Drupal on the go with jQuery Mobile

# Answer
> 3 votes
There is also the jQuery Mobile UI module which has been created by Jason Savio. I attended his presentation on this module at DrupalCamp Boston and totally loved it. It is currently only for Drupal 6 but surely if you reach out to him, he may be able to provide more input on it.

# Answer
> 3 votes
The problem with jQuery Mobile integration for Drupal is that Drupal is much more complex than WordPress. A blog theme only need a frontpage with a listing of latest entries and individual pages, so it's quite easy to make a jQuery Mobile (or any mobile) theme for WP. Drupal sites have a higher complexity. Currently there is no out of the box solution to convert your Drupal sites to a jQuery Mobile site. You need to customize your blocks, build some simple Views for your mobile theme.

---
Tags: 7, theming
---


title: Convert a Drupal 5 site to Drupal 7

text:
# Question
Title: Convert a Drupal 5 site to Drupal 7
We have a site with the configuration of Drupal 5, and we need to convert content, content types, views, and everything into Drupal 7. We have already tried with the normal conversion process like D5 =\> D6 =\> D7, but we are facing many errors; content and views are not imported correctly.

Is there any solution?

# Answer
> 3 votes
From what I've read, going from D5 -\> D6 -\> D7 can be a pretty involved task.

These two pages suggest you may want to start with a clean install of D7, recreating your content types and Views, then using Migrate module or a custom script to migrate the content/users. (The migration path from CCK to the Drupal 7 Fields is discussed here: http://drupal.org/node/1144136.)

I don't know how complex your setup is (how many Views, content types, and modules you have), but it's probably the case you are going to need a fair amount of work to bring your site into Drupal 7.

---
Tags: migrations
---