title: Date value to different date format

text:
# Question
Title: Date value to different date format
I have a date field. In my template I want to display the date in two different ways. I know in display I can set the format used for a date. To print the date in my template I am doing.

```
<?php print $node->field_date[0]['view'] ?>

```

To print as a different format I tried

```
<?php print format_date($node->field_date[0]['timestamp'],"custom","H:i")?>

```

However this does not seem to be showing the correct time...

# Answer
We tend to use:

```

print format_date(strtotime($node->field_date[0]['value']), 'custom', 'H:i');

```

Perhaps that would work in your situation?
> 5 votes

# Answer
One would think that adding logic to honor the user's timezone would do the trick, like this:

```
format_date($timestamp, 'custom', 'g:i a, d F, Y', variable_get('date_default_timezone', 0));

```

but I've found in actual practice that this works better:

```
format_date($timestamp, 'custom', 'g:i a, d F, Y',0);

```

Passing a "timezone" parameter of 0 causes the D6 logic to get the user's configured timezone, or if user configured timezones are not enabled it does the same thing as my first example. So, if you have not, enable user configured timezones and use my second example.

Nice benefit, different users viewing the same info see date/times in their timezone.
> 0 votes

---
Tags: 7, datetime
---


# Question
Title: Can't Remove Image from CCK File Field when editing node (Throbber just spins)
I was able to upload an image, but the thumbnail didn't appear until I hit save on the form. When I try to remove the image, it just sits there spinning the throbber; if I click on "Save" in the form, the image is not removed.

I think this has to do with AJAX getting caught up somewhere, but I don't know how to go about troubleshooting this.

Do you have any idea? I've tried switching the field from "Bar with progress meter" to "Throbber" and that didn't help.

Edit:

I forgot that I updated jQuery to the latest version and used some special code to prevent it from affecting the backend. Here is the jquery\_update\_jquery\_path() function from jquery\_update.module (I modified it to fix this issue by checking for 'edit' in the uri):

```
function jquery_update_jquery_path() {
  $curr_uri = request_uri();
  if (strpos($curr_uri, 'admin') > 0 || strpos($curr_uri, 'edit') > 0) {
  $jquery_file = array('none' => 'jquery.js', 'min' => 'jquery.min.js');
  return JQUERY_UPDATE_REPLACE_PATH .'/'. $jquery_file[variable_get('jquery_update_compression_type', 'min')];
  }
  else {
  $jquery_file = array('none' => 'jquery-1.5.2.js', 'min' => 'jquery-1.5.2.min.js');
  return JQUERY_UPDATE_REPLACE_PATH .'/'. $jquery_file[variable_get('jquery_update_compression_type', 'min')];
  }
}

```

# Answer
> 2 votes
What version of JQuery are you running? I had an AJAX issue (was trying to rebuild derivative images for all nodes of a specific node-type) when using JQuery 1.5.1 instead of the version that is shipped with Drupal 6. Removing 1.5.1 and adding the stock version of JQuery resolved the issue.

# Answer
> 2 votes
I was going to say it was probably permission-related (no delete permission) but if you managed by turning off javascript than its definitely not that.

Turn on firebug, enable the console & turn javascript back on.

If its an ajax error it will show up in the firebug console.

---
Tags: 7, entities, files, javascript, media
---


# Question
Title: Send mail to users including receiver's username
I have searched settings of Contact (in Drupal core), Simple news and Mass contact modules but haven't found a way to include receiver's username in the mail body.

Any suggestions how to do this?

# Answer
> 2 votes
There isn't a setting for that, but when a user sends an email to another user, using the contact form of the other user's account, the Contact module sends a message that start with (I sent an email to myself from Drupal.org):

