# Question
Title: User ID problem when programmatically creating nodes
I have written a migration script that migrates data from Drupal 4.7 to Drupal 6. It is highly customized for my purposes. I am able to create new nodes with no problem. However, after I save the nodes I am noticing that the user that created it is showing up as "Anonymous" and in the database it has a uid of 0. Yet, when I wrote my code I have set it to 1 when the migrated user id has not been found. I have even double-checked to make sure that it is setting the uid to 1.

Why would this be setting it to uid = 0 when I specifically set it to 1?

```
  $node = new stdClass();
  $node->type = 'opinion_article';
  $node->title = $blog->title;
  $node->body = $blog->body;
  $node->teaser = $blog->teaser;

  //We need to associate the content to the user that created it.
  $node->uid = 1;
  $node->name = $account->name;
  $node->status = $blog->status;
  $node->comment = $blog->comment;
  $node->promote = $blog->promote;

  //Set a default topic of Migration Data.
  $node->field_topics[] = array('nid' => 820); ###### Remember to update this node ID to reflect the topic nid on dev once created. It is nid 916 on the dev server.  ################

  //Set the parent group
  $node->og_parent = $parent_nid;

  //Create the node
  $node = node_submit($node);
  node_save($node);

```

# Answer
The problem is that node\_submit() contains the following code.

```
  if (user_access('administer nodes')) {
    // Populate the "authored by" field.
    if ($account = user_load(array('name' => $node->name))) {
      $node->uid = $account->uid;
    }
    else {
      $node->uid = 0;
    }
  }

```

When it's not able to load the user object having `$node->name` as username, it sets the user ID to zero. As you have already set the values for the node object, it is useless to pass the node to `node_submit()`; it would be better to just pass it to `node_save()`.
> 4 votes

---
Tags: nodes, migrations
---


title: Serve a csv file?

text:
# Question
Title: Serve a csv file?
I have a Drupal 7 site. After some form actions, I want the user to be able to click on a link to download a csv file of the results, but I don't need the csv hanging around the site forever. I have the file being written to the temporary file system using the `temporary://` streamwrapper.

Is there functionality in core that can offer this file for download? If so, what is it? Or else, do I need to/can I write a menu callback function that sets the mime header and all that?

# Answer
> 6 votes
Here's how I did it. I saved a file using `file_unmanaged_save_data()`

```
$file = file_unmanaged_save_data($csv, "temporary://" . $filename, FILE_EXISTS_RENAME);

```

Then I made a menu callback that was just `MENU_CALLBACK`, which calls this:

```
function download_file($filename) {
  $filename = t($filename);
  drupal_add_http_header('Content-type', 'application/csv; charset=ISO-8859-1');
  drupal_add_http_header('Content-Disposition', 'attachment; filename=\'output.csv\'');
  echo file_get_contents('temporary://' . $filename);
}

```

I should add an additional check to make sure that the file exists before echoing its contents.

# Answer
> 3 votes
The project Examples has a File Example module demonstrating the Drupal File API (and Stream Wrappers).

---
Tags: files
---


title: Custom Table or CCK?

text:
# Question
Title: Custom Table or CCK?
I'm currently working on a project with a new requirement that, in a nutshell, queues submissions from users and submits them them to a remote API:

* collects submissions from users (with a form)
* each submission points to a record on a remote system (uuid provided by remote API)
* each submission has a status (ie: new, accepted, declined)
* each submission stores a number of other fields of data
* each submission references a node id that already exists in drupal
* submissions with a status of "new" are presented to an administrator, who can accept or decline them (the queue)
* changes to submissions are audited
* submissions are never published as content, as they may contain personal info

Much of the data being stored for each submission is simply for interaction with the remote API. Only a small amount of the data for each submission is for human/administrator eyeballs.

I began architecting the storage for these submissions - basically just a really wide database table with one column that references a node id. The database table will also need to be exposed in Views, so that I can easily build pagable, filterable & sortable html tables. Will also perform some custom bulk operations (View Bulk Operations).

I'm now debating if it would be wiser to use a custom node type with a pile of CCK fields to store these submissions as unpublished nodes, rather than building it all custom. On the downside, I'd have to do a lot of form\_altering to get the submissions form to where I want it, and I really don't need a lot of node functionality (workflow, comments, titles, etc, etc). On the plus side, if using nodes+cck the Views integration comes for free, and it's likely quicker to build.

I'm working in Drupal 6, and an upgrade to Drupal 7 is at least a year out - but it's also something I need to consider when making this decision.

Any thoughts?

# Answer
> 2 votes
Go with CCK.

I've done this in Drupal 5, and I'm doing it again for Drupal 6. It's really not that hard to get this going. You gets all kinds of things for free both with CCK and Views. You already mentioned the benefits for Views, but it's the same for CCK. You simply create everything you need from the UI, and then export it to a file that gets read during your install hook.

Also, why write your own CRUD?

I'm doing something very similar. Take a look at my code over at Syndeploy.

I haven't exported the Views code yet, but I'll get there.

# Answer
> 0 votes
Sincerely, I'd build my own tables and information architecture.

You'll end up spending too much time fiddling with external information (cck) rather than actually getting your stuff to work.

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


title: Users can "promote" node for a fee?

text:
# Question
Title: Users can "promote" node for a fee?
Basically I want a classified ad system where users can pay extra to make their ad more visible - sticky at the top of lists, for example.

lm\_paypal or pay-per-node for the simple payment for posting a classified, but how about the extra payment for making it sticky? Any ideas?

# Answer
> 2 votes
The best answer I could come up with was simply have a different node type that is automatically sticky / treated differently by views, which can then be set as a different price using either of the two modules I mentioned in my question.

---
Tags: 6, payment-gateways
---


# Question
Title: Exposed filter render as autocomplete but I need a select field
I have a moderation queue that uses these filters:

* published: no
* content type: xxxx
* author uid: EXPOSED

Drupal renders the exposed filters as auto-complete, but I need to use a select field. Is it possible?

# Answer
> 2 votes
This is an advance solution. Checkout how this guy did it for a similar problem by creating his own view filter. Creating custom filters in views 2

---
Tags: 6, views
---


# Question
Title: Programmatically add a taxonomy term to an existing content type
How would you programmatically add a taxonomy term to an already created content type? Presupposing that I already have the taxonomy field available on all the selected content-types beforehand.

I wish to bulk add a taxonomy term to several nodes. I noticed in the content display list there is a way to filter down to a term when it already exists on nodes, but is there a way to possibly add it to a content-type that doesn't have it yet?

I read the question and comments for Programmatically create taxonomy term, and this is partially there, but I don't know how to get it further.

# Answer
> 3 votes
You should check out the Views Bulk Operations (VBO) module. It allows you to create a View to generate a list of target nodes (or other things like Users) and perform an action on each of those nodes. One fo the available actions is modifying the taxonomy terms used on these nodes. This is actually the exact example used in the documentation for VBO on d.o. It seems like this is exactly what you're looking to do, just not actually programmatically. Maybe that's ok... but if not, you can create this VBO and then execute it programmatically using `views_bulk_operations_execute`.

---
Tags: taxonomy-terms, batch-operations
---


title: Media Mover and thumbnails

text:
# Question
Title: Media Mover and thumbnails
As it stands now I have MediaMover move images uploaded from Image FUpload CCK to S3 while deleting the source images. However, all I see are lists of the image files that I've uploaded. How can I display a thumbnail instead? I believe that I need to use Views, but I'm a Views noob.

# Answer
I can only assume your media mover process is upload file(s) to site, moved files to S3, copy S3 file location to the CCK field

For Drupal 6:

Install imagecache module and its dependencies. Create a imagecache preset call thumbnail of the size you want.

Create a view. Add the CCK field. In the settings select the format of the thumbnail preset.
> 1 votes

---
Tags: views, media
---


# Question
Title: Is there any way to find broken images across an entire site?
A number of images appear to be missing from within body fields of a site. It may have been like this for a while, so it's hard to say why. Folder/file permissions and paths are correct. The site was never moved and oddly, its only happening on some images and not all. Is there any way to detect which ones are missing on an entire site (40,000+ nodes)

# Answer
You can try the linkchecker module. It does check the source of `<img>` tags in the body, however it doesn't do it perfectly like it does for `<a>` tags.

* If `<img>` have alt text, it thinks it is fine, even though the link is broken
* `<img>` with links like "sites/testing/file/image.jpg" are returned *not* broken, links like "/sites/testing/file/image.jpg" are returned broken
* External links work pretty well.

Your best bet is to use Xenu’s Link Sleuth project (windows freeware)

Additional resources: Here is a comparison of the link page modules. Maybe you can find something else. Broken Link Checker thread on drupal.org
> 3 votes

---
Tags: 7, media
---


# Question
Title: Trade-offs between Job Queue vs. Drupal Queue
Anyone familiar with both Job Queue and Drupal Queue enough to offer an idea of the tradeoffs between the two?

In case it makes a difference, the site I'm working on uses Drupal 6. The queue I'll be creating will check a batch of user accounts with a REST API, to verify whether the users have logged into another system. Until the API gets updated (hopefully soon) each user requires a separate request, which is why I'm batching them.

# Answer
> 5 votes
Drupal Queue is a backport of Drupal 7's queue API for Drupal 6. It provides basically the same features as Job Queue. However a big advantage with Drupal Queue is that it uses the same API as Drupal 7 Core. This means if your module uses Drupal Queue in D6, your upgrade path to 7 will be effortless.

# Answer
> 0 votes
Another module to consider is PubSub.

Unfortunately I have only used PubSub before, not the others, so I can't compare them. If I were coding this, my first attempt would be to "publish" the users and have a drush command that would run periodically that would "subscribe" and handle them in batches.

---
Tags: 7, queue
---


# Question
Title: Highlighting primary link for specific content types
If I have a navigation item called 'News' in my primary links, how would I go about highlighting it for all news content type nodes?

Thanks!

# Answer
For Drupal 6 you have the choice of using the Menu Trails module, or the Menu Position module, which is available for both 6 and 7.

Both modules let you define criteria for where nodes should appear in the menu structure (eg, based on node type, and taxonomy).
> 4 votes

---
Tags: 6, entities, navigation
---


