title: Custom page with user selected nodes

text:
# Question
Title: Custom page with user selected nodes
I want to allow my users to print a pdf with the nodes they want.
I thought to create a view and use the Print module to generate the pdf, but I don't know how to let them choose the nodes.
I tried with Panels, but it's a bit complicated for standard user.
I thought to use some cck field to manage this, but since the custom page is per user, this is not possible.
Did anybody face the same problem?

# Answer
> 2 votes
You can use the Flag module to allow users to select nodes. Flag integrates nicely with Views, so you can create a view of nodes flagged by the current user.

# Answer
> 1 votes
You can try with nodequeue, or flag, and views.

If you use nodequeue, take a look at (for printing) : http://drupal.org/node/348682

---
Tags: 7, views
---


# Question
Title: Updating a field value in database via submit handler doesn't update the user profile in UI
I've created the field "Attending" that is attached to the user profile.
I have created a form with one checkbox element; when submitted, I've confirmed that the attending\_fielddatabase is being updated with the current value (0 or 1), but when I view the user profile through the UI, the updated value isn't being displayed.

The submit handler I am using is the following:

```
function rsvp_aform_submit($form, &$form_state) {
  global $user;
  db_query("UPDATE {field_data_field_attending} SET field_attending_value = :val WHERE entity_id = :eid", array(':val' => $form_state['values']['rsvp'], ':eid' => $user->uid));
  drupal_set_message(t('Your form has been saved.'));
}

```

Do you have any idea?

# Answer
I think that's the caching. First try to clear the cache manually. If that helps you should use cache\_clear\_all() to clear the corresponding cache tables (e.g. cache\_content, cache\_views\_data) after you update the db.
> 2 votes

---
Tags: forms, database
---


title: Check HTTP Status

text:
# Question
Title: Check HTTP Status
Is there a way to see what the HTTP status code is for a given page in Drupal?

For example, if I land on an access denied or page not found, can I see that in a status code and use it?

I am using Contexts to set block layouts, but on a 403/404 page, I don't want to show blocks. The same thing goes for Views- for some reason the pages are not redirecting to my custom error page, so setting ~path is not working.

I know there is a Context Error module that sets context if the page is 403 or 404, but I want to do the opposite, where the context is active IF the page is neither a 403 or 404, so I need to check the headers, not the path.

Edit: Unless there is a part of Context that I am missing to check page/view access?

# Answer
To fix this in context you should be able use context error to create a context; then, create a separate context which only applies if that context is not set.

To check the status code in code you can see what is returned by drupal\_get\_headers()
> 0 votes

---
Tags: 7
---


title: What are the benefits of Views 3?

text:
# Question
Title: What are the benefits of Views 3?
I am exploring a reason to upgrade from Views 2x to 3x.

What major benefits Views 3x provides? Are there any major API changes?

# Answer
There are hundreds of improvements. There are also many API changes, but they would only affect custom code using Views hooks, not the views themselves, which are converted upon update.

Some major features:

* Functionality similar to Semantic Views.
* Group-by support and aggregate functions: you can do queries like "give me the count of nodes written by each user, sort by the amount of nodes DESC."
* Views OR: you can separate different filter conditions by OR.
* Pluggable pagers.
* Pluggable exposed filters: expose items per page, sort.
* Header, Footer, and Empty Text as pluggable areas.
* Pluggable caching.
* More argument, filter, and sort handlers.
* Pluggable backends Flickr API, Apache Solr, RDF, etc.
* Displays can now be disabled, renamed, and reordered, cloned.
* A new UI in the Drupal 7 version.

Most importantly, it provides a much smoother upgrade to Views 7.x-3.x.

See the CHANGELOG.txt for a complete list of changes.
> 3 votes

---
Tags: 7, views
---


# Question
Title: Storing additional data with a node reference
What is the best way to store additional data in a Drupal 6 site pertaining to CCK node reference fields?

Suppose that a content type has a repeating node reference. I would like to be able to describe and/or annotate the node reference and describe the relationship between a "Person" content type and a "School" content type (e.g. "person attended school," "person donated to school"), or just have a chunk of text to go along with the relationship.

If you have a repeatable noderef field, you get a table like

```
CREATE TABLE  `content_field_foo` (
  `vid` int(10) unsigned NOT NULL default '0',
  `nid` int(10) unsigned NOT NULL default '0',
  `delta` int(10) unsigned NOT NULL default '0',
  `field_foo_nid` int(10) unsigned default NULL,
  PRIMARY KEY  (`vid`,`delta`),
  KEY `nid` (`nid`),
  KEY `field_foo_nid` (`field_foo_nid`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;

```

I could create a module that maintains a table like the following, which is used to store the metadata.

```
CREATE TABLE  `mymodule_noderef_metadata` (
  `vid` int(10) unsigned NOT NULL default '0',
  `delta` int(10) unsigned NOT NULL default '0',
  `metadata` longtext,
  PRIMARY KEY  (`vid`,`delta`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;

```

The problem with this is that I would have to do a hook\_nodeapi to update the table on both "nsert" and "update" to be able to handle revision rollbacks. In the particular implementation I am thinking of, there could be a pretty big performance impact of doing this.

Am I overthinking this? Is there a better way to do this?
I searched around for a module that does this, but didn't find anything.

# Answer
> 3 votes
Have you looked at CCK3 for Drupal 6? It's not stable yet, but the package does contain the Multigroup module which may be exactly what you need. A 'multi group' is a group of cck fields which can be repeated just like normal multi-value fields can. This means that you can group a node reference field with a text field and repeat that combination as many times as needed.

If you decide to give it a try, I recommend that you create a test site first to check if Multigroup and the rest of CCK3 is stable enough for your use case and to make sure that it doesn't interfere with other modules you need.

---
Tags: 6, entities
---


# Question
Title: How do I display a "Thank You" message after submitting a Webform 3.x form?
I recently upgraded a Drupal 5 site to Drupal 6. This upgrade also entailed upgrading the Webform module from version 2 to version 3.

I have a very simple webform setup that asks for a name and email address to sign up for a newsletter. Before upgrading, the webform administration area had a textarea labeled **Confirmation message or redirect URL**, but I no longer see this option.

When the form is submitted, it just reloads the form with empty values. The form is submitted properly, but I would like to be able to present a "Thank You" message instead of reloading the form page.

# Answer
> 2 votes
From the webform node, click the Webform tab, then the Form Settings sub-tab. There should be a large textarea labeled "Confirmation message".

If you are on node 1, the URL would be example.com/node/1/webform/configure.

---
Tags: 6, webforms
---


title: open_basedir and file uploads

text:
# Question
Title: open_basedir and file uploads
I've run across a problem where, when open\_basedir is enabled in my php.ini, my file uploads don't work in Drupal. The parent directory *is* included in the open\_basedir list, yet uploads still don't work. I've tested this both on my development server (running Windows Server 2008, IIS7 and PHP 5.3.2) and locally on my pc with XAMPP (running Windows 7 Enterprise, Apache 2.2 and PHP 5.3.5). The results are the same: as soon as open\_basedir is disabled, file uploads within Drupal work perfectly.

Here's an example of the error I get:

```
Warning: move_uploaded_file(): open_basedir restriction in effect.
File(public://field/image/example_1.jpg) is not within the allowed path(s):
(K:\content;L:\content;E:\content;E:\Upload_temp) in file_save_upload()
(line 1528 of E:\content\includes\file.inc).
File upload error. Could not move uploaded file.

```

This is what my File System settings are:

**Public file system path** \- sites/default/files/pictures

**Temporary directory** \- sites/default/files/pictures/tmp

Directory structure goes like this: E:\content\drupal. As evidenced, Drupal is within the bounds of open\_basedir. What am I missing here?

# Answer
The warning appears because public://field/image is not included in the list of directories the open\_basedir allows. Links are resolved, but an external path like public://field/image is not resolved to an internal path; for example, if the code is trying to read http://example.com/img\_png/image.png and img\_png is listen by the open\_basedir directive, the warning will be shown.
> 1 votes

---
Tags: 7, files
---


# Question
Title: Display a field 'Category' on the home page
How do I display a field 'category' (so as 'tags') in the node.tpl.php?

# Answer
Every field that is associated to a node is shown in the node view page, if the field is not set to be hidden.
You don't need to change the template file used for nodes, as it shows all the node fields by default. If you are not seeing a field is probably because that field settings are set to not show that field.

As you are referring to the home page (a.k.a. the front page), which normally shows the teaser of nodes promoted to front page, check the field settings for the teaser view mode.
> 0 votes

---
Tags: 7, entities
---


# Question
Title: Best way for including javascript/jQuery OnLoad in EVERY page on my site
Currently, in my theme.info file I am including 2 scripts:

```
scripts[] = js/backstretch.js
scripts[] = js/scripts.js

```

Backstretch is a jQuery plugin that allows for an expanding background image to cover your entire page.

I am currently using this code to autoload the JS:

```
(function ($) {

    var bgs=["bg1.jpg", "bg2.jpg"];
    var bgr=Math.floor(bgs.length * Math.random());
    $.backstretch(bgs[bgr], { speed: 1000 });

})(jQuery);

```

Two issues:

1. Sometimes it doesn't load the backstretch.js properly which may have something to do with my current OnLoad function in scripts.js. It loads the image but not maximum width/height of the browser initially.
2. For some reason, it doesn't work past 1 level in the site (although the JS seems to load when I check the site (could it be that the location of images is not relative of the JS file?) e.g.,:

> Works: site.com, site.com/page
>
> Doesn't Work: site.com/dir/page, site.com/dir/dir/page

I was wondering in my scripts file what would be the best OnPageLoad (or Preload?) function would be best to use?

Many thanks in advance.

# Answer
> 6 votes
Please read Managing JavaScript in Drupal, specifically the section on Behaviors. You'll need to do something like this:

```
(function ($) {

  Drupal.behaviors.exampleModule = {
    attach: function(context, settings) {
      var bgs=["bg1.jpg", "bg2.jpg"];
      var bgr=Math.floor(bgs.length * Math.random());
      $.backstretch(bgs[bgr], { speed: 1000 });
    }
  };

})(jQuery);

```