> kiamlaluno,
>
> kiamlaluno (http://drupal.org/user/55077) has sent you a message via your contact form (http://drupal.org/user/55077/contact) at drupal.org.
>
> If you don't want to receive such e-mails, you can change your settings at http://drupal.org/user/55077.

The first line contain the receiver's username.

The following snippet is part of the code present in contact\_mail(), the function that alter some of the messages sent from Drupal.

```
case 'user_mail':
case 'user_copy':
  $user = $params['user'];
  $account = $params['account'];
  $message['subject'] .= '[' . variable_get('site_name', 'Drupal') . '] ' . $params['subject'];
  $message['body'][] = "$account->name,";
  $message['body'][] = t("!name (!name-url) has sent you a message via your contact form (!form-url) at !site.", array('!name' => $user->name, '!name-url' => url("user/$user->uid", array('absolute' => TRUE, 'language' => $language)), '!form-url' => url($_GET['q'], array('absolute' => TRUE, 'language' => $language)), '!site' => variable_get('site_name', 'Drupal')), $language->language);
  $message['body'][] = t("If you don't want to receive such e-mails, you can change your settings at !url.", array('!url' => url("user/$account->uid", array('absolute' => TRUE, 'language' => $language))), $language->language);
  $message['body'][] = t('Message:', NULL, $language->language);
  $message['body'][] = $params['message'];
  break;

```

Other modules can change the content for the sent emails, if they implement hook\_mail\_alter(). This means that other modules could remove content from the email sent via the contact form; it also means that another module could replace the username used in the first line with the first and last name provided by the receivers in their user profile.

---
Tags: 7, emails
---


# Question
Title: How to create an unsortable Field with multiple values?
When a CCK field accepts more than one value, the widget will display a sortable table (usually with those cross-shaped handlers); this is the default behavior. I would rather have a non-sortable widget, since the order doesn't really matter. I hope this will avoid the usage of a table element, as well.

How can I achieve this? Do I need to use `hook_form_alter()`?

# Answer
I think you'll need to create your own module for this. Instead of using `hook_form_alter()`, I'd suggest doing things the "cck way". CCK provides hooks which allow modules to provide custom widgets for CCK fields. You can create a module to provide a new Widget option for multi-value fields that doesn't use an HTML table, and doesn't allow for reordering. There's a great article on Lullabot about this. It also talks about creating your own fields and formatters, but you can skip down to the widget part at the end. The sample code is very well documented and should help you understand what's happening. At the very least this will be a great starting point. If something in the article doesn't make sense, feel free to ask for clarifications and I'll add what I can.
> 3 votes

# Answer
In lieu of another answer for the time being, have you considered hiding the handles using CSS or perhaps some jQuery?

Also, could you explain what you mean when you say 'avoid the usage of a table'? Did you mean database table, or HTML table?
> 0 votes

---
Tags: 7, entities
---


title: Getting Views to use custom aliases

text:
# Question
Title: Getting Views to use custom aliases
I have the following custom URL aliases that point to specific Views paths:

* /california/los-angeles maps to /locations/los-angeles
* /username/listing/post maps to /item/post

Views still uses the older, pre-defined aliases. Is there any way to get Views to respect the custom aliases I've set? I'd need to do this at a global level, as there are too many paths to be changed in Views.

# Answer
> 2 votes
The Global Redirect module will fix this right out of the box.

Once enabled, it'll make sure there is only one canonical path available: your custom one. So all mentions of `locations/los-angeles` created by Drupal will be replaced with `california/los-angeles`, so that if you try to access `locations/los-angeles` it'll redirect to `california/los-angeles`.

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


# Question
Title: How to define another data table to join for views (ie from csv file)?
I successfully created two Views query plugins by learning from XML Views. My plugins query a YAML, and CSV file; they are both base view types on their own.

Now I want to learn how to join tables. (The following assumes a minimal views module skeleton called csv\_views, I deleted the query plugin class I mentioned before.)

I thought of a fix table (i.e. a CSV file) that is queried without any additional features. I want to join it to a node table, let's say via title field, both in node (node title) and a column in the CSV file.

What do I need to define in mv csv\_views.views.inc? For now it contains the following:

```
function csv_views_views_data() {
  $data['csv']['table']['group'] = t('CSV');

  $data['csv']['table']['join'] = array(
    'node' => array(
      'left_table' => 'node',
      'left_field' => 'title',
      'field' => 'title',
    ),
);

  return $data;
}

```

Is a field handler necessary?

In which class is the table query execution method defined? Is there a views module I can examine to learn that?
AFAIK all modules which provide tables to be joined use real database tables.

I use Drupal 6 because that is the Drupal version required by XML Views works, but I want to know Drupal 7 too and I could also settle to views 2. I guess it's still the main Views version, right?

# Answer
Views can do some clever things. But I think that joining a sql query to a csv file may be a bit beyond it. (not that I'll be surprised if someone has a solution).

The issue is that within a data engine (sql, mongodb, sparql), views can work well providing that everything you want to work with is also in the same engine. If you wanted to say join a sql table to a sparql query you would have to try and do the join in code. Bring back results from sql and use in sparql or vice versa. This is not a scalable solution. It may work for a few rows, but beyond that you are going to hit some serious performance buffers.

In this case you may have more luck importing the csv file to mysql and using the data module. that should allow you to define joins and use it in your view.
> 5 votes

---
Tags: views
---


title: Node reference autocomplete views issue

text:
# Question
Title: Node reference autocomplete views issue
Firstly, apologies if I use some incorrect terminology - I'm still very much a Drupal newbie!

I'm creating a band website using Drupal 6 with CCK, Views, Date, Calendar, Link, Location and GMap. It has two content types of concern here - Gig and Venue.

The "Venue" content type has a Location field, which stores all the address information. It also has some other fields, for example "Venue Website" (field\_venue\_website).

I want an autocomplete field on the "Create Gig" page to look up an existing venue from the "Venue" content type and display the venues in an autocomplete drop-down list in the following format:

\[Location name\], \[City\], \[Country\]

However, I want to extract more information to be available on the Gig page, preferably like this:

\[Location name\] \<-- preferably as a link to the venue's page \[Street\] \[Additional\] \[City\] \[State/Province\] \[Postal code\] \[Country\] \[Venue Website\] \<-- remember this is a separate field, not from the location field.

I have partially reached my goal, by doing the following:

* Created a "Venue" field (field\_gig\_venue) of type Node reference.
* Set up the field as follows:
    + Autocomplete matching: Contains
    + Size of textfield: 100
    + Required: Off (may change this later)
    + Number of values: 1
    + View used to select the nodes: venue\_search
* Created a View (venue\_search) with the following settings:
    + Row style: Fields
    + **Inline fields:**
    + Location: Name
    + Location: City
    + Location: Country
    + Separator: ,
    + Hide empty fields: Yes
    + Relationships:
    + Content: Venue
    + **Fields:**
    + Location: Name
    + Location: City
    + Location: Country
    + Node: Title (Exclude from display: Yes)
    + **Filters:**
    + Node: Type = Venue

This results in the autocomplete drop-down list displaying as I required. When submitted, the result is \[Location name\] as a link to the Venue's page.

However, I find that the only part of the venue recognised by the autocomplete is \[Location name\]. For example, if I have two venues as follows:

Kentish Town Forum, London, UK

Tunbridge Wells Forum, Kent, UK

When I start typing "forum", I'll get a drop-down suggestion list that looks like the above. Great! However, if I type "UK" or "London", I get nothing.

If it helps, here is the query generated when I preview the View:

```
SELECT node.nid AS nid,
   location.name AS location_name,
   location.city AS location_city,
   location.country AS location_country,
   node.title AS node_title
 FROM drupal_node node
 LEFT JOIN drupal_content_type_gig node_data_field_gig_venue ON node.vid = node_data_field_gig_venue.vid
 LEFT JOIN drupal_node node_node_data_field_gig_venue ON node_data_field_gig_venue.field_gig_venue_nid = node_node_data_field_gig_venue.nid
 LEFT JOIN drupal_location_instance location_instance ON node.vid = location_instance.vid
 LEFT JOIN drupal_location location ON location_instance.lid = location.lid
 WHERE node.type in ('venue')

```

Here are my questions:

1. How do it get it so that the autocomplete will work for the City or Country, too?
2. What is the best way to get the output that I require on the final page (i.e. an address block)? I assume that I can add the other relevant fields and exclude them from display in the View, and they'll be available to use. How should I best use them, though? A single field with the data pre-formatted? A field for each value?
3. How do I then get the data collected from the View into the field(s)?

Any help would be greatly appreciated! Thanks in advance!

\[EDIT\]

As mentioned below, I have discovered that what is happening is this:

The autocomplete field takes the text entered and looks to see what node titles in the "Venue" content type match this text. It then displays the results using my View to format them. Here is a picture to illustrate:

Why is it ignoring my view when checking the entered text, instead checking against node titles?

# Answer
I have an alternative for your 1. question. You could use the module Automatic Nodetitles to automatically create a title for venues in the form `[Location name], [City], [Country]` from CCK fields in your content type. This means you would have to use an additional textfield for the location name, and the title would be automatically created to combine the three fields.

This solution would mean that the city and country would be visible everywhere you use the venue content type title, you'll have to decide if that fits with what you need.
> 0 votes

# Answer
1. You can create a computed field in Venue with the content of the fields you want and use that field.
2. & 3. Once you have the node reference you can show whatever fields you want using a template for the gig. Alternatively you could use a view.
> 0 votes

---
Tags: 6, views, nodes
---


# Question
Title: Organizing uploaded files in folders created by date
This could be very trivial, but I haven't been able to find a good solution.
I have an image field associated with a content type called article, and I wish to organize the files uploaded during content creation in a way that they go to a sub folder (within files/article) which uses the day's date as name.
For example, if the article is created on April 15, then the associated images (the ones added through the image field) go to files/articles/**15-04-2011**/filename.jpg; the articles created the day after will have their associated files in files/article/**16-04-2011**/filename.jpg.

# Answer
> 3 votes
You can use the Filefield Paths module to automatically rename uploaded files according to a scheme defined by tokens. The node creation date is one of the available tokens, so that module should be able to do what you want to achieve.

---
Tags: 7, files
---


# Question
Title: How can I point to an internal anchor using core menu?
We have a navigation menu created using Drupal's built-in menu system. One of our menu items has the path set to "node/100770#digital-anchor," but when the menu is rendered, it strips off everything to the right of the node ID. I've tried this suggestion (using a named id), but the issue isn't that the browser is ignoring everything the node id; it's that Drupal is actually stripping off everything after the id when the menu is rendered. If I look at the rendered source in the browser, it just isn't there.

How can we point to an internal anchor (or named element, if you believe that anchors are deprecated) using the default menu?

# Answer
> 2 votes
I don't think you can do that through the UI.

However, you should be able to specifify it with menu\_link\_save() in a module, for example in a hook\_install() implementation. See the options key.

Looking at url(), something like `'fragment' => 'digital-anchor'` should do the trick.

# Answer
> 1 votes
Check out the l() function built into core.
The function is `l($text, $path, $options = array())`; in that options array you can specify an associative array of HTML attributes to apply to the anchor tag (the array index is "attributes").

# Answer
> 0 votes
I have come across this before. I think it is to do with this issue, in the end I had to create some of my own theme functions to allow it.

---
Tags: 7, routes
---


title: Problem configuring the Calendar module

text:
# Question
Title: Problem configuring the Calendar module
I'm having trouble with Drupal 7 and the calendar (version 7.x-1.0-alpha3) module. The default view is working. It is showing the nodes based on the time they were updated.

I added a date field called time1 to a basic page node type. I added some basic pages with date set for the current date.

I don't know how to make the calendar show the nodes based on the value of time1. I've tried to change the argument as in the picture.

The README.txt of the module says that look the documentation on the project page. However, there is no documentation that applies to Drupal 7 in here http://drupal.org/node/262062

Has someone drupal 7 and the calendar working? What am I doing wrong here?

I don't know could this be related to http://drupal.org/node/1096224 For me none of the month, week or day views are working.

# Answer
> 1 votes
Views 3 has been completely changed; the API has been rewritten. Make sure Calendar is compatible with that version of Views.
Check the Calendar issue queue to see if there are reported issue.

---
Tags: 7, datetime
---


# Question
Title: Views generated block - how to override filter on some pages?
On every page of his new site, the client would like a block with four featured links. This will be fairly consistent throughout the site, but on *some* pages he'd like to override and display four links of his own choosing.

I'm thinking of using Views and/or Nodequeue for the block, but I am not sure how to provide a default that can be easily changed for some nodes? Is there a better way?

# Answer
> 1 votes
I would create a custom module for this, sounds like it could be done quite easily.

1. Create an admin interface where the 4 default links can be entered.
2. Create fields on nodes, where the special links can be entered.
3. In the block view, try to load the node, if possible check for custom links and use default links if needed.

The above solution is good and flexible if you only want links.

If you instead want node references, with the posibility of getting more data, like an image, taxonomy term etc, nodequeue could come in handy instead, as you with views can setup a more sophisticated display easily. It would however become a bit more tricky to override, but could be done via preprocess functions or `hook_views_query_alter`.

# Answer
> 0 votes
Check out the context module: http://drupal.org/project/context

or just edit the block from the blocks page, there is the visibility section where you can specify what paths to show it or what paths not to.

When you make a menu it automatically makes and associated block. So basically make the menus, and set the block visibility according to path or use context.

---
Tags: blocks, views
---


# Question
Title: Adding custom module pages to the Solr index
We're using Drupal 6. I have written several custom modules that generate a number of pages. All the paths are "given" to drupal using hook\_menu() so the system is fully aware of how to access them.

However, if I search for something that I know is on a page I have created with one of these custom modules, it does not appear in search results. We're building a lot of content using custom modules which are pulling data out of pre-existing databases. We need these to be searchable.

How can I add these new paths and the content on these pages into the Solr index?

# Answer
Apache Solr Search Integration is a replacement for the core content search.
This means that the output of your custom modules will appear in the Solr index, if the modules create nodes.

If the content returned by the custom modules is dynamic, then they need to create dummy nodes that they will be updated with hook\_nodeapi(). When ApacheSolr rebuilds its index, it loads the node with node\_load(), which then invokes any implementation of `hook_nodeapi()`, passing "load" as operation parameter.
> 2 votes

---
Tags: 6, search
---


title: Custom token replacement

text:
# Question
Title: Custom token replacement
I am using Notification to subscribe to different content types so that I can receive emails when a user creates/updates a particular content type.

The following is an email I generally receive from Notification.

```
 Greetings, ajinkya.

    These are your messages
    New content of type Blog has been submitted
    - Blog Test, Friday April 12
    Read more [node-url]

```

The problem is that the token `[node-url]` is not being replaced with a link to the node that has been created, and I am not able to find any interface that would allow me modify the token replacement behavior. Do I need to manually change the code in Notification?

# Answer
> 4 votes
The \[node-url\] token is a real token define by the token module. I would make sure you have the latest version of the token module. I believe this token has changed names a couple of times but I think thats the correct token.

I would make sure you're running the latest version of the token module if not update and hopefully that would fix your problem.

---
Tags: 6, tokens
---


# Question
Title: Something I can't understand in Acquia Marina theme
I have downloaded the Acquia Marina theme yesterday.

I cannot understand well the following code; there is a lot of code like the following, in page.tpl.php.

```
<?php print theme('grid_block', $search_box, 'search-box'); ?>
<?php print theme('grid_block', theme('links', $secondary_links), 'secondary-menu'); ?>
<?php print theme('grid_block', $primary_links_tree, 'primary-menu'); ?>
<?php print theme('grid_block', $tabs, 'content-tabs'); ?>
<?php print theme('grid_block', $footer_message, 'footer-message-text'); ?>
..............

```

Acquia Marina theme version is 6.x-3.1. I didn't find a template.php file between its files. Where is the variable declared? Why doesn't the code use `$primary_links_tree` directly?

# Answer
The Acquia Marina theme is a sub-theme of Fusion core. `$primary_links_tree` is defined in the template file of that theme, in the fusion\_core\_preprocess\_page(), which the preprocess function that is called before page.tpl.php is used to output a page. Starting from line 80, you find the following code:

```
$vars['primary_links_tree'] = '';
if ($vars['primary_links']) {
  if (theme_get_setting('primary_menu_dropdown') == 1) {
    // Check for menu internationalization
    if (module_exists('i18nmenu')) {
      $vars['primary_links_tree'] = i18nmenu_translated_tree(variable_get('menu_primary_links_source', 'primary-links'));
    }
    else {
      $vars['primary_links_tree'] = menu_tree(variable_get('menu_primary_links_source', 'primary-links'));
    }
    $vars['primary_links_tree'] = preg_replace('/<ul class="menu/i', '<ul class="menu sf-menu', $vars['primary_links_tree'], 1);
  }
  // ...
}

```
> 1 votes

---
Tags: 7, theming
---


title: How do I use the field API?

text:
# Question
Title: How do I use the field API?
Someone told me that most of the time I will probably want to use the field API (CCK module in D6), rather than adding custom tables or modifying nodes by myself. How do I use the field API? Could anyone can make me an example?

# Answer
> 2 votes
If you've ever used CCK in D6, the Field UI will be rather intuitive. And unless you need to do very custom work, you won't need the Field API at all, just the Field UI.

But if you do need custom widgets or formatters, take a look at the Examples module for some very comprehensive usage of the Field API.

---
Tags: 7
---


title: Same CCK field in one content type

text:
# Question
Title: Same CCK field in one content type
I have a content type named "school;" this content type has the "teacher" CCK field, but the number of teachers is not same for any school.
I need a thing like "add new teacher" button, which can be used to a new "teacher" CCK field. Does anyone know a module to do this?

# Answer
Set the number of allowed teachers to "Unlimited".
> 2 votes

# Answer
School needs to have a nodereference field pointing to teacher. Then, as tim.plunkett said, you need to make the number of teachers node reference field to unlimited. Same as the one detailed here, but the number of values set to unlimited.
> 3 votes

---
Tags: 7, entities
---


# Question
Title: How to make a Feature available only to certain Spaces?
For a Drupal 6 Open Atrium site (i.e., Features, Spaces, Organic Groups) I'm running, I've created some custom Features that only really apply to a handful of the hundreds of groups on the site.

As it stands, the "Customize Features" config screen shows *all* the Features, including those I'd like to intentionally restrict to just a couple of special groups.

What's the best way to prevent these special Features from being offered to every group, while retaining those Features on the special groups?

# Answer
> 2 votes
The features for each space are configured via the `spaces_features_form()` function. You could implement `hook_form_alter()` to selectively and conditionally remove features from specific groups.

```
function MYMODULE_form_alter(&$form, $form_state, $form_id) {
  if ($form_id == 'spaces_features_form') {
    $space = spaces_get_space();
    // Populate the array with hard-coded NIDs, or whatever logic
    // needed to determine if these features should be allowed.
    if ($space->type == 'og' && !in_array($space->group->nid, array(...))) {
      // Hide features foo and bar.
      foreach (array('feature_foo', 'feature_bar') as $feature) {
        $form['spaces_features'][$feature]['#access'] = FALSE;
      }
    }
  }
}

```

# Answer
> 1 votes
Features are modules. Modules are enabled system-wide and cannot be linked to a Space or Group. However, you could control access to them by creating custom permissions, see hook\_perm().

# Answer
> 1 votes
I'd add to this hook\_perm suggestion an alteration on the form to disable the applicable feature based on the group type. hook\_form\_alter probably wont work cause the feature related items won't be present yet. You may have to register an #after\_build hook and then modify the form accordingly.

# Answer
> 1 votes
Context is definitely the way to go.
Context, Features and Spaces are a powerful combination. This DevelopmentSeed post should help: Building a "Blog Feature" in Drupal with Context and Spaces

---
Tags: 6, organic-groups, features
---


# Question
Title: How to alter each article's comment setting by PHPMyAdmin
After I updated my site, I found out that all the node comments are set to "disabled." I then went to the specific content type setting page, and changed the default comment setting to read/write, but the nodes of that content type are still disabled. If I change the comment settings for each node, that would be a too cumbersome work. Is there a way to change each node comment setting using a SQL command?

# Answer
Comment settings for each post are stored in the node table. You can run the following, or similar, query:

```
UPDATE node set comment = 2 WHERE type = 'foo';

```
> 2 votes

---
Tags: 7, comments, database
---


title: Override forum topics list

text:
# Question
Title: Override forum topics list
The forum topics list has this in the table header: Topic, Replies, Created, Last Reply. I just want to remove the Created heading.

Template file forum-topic-list.tpl.php prints the table header with `<?php print $header; ?>`

The template file documentation explains that:

> `$header` is pre-generated with click-sorting information. If you need to change this, @see template\_preprocess\_forum\_topic\_list() @see theme\_forum\_topic\_list().

So I dig around in forum.module and find template\_preprocess\_forum\_topic\_list(). This function appears to prepare the variables for the header, but doesn't create the HTML for the output.
I look up the other function that was referenced, `theme_forum_topic_list()`.

The API documentation reports the following:

> This function is never used; see the corresponding template file instead."

What am I missing here?

# Answer
template\_preprocess\_forum\_topic\_list() initializes the variable with the value returned from \_theme\_table\_cell().

```
global $forum_topic_list_header;

// Create the tablesorting header.
$ts = tablesort_init($forum_topic_list_header);
$header = '';
foreach ($forum_topic_list_header as $cell) {
  $cell = tablesort_header($cell, $forum_topic_list_header, $ts);
  $header .= _theme_table_cell($cell, TRUE);
}
$variables['header'] = $header;

```

```
function _theme_table_cell($cell, $header = FALSE) {
  $attributes = '';

  if (is_array($cell)) {
    $data = isset($cell['data']) ? $cell['data'] : '';
    $header |= isset($cell['header']);
    unset($cell['data']);
    unset($cell['header']);
    $attributes = drupal_attributes($cell);
  }
  else {
    $data = $cell;
  }

  if ($header) {
    $output = "<th$attributes>$data</th>";
  }
  else {
    $output = "<td$attributes>$data</td>";
  }

  return $output;
}

```

The variable `$variables['header']` in `template_preprocess_forum_topic_list()` is the same variable that in forum-topic-list.tpl.php is accessed as `$header`.
> 2 votes

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


# Question
Title: How can I add an extra button & submit handler to an exposed view form?
I would like to add a second button to an exposed view form.

I am able to get the button to display, but not to have it call the button submit handler. Instead, it behaves just like the standard search button that views provides automatically.

How can I have my second button call a separate handler?

Below is what I've tried to do.

(FWIW, my specific goal is to let the user use the exposed view form to search for an existing node, then if he doesn't find it, to go ahead and post a new node. So, I want a button that will call an action to post a new node.)

---

```
function my_module_form_alter(&$form, &$form_state, $form_id) {
  switch ($form_id) {
    case 'views_exposed_form':
      if ($form['#id'] = 'views-exposed-form-my-module-page-1') {
        // Add a button
        $form['my_button']['#type'] = 'button';
        $form['my_button']['#value'] = t('My Extra Button');
        $form['my_button']['#submit'] = array('my_module_button_handler');
      }
      break;
  }
}

function my_module_button_handler($form, &$form_state) {
  // do something here
}

```

# Answer
OK, I got it to work.

Needed to do several things:

1) Turn off AJAX on the form. (When I had it on, it acted as if I clicked on the default button even when I clicked on My Button ($form\_state\['clicked\_button'\]\['#value'\] was always the default button).

2) In my\_module\_button\_handler, not only set $from\_state\['redirect'\] but also set $form\_state\['no\_redirect'\] = FALSE.

If you would know how to have it work with AJAX on, I'd appreciate the tip.
> 2 votes

# Answer
The submit handler is not called by default on a form api element type "button". If you want to execute a submit handler on a button you will need to add

```
$form['my_button']['#executes_submit_callback'] = TRUE;

```

As a side note this will not be the case if the #type was 'submit' because the executes\_submit\_callback is by default equal to true on that element type.

Hope this helps.
> 2 votes

---
Tags: forms, views
---


title: Comet implementation

text:
# Question
Title: Comet implementation
Does anyone know how to implement comet in Drupal? I saw a rudimentary PHP implementation on Stack Overflow. Is there any module which does this?

# Answer
As written in that answer, that is blocking a whole apache thread and therefore not a good idea.

I suggest you have a look at http://drupal.org/project/nodejs. node.js is an event-based webserver written in JavaScript and that is the module that integrates it with Drupal. Then, your clients keep a connection option with the node.js server and you can contact them through that server.

The project is still in development, I don't know how well it is working already.
> 3 votes

---
Tags: 7
---


title: Manipulate search results on site

text:
# Question
Title: Manipulate search results on site
We have a few scenarios on a project where we want results to be presented at the top of the of the page despite not having any keywords in the body copy related to the search keyword.

For instance, if someone on our site searches for "baseball," we'd like a few choice results about "football" to come up, even though the nodes are strictly about baseball.

Are there any modules that allow for this behavior in the search functionality of Drupal?

# Answer
If you are using ApacheSolr then I imagine this could be solved with the use of 'Synonyms'.

See the documentation on this.

Example synonyms file you might use:

```
#Equivalent synonyms may be separated with commas and give
#no explicit mapping.  In this case the mapping behavior will
#be taken from the expand parameter in the schema.  This allows
#the same synonym file to be used in different synonym handling strategies.
#Examples:
ipod, i-pod, i pod
baseball, football

```
> 0 votes

---
Tags: 6, search
---


title: Convert a Flags Link into a Checkbox

text:
# Question
Title: Convert a Flags Link into a Checkbox
Is there a way to convert Flags links into check boxes within a view? I tried the Flag Form module, but it did not work (at least not in a view). I've reviewed the Flags Add Checkboxes as Display Type feature request. The discussion points to using CSS, JavaScript, or hacking the flags template file. Are there any other methods?

I'm not adverse to using JavaScript to do this, but I know little about it.

# Answer
A comment from the Flag Add Checkboxes ad Display Type feature request offered a good foundation for using JavaScript. I read up on JQuery and changed the code slightly to work with D6. All credit goes to ngmaloney.

```
Drupal.behaviors.alter_flag_links = function (context){
    //Returns a checkbox dom object
    var cb_factory = function(class_attr, checked) {
      var checkbox = document.createElement("input");
      checkbox.type = "checkbox";
      checkbox.checked = checked;
      jQuery(checkbox).attr('class', class_attr);
      return checkbox;
    }
    //Convert each link to a form checkbox.
    jQuery('span.your-flag-value').each(function() {
      var flag_link = jQuery(this).children('a');
      if(flag_link.length == 0) {
        return;
      }
      flag_link.html(''); //Hide text
      var flag_classes = flag_link.attr('class');
      var checked = false;
      var class_attr = 'compare-cb';
      if(flag_classes.match(/unflag-action/)) {
        checked = true;
      }
      //Only Add form element if it doesn't exist
      if(jQuery(this).children('input').length == 0) {
        var elem = cb_factory(class_attr, checked);
        jQuery(this).prepend(elem);
      }
    });
    //Attach an event listener to each of the new checkboxes
    jQuery('input.compare-cb').each(function() {
      jQuery(this).click(function() {
        jQuery(this).parent().children('a').click();
      });
    });
};

```
> 2 votes

---
Tags: 7, flags
---


# Question
Title: How do I check whether a node is flagged when it is being deleted?
I'm using the Flags module for some functionality on my site. When a node is deleted, I need to check whether it's flagged or not and take additional action based on that. I've implemented `hook_nodeapi()` in my module to add my logic when a node is deleted. However, it seems I'm unable to check whether the node is flagged or not... I always get `FALSE` when I check, even when I know that node was in fact flagged. My code so far is:

```
// check if this node is flagged for renewal
$flag = flag_get_flag('machine_name_of_my_flag');

if($flag && $flag->is_flagged($node->nid)) {
   // add my custom logic here
}

```

This code is definitely run when the node is deleted. The `$flag` is found correctly, but `$flag->is_flagged($node->nide)` always returns false. I based this code on the documentation for the Flag API. I'm not sure why the `is_flagged` check is always returning false. Is it something to do with the delete action? When I debug this code in xDebug, I can see all the properties of the node object, but I can't find out if it's flagged or not.

# Answer
> 4 votes
That code works, but if the module that implements `hook_nodeapi()` is executed before Flag; differently, it will be executed after flag\_nodeapi(), which removes any reference to the deleted node from the database tables used by Flag.

```
case 'delete':
  foreach (flag_get_flags('node') as $flag) {
    // If the flag is being tracked by translation set and the node is part
    // of a translation set, don't delete the flagging record.
    // Instead, data will be updated in the 'translation_change' op, below.
    if (!$flag->i18n || empty($node->tnid)) {
      db_query("DELETE FROM {flag_content} WHERE fid = %d AND content_id = %d", $flag->fid, $node->nid);
      db_query("DELETE FROM {flag_counts} WHERE fid = %d AND content_id = %d", $flag->fid, $node->nid);
    }
  }
  break;

```

If the short name of the module starts with any letter after the *f*, then that module needs to change its weight to a number lower than 0; it is usually done in the implementation of hook\_install(), or hook\_update\_N().

```
db_query("UPDATE {system} SET weight = %d WHERE name = 'mymodule' AND type = 'module', -1);

```

---
Tags: hooks, flags
---


# Question
Title: How do I include ? and = in a form redirection?
I have a form and I would like to take the value from it, and use it as input for a page view which is created using exposed filters.
I have created a submit handler for my first form. I then redirect to the page view. The challenge is that I want to include search keys in the redirection. I can't figure out how to get this to work because the characters ? and = are converted.

I have created this function.

```
function my_module_my_button_submit($form, &$form_state) {
  $url = 'some-path/search?keys=' . check_plain($form_state['values']['input']);
  $form_state['redirect'] = $url;
}

```

The URL that is created from this is 'http://site/some-path/search%3Fkeys%3Dtest'; the URL I want is 'http://site/some-path/search?keys=test'.

# Answer
> 5 votes
In Drupal 6, instead of setting \`$form\_state\['redirect'\] with a string, you set it with an array with tree items.

```
$form_state['redirect'] = array('some-path/search', 'keys=' . check_plain($form_state['values']['input']), '');

```

The last item would be a value used as anchor. As in your case you don't need it, pass an empty string.

---
Tags: forms, 6, redirection
---


# Question
Title: How to access past DrupalCon website that requires password?
I want to browse DrupalCon websites to learn stuff from past DrupalCon.

Below is partial list:

* Chicago 2011 March http://chicago2011.drupal.org/
* Copenhagen 2010 August http://cph2010.drupal.org/
* San Francisco 2010 April http://sf2010.drupal.org/
* Paris 2009 September http://paris2009.drupalcon.org/
* Washington, D.C. 2009 March http://dc2009.drupalcon.org/
* Szeged 2008 August http://szeged2008.drupalcon.org/
* Boston 2008 March http://boston2008.drupalcon.org/

However, a lot of them (e.g Copenhagen, D.C, Szeged, Boston) require user and pass to login. Not sure why some Con are open to public, some are closed.

Is there a way to obtain an account to access them? or Is there an alternative way to find content of those DrupalCon?

Thanks.

# Answer
The reason they're password-protected is due to a critical security vulnerability in the version of Webform run on those sites. There's an open issue about it, and only the DrupalCon sites updated to a secure version of Webform are allowed to remain up.

In order to gain access to the ones that are still in lockdown, I'd comment on that issue to see what you can do to help get them updated. Otherwise, you can use the Internet Wayback Machine to access Archive.org's cached copy.
> 2 votes

---
Tags: community-official-site
---


# Question
Title: Using an F5 server as reverse proxy cache (instead of Varnish)
Does anyone have any experience, positive *or* negative, with using Drupal behind F5?

Did you succeed or fail?

In either cases, what functionality did you achieve? How far did you get?

# Answer
> 1 votes
I have used F5 as a load balancer with Drupal without issue. We were using varnish between Drupal and the F5 as a reverse proxy.

Pressflow and varnish have been tested well together, F5 is quite a high end bit of kit so I don't know if anyone else has tried it. From what I remember F5 is very flexible so you should be able to get it to work in the same way as varnish (same headers being sent etc).

---
Tags: 7, performance, caching
---


title: Blocks not visible when I log out

text:
# Question
Title: Blocks not visible when I log out
In `Administration -> Structure -> Blocks` I have defined `Search box region` with `search box block` and `Left sidebar region` with `navigation block`. These blocks are visible when I'm logged in but when I log out the blocks disappear?

Do you where is the fault?

I have an idea where could be the problem. There are two files with page template - `page.tpl.php` and `page--front.tpl.php`.

thank you

# Answer
You need to grant permission to search content. `Peoples > permission > Use search checkbox`
> 6 votes

---
Tags: blocks, theming
---


title: Change blog comments display order

text:
# Question
Title: Change blog comments display order
I have a Drupal 7 site with blog and comments enabled for certain user groups and the users complain that in longer discussions like this one the order of comments is totally chaotic, they just can't follow it.

Is there please a way to change the order? I'd be happy with all blog comments sorted by the creation date.

I've looked around, but couldn't find any blog settings. I've tried to construct my own path **admin/content/blog/settings** too, but there was nothing about sorting.

Thank you! Alex

# Answer
You can set the "threading" option for each node type on the node type form (eg. on `admin/structure/types/manage/article`, where 'article' is the name of your content type). Deselecting that will put all comments in chronological order.

As far as I can see, the setting for the sort order (newest first/oldest first) was removed in this issue, but I'm not sure why.
> 2 votes

---
Tags: 7
---


title: Term reference with filter

text:
# Question
Title: Term reference with filter
I wonder if it is possible to add a term reference field with just a subset of the available taxonomy terms. Let me explain. I have a taxonomy vocabulary with a structure like this:

```
- term 1
  - term 1.1
  - term 1.2
  - term 1.3
- term 2
  - term 2.1
  - term 2.2

```

Then I will create a specific content type and for that content type I will add a term reference field. Instead of referencing the whole vocabulary, I need to add only the options for, say, branch 2. I need to show options term 2.1 and term 2.2. In Drupal 6, the Node Reference field allows me to pull the options from a View. But this is a term reference field (it pulls the options from a given vocabulary) in Drupal 7.

I just want to avoid creating several different vocabularies, one for each content type, since their subject is more or less the same. In the future, I could take advantage of the fact that I have shared this resource instead of having a series of scattered vocabulary sets.

# Answer
> 1 votes
I think you want the References module. At the moment it dosn't have the views limitation on valid values committed but there is an issue with a working patch which should allow you to do what you want.

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


# Question
Title: How to get latitude and longitude from user with Form API
I want to create a database-driven website with Drupal 6 to gather some information from users that is related to the location; I want to create a form (and I don't want to use Webforms, or CCK) to get some data from users, and to get coordinates by creating a point on a map (by Openlayers or Gmap API), and then saving those data in a database table. I also want to integrate it with Views module so i can make a query from data.

# Answer
I'm quite happy with the Geolocation Field module for Drupal 7. It allows you to put a field on any entity (user or node or whatever) that uses a map. It also has an html5 module to collect the information. Great stuff, actively maintained.
> 2 votes

# Answer
There is already a module that is doing the form part, see HTML5 user geolocation.

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

> ... a simple module to let users store their location on the edit account page. It uses HTML5’s geolocation API and stores latitude and longitude. How you use that data is up to other modules.
>
> It was used on Drupal.org when Drupal.org used Drupal 6.
>
> For more than users or for a Drupal 7 version, try Geolocation Field with the Geolocation HTML5 widget. Now that it is on Drupal 7, Drupal.org uses the Geolocation Field for this feature.
> 1 votes

# Answer
```
function geo_get_coords($address) {
  $map_key = "put your google map key";
  $url = sprintf('http://maps.google.com/maps/geo?&q=%s&output=csv&key=%s',rawurlencode($address),$map_key);

  if ($result = file_get_contents($url)) {
    $result_parts = explode(',',$result);

    if($result_parts[0] != 200) {
      return FALSE;
    }

    $coords['lat'] = $result_parts[2];
    $coords['lon'] = $result_parts[3];
  }

  return $coords;
}

```
> 0 votes

---
Tags: 6, views, forms, google-maps
---


title: "Add link" in my account menu

text:
# Question
Title: "Add link" in my account menu
The user account page (http://example.com/user) consists of some default tabs like "View," "Edit," etc.

I want to add my menu link over there. The content to be returned should depend on the user ID. How do I do this?

# Answer
> 2 votes
If you just want to add a new tab, then the module should just implement hook\_menu(), using code similar to the following.

```
function mymodule_menu() {
  $items = array();

  $items['user/%user/new_tab'] = array(
    'title' => 'New tab title',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('mymodule_newtab_form', 1),
    'access arguments' => array('access new tab'),
    'type' => MENU_LOCAL_TASK,
  );

  return $items;
}

function mymodule_newtab_form($form, &$form_state, $account) {
  // ...
}

```

`mymodule_newtab_form()` would get the user object in `$account`. That menu callback would build a form using the form API. If the purpose is to output, the menu callback declaration would be similar, except two array indexes, which would be:

```
'page callback' => 'mymodule_newtab_form',
'page arguments' => array(1),

```

The argument passed to the callback would be different too.

---
Tags: 7, routes, users
---


# Question
Title: How do I remove variables from the variable table when my module uninstalls?
I'm working on a Drupal 6 module that adds some variables to the variable table. How can I go about having those variables removed from the variable table when the module is uninstalled?

# Answer
> 13 votes
Keep track of your variables and add appropriate `variable_del()` calls within an implementation of `hook_uninstall()`:

```
function foo_uninstall() {
  variable_del('foo_variable1');
  variable_del('foo_variable2');
}

```

As `hook_uninstall()` is an installation hook, it needs to reside in your module's `.install` file (e.g. `foo.install`).

You ought not to delete *all* variables prefixed with your module's name as namespace collisions will come back to bite you. For example, if your module's name is `foo`, you might think you should just poll the `variables` table for all variables prefixed `foo_`. But what if I write a module named `foo_awesome`? You'd delete my variables, too. That wouldn't be nice.

---
Tags: 6
---


# Question
Title: How to get search to display an error when no search terms are entered
Right now if I don't enter a search query in the drupal search module, it returns results for 'search'. I would like it to display an error prompting the user to enter a search query instead. Is there some sort of setting?

# Answer
The form submission callback for the search form is the following function.

```
function search_form_submit($form, &$form_state) {
  $keys = $form_state['values']['processed_keys'];
  if ($keys == '') {
    form_set_error('keys', t('Please enter some keywords.'));
    // Fall through to the drupal_goto() call.
  }

  $type = $form_state['values']['module'] ? $form_state['values']['module'] : 'node';
  $form_state['redirect'] = 'search/' . $type . '/' . $keys;
  return;
}

```

If, when you don't enter anything, Drupal searches for *search*, there must be a module that alter the content of `$form_state['values']['processed_keys']` when it is an empty string.
> 1 votes

# Answer
I know it's lazy, but I would do it with javascript. You'd save the extra wait time, and the load on your site.
> 0 votes

---
Tags: 7, search
---


title: How to use the $delta argument?

text:
# Question
Title: How to use the $delta argument?
How do I use the `$delta` argument in `hook_block`?

I have tried to used one, but there wasn't any effect.

What is the correct way to do this?

# Answer
> 3 votes
```
/**
 * Implementation of hook_block().
 */
function YOURMODULE_block($op = 'list', $delta = 0, $edit = array()) {
  switch ($op) {
    case 'list':
      $blocks[0]['info'] = t('Block #1 name');
      $blocks[1]['info'] = t('Block #2 name');
      return $blocks;
    case 'view':
      $block = array();
      switch ($delta) {
        case 0:
          $block['content'] = t('Hello for block #1');
          break;
        case 1:
          $block['content'] = t('Hello for block #2');
          break;
      }
      return $block;
  }
}

```

# Answer
> 9 votes
As noted elsewhere, $delta allows one module to return many blocks. It may also be easier to understand if you keep in mind that the $delta need not be numeric. It's simply an identifier.

You use the $delta first when responding to the 'list' $op. Each key in the $block array you return will be a $delta that can be used to configure or render that specific block.

```
switch ($op) {
    case 'list':
      $block['sidebar-links']['info'] = t('Sidebar Links');
      $block['footer-links']['info'] = t('Footer Links');
      return $block;

```

What this is telling the Drupal system is that the module in question has two blocks, one of which is identified by "sidebar-links", the other by "footer-links".

This will place two blocks on the admin/build/block config page. Should you enable both blocks, they will then be rendered by calls to the 'view' $op with the identifying key as the $delta:

```
    case 'view':
      switch ($delta) {
        case 'sidebar-links':
          $block['subject'] = t('Sidebar Links');
          $block['content'] = "super weak";
          break;
        case 'footer-links':
          $block['subject'] = t('Footer Links');
          $block['content'] = "super weak";
          break;
      }
      return $block;
  }

```

As an added bonus, using semantic keys for your blocks will result in easier to read CSS id's. :)

# Answer
> 2 votes
An implementation of HOOK\_block() can contain multiple blocks. The $delta argument specifies to the function which block to output. Example:

```
/**
 * Implementation of hook_block().
*/
function fightfi_block($op = 'list', $delta = 0) {
  $block = array();
  switch ($op) {
    case 'list':
      $block[0]['info'] = t('Sidebar Links');
      $block[1]['info'] = t('Footer Links');
      return $block;
    case 'view':
      switch ($delta) {
        case 0:
          $block['subject'] = t('Sidebar Links');
          $block['content'] = "super weak";
          break;
        case 1:
          $block['subject'] = t('Footer Links');
          $block['content'] = "super weak";
          break;
      }
      return $block;
  }
} // end function fightfi_block

```

# Answer
> 1 votes
It is better to see the example module for all kind of drupal examples.. http://drupal.org/project/examples You will find block example over here....

---
Tags: 7, blocks
---


title: Code for page access

text:
# Question
Title: Code for page access
I would like to use PHP code in nodes of a specific content type. I can check the user's permission with the global `$user` if the user can access the node.

Is there any module to set view for created page content?
Is it secure to check page access with this code?

```
global $user;

// Check to see if $user has the administrator role.
if (in_array('administrator', array_values($user->roles))) {
  // Do something.
}

```

# Answer
> 6 votes
I think you are looking for a node access module. There are many of them, for example http://drupal.org/project/content\_access (configure access with roles directly) or http://drupal.org/project/tac\_lite (control access by adding special taxonomy terms) and many more.

For your second question, you should always define some permissions (with hook\_perm in D6, hook\_permission() in D7) and then check that. That allows to configure through the UI, which roles have that permission and the code is not tied to your specific configuration.

# Answer
> 1 votes
Usually, on Drupal you don't verify if the users has a specific role, but if they have a specific permission; for example, instead of checking of the user has the administrator role, you check if the user has the permission of administrating nodes. This allows to add the permission to other roles without to modify the existing code.
Referring to a specific role is not generic enough to be used in a module that could be installed on different Drupal sites; in the case you want to verify if the users have one of specific roles, you should check each role, while with the permission you possibly check only one permission.

Apart from the modules reported by Berdir, if the content type is a book page, then you can use Book access, which is specific for book pages, and allows to set the users who can move book pages between books.

---
Tags: 7, security
---


title: Add a file-download widget on a form

text:
# Question
Title: Add a file-download widget on a form
I have a file field called "contracts" between my user fields.
What I want is that in the user-profile form this field would come up as a file-download widget.

Does anyone have an idea how to show a file-download widget (even a link to a file would work) in the user-profile form?

# Answer
Assuming that Your Drupal 7 site is a new site (not upgraded from a D6 installation), I think the best approach is to use the Profile 2 module (dependent on Entity API) and add a file field to the user profile.
> 2 votes

# Answer
Drupal 7 includes a file field, and you can add a file field to the user profiles in admin/config/people/accounts/fields.

In the row "Add new field," you select "File" as "Type of data to store;" the form element to show is automatically set to "File," as that is the only form field you can use, in this case. When you click on save, Drupal will allow you to set the settings for the field.

To be able to select the file field, you need to first enable the File module in admin/modules.

Once a file is uploaded, the field will appear as in the following screenshot, in the user profile. (I have used "File" as field label.)

The name of the file downloaded is a link that can be clicked.
The file field has also the option to show the content of the uploaded file, instead of the link to the file.
> 1 votes

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


title: Join or create group on registration

text:
# Question
Title: Join or create group on registration
When people register for my site I want them to either join an existing group or create a new one if it doesn't exist. They can only be a member of one group, and there's only one group type used on the site.

I've got the autocomplete widget set and I want to alter it's functionality so instead of throwing an error message it creates a group. I presume altering og.module is not a good idea as it wouldn't be easy to make my particular changes generic enough to work for lots of use cases so am I right in thinking I would create a custom module to hook into the pre-save functionality of the user entity and do my checking to see if exists, if not then create group and create membership there or is there another way?

I tried using taxonomy as my group content and using a term reference autocomplete field on my user profile, but og doesn't seem to work fully with taxonomy at the moment, and I had other problems with attached field data not saving on taxonomy so gone back to using a node type as my group content type.

# Answer
> 0 votes
`hook_user_insert()` triggers too late in the process. I used `hook_form_FORM_ID_alter()` to change the autocomplete validate callback to use my custom function.

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

  $form['group_audience']['und'][0]['gid']['#element_validate'][0] = 'MYMODULE_field_audience_autocomplete_validate';
}

```

`MYMODULE_field_audience_autocomplete_validate()` is same as the original function, except that, instead of throwing an error, it creates a group.

# Answer
> 1 votes
I think your general premise is sound. I'd be tempted to use hook\_user\_insert() instead, which is called after the user has been created, rather than before, since:

* Your module can't actually fail to create a group or insert a new one.
* hook\_user\_presave is really for modules that want to serialize (simple) data to be stored in the users table itself, which isn't what you're doing.

The necessary hooks in OG7 are all there for checking and creating groups and inserting users.

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


# Question
Title: What's the best way to implement a system to allow the end-user to download and buy documents?
I need some advise on how to build a system to allow users to download and purchase pdf files. A purchase option is a one time only thing and no order history of login is required.

The end user just needs to see a list of documents, some of which can be purchased and then when the hit buy the can pay at a Payment Provider and download.

I don't need a shopping cart, order history, login or anything.

What is the best way to approach this with Drupal 7? I was thinking of maybe using the Entity API to create a download entity, would that make sense.

# Answer
There's a module in progress that provides that for Drupal Commerce, here: http://drupal.org/sandbox/recrit/1118266

You could use it as a starting point, or just for inspiration.
> 1 votes

---
Tags: 7, entities
---


title: Drupal as a simple file manager

text:
# Question
Title: Drupal as a simple file manager
I'm wondering how easily it would be to achieve the following.

* I want to create a Drupal site where users have a small "file area" to upload files.
* I would like to be able to take those files and upload them to another server (using FTP, HTTP posts, or XMLRPC).
* It would be also nice to get the "remote server" directory listing.

I obviously think this can be easily achieved by ftp; but can I tell to the FTP manager to use the username/password couple of the Drupal user? How can I hide those information to the end user?

What I have in mind is the implementation in Drupal of the Dropbox service, where the Drupal site would be the Dropbox provider.

Any ideas on where to get started ?

# Answer
> 2 votes
Take a look at the IMCE module.

It's a powerful upload manager that requires either CKEditor or IMCE Wysiwyg API bridge to work.

It supports per-user upload directories and space quotas, amongst other useful stuff.

As for the XML-RPC, you should take a look at the Services module.

Regardless of the path you take, you will definitely need to add some custom code and, to help with that (Drupal 7 only) take a look at the FileTransfer class. (related question)

---
Tags: 7
---


# Question
Title: Do you have an example of hook_menu() access callback?
I have downloaded the examples project, but in the menu\_example module all the `access callback` are set to `true`.. hard to understand how it works.

In my example, my meno entry should be visible on nodes, but only for roles that have the permissions to edit his own nodes.

I cant find an example a bit more verbose of an access callback.

Do anyone have one?

# Answer
Edit: I missed the part about the "edit own node" permission, because then you must not only check the permission but also if that node belongs to the current user. I've updated my example below but I'm leaving the above explanation as it was.

Is your menu entry below node/nid (e.g. node/1234/something)? Then you probably don't even need a custom access callback.

If you define your menu path like the following example, it will only call the access callback (and therefore your page callback), if you're viewing a valid node.

```
'node/%node/something'

```

This means that it will call node\_load(1234) for the above example and only continue if a valid node object is returned. So you can define your permission with access arguments as usual.

That said, writing an access callback is really simple. It's just a function that will receive whatever arguments you defined in access arguments. For example, the default access callback is user\_access() and when you define your access arguments like `'access arguments' => array('a permission string')`, it will result in the following call: `user_access('a permission string')`.

If you have multiple arguments, these will be passed as second, third and so on argument to your function. To access the currently active node, you can use menu\_get\_object().

So you could write your access callback like this, but again, you might not even need to create one.

```
function yourmodule_access_check() {
  global $user;
  $node = menu_get_object();

  return $node && $node->uid == $user->uid && user_access('edit own ' . $node->type . ' content');
}

```

Instead of hardcoding the permission string, you could pass it as an argument to the function or whatever you want to do.
> 12 votes

# Answer
Drupal is itself an example of how to write code.

The easier example is aggregator\_menu(), which contains the following code.

```
  $items['admin/config/services/aggregator'] = array(
    'title' => 'Feed aggregator',
    'description' => "Configure which content your site aggregates from other sites, how often it polls them, and how they're categorized.",
    'page callback' => 'aggregator_admin_overview',
    'access arguments' => array('administer news feeds'),
    'weight' => 10,
    'file' => 'aggregator.admin.inc',
  );
  $items['admin/config/services/aggregator/add/feed'] = array(
    'title' => 'Add feed',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('aggregator_form_feed'),
    'access arguments' => array('administer news feeds'),
    'type' => MENU_LOCAL_ACTION,
    'file' => 'aggregator.admin.inc',
  );

```

In this case, the access callback is the default (user\_access()), and the access arguments are an array containing the string for the permission. The code cannot check more than a permission; if the permissions to check are two, or the conditions to check are not just permissions, then the access callback should be a different one, including a custom one.

node\_menu() define some menus that use an access callback different from the default one. The function contains the following code.

```
  foreach (node_type_get_types() as $type) {
    $type_url_str = str_replace('_', '-', $type->type);
    $items['node/add/' . $type_url_str] = array(
      'title' => $type->name,
      'title callback' => 'check_plain',
      'page callback' => 'node_add',
      'page arguments' => array($type->type),
      'access callback' => 'node_access',
      'access arguments' => array('create', $type->type),
      'description' => $type->description,
      'file' => 'node.pages.inc',
    );
  }

```

The function that is defined as access callback (node\_access()) is the following one:

```
function node_access($op, $node, $account = NULL) {
  $rights = &drupal_static(__FUNCTION__, array());

  if (!$node || !in_array($op, array('view', 'update', 'delete', 'create'), TRUE)) {
    // If there was no node to check against, or the $op was not one of the
    // supported ones, we return access denied.
    return FALSE;
  }
  // If no user object is supplied, the access check is for the current user.
  if (empty($account)) {
    $account = $GLOBALS['user'];
  }

  // $node may be either an object or a node type. Since node types cannot be
  // an integer, use either nid or type as the static cache id.

  $cid = is_object($node) ? $node->nid : $node;

  // If we've already checked access for this node, user and op, return from
  // cache.
  if (isset($rights[$account->uid][$cid][$op])) {
    return $rights[$account->uid][$cid][$op];
  }

  if (user_access('bypass node access', $account)) {
    $rights[$account->uid][$cid][$op] = TRUE;
    return TRUE;
  }
  if (!user_access('access content', $account)) {
    $rights[$account->uid][$cid][$op] = FALSE;
    return FALSE;
  }

  // We grant access to the node if both of the following conditions are met:
  // - No modules say to deny access.
  // - At least one module says to grant access.
  // If no module specified either allow or deny, we fall back to the
  // node_access table.
  $access = module_invoke_all('node_access', $node, $op, $account);
  if (in_array(NODE_ACCESS_DENY, $access, TRUE)) {
    $rights[$account->uid][$cid][$op] = FALSE;
    return FALSE;
  }
  elseif (in_array(NODE_ACCESS_ALLOW, $access, TRUE)) {
    $rights[$account->uid][$cid][$op] = TRUE;
    return TRUE;
  }

  // Check if authors can view their own unpublished nodes.
  if ($op == 'view' && !$node->status && user_access('view own unpublished content', $account) && $account->uid == $node->uid && $account->uid != 0) {
    $rights[$account->uid][$cid][$op] = TRUE;
    return TRUE;
  }

  // If the module did not override the access rights, use those set in the
  // node_access table.
  if ($op != 'create' && $node->nid) {
    if (module_implements('node_grants')) {
      $query = db_select('node_access');
      $query->addExpression('1');
      $query->condition('grant_' . $op, 1, '>=');
      $nids = db_or()->condition('nid', $node->nid);
      if ($node->status) {
        $nids->condition('nid', 0);
      }
      $query->condition($nids);
      $query->range(0, 1);

      $grants = db_or();
      foreach (node_access_grants($op, $account) as $realm => $gids) {
        foreach ($gids as $gid) {
          $grants->condition(db_and()
            ->condition('gid', $gid)
            ->condition('realm', $realm)
          );
        }
      }
      if (count($grants) > 0) {
        $query->condition($grants);
      }
      $result =  (bool) $query
        ->execute()
        ->fetchField();
      $rights[$account->uid][$cid][$op] = $result;
      return $result;
    }
    elseif (is_object($node) && $op == 'view' && $node->status) {
      // If no modules implement hook_node_grants(), the default behavior is to
      // allow all users to view published nodes, so reflect that here.
      $rights[$account->uid][$cid][$op] = TRUE;
      return TRUE;
    }
  }

  return FALSE;
}

```

There are three points to notice:

* The arguments declared with "access arguments" will be passed to the function in the same order; the function uses a third parameter because it is not used only access callback.
* The function returns `TRUE` if the user has access to the menu, and `FALSE` if the user doesn't have access to the menu.
* An access callback can also be used when a menu should be shown only in specific circumstances.
> 19 votes

---
Tags: 7, routes, hooks, users
---


# Question
Title: Table with sqlsrv driver is not showing headers or pagination
I just wanted to practice doing the table "header sorting" and pagination to display a Drupal 6 table using a simple MSSQL query. At the moment, the table headers are not showing and there is no pagination, but the data in the query is being displayed. Can anyone see anything wrong with the code?

```
/* open database connection */
include "mssqlconnection.inc.php";

/* set up the table headers */
$headers = array(
  '',
  array('image_id' => t('image_id'), 'field' => 'image_id', 'sort'=>'asc'),
  array('geo_post' => t('geo_post'), 'field' => 'geo_post'),
  array('geo_sample' => t('geo_sample'), 'field' => 'geo_sample'),
  array('gps_lat' => t('geo_lat'), 'field' => 'geo_lat'),
  array('gps_long' => t('gps_long'), 'field' => 'gps_long'),
  ''
);

/* Set up and execute the query. */
$sql = sprintf ("SELECT TOP 100 image_id,
  geo_post,
  geo_sample,
  gps_lat,
  gps_long,
  FROM images"
);

/* add the order by clause */
$stmt .= tablesort_sql($headers);

$stmt = sqlsrv_query($conn, $sql);
if ( $stmt === false) {
  echo "Error in query preparation/execution.\n";
  die( print_r( sqlsrv_errors(), true));
}

/* collecting results */

while ($doc = sqlsrv_fetch_object($stmt)) {
  $rows[] = array(
    sprintf($imgPublish . '   ' . $imgDelete, $doc->nid),
    $doc->image_id,
    $doc->geo_post,
    $doc->geo_sample,
    doc->gps_lat,
    $doc->gps_long
  );
}

$table = theme('table', $headers, $rows);
$table .= theme('pager', array(), 10, 0);

return $table;

/* Close the connection. */
include "closemssqlconnection.inc.php";

```

# Answer
theme\_pager() only works in combination with pager\_query() (Or the PagerDefault extender in Drupal 7). And that function is obviously not going to work with sqlsrv().

For Drupal 7, there is the http://drupal.org/project/sqlsrv project, which is properly integrated into the new database abstraction layer. I suggest you have a look at the following answer to see how you might be able to use that in Drupal 6: MSSql or SQL Server Wrapper for custom module? See also How do you make sortable tables with a pager with data from a custom table? for how to create paginated queries with Drupal 7/the DBTNG project.
> 2 votes

---
Tags: 6, theming, database
---


# Question
Title: Getting the role ID from the global $user
I'm very new to Drupal, so please bear with me if this is a dumb question. According to the globals API, the global `$user` object returns roles as an array:

```
[roles] => Array(
  [rid] => name
)

```

If I reference $user-\>roles, it gives me the role names.

Short of looping through like this:

```
foreach($user->roles as $key => $value){
    error_log("key: " . $key . " ; value: " . $value);
}

```

Is there any way to return the role ID (rid) instead of the role name? I need to do conditional processing based on roles, but some of our roles are company-specific, and contain special characters. It would be much easier to work with the ID instead.

# Answer
You can use `array_key_exists()` to do this:

```
$rid = 42;

if (array_key_exists($rid, $user->roles)) {
  // Do stuff
}

```

If you just want an array of RIDs, you can use `array_keys()`:

```
$rids = array_keys($user->roles);

```
> 4 votes

# Answer
```
$rid = 42;
if(isset($user->roles[$rid])) {
  // Do stuff
}

```

is what I usually use. Same basic principle, even more basic coding.

```
array_keys($someArray)

```

as **Mark Trapp** cites is really useful for hunting through the keys of the many huge arrays that Drupal produces - e.g., the $fields variable in views templates - dumping the whole thing creates a mess, with just the keys you can usually figure out which element it is you need, and then just dump that.

For dumping variables, be sure to check out Drupal for Firebug \- makes huge, unwieldy dumps nicely & elegantly separated from your HTML.
> 1 votes

---
Tags: users
---


# Question
Title: How does one create terms on hook_install if hook_taxonomy_default_vocabularies is used in the same module?
I'm attempting to create taxonomy terms in a module that provides the vocabulary needed to create these terms.

The issue I'm having is the vocabulary is not available upon install.

My module implements hook\_taxonomy\_default\_vocabularies. I would like to create these terms in hook\_install.

What is the best way to create these terms?

# Answer
> 4 votes
Although you can use hook\_install(), it's best to use hook\_enable() to check if the vocabulary exists and, if not, create it programatically:

```
$vocabularies = taxonomy_vocabulary_get_names();
$pos = array_search('my_vocabulary', $vocabularies);

if ($pos !== FALSE) {
  // its a keyed array so the $vid is actually $pos
  $vid = $pos;
} else {
  // arrays are more convenient to initialize
  $vocabulary = array(
     'name' => t('My Vocabulary'),
     'machine_name' => 'my_vocabulary',
     'description' => t('My description'),
     'hierarchy' => 1,
     'module' => 'your_module', // or nothing
     'weight' => 1
   );
   // argument must be an object
   $vocabulary = (object) $vocabulary;
   taxonomy_vocabulary_save($vocabulary);
   // horray, we have a vid now
   $vid = $vocabulary->vid;
}

// now that the vocab exists and you know the $vid, create your terms
// ...

```

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


# Question
Title: How to deal with module conflicts ("anti-dependencies")?
I have a module that specifically doesn't work with another module. I want to know if there is a way to check if that module is enabled and abort installation for example or gray out the installation box so that my module can only be installed if that other module is disabled.

It's like inverse dependencies!

Is there any way of doing this *properly* in Drupal?

# Answer
The module just needs to implement hook\_requirements(); a requirement could be that a module is not installed, and if the module returnes an error from `hook_requirements()`, then it will not be installed.

The module should implement code similar to the following one:

```
function mymodule_requirements($phase) {
  $requirements = array();
  // Ensure translations don't break at install time
  $t = get_t();

  if ($phase == 'install') {
    if (module_exists('other_module')) {
      $requirements['mymodule'] = array(
        'title' => $t('My module'),
        'value' => $t('My module is not compatible with Other module.'),
        'severity' => REQUIREMENT_ERROR,
      );
    }
  }

  return $requirements;
}

```
> 8 votes

# Answer
You can use `hook_requirements` for this. You specifically need to check for `$phase == 'install'`, and then return the proper array containing `REQUIREMENT_ERROR`.

The Simpletest module for Drupal 6 has a good example of aborting installation if certain conditions aren't met.
> 5 votes

---
Tags: hooks
---


# Question
Title: Need a list of third party video services that i can offload the conversion and serving up of my private videos?
Can anyone help me to narrow down a list of third party video services that i can offload the conversion and serving up of my private videos?

Requirements are:

1. Already have a Drupal 6 module that integrates the api (Also has a D7 future)
2. Must allow the video to only be viewed on my Drupal site. Not on their site (e.g. not viewable on YouTube)
3. HTML 5/Flash fall back (would be nice, but not necessary.

# Answer
Try these:

with Video module
> 1 votes

# Answer
youtube has an option for "private videos", they won't show up on the youtube site but you can still embed them in your site. Not a slick solution but it's free ;-)
> 0 votes

---
Tags: 6, files
---


# Question
Title: could i overwrite the array value by the preprocess function?
a module that have an array,which value are `$links[0]['text']="hello"` and `$links[2]['text']="world"`. could i overwrite them value by the `mytheme_preprocess_node` function in `template.php`. if can., how do i do?

# Answer
> 1 votes
You could only overwrite them if they are accessible within template\_preprocess\_node(). For example, if the module adds $links to the $vars (or $variables) array, or to the $node object, in its own implementation of preprocess\_node(), you could simply do:

```
$vars['links'][0]['text'] = "i have changed this text";
```
If the module does not add $links to the $vars/$variables array or to the node object, you would not be able to change it from mytheme\_preprocess\_node().

---
Tags: 7
---


title: File upload and file access

text:
# Question
Title: File upload and file access
I should upload an Excel file to a site that define a content type with a file CCK field; the download method is public. How do I set the permissions for the upload folder, if I would like to allow the PHP code to read this file, without to allow users to read this file using its URL? If the folder permissions don't resolve this problem, which module should I use?

# Answer
> 2 votes
If you want to prevent users from downloading the file directly by URL, you should not use the public download method. You should use the private method and use the functions in file.inc to access the files with PHP.

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


title: theme("pager") returns NULL

text:
# Question
Title: theme("pager") returns NULL
I am trying to use theme\_pager to create pagination as below, but pagination does not appear. I have tried using `var_dump(theme('pager', NULL, 10))` and the result is `NULL`.

```
$q="SELECT DISTINCT(node.nid) AS nid, node.type AS node_type, node.vid AS node_vid, node.title AS node_title, node.language AS node_language, node.created AS node_created, node_revisions.teaser AS node_revisions_teaser, node_revisions.format AS node_revisions_format FROM node node  LEFT JOIN node_revisions node_revisions ON node.vid = node_revisions.vid WHERE (node.type in ('slideshow')) AND (node.status <> 0) AND (node.language='$lang') GROUP BY nid ORDER BY node_created DESC";
$result = pager_query($q, 10, 0);
//Process data.
return $output . theme('pager', NULL, 10);

```

also i tried to simplify the query and to make it from one table as below, but this didn't work as well

```
SELECT nid, title, language, created FROM node WHERE node.type='slideshow' AND node.status  0 AND node.language='en' ORDER BY created DESC

```

Any idea is highly appreciated!

# Answer
> 1 votes
The problem is the query that is probably too complex, and `pager_query()` cannot alter it to obtain the total number of row matching the query passed as argument.
As reported in the documentation for pager\_query():

> The pager uses LIMIT-based queries to fetch only the records required to render a certain page. However, **it has to learn the total number of records returned by the query to compute the number of pages** (the number of records / records per page). This is done by inserting `COUNT(*)` in the original query. For example, the query `SELECT nid, type FROM node WHERE status = '1' ORDER BY sticky DESC, created DESC` would be rewritten to read `SELECT COUNT(*) FROM node WHERE status = '1' ORDER BY sticky DESC, created DESC`. Rewriting the query is accomplished using a regular expression.
>
> **Unfortunately, the rewrite rule does not always work as intended for queries that already have a `COUNT(*)` or a `GROUP BY` clause, and possibly for other complex queries.** In those cases, **you can optionally pass a query that will be used to count the records**.
>
> For example, if you want to page the query `SELECT COUNT(*), TYPE FROM node GROUP BY TYPE`, `pager_query()` would invoke the incorrect query `SELECT COUNT(*) FROM node GROUP BY TYPE`. So instead, you should pass `SELECT COUNT(DISTINCT(TYPE)) FROM node` as the optional `$count_query` parameter.

# Answer
> 0 votes
Probably your `$countquery` is not working properly.

You can try with the following code.

```
pager_query($query, 15, 0, $countQuery);

```

---
Tags: 6, paging
---


# Question
Title: is there a way to overwrite the views Sort criteria?
i have overwritten a field's output, and want to use it as the Sort criteria. so i must overwrite the Sort criteria? is there a way to overwrite the views module Sort criteria?

the sort criteria is:

table `votingapi_vote`, the field `content_id`,which is $node-\>nid, the `vaule=1`. i want to to sort it by the number counts of the `vaule`. desc. HOW TO do it?

if i want to alter the sort criteria in the template.php, is there a way to get it?

# Answer
Sure, just use hook\_views\_query\_alter().
You can intercept the view's query object and make any changes you need to it, including (but not limited to) adding/removing sort criteria.

Better WHERE's for your Drupal forums with hook\_views\_query\_alter and Using hook\_views\_query\_alter to change your views sort order give some examples of how to alter a view query.
> 5 votes

---
Tags: 7, views
---


# Question
Title: Javascript code appears in search results
I use JavaScript in the body of a node with some PHP code. After I run cron.php and search on the site, I can see Drupal indexes the JavaScript code contained in a node.

How do I avoid Drupal indexes the JavaScript code?
Alternatively, how do I avoid Drupal indexes those nodes?

# Answer
Since the javascript code is actually part of the node content it would take a bit of work to get it to be ignored.

An easier solution would be to use implement hook\_db\_rewrite\_sql() and excludes from appearing in search results. Here is a great tutorial: Hiding content from Drupal's search system.

That said, there is a module out there that does this, Search Config. However it is marked as obsolete and not being maintained anymore, therefore you might want to think twice before using it.

For the record it does indeed work as designed, and works well! (I use it on my website with no problems).
> 2 votes

---
Tags: 7, search, javascript
---


# Question
Title: Best way to benchmark Drupal stack performance
I recently asked a question regarding Drupal performance and got some great replies.

This got me thinking, **what is a reliable/meaningful way to benchmark Drupal?**

It's easy to say "install APC, memchached & Varnish" or "install module x or y", but how can I quantify just how big of a performance gain I'm getting from each setup? Basically, a sure-fire way to compare setups and find bottlenecks to squeeze the most possible performance from a Drupal site. What is the best method to find out?

Targetting Drupal 6.

# Answer
> 7 votes
I like jmeter, http://jakarta.apache.org/jmeter

It allows actual benchmarking of authenticated sessions, which many of the other approaches like ab do not. There's an article about using jmeter with authenticated users at this link

---
Tags: 6, performance
---


# Question
Title: Location module should lookup address before saving
This question is related to Adding geo location content to node.
I'm trying to get a location saved to a node. The Location module supports this, but I don't like the workflow of this module.

It does the look-up **after** the node is saved, but I would rather do the location look-up **before** the node is saved, e.g. by having a look-up button that, when pressed, queries Google, updates the gmap, and lets the user see the location before saving and not afterwards, which causes troubles, if the input address couldn't be found.

Do you have any idea on how to address this issue?

# Answer
> 2 votes
I think that OpenLayers Geocoder can be the module you are looking for.

> This module extends OpenLayers CCK input widget allowing to mark a location on the map by simply providing its address. A future version will also include support for reverse geocoding.

# Answer
> 3 votes
This doesn't help you with the Location module, but OpenLayers will map the location before the node is saved.

---
Tags: 7, google-maps, location
---


title: Drupal is slow only in IE

text:
# Question
Title: Drupal is slow only in IE
We have had a lot of feedback about our Drupal site running very slow on a different network. Most of the users on this network use IE (IE6 and IE8), which is causing a huge slowdown compared with Firefox.

However, even in Firefox it is still slower than what we would expect. We have put this down to a local DNS issue (the DNS request is timing out after 2 seconds, then works off another DNS sever. I am assuming this is adding a 2 second latency to all page loads?)

What other problem could be causing a dramatic slow down for Drupal, only in IE?

Site in FF from YSlow:

```
Empty Cache = Total Weight - 586.2K
Primed Cache = Total Weight - 267.3K

```

# Answer
> 3 votes
You could use Speed Tracer. It will help you identify and fix performance problems in your website.

# Answer
> 3 votes
Javascript is probably your villain.

Especially on IE6 and IE7 and still in IE8, Javascript is MUCH slower than the rest of the world.

Despite not being the most brilliant piece of js ever, drupal.js is harmless. The real harm probably lies a lot of plugins or maybe one or two poorly-coded scripts that perform some kind of expensive DOM lookup or other task that is negligeable in Firefox et al but really slows down IE.

# Answer
> 0 votes
I have seen this problem when I use the jcarousel module. In IE6 and IE7 it takes much longer to load the page.

---
Tags: 7, performance
---


# Question
Title: Is there any way to reorder the nodes in a View?
I have a complicated View containing many pages and attachments. When I built the View, I didn't think much about the order of the pages and attachments, but now I would like to change the ordering because it affects how they are displayed in the end. I would also like the flexibility to add additional pages in the future and be able to control where those attachments appear in the page.

I know you can control an attachment's position using the Above/Below options, but I have one page with 6 attachments and I can't seem to break the ordering except by creating and deleting nodes.

**Edit**: I discovered that I can accomplish this by exporting the View and reordering the code there and then reimporting, but if a cleaner solution exists, I would love to hear it.

# Answer
You may also consider using the draggableviews module. Basically you create an "administrative" display of your view allowing arbitrary reordering of the content of the "main" display using drupal drag-and-drop interface.

There's also a comparison page for node ordering modules on drupal.org
> 9 votes

# Answer
You can ues the Nodequeue module. Nodequeue allows you to create and arbitrarily sort "queues" of nodes and it integrates with the Views module.

> The Nodequeue module allows users to collect nodes in an arbitrarily ordered list. The order in the list can be used for a any purpose, such as:
>
> * A block listing teasers for the five top news stories on a site
> * A user’s favorite music albums
> * A group of favorite from which one is randomly displayed
>
> Nodequeue provides a simple drag-and-drop interface to manually order any queue.
> 6 votes

---
Tags: 7, views
---


# Question
Title: How to remove height and width attributes from CCK ImageField tags?
I am using Drupal 6 with the CCK ImageField module. By default, it outputs the height and width of the image as attributes of the tag. For my current project, I'd like to be able to override those with CSS. I have not been able to determine which theme function adds those attributes.

Which functions/templates do I need to override to remove those tags?

# Answer
> 1 votes
I found the answer I was looking for, although it required knowing I was also using ImageCache. I needed to override `theme_imagecache()` in template.php:

```
function mytheme_imagecache($presetname, $path, $alt = '', $title = '', $attributes = NULL, $getsize = TRUE) {
  // Overrode the default here to get ride of height and width attributes.

  // Check is_null() so people can intentionally pass an empty array of
  // to override the defaults completely.
  if (is_null($attributes)) {
    $attributes = array('class' => 'imagecache imagecache-'. $presetname);
  }

  $attributes = drupal_attributes($attributes);
  $imagecache_url = imagecache_create_url($presetname, $path);
  return '<img src="'. $imagecache_url .'" alt="'. check_plain($alt) .'" title="'. check_plain($title) .'" '. $attributes .' />';
}

```

That said, Tim's answer is easier and likely would have worked just as well or better.

# Answer
> 4 votes
The attributes are there for browser performance reasons. Overriding them with CSS is still possible. If you want to specify the width, set the height to auto, or vice-versa.

---
Tags: 6, entities, media
---


title: Good practices working with databases

text:
# Question
Title: Good practices working with databases
I'm learning Drupal, and I want to develop a website where the main thing is its database.

I already have the Extended Entity-Relationship Model of the database (kind of complex).

What's the right direction to take when creating a database to be used by Drupal, create it **manually** and do the queries in Drupal using PHP, as it were a PHP+MySQL site from scratch? Does Drupal provide an easier way to do this?

**Edit**:
I'm not a Drupal experienced developer. What I want to know is:

* When working with databases, is any better way of doing this that querying the database using SQL syntax, like if I were developing a PHP+MySQL single page?

I just want to know what Drupal developers usually doe when they want to create a database, insert data, modify data, or do some queries and show the data to the users.

# Answer
Your entity-relationship model is likely going to map to what we call 'Content types' in Drupal.

Content types are defined using the Content Construction Kit module, commonly referred to as CCK.

With CCK, you point-and-click to define what fields you want the content type to have - text fields, numbers, links, references to other content types, references to users in your Drupal site.

With the content types defined, you can figure out what kind of lists for that content you want - tabular, blog-style, etc, and use the Views module to create that listing. Views is a point-and-click query builder, complete with sorting, filtering, access control, dynamic URL arguments, and relationships (think joins) to other content types.

That's typically how 'databases' are done in Drupal - but you don't have to do anything with the database at all, really.

If you've got a really specific use case that can't be solved with some combination of the 7000 or so contributed Drupal modules, then it might be time to grab a copy of 'Pro Drupal Development' and learn module development to integrate your custom module into the rest of Drupal to meet your exact need.
> 10 votes

# Answer
My first reaction is that this is possibly a too-basic question, but on reflection it is worth answering because it is so fundamental to the mindset of working with Drupal that you tend to use the excellent work of others available via modules for most things, and only have to write a little PHP/SQL.

So, unless you're building modules for Drupal you generally don't need to know anything about the underlying database or the way it works.

With Drupal you'll be working Content Types, Nodes, and the modules Views and the CCK to build most of what you need from a site. These modules are building blocks rather than complete drop in plugins that perform a single as one may have seen in less well designed systems. Don't make the mistake of thinking that Drupal is a CMS, it's more like a standard framework without too much coding.

You can get from 0 to 95% of functionality very quickly for most things just using the core and some well chosen modules.
> 4 votes

# Answer
DISCLAIMER : I am not a Drupal Developer

Whenever you use MySQL, you must plan for the amount of storage you expect your site to use.

From personal experience as a MySQL DBA, I have cleaned up Drupal installations and Optmized Queries with a few basic principles in mind.

The main thing I do for any Drupal customer is to CONVERT ALL MySQL DATA TO INNODB. This will eliminate table locking, especially in a high traffic site. You should be all means use the innodb\_file\_per\_table option.

You should make sure you can cache all of your InnoDB data. Therefore, have enough memory to accommodate that. Don't forget to tune the sort\_buffer\_size, join\_buffer\_size, read\_buffer\_size, read\_rnd\_buffer\_size and multiple the sum of them by the max\_connections. Make sure the total memory consumed by MySQL (innodb\_buffer\_pool\_size + key\_buffer\_size + (sort\_buffer\_size + join\_buffer\_size + read\_buffer\_size + read\_rnd\_buffer\_size) X max\_connections) does not exceed 90% of the installed RAM.

It is always good practice to review the DB Layer. Once you implement these suggestions, DB Layer maintenance should be consider when you have significant growth in data or connections. Otherwise, it should be a rare occurrence.
> 2 votes

# Answer
If you where a general user, all you would do is install the site via install.php, and the only thing you need to know about the database is the name, user and password, Drupal will take care of the rest.

If you where needing to do some form of queries as a user you would use the Views module, again not really needing to know anything about the database.

If you where a developer writing custom code or a contrib module and you needed to store information in the database, you may need to write some queries, and others can be take care of by some Drupal functions.

* Setting up your database in the first place you would use hook\_schema(), where you simply need to return your schema in the required format.
* A best practice approach to writing/updating records in a single table is to take advantage of drupal\_write\_record().

There's plenty more reading to be found at: http://api.drupal.org/api/drupal/includes--database--database.inc/group/database/7

Also note that documentation is specific to version.

Hope this somewhat answers your question.
> 1 votes

---
Tags: 7, database
---


# Question
Title: How do I alter a way node is rendered so I can add custom links/buttons?
Sometimes I want to add custom links/buttons specific to a content type to a node when the page for that node is rendered, how would you achieve this when you write a module? An example code to achieve this by adding hello world link somewhere in the page when a node is rendered would be appreciated as the lack of documentation I can find for this is discouraging.

# Answer
The easiest way to do this would be to use Content Templates!

Using this module you can have some fine-grained control over how templates and individual fields are displayed without actually creating a new .tpl.php file for that node (which is another pretty good much more laborious solution)
> 1 votes

---
Tags: 7, nodes
---


# Question
Title: How do I show the image in a node enlarged?
I use the TinyMCE editor as site's editor. When I publish an image, I want the users click the image to view it enlarged.
How can I do this? The image is not a field; it is an image in the node.

# Answer
This can be accomplished using Image Resize Filter

Here is a nice tutorial by Lullabot: Effortless Inline Thumbnails: Image Resize Filter
> 1 votes

# Answer
You can also try using Insert and Colorbox.
> 0 votes

---
Tags: 7, media
---


# Question
Title: How do I hide the body field in a node using hide()?
I'm using the following code, and it simply does not work:

```
 <?php hide($content['body']);
 print render($page['content']); ?>

```

I would like to hide the body field to show it elsewehere.

# Answer
> 4 votes
You're rendering the wrong thing: you need to render `$content`:

```
hide($content['body']);
print render($content);

```

See core's implementation of `node.tpl.php` for more information.

---
Tags: 7, theming
---


title: Do we need PHPMailer?

text:
# Question
Title: Do we need PHPMailer?
We are building our website in Drupal 7. However, I wonder whether we need to configure and setup the PHPMailer module.

We are designing an ecommerce website that will send an email upon registration, online purchase, forum activity, etc.
We are confused about whether we need to configure PHPMailer in Drupal 7 or we can make use of Google SMTP services. We are totally clueless about this as we have been struggling to setup the PHPMailer.

# Answer
You don't need PHPMailer. You *will* need an SMTP server of some description.

If your server is Linux, you will need to install some method of sending email such as postfix. You could either let the server distribute email itself, or configure postfix (or whatever) to relay it to another email server.

If it's Windows, I believe you can configure PHP to use an external SMTP server without needing one on the Drupal server itself.

If you were set on sending messages through Google's SMTP servers, you will probably want to use PHPMailer, as it's set up to make that sort of thing easy. Getting hold of your own SMTP server is not tremendously difficult, however.

Can you tell us more about your hosting environment? Maybe we could be more specific with the answer.
> 5 votes

---
Tags: 7, emails
---