# Question
Title: Is there a CCK fieldtype that would display a static field?
I'm looking for something like the 'textfield' CCK fieldtype, except instead of displaying a label and an edit box with a value - it would just display a label and a value as text during both edit and view operations.

So for example, as a textfield it might display like this: label: \[value\]

as a 'static' CCK fieldtype it would display like this: label: value

I've tried disabling a textfield, but our User Experince folks don't like the fact that the field has a box, but yet really never becomes editable.

Thanks for all your help, Greg

# Answer
If I understand correctly, you don't need an input element at all. In this scenario, you can use `hook_form_alter()` or `hook_form_FORM_ID_alter()` in a custom module of site specific customizations to add a form element of type 'item':

```
$form['my_form_component'] = array(
  '#type' => 'item',
  '#title' => t('My Label'),
  '#markup' => t('This text follows the label'),
  '#description' => t('An optional description appearing below the markup'),
);

```

See the Forms API Reference for more details.

Edit: If you're not interested in custom modifications, the Markup module seems to provide this kind of utility in a contributed module for D6
> 2 votes

---
Tags: entities
---


# Question
Title: How can i modify the height of input textfield in login form in drupal 7?
how can i costumize a form ( for example login form ) in /user and specifically the height of input textfield? And the button "login"? I try with the function theme\_form\_element() but nothing good!

# Answer
.form-submit is for the submit button.

textfield

```
#my-form input {

}

```

text area

```
#my-form textarea {

}

```

form selects

```
#my-form select {

}

```

submit button

```
#my-form .form-submit {

 }

```
> 1 votes

# Answer
The easiest way to do this, is with CSS

An example could be:

```
.form-submit {
  height: 30px;
 }

```

You can't set height on textfields and submit buttons AFAIK, only text areas.
> 1 votes

---
Tags: theming
---


# Question
Title: Adding a full screen background image to Drupal 7 / Bartik theme
Has anyone managed adding an image as background to a Drupal 7 with default Bartik theme?

Maybe using a fullscreenr plugin for jQuery?

I'm not sure where to store that code best and do I need to include jQuery or is it already included (I suppose it is included, but you can't call **$()** for some reason there? What does it mean to be changed in fullscreenr code below?)

And how can I call **$.fn.fullscreenr** (or whatever should be called to plant the background image) in Drupal?

Thank you! Alex

```
/**
* Fullscreenr - lightweight full screen background jquery plugin
* By Jan Schneiders
* Version 1.0
* www.nanotux.com
**/
(function($){
    $.fn.fullscreenr = function(options) {
        if(options.height === undefined) alert('Please supply the background image height, default values will now be used. These may be very inaccurate.');
        if(options.width === undefined) alert('Please supply the background image width, default values will now be used. These may be very inaccurate.');
        if(options.bgID === undefined) alert('Please supply the background image ID, default #bgimg will now be used.');
        var defaults = { width: 1280,  height: 1024, bgID: 'bgimg' };
        var options = $.extend({}, defaults, options);
        $(document).ready(function() { $(options.bgID).fullscreenrResizer(options); });
        $(window).bind("resize", function() { $(options.bgID).fullscreenrResizer(options); });
        return this;
    };
    $.fn.fullscreenrResizer = function(options) {
        // Set bg size
        var ratio = options.height / options.width;
        // Get browser window size
        var browserwidth = $(window).width();
        var browserheight = $(window).height();
        // Scale the image
        if ((browserheight/browserwidth) > ratio){
            $(this).height(browserheight);
            $(this).width(browserheight / ratio);
        } else {
            $(this).width(browserwidth);
            $(this).height(browserwidth * ratio);
        }
        // Center the image
        $(this).css('left', (browserwidth - $(this).width())/2);
        $(this).css('top', (browserheight - $(this).height())/2);
        return this;
    };
})(jQuery);

```

# Answer
> 5 votes
Are you actually trying to use fullscreenr because you want a full screen background image that re-sizes with the browser? Or do you just want to have a background image?

If you're just looking to use a background image, you don't need jQuery. You can just edit the CSS. Though, if you're changing a builtin theme like Bartik, you should actually create a subtheme instead of editing the builtin theme's files.

If you actually need fullscreenr then you need to add the javascript files for the plugin and your file that calls the fullscreenr method to your theme's .info file (again, you should not edit the builtin theme's files, you should create your own subtheme). In the example below, I'm just editing Bartik's files (***don't do this, use a subtheme***). You should add the following to the theme's .info file

```
stylesheets[all][] = jquery/fullscreenr/css/fsbg-style.css
scripts[] = jquery/fullscreenr/js/jquery.fullscreenr.js
scripts[] = js/fullscreenbg.js

```

In this example, I added a `jquery` folder to the theme's folder and put the `fullscreenr` folder containing the plug-in into the `jquery` folder. I also slightly renamed the `style.css` file that comes with the plugin (in addition to deleting all the extra option stuff from that file). I put my code for actually calling the plug-in into the `js/fullscreenbg.js` file. The code looks like (details on why it's wrapped like that in the Drupal docs for changes from D6 to D7):

```
(function ($) {
  // You need to specify the size of your background image here (could be done automatically by some PHP code)
  var FullscreenrOptions = { width: 1024, height: 768, bgID: '#bgimg' };
  // This will activate the full screen background!
  jQuery.fn.fullscreenr(FullscreenrOptions);
}(jQuery));

```

I think this was the part you were really having trouble with.

There are some other minor things you need to do to set up the fullscreenr plug-in. I highly suggest getting it to work on a **very** basic html page outside of Drupal before putting it into a Drupal theme so you know you're at least using the plug-in correctly. Also, keep in mind that Bartik has a lot of other stuff going on with background colors and such on various parts of the page, so just adding the background image without editing the theme's CSS is not going to appear to make any difference.

---
Tags: 7, media, javascript
---


title: MySQL error when creating field schema

text:
# Question
Title: MySQL error when creating field schema
I have a problem when adding a new field to a content type. The schema installer for the specified field always causes the following error:

> Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'NULL DEFAULT NULL, PRIMARY KEY (`entity_type`, `entity_id`, `deleted`, `delta`,' at line 12.

Here is the `hook_field_schema()` implementation:

```
function google_directions_field_schema($field)
{
    return array(
        'columns' => array(
            'lat' => array(
                'type' => 'float',
                'size' => 'big',
                'not null' => false,
            ),
            'lng' => array(
                'type' => 'float',
                'size' => 'big',
                'not null' => false,
            ),
            'mapTypeId' => array(
                'type' => 'varchar',
                'length' => '15',
                'not null' => false,
            ),
            'zoom' => array(
                'type' => 'integer',
                'size' => 'small',
                'not null' => false,
            ),
        ),
        'indexes' => array(
            'lat_lng' => array('lat', 'lng'),
        ),
    );
}

```

I hope somebody can point out my mistake here. If some informations missing, please comment.

Thank you in advance.

# Answer
I fixed this problem by myself. Please note the mistyped column type name `integer` which is now `int`:

```
function google_directions_field_schema($field)
{
    return array(
        'columns' => array(
            'lat' => array(
                'type' => 'float',
                'size' => 'big',
                'not null' => false,
            ),
            'lng' => array(
                'type' => 'float',
                'size' => 'big',
                'not null' => false,
            ),
            'mapTypeId' => array(
                'type' => 'varchar',
                'length' => '15',
                'not null' => false,
            ),
            'zoom' => array(
                'type' => 'int',
                'size' => 'small',
                'not null' => false,
            ),
        ),
        'indexes' => array(
            'lat_lng' => array('lat', 'lng'),
        ),
    );
}

```
> 1 votes

---
Tags: 7, entities
---


# Question
Title: Running multiple Drupal installations on one URL: is it advisable?
My employer is considering replacing our fairly static website with Drupal, mainly so we can more easily implement a few ideas we've had, and also as a way of future-proofing it. It's something of an umbrella organization in that it has a few different customer-facing departments which aren't really related to each other, apart from falling under the same organization.

So, broadly speaking, each department has pretty specific needs - certain types of defined users, types of nodes; some require their own little forums, basic shopping carts, etc. My first instinct is to treat each department as its own Drupal installation with its own specific configuration of modules and keep things separate in that way. That said, there might need to be some functionality that spreads across the entire site. For example, one or two more senior members of staff might need to be able to log in and edit content across a few of the departments.

Is it possible to do this? To run different installations at domainname.org/dept1, domainname.org/dept2, domainname.org/dept3, etc. More importantly, is it advisable? What issues would I be likely to face if I were to go ahead with a setup like this?

# Answer
Not only is it not a problem but it's actually a quite common practice!

Check out this link for some tips: multisite howtos

The only suggestion I have is to give each site a subdomain rather than a subfolder, in my experience this works a lot better:

* dept1.domainname.org
* dept2.domainname.org
* dept3.domainname.org

(with all 3 hosts pointing to the same directory)

**Setup**

To set this up, just add a separate configuration folder under sites for each one:

* /sites/**dept1.domainname.org**/setings.php *// dept1 production*
* /sites/**dept1.stagingdomain.org**/setings.php *// dept1 staging*
* /sites/**dept1.domainname.local**/setings.php *// dept1 development*
* and so on...

Also, you should have separate **files** directories for each site and you can place site-specific (custom) modules on a modules subdirectory under the respective site's settings folder, to keep the /sites/all/modules directory uncluttered!
> 7 votes

# Answer
You should definitely have a look at Domain Access before choosing the multisite route. It can be a lot easier to maintain, and sounds more suited to your use case.
> 3 votes

# Answer
There is another approach: use OG (quite heavy, though).

There is especially a Drupal distribution for this kind of website: http://openatrium.com/
> 1 votes

---
Tags: multi-sites
---


title: Drupal 6.22 - Colorbox plugin missing

text:
# Question
Title: Drupal 6.22 - Colorbox plugin missing
I can't seem to get the colorbox plugin (colorbox-6.x-1.0) working with my Drupal 6.22 site. I'm currently working on Ubuntu Natty, and this is the folder structure for how I have the plugin and module setup:

```
 - sites
    - all
       - libraries
          - colorbox
             - colorbox
                - jquery.colorbox-min.js
                - jquery.colorbox.js
             - [other folders: content, examp1, examp2, examp3, examp4, examp5]
    - default
       - modules
          - colorbox
             - colorbox.module
             - etc, etc

```

Other stuff I already have done:

* jQuery Update plugin installed
* set permissions on `sites/all/libraries` folder using `chmod a+w ~/public_html/drup_test/sites/all/libraries`
* flushed all caches

I'm still after all of this getting the "*You need to download the Colorbox plugin and extract the entire contents of the archive into the sites/all/libraries/colorbox folder of your server*" error. Please could someone help me as I don't know what else could be the problem.

Thanks!

---

**EDIT: SOLVED!!**

With iStryker's help, I realised that there was some weird permission setting on the `/sites/all` folder. Whilst I haven't sorted out the permission issue on that folder, this alternative worked (if this has also happened to you)...under `/sites/default/` create a folder called `libraries` and put your jQuery plugins there. Then in *Drupal Admin \> Administer by Module \> Colorbox \> Colorbox Plugin Settings*, change the plugin path to `/sites/default/libraries/colorbox`. Not the grandest solution, but it works! Note that this also worked for the ShadowBox module and plugin.

# Answer
> 1 votes
Revised:

Your directory structure is correct. Your file directory permissions are not. Your `chmod a+w` command gives read and write permissions. In your case, to get rid error message you must have read and execute permission on the /sites/all/libraries/colorbox & /sites/all/libraries/colorbox/colorbox directories and read permissions on the 2 javascript files. Colorbox.module does a file\_exist call

`if (file_exists($library_path .'/colorbox/jquery.colorbox.js') && file_exists($library_path .'/colorbox/jquery.colorbox-min.js')) {`

Depending on your operating system, and setting, PHP's file\_exists() function is handle differently.

---
Tags: files
---


# Question
Title: How to maintain a local mirror on my Mac?
I have a personal Drupal 6 site being hosted commercially, and I would like to maintain a mirror of the site on my local MacBook for the purposes of developing custom modules and themes before deploying them. My question has two parts:

1. How do I set up my Mac so that it's ready to install Drupal?
2. How do I mirror my live site locally?

# Answer
> 7 votes
First, download MAMP.

Then, use MAMP to run Drupal locally (great info here, on drupal.org). Another option is the Acquia Stack Installer, but that's only better if you plan on running Acquia Drupal (at least, in my experience). MAMP is pretty powerful (I even have it, or XAMPP on Windows) running a few Intranets here and there).

You can either grab the files using FTP, and put them in MAMP's htdocs folder (or configure MAMP better, so you can put the files into your ~/Sites/ folder, for instance, using virtual hosts), or you could use source control, like Git or SVN, to manage your drupal site codebase—then just do a git clone to your computer and you'll have the entire codebase.

Use PHPMyAdmin or some other tool to download the database for your website, and then, using MAMP's installation of PHPMyAdmin, import that database into a database on your local computer. You'll need to make sure the settings.php file for your site can authenticate to MySQL on your local computer.

You can either set up a user for your local MySQL installation with the same password and username as your live server, or you can customize settings.php so it uses a different database name and credentials on your local computer. See, for instance, Suggestions for settings.php - Local dev, Development server, Live server

# Answer
> 3 votes
You can install MAMP on your mac in order to have Apache, MySQL and PHP and once you got Drupal installed, use FTP to access and download the following folders

1. /sites/all/themes
2. /sites/all/modules
3. /sites/default

copy them to your local site. Then add the Backup and Migrate module to your production site and to your local site. Then do the following

1. Create a backup of your production site using backup and migrate
2. Download the backup created
3. Go to your local site
4. Access the backup and migrate and restore the backup

That's it.

# Answer
> 2 votes
I would suggest using virtualbox, and get it to mirror your virtual environment as closely as possible. While you can use MAMP, you may find that there are subtle differences which bite you over time.

You may find that your local mamp is 64 bit and php 5.3, both of which are not guaranteed in the wild and both of which can bite you if you are not expecting them.

# Answer
> 1 votes
We're using Drush to keep sites in sync Dev/Staging/Production sites. Still ironing out the kinks but these two guides were invaluable to getting that rolling.

http://emspace.com.au/article/drush-aliases-primer-live-dev-syncing

http://drupal.org/node/670460

It's not as simple as using Backup and Migrate but I find once things are setup its faster to make small deploys and less prone to human error while updating.

---
Tags: 6, installation
---


# Question
Title: Drupal 7 aliases for a certain content type producing 404
I've got a custom content type ("charity listing"). Nodes in this content type should have the automatic alias charities/view/\[name-of-charity\]. They do indeed have this alias, when I try to edit a node the alias is there. However, typing the URL alias into the browser gives me a 404 error.

I have tried re-generating all the automatic URL aliases. Still doesn't work.

Help much appreciated!

# Answer
Do you have any folder's in your root directory called "charities" or is there any rewrite rule in your.htaccess file? I know it's a long shot, but I had a very similar problem once and this turned out to be the cause.

Also, try putting "?q=" before the alias when you type in the url and see if that works (e.g., http://yourdomain.com/?q=alias/path). it will point to problems related to my other suggestions.
> 2 votes

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


# Question
Title: Display current node rank from votes (voting api) in view
As in Title. I am struggling by programming but with no luck. Mechanism of voting api is too complicated for me. How can I display current node rank (order number) by votes?

My view now:

Sort critera: (Vote results) Vote results: Function desc

Relationships Node: Vote results

When displaying all results it's have order number thanks to view php field module.

Display position in rank of current, single node is hell for me. Custom sql query doesn't work at all.

I am using voting api and rate module.

Please help.

**EDIT**

Since I am using **+1/-1** I try to:

1. Sum +1 Votes
2. Sum -1 Votes
3. Subtract sum of -1 votes from sum of +1

Code:

```
$plus_rates = db_query("SELECT count(value) AS sum, content_id AS nid FROM votingapi_vote WHERE tag = 'vote' AND value_type = 'points' AND value = 1 GROUP BY content_id ORDER BY sum DESC, nid ASC");
                                         $minus_rates = db_query("SELECT count(value) AS sum, content_id AS nid FROM votingapi_vote WHERE tag = 'vote' AND value_type = 'points' AND value = -1 GROUP BY content_id ORDER BY sum DESC, nid ASC");

                     $pluses = array();
                                         $minuses = array();

                     while ( $row = db_fetch_object($plus_rates) ) {

                                            $pluses[$row->nid] = $row->sum;

                     }

                                         $plus_rates = NULL;

                                         while ( $row = db_fetch_object( $minus_rates ) ) {

                                            $minuses[$row->nid] = $row->sum;

                                         }

                                         $minus_rates = NULL;

                                         $keys = array_keys($minuses);

                                         foreach($keys as $k) {

                                                if (array_key_exists($k, $pluses)) {

                                                        $pluses[$k] = $pluses[$k] - $minuses[$k];

                                                }

                                         }

                                         arsort($pluses, SORT_NUMERIC);

                                         firep($pluses, 'pluses');

```

$pluses is sorted DESC but order is totally different from my view display:

* Sort cirteria: (Vote results) Vote results: Function desc)
* Relationship Node: Vote results, Aggregation function: total score

**EDIT 2**

I try to query votingapi\_cache directly but still order is totally different than in views:

> SELECT value, content\_id FROM votingapi\_cache WHERE value\_type = 'points' AND tag = 'vote' AND FUNCTION = 'sum' ORDER BY value DESC LIMIT 0 , 30

# Answer
> 0 votes
Ok I made it,

First View settings (View for main rating listing):

Sort criteria:

(Vote results) Vote results: Value desc, Node: Nid asc

Code:

```
$result = db_query("SELECT c.content_id AS nid, c.value AS sum
                                                                FROM votingapi_cache AS c
                                                                INNER JOIN node AS n ON c.content_id = n.nid
                                                                WHERE c.value_type = 'points'
                                                                AND c.tag = 'vote'
                                                                AND c.function = 'sum'
                                                                AND n.type = 'profile'
                                                                AND n.status = 1
                                                                ORDER BY sum DESC , nid ASC
                                                        ");
                           $is_rated = FALSE;

                                     while ($row = db_fetch_object($result)) {

                                        $counter++;

                                         if ($profile->nid == $row->nid) {

                                            $is_rated = TRUE;
                                          break;

                                         }

                                     }

```

In real it should be turn to temp table and cache too.

# Answer
> 1 votes
Check the comments on this question: Problem visualizing the rating value inside a view

It sounds like you probably haven't set an aggregate function on the Node: Vote Results relationship. You cab definitely display the total votes in a View without writing any of your own code.

# Answer
> 1 votes
`votingapi_vote` is not a table which you can access directly in views. If you use the data module, you should be able to make it accessable to views and create a view on it directly. It will be at a lower level than what you do through nodes but may be simpler for you.

---
Tags: 6, nodes, rating
---


# Question
Title: How to download files which are stored in the folder
I need some guidance regarding how to download a file.

Suppose I have a link called "Download." When I click on the particular link a PDF file should be downloaded.

How can I do this?

# Answer
> 3 votes
1. Make the link point to the PDF file
2. Make sure that the PDF is public accessible.

---
Tags: files
---


title: Module inheritance

text:
# Question
Title: Module inheritance
I'm wondering if there's some kind of inheritance system for Drupal 7 modules.
I want to create a module where users can upload a PDF file (attached to a node) that will bet uploaded to Calameo (a PDF online viewer) via REST web services.

How would I go about that? `hook_file()` doesn't seem to be sufficient and I'd feel kind of stupid just copying the whole file module and doing my adjustments, since I don't want to cope with upload of the file, just processing and displaying of it.

# Answer
> 4 votes
The hook system is the "OOP" way in Drupal. Drupal has been created when PHP was the only PHP version; that means that PHP didn't implement concepts present in other OOP languages, such as protected and private methods, interfaces, etc.

As result, Drupal didn't originally implement as much classes as the ones you find in the latest Drupal release, and classes where not used for the most important parts of the API implemented by Drupal, such as the content API, the form API, and the menu API. Drupal uses a lot of plain functions, but the way they are used allows to implement something similar to OOP concepts. The difference is that in Drupal it is not necessary to create a class that extends another class. Every module that implements the right hook can extend the code implemented by another module.

For example, if you need to extend the form provided by another module, you implement hook\_form\_alter() or hook\_form\_FORM\_ID\_alter(), and you can add form fields from the form created by another module, without to know which is "class" of that module. (Differently, in the OOP paradigm, you need to know which is the class that you want to extend.)