---
Tags: 7, theming, javascript
---


title: How do I remove a view?

text:
# Question
Title: How do I remove a view?
I installed Calendar and created a few views. I decided that I want to begin anew with fresh settings, so I disabled Calendar and removed it. The undesired view disappeared. I extracted a fresh copy of Calendar to sites/all/modules and enabled it, but the old view appears again.

Do you know how to delete them?

# Answer
Modules that are compatible with Views have default views; when you uninstall the module, the default views of that module are removed, but they re-appear when you install again the same module.
If you clone the default view of a module, and then uninstall that module, Views should show a warning about the module not being enabled, and not show the view in the list of views. Again, when you re-install that module, Views should show back the view you created.
> 2 votes

# Answer
If you customized a default view provided by the calendar module, you can revert it back to the default by clicking on "revert" (Click on the pointer behind edit).
> 3 votes

---
Tags: views, 7
---


title: Copying Drupal to a webhosting service

text:
# Question
Title: Copying Drupal to a webhosting service
What is the correct procedure to copy (transfer) a whole Drupal web with database to a web-hosting service? What are the problems that could occur? I'd like to change only the website name from localhost to domainname. It seems that everything else will be the same. I'm using Ubuntu and Drupal 7.0, Apache, Mysql. Should I consider the operating system of web-hosting and their server, database and similar things?

# Answer
> 3 votes
Roughly speaking, the procedure is to

1. copy all files to your webserver
2. create a database on the webserver
3. export the local database
4. import the db export in the webserver db
5. edit settings.php and set the new db name, user and pass
6. enjoy

The recommended webserver specs can be found at http://drupal.org/requirements. Since you have been developing on Linux, Apache and MySQL, use the same on your webserver (unless there is an important reason to change it). Also pay attention to your PHP version. Recent Ubuntu versions come with PHP 5.3, so it's best to use that on your server as well.

To prevent problems while importing your database (especially if you're using a tool like phpMyAdmin), it can help to empty (truncate) all `cache_` tables before exporting it.

---
Tags: 7, migrations
---


title: Calendar Themes

text:
# Question
Title: Calendar Themes
Are there any themes for the Calendar module? The out-of-the-box theme is not great. It be nice to find a new base theme without rolling my own.

# Answer
I do not know of any contributed themes that specifically cater to calendars. However, there are several sites that provide themes that are more likely to have considered Calendar module:
> 2 votes

# Answer
You could also try the FullCalendar module; I think it looks nice.
> 1 votes

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


title: Do not cache custom block

text:
# Question
Title: Do not cache custom block
I have a custom block created in code. I do not want to cache the block. I know I need to use BLOCK\_NO\_CACHE but I am not sure where to use it.

```
function mymod_block($op = 'list', $delta = 0)
{
    // set up an empty array which will contain the block contents
    $block = array();
    if ($op == "list") {
        // Generate listing of blocks from this module, for the admin/block page
        $block[0]["info"] = t('mymod');
    }
    else if ($op == 'view') {
        $block['content'] = "hello world";
    }
    // return the built content
    return $block;
}

```

# Answer
In your list $op, add:

```
$block[0]['cache'] = BLOCK_NO_CACHE;

```

However, note that Drupal 6 will not automatically update your block information, you will have to do that yourself, see privatemsg\_update\_6002() for an example.
> 6 votes

---
Tags: 7, caching
---


# Question
Title: Duplicate nodes returned from a module's SQL query
I'm in a spot of bother customizing the calendar block module for my needs. I've written a custom module that queries my database for published nodes that possess a specific taxonomy term. This works as desired; 3 node objects are returned as an array. However, this array is returned a total of 35 times. When I execute the query in my SQL manager the 3 rows are returned without repetition. Is there anything blatantly amiss in my code I haven't been able to spot?

```
/*
*
* Implementation of hook_calendar_block
*
*/

function calendar_block_mod_calendar_block(&$calendar, &$date, $op) {
  switch($op) {

   case 'alter':
                $sql = "SELECT DISTINCT node.nid AS nid
                                FROM {node}
                                INNER JOIN term_node term_node ON node.vid = term_node.vid
                                WHERE (node.status <> 0) AND (term_node.tid = 5)";

                $results = db_query($sql);

        while ($node = db_fetch_object($results))
        {
          $events[] = node_load(array('nid' => $node->nid));
        }

        foreach ($events as $var){
                $thisPath = $var->path;
                                $nodeTitle = $var->title;
                $thisDate = substr($var->field_event_date[0]['value'],0,10);
                                $realDay = substr($thisDate, 8,2);
                $realDate = substr($thisDate, 5, 2) . "-" . ( $realDay < 10 ? substr($realDay, 1,1) : $realDay ) ."-". substr($thisDate, 0, 4);

                                //$dayInfo[] = array ('date' => $realDate, 'title' => $nodeTitle,  'path' => $thisPath );

                                if ($date->date == $realDate) {

                                    $date->content = '<span class="tooltip">'. l($date->day, $thisPath) .'</span>';
                                    $date->content .= '<div class="tooltip_hidden">'. l($nodeTitle, $thisPath) .'</div>';

                                }
                            }
          break;

        case 'load':

        // Change the weekday's format and set the first day of the week to sunday.
        $calendar->weekdays =  array(
            'su' => 'S',
            'mo' => 'M',
            'tu' => 'T',
            'we' => 'W',
            'th' => 'T',
            'fr' => 'F',
            'sa' => 'S',
        );

        break;
  }

}

```

Edited to include all the code from my module - If anything I hope this can give others a similar starting point. if the code looks like a mess it's because it's my first module.

The code works: nodes with the desired taxonomy term are pulled from the database and each date on the calendar becomes a link to its corresponding node. However on closer inspection the 3 rows are returned 35 times, so doing anything beyond this (e.g. a choice of nodes if there are multiple ones on a single date) becomes a challenge / impossible.

# Answer
> 2 votes
I just took a quick look at the `calendar_block` module. From what I can tell, `hook_calendar_block` op `alter` is called for every single day in the calendar. I guess this makes sense at it allows you to alter the appearance of any day.

My guess is that the calendar on your site has 35 days in it which is why your query is run 35 times.

You could make use of a `static` variable to only do your stuff once or save the query etc.

Something like this could work:

```
function calendar_block_mod_calendar_block(&$calendar, &$date, $op) {
  switch($op) {
    case 'alter':
      static $events;
      if (empty($events)) {
        $sql = "SELECT DISTINCT node.nid AS nid
              FROM {node}
              INNER JOIN term_node term_node ON node.vid = term_node.vid
              WHERE (node.status <> 0) AND (term_node.tid = 5)";

        $results = db_query($sql);

        while ($node = db_fetch_object($results)) {
          $events[] = node_load(array('nid' => $node->nid));
        }
      }
      ....
  }
}

```

The above code doesn't catch the case where there is no result and is just meant as a proof of concept.

**Update**:
If you only want to run the entire code once, you could do something like this:

```
function calendar_block_mod_calendar_block(&$calendar, &$date, $op) {
  switch($op) {
    case 'alter':
      static $code_executed;
      if (!$code_executed) {
        ...
        $code_executed = TRUE;
      }
  }
}

```

---
Tags: 7, database
---


# Question
Title: Anonymous user edited data as draft/revision in drupal 6
I have a problem(may be only for me). My requirement is anonymous user or registered user if they like to make a modification in a node they should be permitted but the modifications made by them should be saved as draft until the admin approves them.

Please let me know how this can be achieved.

# Answer
> 2 votes
You can accomplish this with the Workflow module. You probably also need the Revisioning, Module Grants and Rules modules.

---
Tags: 6, nodes
---


# Question
Title: Are there cases where a third-party module would need to use its own file similar to xmlrp.php, cron.php, or authenticate.php?
Drupal 7 comes with some files (authorize.php, cron.php, update.php, xmlrpc.php) that bootstrap Drupal, and execute specific tasks.

Are there any cases where a module would need a similar file to bootstrap Drupal, and execute specific tasks? What are the pros of using this method instead of using a menu callback?
Why does Drupal use cron.php, but it uses a menu callback for the batch operations?

# Answer
> 2 votes
If you examine these files you will see that they share the bootstrap process, but the rest is different.

`index.php` calls menu\_execute\_active\_handler, which is a fairly heavyweight function. It essentially does everything to render a page (lots of hooks get called).

`cron.php` just calls drupal\_cron\_run, which is fairly lightweight (it just calls everything that implements hook\_cron and also bumps up the execution time via set\_time\_limit. This can decrease the memory footprint for expensive tasks (like rebuilding search indexes).

### Addendum to address the comment

Routing everything through index.php is good (front controller pattern). However, I see it being acceptable to have an extra script entry point for maintenance tasks that essentially run a single hook. I think of this as tasks that could normally be handled by drush, but need to be web-accessible or if a site doesn't have CLI capabilities. I have also run into a few cases where a site would bootstrap, but abort because of major problems (like a severely damaged menu cache). A maintenance script can fix this, if Drush can't be used.
It is worth noting, though, that extra precaution needs to be taken to lock down the scripts against malicious access and use.

# Answer
> 2 votes
Take a look at the discussion on this question What's the fastest method/implementation for an Ajax callback?

It shows that you can sidestep (or partially sidestep) index.php for performance reasons. This is unlikely to be a whole page, but perhaps a module specific ajax lookup.

Doing so carries potential security risks and compatibility risks so should only be done so in cases where you really need it to be fast and you don't need the flexibility that a normal menu callback will allow.

---
Tags: 7
---


# Question
Title: Views Row style Node heading between different dates
I need a view that display full nodes. So I have set my row style to Node. SO I have.

* Node 1
* Node 2
* Node 3

What I want is

* 11/05/2010
    1. Node 1
* 10/05/2010
    1. Node 2
    2. Node 3

I want to place a heading between each group of nodes on a certain date. Can this be done?

# Answer
I think you need fields to group by date. You can use Views node field to have a field that shows as a node (with a choice of build mode). I think that should work.
> 0 votes

---
Tags: 7, views
---


# Question
Title: Which library is better for image processing, GD2 or ImageMagick?
Is ImageMagick is supported by Drupal 7? If the answer is positive, which is better for image processing, between GD2 and ImageMagick?

Are any other alternatives for Drupal 7?

# Answer
> 5 votes
This depends on how many images you will be making on the fly and how many you will have cached.

100% true sweeping statement backed up by no cited sources: "The internet is all about speed."

If you are taking twice as long to render in Imagemagick then you are going against 'The Internet is all about speed'. But yoursite may not have lots of fresh big images getting themselves perpetually updated all the time, in which case use ImageMagick with some caching.

# Answer
> 6 votes
Drupal 7 supports ImageMagick with the ImageMagick module

I suspect better is subjective depending on your specific image manipulation tasks. The benchmarks I could find didn't conclusively favor either one overall but specific tasks were faster in one or the other. Opinion favors ImageMagick for quality but recent posts suggests GD2 has caught up.

---
Tags: 7, media
---


# Question
Title: Embedded images not shown in Google Chrome
I just realized that my embedded images, from an external source, aren't shown up in Google Chrome, but they are working fine in Safari and Firefox.
I cannot even click the link I generated with the tag, as it's not clickable.

Maybe someone has an idea on why this is happening.

```
<a href="content/httpwwwgooglede#content-top" title="Hier geht's zur Homepage von http://www.google.de"
<img width="404" height="304" border=1" title="" alt="Hier gehts zur Homepage von" http://www.google.de src="http://www.example/external/shots/get.thumbshots.ru/%3Furl=www.google.de%26size=m%26v=1%26lang=en%26"></img></a>

```

This was generated through the Display Suite Module, within a view:

```
<?php $text = ltrim($object->field_link['0']['url'],'http://')?>
<?php $orig = drupal_lookup_path(source,$object->path); ?>
<a href="<?php print $orig; ?>" class="homepages_klein" title="Hier geht's zur Homepage von <?php print $object->title; ?>">
<img width="202" height="152" title="<?php print $title; ?>" alt="Hier gehts zur Homepage von" <?php print $object->title; ?> src="http://www.kwengo.de/external/shots/get.thumbshots.ru/%3Furl=<?php print $text;?>%26size=m%26v=1%26lang=en%26" /></a>

```

# Answer
Is that an exact copy-and-paste? It isn't valid HTML. Try

```
<a href="content/httpwwwgooglede#content-top" title="Hier geht's zur Homepage von http://www.google.de">
<img width="404" height="304" border="1" title="" alt="Hier gehts zur Homepage von http://www.google.de" src="http://www.example/external/shots/get.thumbshots.ru/%3Furl=www.google.de%26size=m%26v=1%26lang=en%26" />
</a>
```

I think I fixed everything...

Whenever you have browser differences, run your page through http://validator.w3.org/ and fix the errors first.
> 3 votes

---
Tags: 7, media
---


# Question
Title: CCK Nodereference individual imagefields
Is there a way to use a nodereference field on each individual image in a node? The images are CCK imagefields.

# Answer
I don't think so, no. A node reference as its name suggests references an entire node. I've not heard of a CCK type that references another CCK field, though I could find a reference to a module that did that for D5. If that's your requirement, my recommendation would be to use an image-as-node method.
> 1 votes

# Answer
Looks like there was a d5 module for that: fieldreference. Here you'll find a discussion about a d6 port. Maybe you could use viewreference or noderefenrece in conbination with a view to solve your problem as stated in the discussion.
> 0 votes

---
Tags: 7, entities, media
---


title: Private File System and User Access

text:
# Question
Title: Private File System and User Access
Is there a way to protect Drupal files from being accessible by the file path (putting http://www.domain.com/files/image.jpg) in the browser URL from users poking around?

# Answer
> 1 votes
You can choose to let Drupal handle all file requests, this is done under file settings be selecting private files (`admin/settings/file-system`).

The access check is done in `hook_file_download`.

You should be aware that doing this will slow down the process of loading the files as Drupal has to be bootstrapped for every file that needs to be downloaded.

**Update**

The above method works be changing the file path created by `file_create_url` to a path that looks something like this: `system/files/[path]`. But I don't actually think that it prevents users from accessing the file directly. This would have to be setup in your webserver of choice. So all files would be protected that implement use `file_create_url` which should be any file/file link. Drupal also add some handling core files like user profile images. That leaves the access handling for all other files to you, which means you could allow imagecache files, while denying the original or whatever you like.

# Answer
> 2 votes
I see two ways of doing that:

1. Change the "files-mode" to private via `admin/settings/file-system` (as googletorp stated) AND changing the filepath to somewhere outside of your webserved files.
2. Change the "files-mode" to private and set some rewrite rules inside your `.htaccess` (or elsewhere in your webserver config). this gives you more control which files you want served private and which public. Something like:

```
RewriteEngine On
RewriteCond %{REQUEST_URI} ^/sites/default/files/(private/.*)$
RewriteRule ^.*$ /system/files/%1 [L]

```

Now every request directly to the "private" files will be rewritten to the systempath which is controled by drupal. So no access without drupal is possible.

---
Tags: 7, files, users
---


# Question
Title: Invalid argument supplied for foreach() error in a custom view
I wanted to display a table vertically and I found some code to do so, but I'm getting the following error:

```
warning: Invalid argument supplied for foreach() in site/modules/views/theme/views-view-table.tpl.php on line 35.

```

Line 35 contains the following code: `<?php foreach($row['title'] as $title): ?>`.

If I comment out that line, the table stops to be displayed vertically. I read on drupal.org forums that modifying the user's view permissions was a way to resolve, but I granted all permissions to views and I am still getting the same error.

How can I avoid the error appears?

# Answer
I fixed it..anyone using views hacks will need to nest the above statement in an php if statement to ensure there is data in the array.
> 0 votes

---
Tags: 7, views
---


# Question
Title: First AJAX request is working very well, next takes too much time
I'm working on ajaxing my site, for a long time now.
I found a method that's working for me, but only the first AJAX request is working the right way; the next request takes at least twice the time.

I thought, that it behaves like that because I load the whole scripts from a template file with every request. I removed the `print $scripts` from that template file; the result is that the requests take the same time took before.

This is the content of the files I am using.

**my\_ajax.module**

```
function my_ajax_init() {
  drupal_add_js(drupal_get_path('module', 'my_ajax') . '/my_ajax.js');
}

function acquia_slate_preprocess_page(&$vars, $hook) {
  if (isset($_GET['ajax']) && $_GET['ajax'] == 1) {
    $vars['template_files'][] = 'page-ajax';
  }
}

```

**my\_ajax.js**

```
Drupal.behaviors.my_ajax = function (context) {
  $('#content-group-inner a').live('click', function (e) {
    $('#content-group-inner a').not('.my_ajax-processed').addClass('my_ajax-processed');
    var url = $(this).attr('href');
    $('#content-region-inner').empty().html('<img src="ajax-loader.gif" style="margin-left:50%;"/>');
    $('#content-region-inner').load(url, 'ajax=1', function () {
      Drupal.attachBehaviors('#content-region-inner');
    });

    return false;
  });
};

```

**page-ajax.tpl.php**

```
<?php print $styles; ?>
<?php print $setting_styles; ?>
<!--[if IE 8]>
  <?php print $ie8_styles; ?>
<![endif]-->
<!--[if IE 7]>
  <?php print $ie7_styles; ?>
<![endif]-->
<!--[if lte IE 6]>
  <?php print $ie6_styles; ?>
<![endif]-->
<?php if ($local_styles): ?>
  <?php print $local_styles; ?>
<?php endif; ?>
<title><?php print $head_title; ?></title>

<?php if (arg(0) != 'admin') { ?>
  <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
  <script type="text/javascript">
    var $jq = jQuery.noConflict();
  </script>
<?php } ?>
<?php  print $scripts; ?>
<a name="main-content-area" id="main-content-area"></a>
<?php print theme('grid_block', $tabs, 'content-tabs'); ?>
<div id="content-inner" class="content-inner block">
  <div id="content-inner-inner" class="content-inner-inner inner clearfix">
    <?php if ($title): ?>
      <h1 class="title"><?php print $title; ?></h1>
    <?php endif; ?>
    <?php if ($content): ?>
      <div id="content-content" class="content-content">
        <?php ?>
        <?php print $content; ?>
        <?php print $feed_icons; ?>
      </div><!-- /content-content -->
    <?php endif; ?>
  </div><!-- /content-inner-inner -->
</div><!-- /content-inner -->
<?php print $closure; ?>

```

# Answer
> 2 votes
I found a solution that's working for me. I just changed that:

```
$('#content-region-inner').load(url, 'ajax=1', function () {
      Drupal.attachBehaviors('#content-region-inner');

```

into that:

```
var result = $('#content-region-inner:not(.my_ajax-processed)', context)
    .load(url,'ajax=1',function() {
               Drupal.attachBehaviors(result);

```

When using that, Drupal only fires up `Drupal.attachBehaviors()` once a time, no matter how much requests you do.

I hope this is working for you, too

---
Tags: 7, ajax, javascript
---


# Question
Title: Notification email on Content creation - admin approval?
I made a custom content type to replace comments, as the current comment options are not satisfactory for me. Anonymous users can create this content type (comment).

I need to send an email to the administrator users each time a new comment is written, to allow them to publish the new comments.

I searched for notification email, but it is not what I expected; it only allows to send emails on regular basis. Maybe I could not make it work.

How can I send automatic emails to administrators to notify them a new comment has been created, and it is waiting for approval?

# Answer
You should try the Rules modules, it can does exactly what you want.

> The rules module allows site administrators to define conditionally executed actions based on occurring events (known as reactive or ECA rules). It's a replacement with more features for the trigger module in core and the successor of the Drupal 5 workflow-ng module.
> 4 votes

# Answer
Another option would be the Subscriptions module.

> This module enables users to subscribe to be notified of changes to nodes or taxonomies, such as new comments in specific forums, or additions to some category of blog. Once enabled, all nodes will have an additional link that allows the user to change their subscriptions. Users have tab on their user screen to manage their own subscriptions. Users can also set an auto subscribe function which notifies the user if anyone comments on posts they have made. Admins can set this on by default.
> 0 votes

---
Tags: 7, notifications
---


title: Load custom template from MENU_CALLBACK

text:
# Question
Title: Load custom template from MENU_CALLBACK
Here's my current situation: I have an external authentication platform that loads in Drupal via an iframe. When the user is authenticated, the external application redirects the user to a Drupal endpoint I set up using:

```
function mymodule_menu() {

    $items['mymodule/oauth'] = array(
        'title' => 'My Module Receiver',
        'page callback' => 'mymodule_oauth',
        'access callback' => TRUE,
        'type' => MENU_CALLBACK,
        'file' => 'mymodule.pages.inc'
    );

    return $items;
}

```

And then my callback:

```
function myapp_oauth() {

    // Does some stuff, authenticates the user, etc

    echo '
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<body>
<p>Please wait...</p>
<script type="text/javascript">
  // Check if we are in an iframe or not
  if (window.location.href != window.parent.location.href) {
    // Reload the parent page
    window.parent.location.reload();
  } else {
    // Not in an iframe, so go to the home page
    window.location.href = "' . base_path() . '";
  }
</script>
</body>
</html>
';
    exit;

}

```

This seems like an incredibly sloppy way to handle this to me, I would prefer not to have to exit the application, and ideally I would want to simply define a tpl template file to load in place of the theme files for this page. Can someone recommend a better way to handle this?

# Answer
You can define a theme function that uses a template file, and then use theme function to for the menu callback output.
The following is example code for Drupal 7; similar code can be used for Drupal 6.

```
function mymodule_theme() {
  return array(
    'mymodule_oath' => array(
      'variables' => array('id' => NULL), // This is the list of the variables that will be passed to the template file.
      'template' => 'mymodule_oath', // Change this to the template file name.
    ),
  );
}

function mymodule_oath() {
  // Does some stuff, authenticates the user, etc.

  print theme('mymodule_oath', array('id' => 10));
  return NULL;
}

```
> 3 votes

# Answer
If you return false from your menu handler, Drupal will not call `page.tpl.php`.

So:

```
function myapp_oath() {
    // Echo your page here
    return false;
}

```

How to define the template depends a little on which version of Drupal you are using, but have a look at `hook_theme()` and `theme()` as a starting point.
> 1 votes

---
Tags: routes, hooks, theming
---


title: Using tokens under exposed views filter

text:
# Question
Title: Using tokens under exposed views filter
I have created a view with an exposed filter. In my display I have an Using tokens section that I do not want to display:

Using the theme developer this is the closest I can get to it:

So it seems to part of views bulk operations. How can I get rid of this text?

# Answer
I needed to overide a function in my template.php in my theme:

```
function blogbuzz_views_bulk_operations_fields_action_form($form) {
  $output = '';
  $access = user_access('Use PHP input for field settings (dangerous - grant with care)');
  if ($access && $form['#settings']['php_code']) {
    $output .= t('<h3>Using the Code widget</h3>
                  <ul>
                  <li>Will override the value specified in the Field widget.</li>
                  <li>Should include <?php ?> delimiters.</li>
                  <li>If in doubt, refer to <a target="_blank" href="@link_devel">devel.module</a> \'Dev load\' tab on a content page to figure out the expected format.</li>
                  </ul>', array('@link_devel' => 'http://www.drupal.org/project/devel')
    );
  }
}

```
> 0 votes

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


title: Redirect node type to a view

text:
# Question
Title: Redirect node type to a view
I have created a view that lists all the nodes of a certain type. If you go to view the node on it's own page I would like it to forward to my view. I tried doing this using rules but as I display the full nodes in my view it created a loop. I could give all my nodes a /nodetype/title path if I can set up some wildcard redirect.

# Answer
You could try this:

```
function MYMODULE_nodeapi(&$node, $op, $a3 = NULL, $a4 = NULL) {
  if ($op == 'load' &&
      $node->type == 'your_type' &&
      $_GET['q'] == '/node/' . $node->nid) {
    drupal_goto("/", NULL, NULL, 301);
    exit;
  }
}

```

It has the advantage of not using `hook_init()` and working regardless of custom url aliases.
> 0 votes

# Answer
Assuming you have a pathauto setting, such as, "the-base-from-the-auto-setting/\[nid\]", and all of these nodes use the automatic alias and not a custom alias, you can implement hook\_init() in a custom module:

```
function mymodule_init () {
  $path = drupal_get_path_alias(request_uri());

  if (strpos($path, "/the-base-from-the-auto-setting/") !== false) {
    drupal_goto("/the-path-of-the-view/", NULL, NULL, 301);
    exit;
  }
}

```

Note that drupal\_goto() calls exit on its own, but I keep the `exit` there as a reminder.

The above is untested, but modified from a code snippet that I frequently use that does a drupal\_not\_found(). See http://drupal.org/node/846930#comment-3451328 for more details.
> 0 votes

---
Tags: 7, rules, uri
---


# Question
Title: How to Remove read more link from front page
I use the Zen theme. I tried the solution given in Remove the 'read more' and 'Add new comment' links on the home page but I get a server error.

How can I remove the *read more* link from the front page?

# Answer
> 1 votes
The problem is in the node rendering, not the page rendering. Its a lower/smaller level than the preprocess page. You can use node template overrides such as "node-fonts.tpl.php" where "fonts" is the name of the node type. You will copy "node.tpl.php" to make this then modify it to your liking. This template is found in "\[SITE ROOT\]/modules/node/". Copy this to your theme folder. When I do this I create a subfolder called "node" to help organize the theme overrides.

If you want an easier solution then I would use ConTemplate (otherwise known as Content Template). This will allow you to control this from the content type admin config (creates a template tab which has options for the teaser and the full node). This also provides details about the available variables and sample data from the last inserted node of the type you are looking at.

---
Tags: 7, theming
---


# Question
Title: Can 'terms' be shared across 'vocabularies'?
I think I might have a fundamental misunderstanding of how taxonomy works in Drupal.

I've set up some vocabularies, such as 'accommodation', 'things to do' and 'eating out'. Within those, I've added parent terms 'accommodation types' and 'ratings' for accommodation, 'nationality' and 'suitable for' for eating out and so on.

Both vocabularies share some common features, though, such as 'location'. I set up 'location' within the 'accommodation' vocabulary first and then tried to make it available to 'eating out' by setting it as a parent, but I could only see other terms within the vocabulary.

What is the best way for me to allow each vocabulary to share a location without manually recreating and updating a 'location' term in each vocabulary (which surely must be the incorrect way of doing what I'm trying to achieve?)?

# Answer
It sounds like you are using vocabularies where you could be using nodes.

So a node called the 'grand hotel' would have a rating, it may be suitable for some types of people and may also have a location.

So you can create node type 'accommodation' which can use the vocabulary 'accommodation types', 'suitable for' and 'location'.

You could have a node type 'eating out' which can use the vocabulary 'cuisine type' but share 'suitable for' and 'location'

So each cafe or hotel could be a node of the respective type, but could appear in the search results for 'London' for example.
> 0 votes

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


# Question
Title: Remove the 'read more' and 'Add new comment' links on the home page
How do you remove or modify the list of links shown after the content?

# Answer
In your theme's template.php file, add this snippet:

```
function THEMENAME_preprocess_node(&$variables) {
  if ($variables['is_front']) {
    unset($variables['content']['links']);
  }
}

```

Remember to clear the cache afterward. And replace THEMENAME with your actual theme.
> 14 votes

# Answer
Modify the node template...

You can use node template overrides such as "node-fonts.tpl.php" where "fonts" is the name of the node type. You will copy "node.tpl.php" to make this then modify it to your liking. This template is found in "\[SITE ROOT\]/modules/node/". Copy this to your theme folder. When I do this I create a subfolder called "node" to help organize the theme overrides.

If you want an easier solution then I would use ConTemplate (otherwise known as Content Template). This will allow you to control this from the content type admin config (creates a template tab which has options for the teaser and the full node). This also provides details about the available variables and sample data from the last inserted node of the type you are looking at.
> 0 votes

---
Tags: 7, navigation, nodes
---


title: Error using form API on AJAX submit

text:
# Question
Title: Error using form API on AJAX submit
I am writing a form using the Drupal 7 form API. On submitting the form (via AJAX), the following error is displayed:

> An AJAX HTTP error occurred.
> HTTP Result Code: 500
> Debugging information follows.
> Path: /en/system/ajax StatusText: Internal Server Error ResponseText: Recoverable fatal error: Argument 1 passed to drupal\_array\_nested\_key\_exists() must be an array, null given, called in /drupal7/includes/form.inc on line 1986 and defined in drupal\_array\_nested\_key\_exists() (line 6296 of /drupal7/includes/common.inc).

I have two buttons on the form (copy & submit); one is an AJAX call which does some stuff, and the other is used to save the entered data.

This is the code I'm using:

```
function foo_form ($form, &$form_state, $foo) {
  $form['#foo'] = $foo;
  $form_state['values'] = $foo;

  $form['#prefix'] = '<div id="foo-form-wrapper">';
  $form['#suffix'] = '</div>';

  $form['copy'] = array(
    '#type' => 'submit',
    '#value' => t('Copy foo'),
    '#limit_validation_errors' => array(),
    '#submit' => array('foo_form_submit'),
    '#ajax' => array(
      'wrapper' => 'foo-form-wrapper',
      'callback' => 'foo_form_callback',
    ),
  );

  $form['name'] = array(
    '#type' => 'textfield',
    '#title' => t('Name'),
    '#required' => TRUE,
    '#maxlength' => 255,
    '#default_value' => (!isset($form_state['values']['name']) ? $foo->name : $form_state['values']['name']),
  );

  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Save'),
  );

  return $form;
}

function foo_form_callback($form, $form_state) {
  return $form;
}

function foo_form_submit ($form, &$form_state) {
  // Did we use the AJAX Call?
  // @todo: can we check this some other way?
  if (!isset($form_state['triggering_element']['#ajax'])) {

    // We didn't, save the entered values

    $form_state['rebuild'] = false;
    return;
  } else {

    // We did, do some behind the scenes stuff...

    $form_state['rebuild'] = true;
  }
}

```

Does anyone have an idea of what could be wrong?

# Answer
This line is wrong:

```
$form_state['values'] = $foo;

```

No idea what you are trying to do here, but you must not mess with `$form_state['values']` directly.

And what you are trying to do with the #default\_value shouldn't be necessary either. Form API should automatically re-use an already entered value, without you having to set it as the default\_value.
> 3 votes

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


# Question
Title: Drupal Commons notifications queue is not working
I have a site where we noticed the notifications are no longer working. The Queue states there are 238 notifications, and they are set to process immediately. The send method is "mail," and other emails go out from the site with no issue (e.g. registration emails).

I'm looking for any information which may help me troubleshoot this issue. There are no entries made in the watchdog table, no settings that I can see to log any kind of debug information, and no general setting or indication where I can see that would cause the problem.

The only thing I can guess is that updating Drupal Commons from an early version to 1.5 broke notifications in some way that I'm not familiar with. The only significant thing I turned up on Google is this: http://network.acquia.com/node/1469103.

It's a combination of so many modules interacting that I'm honestly not even sure where to start.

# Answer
The most obvious thing would be that cron is not running. You can see the last time it ran by looking at the site status report, that will also give you a link to run it manually.
> 1 votes

---
Tags: 7, emails, notifications
---


# Question
Title: How do you build a query to get a series of nodes and their field values filtered by field values?
Hopefully someone with Drupal 7 experience can point me in the right direction.

I'm creating a custom module to query some nodes and group and sort them by their field values.

I tried to use Views but it seems that it's not possible to get the results in the format I need so I've decide to query the database directly and build my own output.

What's the easiest way to query nodes in Drupal 7 as I notice there is a table for every field now which would seem to make any query that I have to write extremely complex?

Are there any methods to query node data and filter/group the results or can it only be done using raw SQL.

If the latter can you show me an example query that includes Drupal 7 Field values?

# Answer
I second Jeremy's suggestion of trying harder with views. However, if you absolutely must write your query directly in code, you'll want to use `EntityFieldQuery`.

For example, to get a count of all nodes with a text field value of 'foo':

```
// Get field information
$field = field_info_field('field_name');
$query = new EntityFieldQuery;
$query->entityCondition('entity_type', 'node')
  ->entityCondition('bundle', 'NODE TYPE')
  ->fieldCondition($field, 'value', 'foo')
  ->count();

$count = $query->execute();

```

If you don't want a count, but results instead, you would leave off the count part, and fetch results:

```
foreach ($query->execute() as $entity_type => $entities) {
  foreach ($entities as $entity_id => $entity) {
  ...
  }
}

```

The Commerce Guys also have a good blog post detailing a simple use case.
> 12 votes

# Answer
> I tried to use Views but it seems that it's not possible to get the results in the format I need so I've decide to query the database directly and build my own output.

My first suggestion would be to try harder with views.

> What's the easiest way to query nodes in Drupal 7 as I notice there is a table for every field now which would seem to make any query that I have to write extremely complex?

Yes it would be, which is why I made the first suggestion.

One tip could be to use a view to do the query but to produce your own output by invoking the view programatically.

A second tip would be to use the query which is generated by views as a starting point.

Fields in drupal 7 are defined via the field api. So you would need to look into that to find out how the fields are stored and help you to define your query. It can be done but it is not straightforward.
> 1 votes

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


# Question
Title: How to update path alias using MySQL command line
Many words have been renamed in the node using the below code:

```
update node set title = replace(title,'Apple','Orange')
update node_revisions set title = replace(title,'Apple','Orange');

```

But now I need to know how to update the path aliases using the MySQL command line; using the Drupal administration interface is very tiring, for thousands nodes.

# Answer
> 1 votes
I don't think you will have much success using mysql, the quickest way is likely to write a script that bootstraps drupal, loads each node and then saves the node, I think this should update the aliases.

# Answer
> 1 votes
You can find this interesting, it's the source of the pathauto\_nodeapi().

When you update a node, the function `pathauto_node_update_alias($node, 'update');` is called and update the path accordingly.

If you dig up into the source code, you'll reach the sql but as @user1258 says, it's not a very good practice to bypass the api and going directly through the db.

---
Tags: path-aliases, database
---


# Question
Title: Can Rules be used to disable the logo variable on some pages?
I have a change in Drupal 6 that I would like to make quickly without doing another SVN roll (until I get a more permanent solution in place) and I would like to create a triggered rule that will null the $logo variable that is being sent to the theme before it gets there.

I know how to tell it to identify the page in question and control it based on role. However, I am having trouble figuring out what PHP code to use in the custom PHP code section. Partly because I just don't know what variables are available nor at what point in the code flow I am sitting in (which is important for this).

Does anyone have any ideas or suggestions?

# Answer
I don't think that I'm on the wrong way (correct me if) but I think you should do a `hook_preprocess_page(&$vars)` in your theme's `template.php` and unset the `$var['logo']` when you meet your condition.

I wouldn't do that with Rules, I don't even know if it's possible.
> 1 votes

---
Tags: rules, theming
---


# Question
Title: Custom content type on registration form. No node title field
I set my custom content type to show on user registration form. I see cck fields, but I don't see node title field (required field) :(

Could somebody give any advice?

# Answer
Since you're using Content Profile, I assume you also enabled Content Profile User Registration. In the readme file of Content Profile you'll find:

> * The weight of the profile (configurable at the content profile settings) controls the position of the form elements on the registration page.
> * You may also hide some form elements at the settings. Basically it allows you to hide non-required CCK fields as well as the title. If the title is hidden, it is set to the user's name.
> * For more control over the title use the "Automatic Nodetitles" module, which can be found at http://drupal.org/project/auto\_nodetitle. It integrates fine with this module.

This means that you should be able to change the settings (like showing the title field) at `admin/content/node-type/[profile-content-type]/profile`, although I personally like auto\_nodetitle to set the title on content profiles.
> 1 votes

# Answer
Do you need title or you want it because form gives you error? Maybe Automatic Nodetitles (http://drupal.org/project/auto\_nodetitle) can help you? You can use that to have node automatic title like "Profile of \[Name\] \[Surname\]" and title will not be required field.
> 1 votes

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


# Question
Title: Create Content Type with a Default Title
How would for the Title of something to be default, static, unchanageable?

I've got a content type (plus others planned) that I plan on using as a data submittal for stuff similar to a "Quote of the Day" or "Create an Event for the Calendar" type content. I plan on keeping these "nodes" hidden for the most part and using views to view, edit, add, delete. The title will be mostly wasted space and unneeded.

How Can I do a Default, unchangeable Title for "Create" screen? Or... change a title for a content type to a different field type (Say... Date Field)?

# Answer
The Automatic Nodetitles module can do what you're looking for. When used in conjunction with the Token module, you have lots of options.
> 4 votes

---
Tags: 7
---


# Question
Title: how do I troubleshoot an external database access?
I successfully setup a Drupal 6 site to access external databases and present them in tables via Views.

Now I am trying to move to Drupal 7, and I'm not sure how to troubleshoot. In Drupal6, I can open table wizard after editing the settings.php file; it shows the new tables and I can add them.
Is there a way to know if Drupal 7 can see the database? I edited the settings.php file and created a module that is supposed to describe the database to Drupal 7, but I don't see the tables anywhere.

Any suggestions on how to troubleshoot? I don't get any errors or feedback; it simply doesn't do what I want it to do.

This is my code. I have a file called datamodel.module:

```
function datamodel_views_api() {
  return array(
    'api' => 2,
    'path' => drupal_get_path('module', 'datamodel'),
  );
}

```

I have also a file called datamodel.views.inc. This file is very long but I basically got everything working in drupal6 using table wizards; then I used the table wizards to Views definition for `hook_views_data()`, which I put in the following code.

```
function datamodel_views_data() {
  $data = array();
  $data['FundManager'] = array(
    'FundManager' => array(
      'title' => t('FundManager'),
      'help' => t('FundManager.FundManager'),
      'field' => array(
        'handler' => 'views_handler_field',
        'click sortable' => TRUE,
      ),
      'filter' => array(
        'handler' => 'views_handler_filter_string',
        'allow empty' => TRUE,
      ),
      'argument' => array(
        'handler' => 'views_handler_argument_string',
      ),
      'sort' => array(
         'handler' => 'views_handler_sort',
      ),
    ),
    'fundManagerCode' => array(
      'title' => t('fundManagerCode'),
      'help' => t('FundManager.fundManagerCode'),
      'field' => array(
        'handler' => 'views_handler_field_numeric',
        'click sortable' => TRUE,
      ),
      'filter' => array(
        'handler' => 'views_handler_filter_numeric',
        'allow empty' => TRUE,
      ),
      'argument' => array(
        'handler' => 'views_handler_argument_numeric',
      ),
      'sort' => array(
        'handler' => 'views_handler_sort',
      ),
    ),
    'FundManagerFirm' => array(
      'title' => t('FundManagerFirm'),
      'help' => t('FundManager.FundManagerFirm'),
      'field' => array(
        'handler' => 'views_handler_field',
        'click sortable' => TRUE,
      ),
      'filter' => array(
        'handler' => 'views_handler_filter_string',
        'allow empty' => TRUE,
      ),
      'argument' => array(
        'handler' => 'views_handler_argument_string',
      ),
      'sort' => array(
        'handler' => 'views_handler_sort',
      ),
    ),
    'FundManagerStartDate' => array(
      'title' => t('FundManagerStartDate'),
      'help' => t('FundManager.FundManagerStartDate'),
      'field' => array(
        'handler' => 'views_handler_field',
        'click sortable' => TRUE,
      ),
      'filter' => array(
        'handler' => 'views_handler_filter_string',
        'allow empty' => TRUE,
      ),
      'argument' => array(
        'handler' => 'views_handler_argument_string',
      ),
      'sort' => array(
        'handler' => 'views_handler_sort',
      ),
    ),
    'FundManagerDescription' => array(
      'title' => t('FundManagerDescription'),
      'help' => t('FundManager.FundManagerDescription'),
      'field' => array(
        'handler' => 'views_handler_field',
        'click sortable' => TRUE,
      ),
      'filter' => array(
        'handler' => 'views_handler_filter_string',
        'allow empty' => TRUE,
       ),
       'argument' => array(
         'handler' => 'views_handler_argument_string',
       ),
       'sort' => array(
         'handler' => 'views_handler_sort',
       ),
    ),
    'FundCode' => array(
      'title' => t('FundCode'),
      'help' => t('FundManager.FundCode'),
      'field' => array(
        'handler' => 'views_handler_field_numeric',
        'click sortable' => TRUE,
      ),
      'filter' => array(
        'handler' => 'views_handler_filter_numeric',
        'allow empty' => TRUE,
      ),
      'argument' => array(
        'handler' => 'views_handler_argument_numeric',
      ),
      'sort' => array(
        'handler' => 'views_handler_sort',
      ),
    ),
    'table' => array(
      'group' => t('FundManager'),
    ),
  );

  return $data;
}

```

I thought I followed the instructions, but nothing happens after I enable the module.

# Answer
> 1 votes
There are a few things you can do to debug this.

First up try switching the database and doing a general query on your 'fundmanager' table

Something like

```
 db_set_active('myexternal');
 $result = db_query('SELECT FundCode FROM fundmanager');
 db_set_active('default');

```

This will test that the database connection is working and visible from drupal.

If that is ok you can put some debug code in your `hook_views_data()` to make sure that is being called. Clear the cache and go to the list views page.

If both of these are present then it is likely a bug in your tablewizard code. This is a little buggy with external databases. It should define `base_database` somewhere but there is a bug

# Answer
> 0 votes
Most of the time, when something goes wrong there is an error displayed or logged *somewhere* depending on your PHP and system setup. Most Linux distributions provide a *production safe* PHP distribution that disable errors display. For developement, I suggest you enable errors display for PHP and install xdebug to enable stack traces in error messages.

In some rare occasions, Drupal fails to report an error and silently ignore the error. For these cases, tracing execution using Xdebug or the Zend Debugger are the best options. But they may take time to setup.

---
Tags: 7, database
---


# Question
Title: How to track popular categories (taxonomy terms)
On a website, we want to be able to produce a list the most popular categories (taxonomy terms). We don't want to rank terms by *term page* views but rank terms by *content page* views. When a user views a node page, the score/rank of all terms associated with the node should increase.

I couldn't find any module that provides this feature. As most statistics modules count and aggregate pages views, an acceptable solution would be using a reliable page view counting module that stores its information in the database (or any query-able external *datastore*). From there, a periodic ranking of the terms' popularity could be computed.

The solution has to work behind a caching reverse-proxy and when Drupal caching is enabled.

Note: we are already using Google Analytics to track traffic.

# Answer
> 2 votes
I don't know of a module which does this but you may be able to do it via google analyitics

token array will allow you to put all taxonomy terms into a custom variable

google analytics reports allows drupal to create reports from GA

So in theory you should be able to do this, I'm not sure how GA handles multiple values for the taxonomy

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


# Question
Title: How to do (unit) testing of Drupal specific JavaScript code?
For PHP code in custom module, we use SimpleTest. But how do you test the JavaScript code in a module or a theme?

I known about JavaScript testing frameworks like Jasmine or QUnit, but I'm curious to known if and how they are used to test Drupal specific JavaScript code.

# Answer
Right now we don't have any automated testing of the UI. There have been talks about using Selenium and there is even a proposed session about it for DrupalCon London, but i don't know of any work that has been done yet.

This could be a nice contribution for Drupal 8.
> 4 votes

# Answer
There is currently a gsoc project which takles with this problem: http://groups.drupal.org/node/139709

This plan sounds like a good solution
> 1 votes

---
Tags: javascript, testing
---


# Question
Title: Set location country based on coordinates
Is there a way to have Location pick the appropriate country based on the latitude/longitude entered when the node is saved?

# Answer
I believe Location has the ability to be added with a CCK field. The coords can then be converted into a long address. From there you should be able to pull out the country.

If you want to get even fancier you can use OpenLayers to show the location on a map. Does that answer your question?
> 2 votes

---
Tags: 7, location
---


# Question
Title: Show activities on users' posted content
I would like to provide a view, and something like a newsletter, where the users can see what actions (e.g. commented) are done on their posted content.

I thought I could do this with Activity, but I can only catch the events the users did on their posts.
Do have any idea on how to provide this?

# Answer
There's a module called Heartbeat that should achieve what you're looking for.

Here is a quote about it (from the module's project page):

> ... displays **user activity** on a website. This module is an API to log activity. The logged data contains message structures, attributes and variables. Once the activity messages exist in the database, they will be parsed and build into activity streams.
> 2 votes

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


title: Displaying node fields in a view

text:
# Question
Title: Displaying node fields in a view
I have a content type called Snippet. Snippet will have one image field and unlimited text fields.

I want to output fields in Views as:

* image field (image.png)
* text field (Text1)
* text field (Text2)
* text field (Text3)
* text field (Text4)

The image field is always first, and the different text fields follow it. I want to put this into a slideshow format with fade transitions.

Right now, the image field keeps reproducing itself after every text field.

Do you have any idea? Do I need to use grouping?

# Answer
> 2 votes
First, you should use Views Slideshow to do this.

On Drupal 7, add 2 more text fields in your content type; then add them to the view using *Content: \[your text field name\]*.

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


# Question
Title: A view of full nodes with comments that are a content type
I have split up this question into other questions previously trying to join them up to create my final solution. However the combination of what I am trying is causing problems.

I need a comment field to be able to use a CCK field. To do this I am using the nodecomment module as it allows you to use a content type for comment (http://drupal.stackexchange.com/questions/3202/creating-threaded-nodes). I will call this type CustomComment.

I have a custom node type, NodeType. This uses CustomComment for it's comments.

I need to create a view of NodeType. Which prints the full node (not fields). I also need to print the Comments as full nodes as well. Can anyone give any additional pointers. Part of me is thinking It might be better for me code this myself.

# Answer
First thing that comes to mind:

1. make a view for the nodeTypes
2. make a view for the customComments
3. take the corresponding view-template (depends on your views, check the views theme-information) of the nodeTypes-view and render the customComments-view inside it using views\_embed\_view()

Maybe there is a simpler approach for that.
> 1 votes

---
Tags: views, 7
---


# Question
Title: What are some ways to implement a hierarchical taxonomy page structure?
I'm currently trying to decide how to architect a client's site, and they need to have the need to have a hierarchical page structure. This must be able to go at least 3 levels in depth and have the option of exposing various filters.

I would assume that using a view that accepts multiple arguments and using taxonomies would be the way to go about developing this, but I wanted to ask this community if there were any contrib module alternatives I might look into as well.

# Answer
Drupal taxonomy was born for these needs.

And *Views* is perfect if you need simple filters.

If it's a high volume of pages and search functionality is going to be important, you can integrate it with Apache Solr and use **Facets** to filter. What better example than drupal.org
> 1 votes

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


title: Display a block in a page

text:
# Question
Title: Display a block in a page
I have a block created with Views that I want to display in a node where "PHP filter" is enabled. How can I display the content of that block?

All the examples I can find seem to be for Drupal 6.

# Answer
> 1 votes
```
     $block = module_invoke('views', 'block_view', 'ViewName-DisplayId');
     echo $block['content']['#markup'];

```

Parameters in module\_invoke:

1. module to call: 'views'
2. hook to call, in this case 'block\_view'
3. View name and display id of the block, separated by an hyphen. For example 'testview-block\_1'

The display id of the block it will show only when hovering the mouse over the "Block" word in the Views page of the Block. You will see an url like this: http:///admin/structure/views/nojs/display/testview/**block\_1** The **block\_1** is the display id in this case.

---
Tags: views, 6, blocks
---


title: What is the datatype?

text:
# Question
Title: What is the datatype?
The data I need are reported by Devel to be objects of stdClass.
What is that class? Is it a $node, $term or $page? Without guessing, how do I determine what that object is, in order to extract data?

# Answer
So, you have a variable. Lets say $object, and you call dsm, dpm, dvm or one of devel's other debugging functions to inspect it:

```
$node = node_load(1);
dpm($node);

```

Devel gives you something back like this:

```
object(stdClass)[79]
  public 'nid' => string '1' (length=1)
  public 'type' => string 'profile' (length=7)
  public 'language' => string '' (length=0)
  ...

```

The stdClass part just means that its a generic empty class, not any particular type of object. So, you can access all of its properties using standard object notation, but there are no object specific functions that you can call from the object.

So, for example, you can call:

```
$nid = $node->nid;
$type = $node->type;

```

But you can't do anything like this:

```
$result = $node->some_special_node_function();

```

Because there are no special node functions.

In Drupal, most things that get retuned as objects are just generic objects without any type special attributes or functions.
> 3 votes

---
Tags: 7
---


# Question
Title: Why creating the front page doesn't work?
I created the file named page--front.tpl.php, which is empty, in the Garland theme and set the front end to it. I still can access the front page: why?

# Answer
> 1 votes
Have you cleared the cache after you added the new template file in the theme directory? You should always clear the cache, once you change a template file for a theme already installed, or you add a new file that was not used before.

---
Tags: 7, theming
---


title: How to make a form on the backend?

text:
# Question
Title: How to make a form on the backend?
I want to create a form for the backend in Drupal 7, something like the following:

```
label 1   text box
label 2   text box
label 3   text box
label4    image
image

```

I then invoke the form output in the front page and other pages.

# Answer
You could do this by creating a content type with fields, or using Webform module. A lot depends on who will be filling out the form (anonymous visitors, content editors) and what you need to do with the results.
> 2 votes

---
Tags: 7, forms
---


# Question
Title: Adding the button implemented from "Printer, e-mail and PDF versions" in node.tpl.php
I am using Printer, e-mail and PDF versions, and I was wondering if there were a way I could place the print button in node.tpl.php above the `$content` area, instead of through the Drupal administration area. Could that be done through a variable?

# Answer
> 1 votes
In the administration area, disable the insertion of the link, then add the following (depending on which modules you use) to your `node.tpl.php`:

* Print: `<?php l('Print', 'print/'.$node->nid); ?>`
* Print to PDF: `<?php l('PDF version', 'printpdf/'.$node->nid); ?>`
* Send by email: `<?php l('Send by email', 'printmail/'.$node->nid); ?>`

---

However given you have your own theme template, it could be better to just modify the CSS applied to the print link(s) to be in a different location on screen.

# Answer
> 1 votes
Another options could be to use something like Display Suite to manage the layout of your node display rather than writing custom templates. Since the Print module implements hook\_content\_extra\_fields, the Print option should show up as a CCK field, that you could then drap/drop to your desired location.

---
Tags: 7, theming
---


# Question
Title: PHP XML parsing + daily authentication request
I have a news provider who sends me non-RSS XML feeds through HTTP requests that then need to be parsed to be used on my site. However, my first request to the external server always has to be an authentication request which expires after 24 hrs. The authentication ID gets sent back to me as an XML tag attribute in the source code of an otherwise empty document. I then have to include this ID with every news request I send back to the news server.

Is there any way to automate this entire process through a series of Drupal 6 modules, or is it just best to write the code directly in the template files and schedule a daily task to request the authentication ID?

# Answer
> 1 votes
You could write a module where you implement hook\_cron() to get the authentication ID and then store in the drupal DB (e.g. as variable via variable\_set()). After that you can use it inside your templates without any worry. But you have to trigger your `cron.php` once a day via a sytem cron-job or the poormanscron module. For PHP xml-parsing take a look at SimpleXML.

EDIT: Module creation:

For this job it would be a simple module. Take a look at the module-dev-guide. First you create a `YOURMODULE.info file`. After that you put your code inside a `YOURMODULE.module` file. Than implement that `hook_cron()` like that:

```
function YOURMODULE_cron() {
     update_news_service_id();
}

function update_news_service_id() {
    // add your code here
}

```

One more comment: If you try to solve it this way you must consider calling `update_news_service_id()` from the template (or `..._preprocess()`) if you run into an expired service id-error.

---
Tags: users, 6
---


# Question
Title: Migrating stories from Drupal 5 to Drupal 6
I am designing a Drupal 6 website from scratch, but I need to import about 5,000 story type nodes from a Drupal 5 website into the new one. What might be some of the ways to do that?

# Answer
I would personally follow the steps described below:

1) Transfer my Drupal 5 site in a test machine (possibly a local VMWare Development Machine).

2) Convert the Drupal 5 site to Drupal 6 using the guide that you can find here.

3) Use a Node Export/Import module to transfer the nodes from the local site to the new/from-scratch-built website. (e.g. Node Export module)

Note: If you do not know how to transfer your live site to your local machine the steps that I usually follow are:

a) Download the live site's files locally

b) Export the live database through PHPmyAdmin and save it locally

c) Import the database in my local MySQL server

d) Most of the times the links don't work properly in the local machine. The most common reason for this is that the local server does not have the capability for clean URLs so I add this to the httpd.conf:

```
<Directory /var/www/yourDirName>
   RewriteEngine on
   RewriteBase /yourDirName
   RewriteCond %{REQUEST_FILENAME} !-f
   RewriteCond %{REQUEST_FILENAME} !-d
   RewriteRule ^(.*)$ index.php?q=$1 [L,QSA]
</Directory>

```

and restart the apache server (notice that you will have to replace the "yourDirName" part with whatever your dir name actually is)
> 3 votes

# Answer
You might want to take a look at the Table Wizard module, which can assist with node imports from other systems (drupal sites or otherwise).
> 2 votes

---
Tags: 6, nodes, migrations
---


# Question
Title: How to detect when a user navigates to a taxonomy term page and access that terms data?
I'm making a custom directory navigation using the PHP code filter, and putting the code in a block. I need to detect when a user navigates to a taxonomy term page, and extract data related to the term so I can display the children of that term, just like a web directory.

# Answer
> 1 votes
Since there is no global variable that you could use to load the node, you will have to use code like the following:

```
<?php
if ( arg(0) == 'node' && is_numeric(arg(1)) && ! arg(2) ) {
$node = node_load(arg(1));
}
dsm(get_defined_vars());
?>

```

The dsm(get\_defined\_vars()); part is of course optional and will only work if you have the devel module enabled. However, if you do have devel, you will be able to see the whole $node object and the tags associated with the specific node.