In the specific case, if you need to provide a way to allow users to upload a file while they are editing a node, which is then uploaded to a service site, then you can:

```
$form['mymodule_pdf_file'] = array(
  '#title' => t('Image'),
  '#type' => 'managed_file',
  '#description' => t('The uploaded PDF will be loaded on the Calameo web server.'),
  '#default_value' => variable_get('mymodule_pdf_file', ''),
  '#upload_location' => 'public://mymodule_pdf_files/',
);

```
* Add a form submission handler that load the file using `$file = file_load($form_state['values']['mymodule_pdf_file'])` upload it to the Calameo server.
* The files uploaded with the "managed\_file" form field are temporary, by default; that means they are removed when they are 6 hours old, the first time the cron tasks are executed. If you want to make them permanent, then you should use code similar to the following one:

```
$file = file_load($form_state['values']['my_file_field']);
$file->status = FILE_STATUS_PERMANENT;
file_save($file);

```

# Answer
> 2 votes
Drupal uses the the hook system, se the docs about the OOP in Drupal.

To make it short.

You can hook into the file system and do the processing you need; where and how to hook into depends on how you plan on using the file system, for example a file field or something else. If you want to create the upload form itself, save file uploads is pretty simple with `file_save_upload()` and `file_move()`.

Drupal has the entire theme system to control how something is displayed. There are many hooks that allows module to alter the output, and the site theme has the final say. Again how to proceed depends on your use case. If you use fields, creating a formatter would be the simplest way to create your custom output of the file.

You might want to take a look at the Scribd field, which might be doing what you want (only Drupal 6 atm, but the concept is still worth exploring it).

---
Tags: 7
---


# Question
Title: Extract the CSS class depending on the user type
Is it possible to extract the PHP string for user type, when the user is not an administrator user?

I need to discern between staff or non-staff users. I am aware of `$is_admin`, but in this case I would need something like `$is_staff`.
I need this so I can apply CSS styles to hide/show some fields that I want to be visible only to staff users.

Is anyone aware if there's anything that might help me?

# Answer
> 5 votes
If `$user` is the user object, then `$user->roles` is an array containing all the roles the user has. Drupal doesn't have the concept of user type, and the user roles are the closest it has.

If you want to check if the user has the "editor" role, for example, you can use code similar to the following one:

```
$global $user;

if (in_array(array_values($user->roles), "editor")) {
  // The user has the "editor" role.
}

```

Depending on what you are trying to achieve, you could also be interested in checking if the user has a specific permission, which is what is normally done in Drupal, where instead of checking the role assigned to a user, it is checked which permission the user has (using user\_access()).

As for hiding a form field, this can be done implementing hook\_form\_alter(), or hook\_form\_FORM\_ID\_alter() and altering the property "#access" of the form field.

Supposing that "example\_form" is the form ID for the form you want to modify, and "file" is the ID for the form field to change, then you can use code similar to the following one ("mymodule" is the name of the module; change it to match the name of the module that contains the hook):

```
function mymodule_form_example_form_alter(&$form, &$form_state) {
  $form['file']['#access'] = user_access('administer file');
}

```

"Administer file" is the permission that the user needs to have. Alternatively, if you want to only check if the user has the "editor" role, you can use code similar to the following one:

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

  $form['file']['#access'] = in_array(array_values($user->roles), "editor");
}

```

The global variable contains the user object for the currently logged in user.

---
Tags: users, theming
---


# Question
Title: Views... no format options in Fields->User?
In any Field using the USER type there are no format options. I'm making a user\_picture view and want to use the image cache option. But, at the bottom of any Field (pertaining to USER) where Format\* usually shows up, it's not there. Any ideas why? Thank you.

Also, Format\* works for nodes/content types. So, it's installed and working functionally.

# Answer
The short answer is that the user image is not a field unlike images attached to nodes. Views is using the field formatter that applies to fields and the way they are themed to allow you to select how you want to theme the field. This functionality doesn't work for properties like the user image.

The same goes for the say the node type. You can't select how to display the node type.

The easiest thing to do, is properly get the raw url and with theming turn it into the image with the image cache preset you want to use.
> 1 votes

---
Tags: views, 6, media
---


# Question
Title: How can I programmatically delete a user?
I'm new to Drupal development and am way over my head on this one. My company runs a subscription-based site offering market research to corporations. A company pays for a subscription and is granted a certain number of users. The person designated as primary user has the ability to add the remaining users themselves. We now need to add a function to allow them to delete a user who is no longer with their company. In doing so, we need the following to happen:

1. Delete the record from "users" database table
2. Change the author on any node created by the deleted user to "Anonymous"
3. Send an email to our internal support address letting them know that the user should be removed from other non-connected systems

The previous developer created a custom module for account management that allows adding users under several different circumstances. For example the user is completely new to the company adding it, which means they need to be added to our other unconnected systems as well, as opposed to providing a Drupal account to a user who is already in our other systems.
Currently a lot of stuff is being done with JavaScript using `Drupal.parseJson` to process the request based on the segments of the URL clicked. This was done for the sole reason of being able to update the page with the user list without a complete refresh. I personally don't care if this new function works that way, or if it needs to hit the server and refresh the page. I just need to find a way to do everything in the above list with a single click.

I've looked at the API and found `user_delete`, but it requires two params - `$edit` and `$uid`. The uid is no problem, but all I can find about `$edit` is that it's "an array of submitted form values." We're not using a form, though; our user lists are static text, and the actions all occur onclick of an href (at this point); so there's nothing being submitted. Is there any way I can fake the values of `$edit`? Or is there another way to do this? I'm reading about `hook_user()` and thinking that I'd call `user_delete()` somewhere to do the actual delete, and then my `hook_user()` implementation would handle the rest with the `$op = delete` param. But before I worry about how to get the other stuff happening, I need some guidance about how to call `user_delete()`.

Is it even worth it to use `user_delete()`? Would it be less trouble to just write my own queries to delete the user record and change any content records to "Anonymous"?

# Answer
This is not that hard, for D6 it would look like this:

1. Delete record from Drupal database users table;

```
user_delete(array(), $uid);

```
2. Change author on any content created by deleted user to Anonymous;

handled by the node module.
3. Send an email to our internal support address letting them know that the user should be removed from other non-connected systems

```
drupal_mail(...);

```

See `hook_mail` for details.
> 6 votes

# Answer
> Is it even worth it to use user\_delete()? Would it be less trouble to just write my own queries to delete the user record and change any content records to "Anonymous"?

To delete a user account, and assign all the nodes the user authored to the anonymous user, you simply need to call `user_delete(array(), $account->uid)`, or `user_delete(array(), $uid)`, depending if you have an user object, or a user ID.

As for assigning the nodes created with the user account being deleted, `user_delete()` invokes all the implementations of `hook_user()` passing "delete" as value for `$op`. The Node module implements the hook using the following code:

```
function node_user($op, &$edit, &$user) {
  if ($op == 'delete') {
    db_query('UPDATE {node} SET uid = 0 WHERE uid = %d', $user->uid);
    db_query('UPDATE {node_revisions} SET uid = 0 WHERE uid = %d', $user->uid);
  }
}

```

As you see, the function already updates the nodes authored by the user account being deleted, and any node revisions where associated with that user account.

The first parameter required from `user_delete()` is normally not used from the implementations of `hook_user()`, when the `$op` parameter is set to "delete." In most of the cases, the modules just use `$account->uid` to identify the user data they wrote in their own database tables. Even supposing the modules saved the data using another value to identify the user account, it is a value contained in the user object.

As per writing your own queries to delete the user account, I would not suggest doing it, as there could be modules that need to be informed when a user account is delete, usually to delete the data the module associated to that account. Rewriting code when there is already a function for this specific purpose could mean also to update the code when passing to a new Drupal version. The code would not be as generic as the code already used by Drupal.
> 4 votes

# Answer
**Non-Coding method:**

Modules needed: Triggers (part of core)

Step 1: Enable trigger module

Step 2: Create the send email action

* goto admin/settings/actions
* create 'Send email...' action
* fill out the form

Step 3: Create the trigger

* goto admin/build/trigger/user
* under *Trigger: After a user has been deleted* choose the action you just created

And your done! By default, when you delete a user, all of their post turns to *anonymous*.

Revised:

You now have a choice of where you want to delete users now.

* You can bulk delete users by going to `/admin/user/user`
* Go to the user profile page and delete
* Create your own custom module and function that calls user\_delete(array(), $uid)

Everyone of these ways will automatically sent an email out for every deleted user. I believe this way is more flexible as you can change the email body and recipient without editing any code.
> 0 votes

---
Tags: 6, hooks, users
---


# Question
Title: Views listing of content types a user is allowed to create
My site allows any user to register but I can verify who they are and then assign a role if I am satisfied.

Can anyone tell me how I can list the content type(s) a user with a particular role is allowed to create? Is this accomplishable via Views?

I also need to detect if they are allowed to create content and display a message to them if they are not.

Thanks.

# Answer
Like @googletorp said, you can't do this with Views, you will have to create a custom module. If you are creating your own module, this short snippet will give you an array (`$types`) with the links to content types the logged in user can create (D6). If the user cannot create any content types it will show a message:

```
<?php
  $types = array();
  foreach (node_get_types('types', NULL, TRUE) as $type) {
    if (node_access('create', $type->type)) {
      $types[$type->type] = l($type->name, 'node/add/' . str_replace('_', '-', $type->type));
    }
  }
  if (count($types) == 0) {
    drupal_set_message('You cannot create any content types!', 'warning');
  }
?>

```
> 1 votes

# Answer
This is not really something you can do with views. If you go to node/add you get the list of content types you can create. You could look in the code and copy/paste it to create a list of content types a user can create or simply link to that page instead.
> 0 votes

---
Tags: views, users, nodes
---


title: Ctools wizard back button with #action

text:
# Question
Title: Ctools wizard back button with #action
I'm trying to build a multi-step form with Ctools that will submit to another website upon completion (a hosted payment page). On the last form page, I have set the `#action` property in the form array to allow it to submit to this other website. My issue however is that this seems to affect the Back button behavior on this form page and directs me to the website I specified in `#action` when clicked, which is obviously not desired.

Are there additional settings I can tweak to make the Back button behave correctly with the `#action` property set?