Notice, that if you are in a term page, you can use the same principle to load a specific term. For example:

```
<?php
if ( arg(0) == 'tag' && is_numeric(arg(1)) && ! arg(2) ) {
$term = taxonomy_term_load(arg(1));
}
dsm(get_defined_vars());
?>

```

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


title: Customizing a block

text:
# Question
Title: Customizing a block
Is there a way to customize a block as follows?

```
label   input text box(the editor can input the content)
label   input text box(the editor can input the content)
label   input text box(the editor can input the content)
image(the editor can upload a image)

```

# Answer
> 2 votes
You can create a node-type with these fields and embed the node form in a block.

# Answer
> 0 votes
Perhaps you want to look at something like Node Blocks which lets you use all the power of CCK when building blocks. Technically you do end up with a node and a block, but I don't think that's a problem. Just use something like Search Restrict to stop people from ever finding the node.

---
Tags: 7, blocks
---


# Question
Title: Is it possible to create a menu item and leverage path aliases?
I am trying to create a menu item that loads a view mode that calls the callback function with the path alias.

```
$items['node/%/%'] = array(
  'page callback' => '_node_view_load',
  'page arguments' => array(1, 2),
  'access callback' => TRUE,
  'type' => MENU_CALLBACK
 );

function _node_view_load($node_id, $view_mode = 'default') {
  return drupal_render(node_view(node_load($node_id), $view_mode));
}

```