# Answer
> 0 votes
I'm not able to use CURL or drupal\_goto(), as I needed to submit to the hosted payment page with the POST data, and be on the actual page (something only achievable with a physical form submission).

I ended up attaching a javascript click behavior to the back button to get the desired effect. Probably not the best solution, but it created the desired behavior.

# Answer
> 0 votes
You could drop the `#action`, then add some `curl()` code to your `#submit` callback function for the final step.

Trickier, sure, but it'll work without messing up the form caching for Drupal.

# Answer
> 0 votes
A simple solution would be to add a `drupal_goto` call to redirect to the payment site in the submit handler for the completion step.

---
Tags: 6, forms, chaos-tool-suite
---


# Question
Title: How do I include the full body field in the RSS feed for a taxonomy term?
How do I include the full body field in the RSS feed for a taxonomy term?

I tried enabling the default taxonomy view in Drupal, but it doesn't let me select any fields in the field list area.

# Answer
Drupal 6:

The easiest way is to:

Change the setting in /admin/content/rss-publishing

Or:

1. Install views
2. Enable taxonomy\_term view
3. Edit the 2 Feeds
    * Click on the gear right of *Row Style*
    * Change to full text
> 0 votes

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


# Question
Title: Problem changing the parent group for a node
I am trying to programmatically update the parent group of a bunch of nodes. But I am not having much luck. Below is what I have tried. What am I doing wrong here?

```
foreach ($groups AS $group)
{
  $node = node_load($group->nid);
  $node->og_parent = 23; //I also tried "$node->og_parent = array('nid' => 23);"
  node_save($node);
  unset($node);
}

```

One thing to note is that all of these groups already have a parent group set. Also this is on Drupal 6.

Thanks!

# Answer
> 1 votes
Ok, I figured this out. Here is what I had to do.

I had to address this slightly differently. I just had to change `$node->og_parent = 23;` to `$node->og_parent->nid = 23;`.

I just had to address the specific node id and that fixed it.

---
Tags: nodes, organic-groups
---


# Question
Title: Drupal7, draggable menu reordering missing, weight dropdowns instead
My client cannot see the draggable arrows next to menu items in the list view, while I can. I checked the cookies and it appears he is missing a cookie that I have in my browser:

> Drupal.tableDrag.showWeight

I'm not sure if this is relevant, but it looks quite promising.

We are both using Google Chrome 13.

Has anyone experienced this problem before, is there a way to force Drupal to regenerate the cookie?

# Answer
> 7 votes
Has your client accidentally clicked on "Show/hide row weights" in the top right corner of the menu list?

---
Tags: 7, routes
---


# Question
Title: Site turned to maintenance mode without changing any settings
I have a client who's site maintenance came up without anyone touching it. What would cause something like this?

I have theories that it's the backup module. Would that be possible?

I just went and turned maintenance mode off last night and just now but the maintenance mode eventually goes back up.

I reviewed this thread but it wasn't related: How to access the admin pages for a site stuck in maintenance mode?

Since, I'm pretty sure that clean url's are turned on already.

# Answer
> 3 votes
Drupal will show a site as offline if it cannot connect to the database, so you may want to check that the database is up and running.

---
Tags: 6, maintenance-mode
---


# Question
Title: How do I use the Hierarchical Select module?
I'm a total newbie in Drupal.

I have successfully installed Drupal 7 in my WAMP installation, downloaded the Hierarchical Select module, put it in the sites/all/modules folder, and enabled it.

How can I now use it? I don't see any option.

# Answer
> 1 votes
**Solution**

It seems that the read me file for Drupal 7 needs updating. Things have changed from Drupal 6 to Drupal 7. You will find Hierarchical Select available as a widget for the term reference field. To use it, select it at for the field you want to use it for. Also you should use alpha releases at your own risk. They are expected to have bugs.

**README**

You should read the README file!

From the Drupal 7 version:

> Installation
>
> ---
>
> 1) Place this module directory in your "modules" folder (this will usually be "sites/all/modules/"). Don't install your module in Drupal core's "modules" folder, since that will cause problems and is bad practice in general. If "sites/all/modules" doesn't exist yet, just create it.
>
> 2) Enable the module.
>
> 3) If you want to use it for one or more of your vocabularies, go to admin/content/taxonomy and click the "edit" link for a vocabulary. Now scroll down and you'll find a whole range of Hierarchical Select settings. All settings are explained there as well.

# Answer
> 0 votes
If you have added a taxonomy term field ("tags") to the "Article" content type, then the settings for the Hierarchical Select module are at admin/structure/types/manage/article/fields/field\_tags/widget-type.

You need to select "Hierarchical Select" as widget type.

---
Tags: 7
---


# Question
Title: Grant users of role the ability to edit users that have specific role
Is there a way to make it so users of role A can edit/create users with role B, but not users of role A?

# Answer
> 1 votes
Try the User protect module.

---
Tags: 6, users
---


# Question
Title: Rewriting taxonomy term in exposed filter
I have an exposed taxonomy term filter with values of "true" and "false". I would like to simply rename the options to "yes" and "no".

I can't simply change the taxonomy tern name since I am importing the values from a XML file.

How would you suggest I do this? Is there a simple CSS rewrite - changing true to yes, and false to no? Is there a field theme function I should use?

Thanks for any help.

# Answer
The easiest way is to use `hook_form_alter` to alter the names displayed in the options.

An alternative and a bit more tricky way, is to create your own views\_filter\_handler for them term used in the view, and customize how the exposed filter form should look like. This is a good solution if you are creating many views and want a single place to do the alterations. See How do I add dropdowns in Filter Criteria in Views module? for more info.
> 1 votes

---
Tags: taxonomy-terms, views, theming
---


# Question
Title: How much data is ok to put in the global $user object or $_SESSION variables?
I'm building a site and there are some pieces of information that I am going to use constantly. My thinking is that instead of making a ton of database calls, that I would put some of these critical pieces of info in the $user object or $\_SESSION variables. The question is, however, how much is too much info in these variables? Which should I use?

# Answer
It's hard to put a limit on things like this. But if you have more than a few pieces of data related to the user, you should probably put it in a table of it own. You can add the data to the user when loaded, and the performance hit will only be a few ms, not measurable really. You will make things easier on yourself by being able to query the data instead of having it stored as serialized data.

One thing to note about `$_SESSION` is that it should only be used for storing temporary data. A use case could be storing the values entered in a form, to let the user pick up from where he left, if he moves away from the form and comes back later.
> 3 votes

# Answer
This isn't a drupal way of dealing with global data. But if you want to go this way you are limited only by the memory available for your php script which is set in the `php.ini` under the `memory-limit` variable. Normally it would be set to 16-32MB but of course if you are able to modify the `php.ini` settings you could make it higher.
> 0 votes

---
Tags: 7, users
---


# Question
Title: Any working techniques or examples for a multistep AJAX enabled node form
There's an AJAX enabled multistep form in the examples module and another in Chaos Tools (ctools\_ajax\_sample.module) In both cases the form is built in the function and doesn't use the default core node form.

Closer to what I'm after is a multistep node form using hook\_form\_FORM\_ID\_alter() but this one isn't AJAX.

Is it possible to use `hook_form_alter()` to create a multistep node form that is AJAX enabled, or should I build my multistep form independently, then use `drupal_form_submit()` or a new node object to save the data?

Drupal 7

# Answer
> 1 votes
I think trying to use multistep, ajax and the core node form may be quite tricky. I am not going to say impossible, but I think it would be a lot of work.

I would think using a custom form and saving the node as you suggest may be easier, what you'll loose with this is the flexibility of having it integrated, so if you add a new field to the node, you will need to change your form.

---
Tags: nodes, ajax, forms
---


# Question
Title: Is there potential performance loss by using multiple nodeapi calls instead of one?
I have a fairly large site with multiple custom modules. I've started to split some of the larger modules out into smaller more maintainable ones.

I have one particular module that I'm splitting into three. It has a hook\_nodeapi function that does various different things, would there be much of a performance loss in splitting one nodeapi call into 2 or 3? Has anyone done any benchmarks on this subject?

# Answer
There is a performance loss with additional modules. Mostly due to more opening parsing and function\_exists() and memory use.

Node api in 6 will be called for every node action and called for each node. (in 7 multiple nodes can be used at once and there is a separate hook for each action)

So if you are careful:

* Put all your code inside a switch($op);
* Check the content types to work on what you need
* Keep DB queries to a minimum

there will be little overhead (some but not overwhelming).

If on the other hand your nodapi call, share DB queries (or can share DB queries), have a lot of setup / code which is common, then you may start to be hurting yourself performance wize.

One way round this is to be a bit more selective with the code you include:

```
mymodule_nodeapi($op, ...) {
 switch($op) {
  case 'load':
    // Insert common code here.
    if ($node->type == 'my_complex_node_type') {
      module_load_include('inc', 'mymodule', 'complex_type');
      mymodule_complex_load($node);
    elseif ($node->type == 'some_other_node_type') {
      module_load_include('inc', 'mymodule', 'other_type');
      mymodule_other_load($node);
    }
  break;
 }
}

```

*Rough pseudo code*

You can keep your code in seperate files to aid maintainability and keep load time down as files are only included/parsed when needed.

The downside is you need to manage the include and callback yourself rather than relying on module\_invoke\_all.
> 1 votes

---
Tags: 6, performance
---


# Question
Title: Problems primary links translate drupal 6
I have translate the link in my menu (primary links) in spanish, when i change the language from italian to spanish all the voices of the menu are translated except one ( the voice **apartamentos**) that is not visible but is right activated and setting as the other links. Do you know something?

# Answer
> 1 votes
I flush all the caches and the problem dont exist!

---
Tags: routes, i18n-l10n
---


# Question
Title: Can I use the $language variable in a Drupal 6 template file?
Is it correct to use the `$language` variable to make conditions in the page-front.tpl.php?
Is `if ($language == 'es')` correct?

# Answer
> 4 votes
The variables that are usable in a page template are visible in the source code of template\_preprocess\_page(). The template file you are referring to has the variable `$language`, which is a copy of the global `$language`, where `$language->direction` has instead the values "rtl" and "ltr."
The content of `$language` is an object with the following properties:

* 'language'
* 'name'
* 'native'
* 'direction'
* 'enabled'
* 'plurals'
* 'formula'
* 'domain'
* 'prefix'
* 'weight'
* 'javascript'