This works if you go to /node/%/view\_mode. However, it does not work if you got to /alias/view\_mode. I get page not found. Is there a way to bind menu items to path aliases?

# Answer
You'd have to extend the pathauto system to handle your specific pattern, like it does for node/x/feed items.
> 1 votes

# Answer
I think that the Sub-path URL Aliases module will do what you want.
> 0 votes

---
Tags: 7, routes, hooks, path-aliases
---


title: post editor with image upload

text:
# Question
Title: post editor with image upload
I need a module or patch or something for a post editor that lets you upload images into the post

any help is appreciated.

# Answer
> 1 votes
The Media module might be a good solution to this, depending on your needs. It is still under development and still has a few issues, but it's probably stable enough to us (we are using it on several production sites without any problems). I think this module has the best approach to the problem of embedding images within node content.

---
Tags: 7, media, nodes
---


# Question
Title: The differences between date time zone handling
There are several options for time zone handling, Site's time zone, Date's time, User's time zone, UTC and no time zone conversion. What are the differences between them?

One case would be a television broadcast where everybody in the world would experience simultaneously. Would User's time zone be correct to use? If the broadcaster put 8:00pm while living in New York someone in California would experience this at 5:00pm.

Or, the case, a poetry slam is happening in New York City and anybody who wants to experience it will have to physically be there at 8:00pm meaning it might be happening at 5:00pm in California but that doesn't matter to the person in California. What matters is that they are at the place at 8:00pm in New York so the time shouldn't change no matter where the user is or what time in their timezone the poetry slam is going on.