The line of code you wrote needs to be written as `if ($language->language == 'es')`.

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


# Question
Title: How to modify the Drupal Solr Search fields / apply custom fields / modify results
Am attempting to understand the report in admin/reports/apachesolr (Drupal 6). There are a large number of fields, and I am trying to understand

1) Are these the fields within the Solr index that are being populated, or are these within Drupal?

2) Assuming they are the Solr index fields, how can I make reference to them? For example, I have added a custom module that hooks into hook\_apachesolr\_modify\_query

$query-\>add\_filter("type", 'job'); // Works fine

$query-\>add\_filter("sis\_cck\_field\_job\_approved", 1); // Unsure

Will this filter on those custom CCK fields?

In addition, I am attempting to customise the way that the search captures search terms, applies those additional terms to specific fields and potentially saves them for emailing at a later date. With a little research I have come across Panels + Apache Solr Panels as one approach, and Views 3 and Apache Solr Views as an alternative approach. Is either preferred for a production site? I am specifically looking to

1) Add extra field filters to the search form

2) Build custom field filters (e.g. between Date X and Y)

3) Format the returning results, to show / hide specific node data, and censor particular fields based on a role.

Greatly appreciate all and any response!

Craig Moore

# Answer
I think that you may find that the Apache Solr Views module will do what you are wanting fairly well.
> 1 votes

# Answer
Looks like work is still being done on the date field side of things - see http://drupal.org/node/642430 for patch posted July 11 2011
> 0 votes

# Answer
Just for the record, I am outlining what I ended up doing.

I created a custom module using hook\_block, a quick test to what roles the user had, and then rendering a custom form (using the forms api). The form had a collection of fields, some of which were dropdowns etc populated from the "allowed values" from the various fields, e.g.

// Get the global\_settings like you described.

$serialized\_data = db\_result(db\_query("select global\_settings from content\_node\_field where field\_name='field\_job\_type'"));

$unserialized\_data = unserialize($serialized\_data);

foreach (explode("\n", $unserialized\_data\['allowed\_values'\]) as $type) {

```
$type = trim($type);
$types[$type] = $type;

```

}

$form\['contract\_type'\] = array(

```
'#type' => 'select',
'#title' => t('Contract type'),
'#options' =>$types,

```

);

with a callback that essentially constructed a url and submitted it with drupal\_goto(), in the format

url

/search/apachesolr\_search/test

parameters filters=created:\[2011-04-23T13:37:09Z%20TO%202011-07-22T13:37:09Z\]%20&solrsort=created%20desc

etc

So to recap I used hook\_block, a custom\_job\_search\_form() function to generate the form, fed it into drupal\_get\_form() to render the form, and finally a custom\_search\_my\_job\_form\_submit() which processed the variables and updated with drupal\_goto.
> 0 votes

---
Tags: views, search, entities
---


title: "AND" condition in multiple arguments

text:
# Question
Title: "AND" condition in multiple arguments
I am using Views 3 on Drupal 7.

I have a node with multiple terms, and I want to get nodes with all own tids at once.

I configure the contextual filter using the following values:

* Specify validation criteria:
    + taxonomy term
    + my vocabulary
    + Term IDs separated by , or +
* Checkbox "Allow multiple values" is on.

I try to pass '1,2' as argument to the view, and I get:

> node 1 (tid 1)
> node 1 (tid 1, 2)
> node 2 (tid 2)
> node 3 (tid 2)

By the way, the '1+2' argument gives me the same thing, and it's all right.

Why can't I get a result like the following?

> node 1 (tid 1, 2)

Do you have any suggestions?

# Answer
The problem is the way this is stored (1 to many relationship). There is no simple way of asking for nodes with terms 1 and 2.

To query for nodes they way you describe you would have to select nodes that has tid 1 and the nid is in a list of nodes that has tid 2. This is possible to do, but not something views support AFAIK.

To get this list, it would be easier to create the query yourself, or resort to `hook_query_views_alter`, which easily gives problems when maintaining.
> 2 votes

---
Tags: 7, views
---


# Question
Title: How to have CCK "Select list" field on my content type?
I want to include in my content type a CCK "Select List" field. Which module(s) should I enable so as to have it as a choice? Thanks

# Answer
> 3 votes
You have to enabled Option Widgets, as well as Number and/or Text.

Create a new field by going to admin/content/node-type/%content-type%/fields *(where %content-type% is the machine name of your content type)*

Create a new field. If you enabled Text module, you have the option of Text. If you enabled Number, then you have the option of Decimal, Float and Integer.

Select the Operations you want

Clicking Save will take to the Field setting page. Scroll down to the bottom and type in the allow values for your option widget.

And you are done.

# Answer
> 1 votes
CCK is the module you need - turn on *Options Widget* in your modules list under the CCK category. If you're using Drupal 6, the configuration should look like

If you're using Drupal 7, it should be even more straight forward as it's one of the options presented in the Field Type.

---
Tags: entities
---


# Question
Title: How to change the logo image dynamically when user change language?
How to change the logo image dinamycally when user change language by clicking in the flag? Exist an easy way to resolve this problems?

# Answer
paste in page.tpl.php some condition like

```
if ($user-> language == 'ru') $logo_url = '../rus.jpg'

```

etc
> 1 votes

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


title: Modify form values before creating node

text:
# Question
Title: Modify form values before creating node
I would like to use user-submitted data from one form field and add it to anther field, then submit the form to create a node that has my custom data. I'm having a hard time doing this. Any help is appreciated.

# Answer
This is what the node api hooks are good for.

From the docs:

> The node passed validation and is about to be saved. Modules may use this to make changes to the node before it is saved to the database.

You don't specify D6 or D7

**In D6**

hook\_nodeapi() $op == 'presave'

**In D7**

hook\_node\_presave()

You can modify values in your implementations of these hooks and they will be saved.

*edit*

If you need the NID you have to use hook\_node\_insert, but you will have to save to the DB directly.
> 8 votes

---
Tags: forms, nodes
---


# Question
Title: How translate a static block in drupal 6?
Does a variable exist that I can use to translate a static piece of text in a block? For example:

```
<?php if($language==english): ?>
   do something...
<?php endif; ?>

```

# Answer
> 1 votes
try this:

```
if ($user->language == 'ru') print 'Привет чувак!';
if ($user->language == 'en') print 'Hey Dude!';

```

---
Tags: 6, i18n-l10n
---


title: Drupal View Deleted by mistake

text:
# Question
Title: Drupal View Deleted by mistake
So this is my problem. I deleted a view for my drupal 5 site and have no idea to recreate it. I've tried to recreated the view but it's not the same what so ever. The view I deleted was for a video page. It displayed videos, from third-party sites. The view displayed the title and a thumbnail of the the embedded video. The view that I recreated only displays the video link and not the thumbnail too. I've tried altering the fields to display the thumbnails. But with no luck. Any Ideas?

# Answer
> 2 votes
There is no built-in way to restore a deleted view. Check if you have an old database dump somewhere (a regular backup, or maybe you created one when you put your site live). Depending on your hosting setup, your webhost may also have created backups of your server.

If that all fails, I'm afraid you will need to rebuild your view manually. While you're at it, consider upgrading your site to Drupal 7. Newer versions of Views make it really easy to export your view to code, so you can store your view in a version control system and never lose it again.

---
Tags: files, views
---


# Question
Title: How to use php filter for "contact page" in drupal 6?
How can I set the PHP filter for the "contact page" in Drupal 6? I want to insert some PHP code in the description of the contact form page. Thanks

# Answer
If your want to enable php code filter for user end, it could be dangrous for your site. Any one can perform some dangerous activity by adding php code. or if you want to alter the "contact form" then you have to use "hook\_form\_alter".
> 3 votes

---
Tags: 6, theming, input-formats
---


title: Advanced people filter in Drupal 7

text:
# Question
Title: Advanced people filter in Drupal 7
I would like to set up more filtering for the 'People' list in a D7 site -- by username and also by other fields I've attached to my users.

I haven't yet seen any way to hook into or modify the default functionality (please update me if I am mistaken). I did some googling and found reference to the Views Bulk Operation, but even the maintainer said very recently that it's still buggy, so I don't want to use it.

I also found this page which recommends creating a view -- is this the way I should do it?

# Answer
> 2 votes
Yes views is what you want to do. So long as you are using fairly standard modules (like profile) for your fields. You can create filters for any of them.

Create a view with the base type of 'user' and you should be good to go. You will need views and views\_ui module enabled.

Just be a little careful that if your view is open to the public you could potentially expose things like email address to the web.

---
Tags: users, input-formats
---


# Question
Title: Set the role of users when you're not the administrator user
Is it possible to do this? I can't see any permission I can grant for roles. I want to let a user create other users, but only of a specific role.

# Answer
> 3 votes
See the Role Delegation module for this feature.

# Answer
> 0 votes
I used this logic to get such a functionality in a project. and i hope it will be helpful to you.

```
function custom_module_name_perm(){
  return array('create specific role user');
}

function custom_module_name_menu(){

  $items = array();

  $items['custom-user'] = array(

     'title' => t('User Account'),

     'page callback' => 'drupal_get_form',

     'page arguments' => array('user_register_form'),

     'access arguments' => array('create specific role user'),

 'type' => MENU_CALLBACK

  );
}

function user_register_form(){
    $form['mail'] = array(

      '#type' => 'textfield',

      '#title' => t('Email Address'),

      '#size' => 25,

      '#required' => true,

      '#weight' => 10,

    );

    $form['name'] = array(

      '#type' => 'textfield',

      '#title' => t('Username'),

      '#size' => 25,

      '#weight' => 20,

    );

    $form['pass'] = array(

      '#type' => 'password',

      '#title' => t('Password'),

      '#size' => 25,

      '#weight' => 30,

    );

}

function user_register_form_submit(&$form, $form_state){

      $values = $form_state['values'];

      $save_user = user_save('', $values);

      $load_user = user_load(array('mail' => $values['mail']));
      $rid = <your role id>;
      db_query("INSERT INTO {users_roles} (`uid`,`rid`) VALUES (%d, %d)",          $load_user->uid, $rid);

}

```

---
Tags: 6, users
---