# Answer
> 13 votes
The Date module's documentation page describes the difference between the 5 options fairly well.

From that page:

There are 5 different options for field Time zone handling:

1. **Site's time zone** \- When entering data into the field, the data entered is assumed to be in the site's time zone. When the data is saved to the database, it is converted to UTC. When retrieved from the database, the data is converted to the Site's time zone for annonymous users or the User's time zone for logged in users when User-configurable time zones is enabled.
2. **Date's time zone** \- With this option enabled, the date field adds a select box to explicitly specify the time zone for the date entered. When the date is saved to the database, it is not converted & the time zone information is saved with the date. When retrieved from the database, no conversion is performed and the date is displayed exactly as entered.
3. **User's time zone** \- When entering data into the field, the data entered is assumed to be in the user's time zone. When the data is saved to the database, it is converted to UTC. When retrieved from the database, the data is converted to the Site's time zone for annonymous users or the User's time zone for logged in users when User-configurable time zones is enabled.
4. **UTC** \- When entering data into the field, the data entered is assumed to be in UTC time zone. When the data is saved to the database, it is converted to UTC (e.g. no conversion necessary). When retrieved from the database, the data is converted to the Site's time zone for annonymous users or the User's time zone for logged in users when User-configurable time zones is enabled.
5. **No time zone conversion** \- The date entered is not converted when saved to the database. When retrieved from the database, the data is NOT converted and is displayed exactly as entered.

---
Tags: 7, datetime
---


title: Deleted content still in database?

text:
# Question
Title: Deleted content still in database?
I recently went through a Drupal site I'm helping manage, doing a batch delete on a bunch of spam tickets through Administer \> Content \> Edit.

As it turns out, though, the data for this content seems to still be stored in the database, and is shown on our ticket list. Taking a look at a database dump taken after the deletion took place, confirms that they are in fact still present in the `node` and `node_revisions` tables.

Trying to access any of the tickets gives a "Page not found", and they're not listed in the "Edit Content"-list. Clearing the cache has been tried, and didn't resolve the issue.

In case it's useful, the node types are `ticket`.

Any insight into what has gone wrong and how to fix it would be most appreciated.

# Answer
> 2 votes
Turns out that tickets posted by deleted users do not show up in the management interface, but did show up in our view.

Problem was resolved by changing the owner of the tickets to a dummy user, then deleting them through the management interface.

---
Tags: 7, nodes
---


# Question
Title: How to add additional tab in the User Profile page using views
I have installed the flag module and it comes with some 2 views that are added to the list of views. One of them will stick to the user page as an additional tab and when clicked will show a list of all the nodes that were flagged by that specific user being previewed. So far so good.

The problem is that in my website I don't use the path "user/**uid**" for the user pages. I use the path (example) "somethingelse/**uid**". When I enter the view and edit the path for this tab page with "somethingelse/**uid**", save the view and reload the user page... the tab with the list of items flagged by the current user disappears completely.