# Question
Title: How to take care of .htaccess of all sites in multi-site setup on Linux?
I've read this article: http://drupal.org/node/290768 which explains multisite settings on Linux.

But I need separate .htaccess for each site. How do I do it?

# Answer
You *cannot* have separate .htaccess files in Drupal's root directory.

You *can* have different rewrite condition inside your Drupal's root .htaccess file .

You *can* have separate .htaccess inside your sites/%mysite%/ directory which will control all the files, modules, themes, etc related to that specific site.
> 1 votes

---
Tags: multi-sites
---


title: WYSIWYG on panel panes

text:
# Question
Title: WYSIWYG on panel panes
Is it possible to use a wysiwyg editor like TinyMCE for editing content in panels. I want to be able to use TinyMCE for editing 'custom content'.

Another note: is it better to create nodes and just add them to the panel or to use the 'custom content' feature? Thanks!

# Answer
The last time I added Panels to a site, I used this code to preload the required libraries on panels edit pages.

```
  // Panels support.
  if (module_exists('panels') && $form_id == 'panels_edit_display') {
    // Load potential editor.
    foreach (filter_formats() as $format => $object) {
      if ($profile = wysiwyg_get_profile($format)) {
        wysiwyg_load_editor($profile);
        wysiwyg_add_plugin_settings($profile);
        wysiwyg_add_editor_settings($profile, 'advanced');
      }
    }
  }

```

From http://drupal.org/node/356480#comment-1190907 and the patch located in http://drupal.org/node/356480#comment-4256204.

This setup worked with:

* Drupal 7.0
* Latest WYSIWYG 7.x-2.x-dev from git
* CKEditor 3.6
* Panels 7.x-3.0-alpha3
* CTools 7.x-1.0-alpha4
> 2 votes

---
Tags: 7, panels
---


title: Where are temporary files created?

text:
# Question
Title: Where are temporary files created?
I want to know where Drupal (or its modules) create temporary files. Are they put in sites/default?

I'm especially talking about Drupal 6.

# Answer
> 17 votes
Files are created in the directory whose name is returned from file\_directory\_temp() which returns:

* The value of the Drupal variable "file\_temporary\_path," which is set from the setting page on admin/config/media/file-system (Drupal 7) or admin/settings/file-system (Drupal 6).
* If that Drupal variable is not set, then the function checks one of the following directories; if one of those directories exists, then it is returned (and used).

+ the directory returned from `ini_get('upload_tmp_dir')`
    + on Windows, the directories "c:\windows\temp" and "c:\winnt\temp."
    + on OSes different from Windows, the directory "/tmp."
    + on PHP version 5.2.1 or higher, the directory returned by `sys_get_temp_dir()`.
* If the variable "file\_temporary\_path" is not set, and the directories I listed in the previous point don't exist, or are not writable, the function uses the value of the Drupal variable "file\_public\_path"; by default that directory has the value `conf_path() . '/files'` that is the directory "files" contained in the directory containing the setting.php file used for the Drupal site.

The function set the variable "file\_temporary\_path" to the directory it found.

As far as I know, any module opens temporary files using a path starting with "temporary://" (available only in Drupal 7 and higher) or uses `file_directory_temp()`. The directory returned from `file_directory_temp()` can change from system to system, but modules always use that directory.

Drupal modules don't have the permission to write the directory containing the modules; it's quite difficult a module uses that directory to create temporary files. If you find a module that uses the directory containing the modules (or any sub-directory of that directory) report that as a bug.

# Answer
> 3 votes
The setting page at admin/settings/file-system contains settings for the directory used for temporary files.

Some modules could choose a different directory for temporary files. There's no standard folder location.

For example, the ctools module will create temporary cached files in the /sites/default/files/ctools directory. So it may vary.

---
Tags: files
---


title: Add Node Content Before A view?

text:
# Question
Title: Add Node Content Before A view?
What's the best approach at adding a node above a view. Right now i'm using the views html (before) to add 3 links to pdf's and some text.

I'm not interested in using panels; primarily, because the content has to appear below the view header.

Would it be best to add each file as nodes and join the view with a relationship?

# Answer
> 3 votes
Change the page view to a block view and add the block to the nodes in the content region.

# Answer
> 3 votes
As NMC said, views attachment is probably the easiest solution, to attached a view to your node.

You asked to display a node above a view. Depending on your arguments of your view, the easiest way is to use Attaching Display.

In your view:

* Create a new display called Attachment.
* Change Attachment Settings -\> Position: Before.
* Change Attachment Settings -\> Attached To: to the view you want.
* (Optional) Override and change the Style settings -\> Row Style: from Fields to Node (maybe also have to override Style settings -\> Style to unformatted before).

# Answer
> 0 votes
If the information you want to insert before the view is in a node, you can add a Views Attachment to your Page View so that the attachment View is rendered not on top of the Page View but within, below the Page View header.

---
Tags: views
---


# Question
Title: When using the batch API, can I setup multiple batch jobs or can I only setup one batch with multiple operations?
When using the batch API, can I setup multiple batch jobs or can I only setup one batch with multiple operations? I ask because of a data migration I am doing.

Also, will it run the batches and operations in the order they are received or are they run concurrently? I need to have some items imported before others. So I am concerned about this.

# Answer
You can call batch\_set() more than one time, and batch\_process() will execute all the batch sets that have been set with every call to `batch_set()`.

Normally a module will call `batch_set()` once, and pass as `$batch['operations']` an array containing all the functions to call, but if two different modules are setting their own batch sets, they will be both executed.
> 1 votes

---
Tags: 6, batch-operations
---


# Question
Title: How to positioning a field before another specific field with hook_form_alter()
I'm modifying a form by adding another text input, and I need to add this input right before a field. How do i do it? this is my code and it's working correctly:

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

    $form['input_latitude'] = array(
      '#type' => 'textfield',
      '#title' => t('Search address'),
      '#default_value' => '',
      '#prefix' => '<div id="map">Mappa qui</div>',
    );

}

```

I just need to position this before `$form['field_latitude']`.

# Answer
Set the weight property of your required lower than other.

$form\['field\_latitude'\]\['#weight'\] = 0; $form\['input\_latitude'\]\['#weight'\] = -10;

or function provintegra\_form\_alter(&$form, &$form\_state, $form\_id) {

```
$form['input_latitude'] = array(
  '#type' => 'textfield',
  '#title' => t('Search address'),
  '#default_value' => '',
  '#prefix' => '<div id="map">Mappa qui</div>',
  '#weight' => -10,
);

```

}
> 6 votes

# Answer
Each form element can have a weight.

> Description: Used to sort the list of form elements before being output; lower numbers appear before higher numbers.

See the example on the api.drupal.org page
> 1 votes

# Answer
Setting the "#weight" property for the form field works, but it doesn't give you the certainty the form fields are consecutive. If you want to be sure they are consecutive, you should use code similar to the following one (I suppose the form is not already using "latitude" as array index):

```
function provintegra_form_alter(&$form, &$form_state, $form_id) {
    $form['latitude']['input_latitude'] = array(
      '#type' => 'textfield',
      '#title' => t('Search address'),
      '#default_value' => '',
      '#prefix' => '<div id="map">Mappa qui</div>',
    );

    $form['latitude']['field_latitude'] = $form['field_latitude'];

    unset($form['field_latitude']);
}

```

This is similarly to what done in node\_content\_form(), where the form field for the node body, and the fields to select the input format are placed in the same array index (`$form['body_field']`). The structure of the node edit form array is the following:

```
  $form['body_field']['teaser_js'] = array(
    '#type' => 'textarea',
    '#rows' => 10,
    '#teaser' => 'edit-body',
    '#teaser_checkbox' => 'edit-teaser-include',
    '#disabled' => TRUE,
  );

  $form['body_field']['teaser_include'] = array(
    '#type' => 'checkbox',
    '#title' => t('Show summary in full view'),
    '#default_value' => $include,
    '#prefix' => '<div class="teaser-checkbox">',
    '#suffix' => '</div>',
  );

  $form['body_field']['body'] = array(
    '#type' => 'textarea',
    '#title' => check_plain($label),
    '#default_value' => $include ? $node->body : ($node->teaser . $node->body),
    '#rows' => 20,
    '#required' => ($word_count > 0),
  );

  $form['body_field']['format'] = filter_form($node->format);

```
> 1 votes

---
Tags: forms
---


# Question
Title: Creating a Faculty and Staff Directory with Links to their Profile Pages
If I add a field to a regular content type, I can configure that field in a view to link to the page for that content type. On the other hand, if I add a field to a User type, it seems that I cannot link that field in a view back to the user profile. How can I link a User field to the respective user's profile page?

Cheers.

# Answer
> 3 votes
The short and simple answer is there is no way to link a custom User field to the user page itself. However, this can be achieved by manipulating the view to expose the pertinent field data.

The situation is we have a couple of custom fields added to a User type. These are last and first name fields (field\_last\_name and field\_first\_name, respectively). Unfortunately there's no easy way (or is there?) to link these fields directly to their respective user's profile page through Views. I have posted an answer below that goes the theming route by creating .tpl.php files, but we don't want to do that because we also work with people who aren't coders. So how do we do this without code? WITNESS THIS!

Let's say we want to display a list of users' names, titles, phone numbers, email address in tabular format on a page. Great, pretty standard. Do the following (I will assume you've created the page already in Views):

* Add the User: Name (the one built into Drupal), field\_last\_name and field\_first\_name fields, rearrange them so that they're at the top, and then (this is VERY IMPORTANT), exclude them from being displayed
* Add the field\_last\_name and rearrange it so that it's below the first two instances of field\_last\_name and field\_first\_name

Now, we're going to configure the last field that should be in the list: field\_last\_name.

* Set it's label to Name
* Open up the Rewrite Results pane
* Check off 'Rewrite the output of this field' and 'Output this field as a link'
* Under 'Output this field as a link', check off 'Use absolute path'
* For the Rewrite text area, enter "\[field\_first\_name\] \[field\_last\_name\]"
* For the link URL, enter "users/\[name\_1\]" (name\_1 might not be the same for you, just use whatever == User: Name when looking at the Rewrite Patterns

Apply and Save

You can edit your table settings so that it's displaying the way you want it to display. You should now have a collection of names that link directly to their users' profile pages.

Essentially, we've exploited the rendering order of the fields. Since we organized our fields such that the username, first name, and last name came before every other field, their values were available to the Rewrite processor in the remaining fields.

The reason I chose the field\_last\_name field, was because that if you choose to enable column sorting on the table, then the table will still sort on the initial value provided by that field, and not the rewritten result. I wanted to sort by last name in my own case, this may differ for you.

Also a note, I have presupposed that you are using Pathauto to create friendly URLs in your website, and so the path to a user profile would look like http://site/users/username rather than http://site/users/uid. If this is not the case for you, and you'd like to use the UID field instead, substitute out the User: Name field for User: UID, and the procedure shouldn't change besides that.

Hope this helps someone, I was pulling out my hair for a long time until I figured out this little gem.

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


title: CCK Field Not Appearing in Row Array

text:
# Question
Title: CCK Field Not Appearing in Row Array
In Drupal 6, I added a custom field and attached it to a custom post type. I added sample articles and sample data in that custom post type. I added that custom field to a view. On individual articles, the custom field data shows up. But on a template that shows the five latest articles does not show the custom field.

I put this on that template:

```
<?php
 print '<pre>' . htmlentities(print_r($rows)) . '</pre>';