How can I bring that tab back on the user page? I am on Drupal 7.

# Answer
> 1 votes
`somethingelse/<uid>` is a path alias for `user/<uid>`. When you set the path for a view, you need not to use path aliases.

---
Tags: 7, views, users, flags
---


title: Drupal 6 / Views / XSS-SQL Injection

text:
# Question
Title: Drupal 6 / Views / XSS-SQL Injection
First, let me start off by saying I have never worked with Drupal before. I've never even so much as looked at it. So forgive me if I'm asking obvious or rudimentary questions.

Yesterday, we were notified via a very kind customer of a potential SQL injection / XSS attack in one of our websites (by 'our' I mean a site run by a marketing team here with little interaction from IS or the DBA groups). After looking at it and testing it is indeed a problem and I was tasked with going about resolving the issue.

Screenshot time!

The problem.

Unescaped user input.

Which then spits out on the actual web page:

Now, from what I've gathered from talking to our marketing team that manages this, there's a concept of views in Drupal that they use to build up this query. I dug in and here's what I see for the page in question.

Now, I'm unsure if this filter parameter is even related to the view or if this is some separate functionality I'm unaware of. Can anyone out there more versed in Drupal point me in the right direction to escape this input. I was hoping I could have just opened a query and thrown an escape function on the parameters but it seems I'm going to have to dig in a bit more.

# Answer
I would check your versions, drupal will tell you if there are any security announcements for the current version. Login and go to /admin/reports/status

The other thing worth noting is that you should look at the page display (the second link from the top on the left) I'm not convinced that you have an SQL injection going on there `<bad%` is just a string in the query there is plenty of filtering that goes on in drupals internals against this.
> 3 votes

---
Tags: 6, views
---


# Question
Title: How do I avoid hard coding the links in a custom made navigation bar?
I'm creating a custom navigation bar in drupal. I went ahead about this by creating it as a block and gave it all the neceassary CSS, but something that is not quit clear to me is how can I avoid the hard coding for the links? or any other ways that I can achieve the same result?

# Answer
> 2 votes
You should create a menu for this (drupal menus works with system paths, no need to "hardcode" the links) and display this menu in a block where you want.

---
Tags: 7
---


title: Registration full name

text:
# Question
Title: Registration full name
I would like to edit the registration fields, but I can't find where to do it. I want to replace the username field on the registration form with two fields for first name and last name, which are then used to create the username as `<first name> <last name>`.

# Answer
> 2 votes
There is Auto Username for Drupal 6, and there is a Drupal 7 port of the module sitting in the issue queue.
Perhaps you could test the zip that is attached to that ticket, and help fixing any bugs. ;)

Alternatively, perhaps you could make this happen using the Rules module.

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


# Question
Title: Custom CCK Currency exposed filter for available currencies
I am trying to set the available currencies programatically like this:

```
function mymodule_form_alter(&$form, $form_state, $form_id) {
    /** Modify exposed filter views */
    if ($form_id == 'views_exposed_form') {
        $form['field_1hour_currency']['#type'] = 'select';
        $form['field_1hour_currency']['#options'] = array('EUR','USD');
    }
}

```

But I get `An illegal choice has been detected. Please contact the site administrator.` error in the view.

How can I set a select list of available currencies in the views exposed filter for a CCK currency field?

Thank you

(using D6, Views 2 and latest CCK Currency)

# Answer
> 0 votes
```
function mymodule_form_alter(&$form, $form_state, $form_id) {
  if ($form_id == 'views_exposed_form' && $form_state['view']->name == 'myview') {
    // Add our custom All buttons.
    $form['field_1hour_currency']['#type'] = 'select';
    $form['field_1hour_currency']['#options'] = array(
      '' => t('<Any>'),
      'USD' => 'USD',
      'EUR' => 'Euro'
    );
  }
}

```

The key is to ensure you include the empty option:

```
'' => t("<Any>")

```

See http://drupal.org/node/463990

You may want to post this solution on your issue on drupal.org too if it works for you: http://drupal.org/node/1155934 ;)

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


# Question
Title: Restricting node reference values to owner
I have played with a bunch of modules (Node Reference Node Access, Views Field, View Reference) and can't seem to find one that does a very simple job; In one content type I want a field that provides a select list of all nodes owned by current user from another content type.

Think of it (roughly) as blog content types.

* Blog 1 - Owned by user 1
* Blog 2 - Owned by user 2
* Blog 3 - Owned by user 1

In another content type (updates) we'll have a field that is used for building a relationship (ie, select the blog that this update will be related to) and that field should be populated with the blogs owned by that user;

* Select Blog (for user 1 the list would contain;
    + Blog 1
    + Blog 3

I have read so much, installed so many modules and I just cant get it to work. The closest I have got is a field that contained the name of the view, which is not overly helpful.

**EDIT:** Screen Shots:

# Answer
> 4 votes
I managed to get this working in Drupal 7.

1. Install the very latest development snapshot of Views 3.
2. Install the very latest development snapshot of Chaos tools suite.
3. Install References beta-3.
4. Enable the Views UI module and the Node References module that comes with References.
5. Create a new view.
6. Add a 'References' display to that view - note, this is a special Views display type that you get from installing the References module - it is not a Page or Block display.
7. Add a Node reference field to your content type. You will now be able to select the Views display that you created in step 6 to filter the list of nodes that can be referenced. You do this in the 'VIEWS - NODES THAT CAN BE REFERENCED' fieldset.

# Answer
> 5 votes
If I understand you right, you can use a View as the source for the nodereference widget, and give it appropriate filters to only show nodes of a certain type authored by the current user. To use a view (assuming you have Views installed and appropriate perms) you can

* edit the nodereference by going to *Content management* -\> *Content types* -\> *Edit \[whatever content type\]* -\> *Manage fields* -\> *\[whatever field name\]*;
* in the fieldset *Global settings* click to expand the fieldset *Advanced - Nodes that can be referenced (View)*;
* select the appropriate view in *View used to select the nodes*;
* if you want to use arguments you can specify them in *View arguments*.

# Answer
> 2 votes
For D7 you will need to use the references module, this allows you to filter by a view much in the way that Andy has described in his question.

*note: beta-2 which should have the code in has only just come out (may 7th) so even if you tried it before it is worth downloading again.*

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


# Question
Title: Which module(s) should I use to create a customer support section?
I've got a site where I need to get a customer (**not client**) support system set up. Support Ticketing System, unfortunately, is geared towards client support. I think Storm is too (it's huge, in any case).

The way I see it, I've got a few options:

* Set up a different installation of Drupal entirely and use something like OpenAtrium or Drupal Commons for the support area. OMG overkill. Plus I'd like to just have it be a coherent part of my current site, same theme and shared logins and all that.
* Patch Support ticketing system, or Storm, or whatever module I wind up using.
* Use CaseTracker + Mailhandler to get a simple system, but I'll probably wind up still needing to do an amount of configuration to get it working.
* Give up and use something like Trellis Desk on a subdomain.

One thing that maybe makes my search a little harder is that I'm adamant about having inbound email integration. The same way that we do, customers want to email an address and get a support ticket created. If this functionality isn't there, they'll send an email.

# Answer
See Similar Module Review page and choose the one that works best for you.
> 3 votes

# Answer
I've seen the Feedback module used with great success, I would recommend trying it out.
> 1 votes

---
Tags: 7
---


# Question
Title: Creating folders for images using Tokens module
I have a node for a photo. I want to know what is the best why to define the file path for the images. The images will be user submitted.

Ideally, I would have liked the path be sites/default/files/photo/\[node-reference:NID\] so that each node would have all the image nodes associated with it in their own folder. This would make it easier to migrate the images since not only in the database but also in the file system would describe which images belong to which. Because the referenced node isn't available for the Tokens module I need to come up with a different strategy.

I have considered things like user sites/default/files/photo to dump all the images into one folder which might become a mess over time or sites/default/files/photo/\[user id\] so that each user's images are in separate containers. I don't know what the benefit of that would be.

I'm also thinking about creating a name convention for each image to that it has the node reference NID and user name in code. Is it worth the effort?

I'm looking at the image scr attributes on websites like grammy.com and examiner.com to see how they set it up. It looks like the examiner.com uses a hash to name the image.

Does anybody have any ideas on how to do this?

# Answer
> 2 votes
Since Token does not yet have support for field tokens, I would choose a temporary convention that makes sense to you. Once that feature is added, you can use FieldField Paths to reorganize your files.

---
Tags: 7, files, tokens
---


# Question
Title: Connecting to a database from another application
What is the proper way to do a remote connection to my Drupal database from a remote application? I am trying to integrate IPB with Drupal so I would like to modify my Drupal database from IPB.

# Answer
Since you asked, the "correct" way would be to implement a simple web-service in Drupal in order to perform these tasks remotely from your application. You could build a simple RESTful API to handle all your CRUD needs, for example.

The Services module is an excellent starting-point.

The reasoning for this is that you should really avoid modifying your Drupal database directly (unless you really know what youy are doing) and even if you must, connecting to it directly from another application is not only bad practice but a security risk too!

Please reconsider and use a webservice-approach, think of the kittens! :)
> 8 votes

---
Tags: 7, database
---


# Question
Title: How to expose individual form elements from user-register-form
So I have a work flow/use case as such:

* an administrator user creates a user account, associating it to the "guest" role
* the guest users receive a login link
* once they log in, I want them to provide some information (in this case, rsvp status, a custom field I've added to the user profile)

Is it possible to display just the rsvp form field of the registration form, so they can update it when they log in (e.g., they submit one field only and the profile is updated)?

Is there another way to do this? I'd rather do this in code since it's part of a custom module that is nearly completed.

# Answer
If your doing your own module hook\_form\_alter is the way to go. so long as all required fields are already supplied you should be able to set all other fields to have type hidden.

If you are looking to do something similar you may want to look at the event and rspv modules.
> 1 votes

# Answer
Perhaps you could use Profile Setup and Pageroute, and Rules to guide people through the process of providing your basic information when first logging in.
> 0 votes

---
Tags: forms, users
---