?>

```

And the custom field does not show in the array as it should.

This is the field I'm trying to show:

So is there somewhere else I need to activate this field? Thanks in advance.

# Answer
> 1 votes
If you use (display: node) you can check:

admin/content/node-type/{Your-Content-Type}/display

else if you use (display: fields) check you add it to fields.

---
Tags: theming
---


title: How to theme a menu block?

text:
# Question
Title: How to theme a menu block?
I have created a custom menu (lets call it "mynav") and in my theme I've created a template specifically for it (`block--menu--menu-mynav.tpl.php`) which contains:

```
<div id="mynav" class="<?php print $classes; ?>"<?php print $attributes; ?>>
  <?php print $content ?>
</div>

```

This works fine.

However I'd prefer to apply the id to the unordered list that is generated and contained in `$content`. I guess I need to create a function `MYTHEME_links__system_mynav_menu` like this:

```
function MYTHEME_links__system_mynav_menu($variables) {
  return "TEST"; // Generate HTML here (<ul id="mynav">...)
}

```

but it doesn't seem to have an affect.

What am I doing wrong?

# Answer
> 25 votes
In order to theme the unordered list, you need to call theme\_menu\_tree(). You can edit your template.php in order to call this.

```
function THEMENAME_menu_tree__MENUNAME($variables){
  return '<ul class="your-custom-class" id="your-custom-id">' . $variables['tree'] . '</ul>';
}

```

Then, if you want to theme your links, call theme\_menu\_link().

```
function THEMENAME_menu_link__MENUNAME($variables) {
  $element = $variables['element'];
  $sub_menu = '';

  if ($element['#below']) {
    $sub_menu = drupal_render($element['#below']);
  }
  $output = l($element['#title'], $element['#href'], $element['#localized_options']);
  return '<li' . drupal_attributes($element['#attributes']) . '>' . $output . $sub_menu . "</li>\n";
}

```

Now, the problem with Drupal 7 is that there is a major bug when it comes to displaying the active trail of custom menus.

See issue
Issue #520106 - No way to dynamically set active trail
Issue #942782 - Custom menus never receive an active trail

You are basically out of luck if you want some true custom menus. These issues are very long standing in the drupal community so I am not sure if they will be fixed anytime soon. I don't know if there is some PHP that can help with it. You can turn to some alternative modules in order to help ease functionaltiy, like Menu Attributes and Menu Block. They both can help get around the cruddy menu system in Drupal 7.

# Answer
> 2 votes
Inside your theme's template.php, this was the way to do things in Drupal 6

```
function MYTHEME_links__system_mynav_menu($variables) {
  return "TEST"; // Generate HTML here (<ul id="mynav">...)
}

```

In Drupal 7 you need to call

```
  function MYTHME_menu_link(array $variables) {

  }

```

---
Tags: 7, routes, theming
---


# Question
Title: How do I append a unique menu ID to the menu?
I'm using Drupal 7 and I want to append a unique ID to specific menus. My search result gives me the way to change the item of the menu, but I want to change the menu itself. Is there a way to do that?

# Answer
> 0 votes
Quick and dirty way:

Go to your themes directory and open up page.tpl.php. I'm using a Zen based theme and I have the following code which will print the secondary menu:

```
     <?php print theme('links__system_secondary_menu', array(
       'links' => $secondary_menu,
       'attributes' => array(
       'id' => 'secondary-menu',
       'class' => array('links', 'clearfix'),
      ),
      'heading' => array(
        'text' => $secondary_menu_heading,
        'level' => 'h2',
        'class' => array('element-invisible'),
      ),
    )); ?>

```

That can simply be edited to (modified line has asterisks):

```
     <?php print theme('links__system_secondary_menu', array(
       'links' => $secondary_menu,
       'attributes' => array(
       ***'id' => array('secondary-menu', 'my-new-id'),***
       'class' => array('links', 'clearfix'),
      ),
      'heading' => array(
        'text' => $secondary_menu_heading,
        'level' => 'h2',
        'class' => array('element-invisible'),
      ),
    )); ?>

```

**Edit:**

I don't really understand you when you say you're having trouble with the multi-dimensional menus and languages, but if you need more control, why not use theme\_menu\_tree? Override that in your theme's template.tpl.php with something like:

```
function my_theme_name_menu_tree($variables) {
  if ($variables['some_condition_you_care_about'])
    return '<ul class="menu" id="my_custom_id">' . $variables['tree'] . '</ul>';
  else
    return '<ul class="menu">' . $variables['tree'] . '</ul>';
}

```

# Answer
> 1 votes
You can use the menu attributes module to add custom classes, id's, names etc... to any menu item in Drupal. Very handy module when you are looking to alter Drupal's menu system to create a custom look.

# Answer
> 1 votes
As an alternative solution maybe you'd consider using the Menu block module. You use it to create blocks for specific menus, with custom depth ranges, starting item etc.

I think I use it for every menu in my site now as I love having that control AND **as an added bonus it will add your unique IDs to each menu.**

# Answer
> 0 votes
In order to theme the unordered list, you need to call theme\_menu\_tree(). You can edit your template.php in order to call this.

```
function THEMENAME_menu_tree__MENUNAME($variables){
  return '<ul class="your-custom-class" id="your-custom-id">' . $variables['tree'] . '</ul>';
}

```

Then, if you want to theme your links, call theme\_menu\_link().

```
function THEMENAME_menu_link__MENUNAME($variables) {
  $element = $variables['element'];
  $sub_menu = '';

  if ($element['#below']) {
    $sub_menu = drupal_render($element['#below']);
  }
  $output = l($element['#title'], $element['#href'], $element['#localized_options']);
  return '<li' . drupal_attributes($element['#attributes']) . '>' . $output . $sub_menu . "</li>\n";
}

```

Now, the problem with Drupal 7 is that there is a major bug when it comes to displaying the active trail of custom menus.

See issue
Issue #520106 - No way to dynamically set active trail
Issue #942782 - Custom menus never receive an active trail

You are basically out of luck if you want some true custom menus. These issues are very long standing in the drupal community so I am not sure if they will be fixed anytime soon. I don't know if there is some PHP that can help with it. You can turn to some alternative modules in order to help ease functionaltiy, like Menu Attributes and Menu Block. They both can help get around the cruddy menu system in Drupal 7.

---
Tags: 7, routes
---


# Question
Title: Different blocks on the same page, dependent on source link?
Is it possible to have a page that shows (e.g.) one of three different blocks, depending on the originating page link? I'm thinking the only way to achieve this would be to use # or something similar at the end of the URL.

Example:

```
link one: mysite.com/mypage#one
link two: mysite.com/mypage#two
link three: mysite.com/mypage#three

```

And then create the three blocks, with the visibility settings set appropriately.

Is this a robust solution that would work with URL aliases etc.?

Cheers, James

# Answer
> 2 votes
If you do it programmatically you can always parse url and display different content for different anchor or other param. You can always use one block for display content according to conditions.

Take a look to Context or Rules modules, maybe you find easier solution

---
Tags: blocks, uri
---


title: Access database tables with Views

text:
# Question
Title: Access database tables with Views
I want to show some fields of a database table with Views. There is no node type, fields, or something like that for this database table. How can I do that?

# Answer
> 4 votes
If you are using Drupal 6 and Views 2, the easiest way to accomplish this is by utilizing the Data module.

If you can't use the Data module and have to do this programmatically for one reason or another, the following steps will get you on your way to achieving your goal of being able to manage your custom tables through the Views GUI. The first step is implementing hook\_views\_api() in a custom module. hook\_views\_api() tells which version of Views you are working with and will be similar to the code below:

```
function mymodule_views_api() {
  return array('api' => 2.0);
}

```

Change the version number depending on which version of Views you are using. Then you will define your table structures in hook\_views\_data(). It is a fairly lengthy discussion, so I will point you to the resource at http://views-help.doc.logrus.com/help/views/api-tables on how to do this.

In order to add fields, sorts, etc. using your table's fields, you will have to add "handlers" to the various field definitions in hook\_views\_data(). The documentation at http://views-help.doc.logrus.com/help/views/api-handlers is a great overview of how handlers work, and the article by Treehouse Agency is a good working example of creating handlers and adding them to your fields.

Views programming is very tough at first, and it is always helpful to look at the built in examples that come with Views. For example, the modules/node.views.inc file will have the hook\_views\_data() implementation for the core Node module, and the module/node directory will contain all of the handlers it utilizes.

---
Tags: views, database
---


# Question
Title: Disable the default username in the registration form
I just installed and configured the logintoboggan module; I created extra fields and they are displayed just fine. I can't remember how to disable the drupal default username field on the registration form.

Can anyone assist me?

# Answer
> 5 votes
To disable a field in a form you must use hook\_form\_alter() like

```
MYMODULE_form_alter($form, $form_state, $form_id) {
  if ($form_id == 'user_register_form' ) { // id of registration form
    $form['account']['name']['#access'] = FALSE;
  }
}

```

> *#access*
>
> Used by: All elements and forms
>
> Description: Whether the element is accessible or not; when FALSE, the element is not rendered and the user submitted value is not taken into consideration.

I would also like to mention for other people reading this that this can also be accomplished with the email\_registration module

---
Tags: forms, users
---