# Question
Title: Is it possible to create a "Meta-Forum" view when using organic groups?
We are using Drupal 6.x with organic groups. The groups have very different users and permission sets, and each group has a forum.

I was wondering if it is possible to have a kind of "Meta-Forum" view, i.e. one view in which all of the different Forums the user has access rights to are displayed, organized by group.

I have had a look at configuring a View for this, and while I am able to get things like a list of the most recent forum entries in all the subscribed groups, I was not able to get a "forum type" view where I have the groups on the highest level, then the individual forums and posts below this.

Is something like this possible?

# Answer
> 2 votes
It is very easy to build such of "forum" using Views. If you are using Organic Group Access, the view will be automatically filtered and only the content accessible to the user will be displayed.

Note that the OG Forum module has been abandoned due to security issues and should not be used. Depending on your requirements, it might be easier to simply use standard Views for the group forums (after all, a forum is nothing more then a View of taxonomy terms attached to a View of nodes).

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


# Question
Title: List Private Organic Groups Publicly without giving access to the node page?
I have a view setup to list my OG Nodes, those nodes and their greater content need to be private to only the group, but on the front end of the site I want to list some of the featured Nodes. As it stands the node access system is removing those nodes from my public listing. Any solutions to keep the full node private, but list these OG Nodes publicly?

# Answer
You can tell Views to ignore the access control of some of the Views. On Views 3.x, this parameter can be found under "Query Settings" / "Disable SQL rewriting", and is described as:

> Disabling SQL rewriting will disable node\_access checks as well as other modules that implement hook\_db\_rewrite\_sql().

The full nodes will stay private, so you should make sure not to link to them in the View so that your users do not land on "Access Denied" (403) pages.
> 6 votes

---
Tags: organic-groups
---


# Question
Title: Best practice for avoiding module / theme / profile name clashes?
We currently have our code managed such that each site has its own theme and install profile. These have naturally evolved in such a way that the names of these items (and their directories) tend to be the same.

For example, one site's theme and profile are both called 'dennis'

This causes problems with feature servers, and (I'm suspecting) with Aegir.

Now... it's relatively easy to rename either of these (although, for various reasons it's noticeably easier to rename the profile). Is there any sort of best practice here, ie is it normal to call the theme dennis\_theme, or the profile dennis\_profile? Should I apply this convention to both, or just to one?

# Answer
> 10 votes
In my office we usually have a site key that gets used for most things.

* Client: Acme Company & Co
* Key: acme
* Site Folder: /path/to/WebServer/sites/`acme`
* Custom Modules: `acme_tweaks`, `acme_form`s, `acme_blocks`, `acme_settings`
* Theme: `acme_theme`
* Repo: `acme.git`
* etc...

For code that we re-use from site to site, we ensure that it's generalized and client ambiguous and then add it to some common modules that are part of our default module set - such as:

* `theme_tweaks`
* `template_suggestions`

Our rule is that unless it can be applied to all our client sites (at least moving forward) then it shouldn't go in `theme_tweaks` but in `acme_tweaks` etc.

# Answer
> 1 votes
A way to avoid name clashes for custom modules that are used for specific sites, is to use the site name to create the module name. For example, the short name used for "Drupal.org customizations," which is the project containing modules used specifically on drupal.org, is *drupalorg*, while a similar project containing custom modules for groups.drupal.org is *groupsdrupalorg*.

You could also avoid to use the top-level domain, if you think that you will not create modules for sites with a domain name that differ only for the top-level domain (e.g. bingo.com and bingo.it).

# Answer
> 1 votes
Of course using a project 'machine\_name' as a namespace will help. What I figure out first is which of the modules, install profiles, themes (and makefiles) I will release to the public (github, drupal.org, etc). The ones I will release get generic names, while the other ones get PROJECTNAME\_short\_description as a name.

For a hacker community project I am developing, the generic zen sub-theme I developed is called 'Conway', while the actual theme (using Conway as a base theme) is called 'hacker\_theme'. Same goes for hacker\_event\_feature, hacker\_install\_profile, hacker\_distro (a kit-compliant distribution specific feature, equivalent to the projectname\_tweaks module I see everywhere).

---
Tags: coding-standards
---


# Question
Title: How to hook theme of the main system menu in drupal 7 to display only some of the elements?
I want to modify the main system menu in Drupal 7. Actually I want to display only some specific elements of the menu and hide some other specific elements, in a given case (which I will implement by a `if` or `switch` statement in a function).

What is the easiest way to do this ? And how to do it ? Can you give me an example ?

I have read that using `hook_theme` or `hook_menu` can be done, but I have no idea how to do this.

# Answer
> 4 votes
There are different levels to alter the system menu. If you want to add a top level container like drupal commerce does for the admin shop section, you need to add a menu item with hook menu like this:

```
// Top level "Store" container.
$items['admin/commerce'] = array(
  'title' => 'Store',
  'description' => 'Administer your store.',
  'page callback' => 'system_admin_menu_block_page',
  'access arguments' => array('access administration pages'),
  'file path' => drupal_get_path('module', 'system'),
  'file' => 'system.admin.inc',
  'weight' => -7,
);

```

`system_admin_menu_block_page` is what will do the job, of making it a part of the system menu.

If you want to make the menu appear under one of the sections, like configuration etc, you just need to adjust your path in hook\_menu, fx

```
$items['admin/config/section'] = array(...);

```

Every time you want to create a section that should hold other menu items, simply add

```
'page callback' => 'system_admin_menu_block_page',
'access arguments' => array('access administration pages'),
'file' => 'system.admin.inc',
'file path' => drupal_get_path('module', 'system'),

```

When creating a menu item in a section, just create a normal menu item.

**Update**
Since the menu structure is cached, you can't alter the menu by a per user scenario. But there are still some methods available.

* Since menus are only displayed if the user has access, you could create a custom access control function for all the menus and put your logic in there.
* You could also try to do this in the theming layer, and alter the output to only display the desired menus. I haven't tried this in Drupal 7, but generally, altering the output of menus this way is hard, as the menu system is quite complex.

If you need to alter the menus, to change the access control, you should use `hook_menu_alter`.

# Answer
> 2 votes
You want to hide the menu based on a condition. It depends on what the condition is, however. If you can base it on role, there is a module for that: Menu Per Role

If you have more complicated logic you may have to create different menus for the different cases. The menu system caches menus so it is difficult to alter dynamically. By creating multiple menus, you can show different ones in a block based on your condition by using the Menu Block module.

# Answer
> 2 votes
Without more information about your use case (including: the content of this mysterious condition "which \[you\] will implement by a if or switch statement in a function", and the definition of "some part of the menu"), it is difficult to give you a definite answer.

Just know that Drupal's menu system is a complex tool designed to handle a wide variety of use cases and menu structures. Its standard display logic is designed to show the user only the links it can actually access, so that no Drupal user should ever land on a 403 page.

The menu system also supports dynamic alterations of the menu links (and of their visibility) via `hook_translated_menu_link_alter()`, but it requires a little bit of work:

* First you need to mark the menu links you want to target as "alterable", for example by settings their `$link['options']['alter']` to TRUE in a hook\_menu\_link\_alter() or hook\_menu\_alter() if they are menu router items.
* Then you can implement `hook_translated_menu_link_alter()` and set the `'access'` property of the links you want to hide to `FALSE`.

You can also use per-packaged solutions like the menu\_per\_role module already mentioned.

Modifying the menu structure just before rendering in the theming level is *never* the solution.

# Answer
> 1 votes
There are many ways you could do this in the theme template files, or in a preprocessor. However if you don't want links in the menu why not just go to /admin/build/menu and remove them from the menu?

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


title: Are taxonomy fields exposed to views?

text:
# Question
Title: Are taxonomy fields exposed to views?
I am trying to create a view of nodes that have a taxonomy reference field. I can get the taxonomy term but do not see the taxonomy fields that I've created exposed to views. Google searches do not reveal anyone else having the same issue. Am I missing something right under my nose?

# Answer
Are you using Relationships? It's right there in the views edit page. Since you're showing nodes, you are probably going to need to declare you want to show taxonomy term fields.
> 2 votes

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


# Question
Title: Are "files[]" from custom_module.info not included on form submits?
I have a module that I am porting to Drupal 7 (specifically, Taxonomy Views Integrator) and there are 2 include files `tvi.admin.inc` which *were* included via the module's .info file:

`files[] = includes/tvi.admin.inc`

The `tvi.admin.inc` houses the functions that the `tvi.module`'s `hook_form_alter()` uses, including the **validation** & **submit functions**

Although alterations made using the `hook_form_alter()` work properly, **after submit** the validation & submit functions in `tvi.admin.inc` are not available and throw an undeclared function error.

*p.s.*

I've checked the initial issue for the extended .info module registry via: http://drupal.org/node/224333#registry and it does say the following which *may* provide us with an answer:

> Files containing only functions need not be listed in the .info file.

**As a Workaround,**

I now use `module_load_include()` to load the `tvi.admin.inc` at the top of the `tvi.module` which, on form submit, still includes the inc and thus the validation / submit functions.

# Answer
Files listed in *.info* files are not automatically included when the module is loaded; they are loaded when a module tries to create an object for a class that PHP doesn't find. In that case, a callback registered with spl\_autoload\_register() will check the content of the Drupal registry to find which file needs to be loaded to allow the creation of the object.

The only way to load a file containing a function is to use `module_load_include()`.
In the specific case, where the function to load is a form validation handler (or a form submission handler) that is added to a form altered with `hook_form_alter()` (or `hook_form_FORM_ID_alter()`), I would rather keep the form handlers in the same file containing the hook implementation. Technically, the file is loaded by `hook_form_alter()` when it is not necessary, as the form handlers are used after the form has been submitted; so far the code worked, but it is not said that it would not work in future versions of Drupal.

Drupal 7 allows modules to implement hook\_hook\_info(), which is used from Drupal to know in which files the hook implementations are defined. The System module define its own implementation, which contains the following code:

```
function system_hook_info() {
  $hooks['token_info'] = array(
    'group' => 'tokens',
  );
  $hooks['token_info_alter'] = array(
    'group' => 'tokens',
  );
  $hooks['tokens'] = array(
    'group' => 'tokens',
  );
  $hooks['tokens_alter'] = array(
    'group' => 'tokens',
  );

  return $hooks;
}

```

With this implementation of the hook, when Drupal is looking for the file containing the implementation of `hook_tokens()` for the module custom.module, it will look for the file custom.tokens.inc contained in the directory where the module custom.module is installed.
Third-party modules are allowed to implement their own `hook_hook_info()`, but it should be remembered they are modifying where Drupal looks for the hook implemented by other modules too, which means that changing the group for `hook_token_alter()` changes the files where Drupal looks for any implementation of `hook_token_alter()`.

It is possible to use `hook_hook_info()` to keep some hooks in a file that is different from the module file, using an implementation similar to the following:

```
function custom_hook_info() {
  return array(
    'form_alter' => array(
      'group' => 'form',
    ),
  );
}

```

What I reported before is still valid; future versions of Drupal could stop working because they would not find where the form handlers are, even though they know where to find the implementation of `hook_form_alter()`.
This is the reason I keep to put the implementation of `hook_form_alter()` (or `hook_form_FORM_ID_alter()`) and every related form handler in the module file.
> 16 votes

# Answer
Only classes are tracked and automatically included. Everything else needs to be included manually.

Also, I'm not really sure what you are doing here, you do not need to alter your own forms. Second, \_submit()/\_validate() callbacks should be in the same file as the form function itself then you don't need to include them manually.
> 2 votes

---
Tags: 7
---


# Question
Title: "Enterprise" authentication, single sign-on and user provisioning for multiple sites
I'm looking for a solution for user provisioning, authentication and single sign-on which will make it easy for me to manage accounts for all the staff at my company across all of the sites we work on.

My main goal is to have a single point at which I can add/remove users to grant/revoke access to all the sites our staff will need to work on. This is obviously a pretty useful thing on it's own, but it'll also mean that I can ask staff to change passwords regularly without it taking a day to go through every site, etc. All this is in addition to "normal" users which vary from site to site.

The shared tables approach won't work (and wouldn't use anyway), I don't fancy setting up an LDAP server just for this, none of the sites share a domain so Bakery won't work, the OpenID module allows any provider so I can't trust the profile details to automatically set roles, etc.

Is there an existing (production ready) solution that uses, e.g., OpenID but lets me restrict the provider/s to those I can trust? Should I just bite the bullet and start trying to hack at the OpenID module? Am I barking up the wrong tree?

# Answer
> 1 votes
You would have to use a few modules working together to make this happen.

Development Seed had an interesting demo using OpenID, PubSubHub and Feeds. They detail it at http://developmentseed.org/blog/2010/mar/02/simple-sign-openid

lordg's comment re: hubs is exactly what they did.

# Answer
> 0 votes
Have a look at multisite\_login, it should help you get to what you are looking for. I haven't used it myself yet, but the description appears to fit quite well. You could contact that maintainer to get some customizations or become a co-maintainer of it.

---
Tags: users
---


title: Node Access table goes empty

text:
# Question
Title: Node Access table goes empty
I currently have a project where I am inserting mulitple records into Drupal using node\_save. Its usually a couple of hundred at a time. For some reason, sometimes the node\_access table ends up empty, resulting in the data "appearing" deleted to the users.

Does anyone know what could possible be happening?

I have reviewed the node\_save code and notice is does run a call to rebuild the node\_access table via `node_access_acquire_grants($node)`. Currently I have no modules implementing node\_access hooks.

My one thought was to just call node\_access\_rebuild() once I've finished inserting. I also run the process a few times every hour.

Side Note: Drupal may not be the right system for the bulk inserts and volume, but that is not the discussion I wish to have on this question.

# Answer
The only moment where the node access table could be empty is when node\_access\_write\_grants() (or node\_access\_rebuild()) deletes the content of the table before to repopulate it.
In the case of `node_access_write_grants()`, the table could become empty only if the table contained the access data for a node; in the case of `node_access_rebuild()`, the table becomes empty in any cases.

Sometimes the `all` entry can vanish, as node\_access\_acquire\_grants() adds that entry only if no modules returned access records for the node passed as argument to the function, and `node_access_rebuild()` adds that entry if no module returned access records.

To notice also that, in the case the `$realm` passed to `node_access_write_grants()` doesn't match with the value contained in `$grant['realm']` (for all the grants passed to the function), then `node_access_write_grants()` will delete the access records for the node passed as argument, but it will not save any access records.

```
// Only perform work when node_access modules are active.
if (count(module_implements('node_grants'))) {
  foreach ($grants as $grant) {
    if ($realm && $realm != $grant['realm']) {
      continue;
    }
    // Only write grants; denies are implicit.
    if ($grant['grant_view'] || $grant['grant_update'] || $grant['grant_delete']) {
      db_query("INSERT INTO {node_access} (nid, realm, gid, grant_view, grant_update, grant_delete) VALUES (%d, '%s', %d, %d, %d, %d)", $node->nid, $grant['realm'], $grant['gid'], $grant['grant_view'], $grant['grant_update'], $grant['grant_delete']);
    }
  }
}

```

The same can happen if a module calls `node_access_write_grants()` using the default value for `$delete`, and there aren't modules implementing `hook_node_grants()`.
In these cases, the node access table can become empty if the table contained data only for the node passed as argument to `node_access_write_grants()`.
> 1 votes

# Answer
The node\_access table is only populated if you use a node access module.

Some examples are Content Access, Taxonomy Access Control Lite, or Node Access.
> -1 votes

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


title: External JS libraries

text:
# Question
Title: External JS libraries
I have a few external js files that I call in my page, at the moment these are called via script tags in the header.

I am tempted to pull these locally and include them in my themes script file to decrease the load time of the page. I know there is an overhead to keeping the scripts up to date but if it decreases the total load time of the page it may be worth it.

Is there a good practice for this? Should I keep them external or is it good to include them in the drupal JS structure?

# Answer
> 6 votes
I think it highly depends on what the script is. There are definitely advantages to using third party scripts rather than including them locally. In most cases, I'll try to use the google Library API (http://code.google.com/apis/libraries/) when possible for things like swfobject, webfont loader, and the like. The advantage here is that clients may already have these libraries cached, giving a performance increase over hosting them locally. For situations where there is not a widely used third party host for scripts, I'll usually add them to sites/all/libraries/$library\_name and include them locally, so you can take advantage of Drupal's ability to aggregate and minify JS.

# Answer
> 3 votes
The net effect of pulling external scripts locally depends on a lot of factors. Consider for example that:

* All browsers have limits on the number of resources (Javascript / CSS / Images) they concurrently pull from a given server; increasing the number of resources on a domain can as a consequence increase the total page load;
* The central distribution points (Google Libraries API, etc.) are geographically distributed and probably more reliable and faster then your own servers;
* The clients are likely to have the library already in cache if it is distributed from the central distribution point;
* Drupal 6 is particularly dumb in how it does the aggregation of JS and CSS files, and this can lead in your clients having to download the same library several times if they visit pages on your website that have a different set of Javascript files.

In consequence, I would advise again switching to a local version if you are already using a CDN hosted version.

# Answer
> 3 votes
Look at the emerging module Advanced CSS/JS Aggregation -- it aims to provide the most complete and efficient aggregation system ever.

---
Tags: 7, javascript
---


# Question
Title: Best practice for custom module variable names?
I've gotten into the habit of doing pretty robust configuration panes for my modules now, and I'm finding the variable names & management to be quite the **pain**.

I have variables like `mymodule_section_subvar_varname_type_context` and I not only loose track of the order of the elements in my variable names but I feel as if having a variable name that long is a design flaw.

I've been considering using a serialized array in a variable `mymodule_section_settings` in conjunction with a set of functions that make it easy to maintain that array but I'd love some input in what (if any) best practices have been established outside of prefixes and/or examples of modules that we trust and what they are doing for large sets of variables.

Thanks!

# Answer
> 7 votes
It is possible to use a Drupal variable to contain an array; that is what Drupal core modules do too (see book\_type\_is\_allowed()).

It is possible to use a single Drupal variable to contain different settings used by a module into an array. With the form `#tree` attribute is still possible to use system\_settings\_form() to save the array into a Drupal variable without writing any additional code. Serializing the de-serializing the code is automatically done by the Drupal core functions that handle Drupal variables (see the code of variable\_set()).

The question is then: when should a single Drupal variable be used to contain different settings? I would use a single variable for settings that are used by a function, or a group of functions; if the array contains values used by (for example) 10 different functions, but those functions access a single value (or a couple of values) from that array, then I would not use a single persistent variable for the settings.

# Answer
> 2 votes
If a set of settings are related then putting them in an array makes sense. For example if you are doing `several variable_get`'s sequentially. It gives you some flexibility as well as being potentially a little faster.

However this will make it difficult for other programs to edit your settings manually via something like drush vset or strongarm. In these cases long variable names can actually be helpful.

---
Tags: configuration
---


title: Change $<field_name>_rendered output?

text:
# Question
Title: Change $<field_name>_rendered output?
In a node I get the values of CCK fields as $ array or $\_rendered as the rendered view of the field. How can I change the `$<field_name>_rendered` from its default way of rendering?

# Answer
> 6 votes
Drupal is amazing in the many ways it let's you override the final rendered HTML. I want to point out that you can also override how the field is rendered at the theme layer.

Just copy the file ...contrib/cck/theme/content-field.tpl.php to your personal theme folder. and rename it to

content-field-\[field\_name\].tpl.php where \[field\_name\] is the id/name of the cck field you want to override.

Just edit that file to your liking. And make sure you reconstruct the theme chache tables so that Drupal recognizes the new template file.

# Answer
> 6 votes
The Custom Formatters module will help you quickly and elegantly. Here is a quote about it (from the module's project page):

> ... allows users to easily create custom CCK/Field Formatters without the need to write a custom module. Custom Formatters can then be exported as CTools Exportables/Features or Drupal API Formatters.

# Answer
> 5 votes
CCK fields use something called field formatters to control it's output. This is also how fields do it in Drupal 7. Field formatters is really just a theme function that's called.

In the content type setting: *Display fields* it's possible to select a formatter for normal view mode and teaser view mode. If the default formatters are not usable, you need to create your own formatter for the field and a theme function that will control how it's rendered.

I've written a blog post: *Creating a field formatter for CCK* a long time ago, at times I still use it myself for reference so it might help you out.

Alternatively you can use your theme to overwrite the default theme function for the formatter. This will however change all fields on your site with the selected formatter.

---
Tags: 6, theming, entities
---


title: Multiple "unused" Views displays

text:
# Question
Title: Multiple "unused" Views displays
I'm creating a heavily customised website in Drupal. I want to use Views as a data source for a page with several options, where each option corresponds to a different display in a View. The reason I want to use Views is that they are easily configurable through a UI, so they are easy to tweak/change later if the need arises.

Unfortunately though, it seems like I can't create a display of a view that doesn't have some form of side effect (ie, a page display will create a new page). Does anyone have any bright ideas?

# Answer
> 6 votes
http://drupal.org/project/embed\_views "This is a views display based on the default views display that does not have any additional features or "cruft" that you can use to create embed views for your site."

# Answer
> 1 votes
As far as I know you can't just "unpublish" a view...

My suggestion would be to set the "access" setting of a view and make it only acessible for your own user or an admin role, that way its there but no-one can access it.

# Answer
> 1 votes
You can embed a view in code as well. You'd want to edit your template.php file and in hook\_preprocess\_page or hook\_preprocess\_node (depending on what you're actually adding the views to) you can embed a view with the following snippet:

```
function mytheme_preprocess_page(&$variables) {
  // check $variables for your particular page
  ...
  // embed a particular view's default display
  $variables['embeded_view'] = views_embed_view('view_name', 'default');
}

```

In the example I've created a new variable ('embeded\_view') which can then be printed in your page's tpl file.

# Answer
> 0 votes
I often create multiple page displays that go to the same page. Does only one path is added (that should solve your problem)

Then I take advantage of the fact that Views always returns the first display that the user has access to. so I make sure that add restrictions in accordance to that rule.

So if if I have an admin-type display and a regular display, I make sure that the admin display is first and the regular display is second. I add a restriction to the first one and add no restriction to the second one.

---
Tags: 7, views
---


title: default routing of custom module

text:
# Question
Title: default routing of custom module
I'm trying to write my first module and am using the hook\_menu to route the pages. The module consists of a multi-step form and two static content pages.

```
/**
 * Implements hook_menu().
 */
function order_menu() {
  $items = array();

  $items['order/form'] = array(
    'title' => 'Order Form',
    'description' => 'Order multistep form.',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('order_form'),
    'access callback' => TRUE,
    'file' => 'order_form.inc',
    'tpe' => MENU_CALLBACK,
  );

  $items['order/cancel'] = array(
    'title' => 'Order Cancelled',
    'description' => 'Order cancelled.',
    'page callback' => 'order_cancel',
    'access callback' => TRUE,
    'file' => 'order_form.inc',
    'type' => MENU_CALLBACK,
  );

  $items['order/success'] = array(
    'title' => 'Order Success',
    'description' => 'Order Successful.',
    'page callback' => 'order_success',
    'access callback' => TRUE,
    'file' => 'order_form.inc',
    'type' => MENU_CALLBACK,
  );

  return $items;
}

```

What I want to do is be able to access 'example.com/order/form' from 'example.com/order' but when I change the menu hook from $items\['order/form'\] to $items\['order'\] it displays as page not found.

Any suggestions as to how to how to get the module to display the content I want from example.com/order?

# Answer
Did you force Drupal to rebuild the menu, after you changed the code? If you don't do that, Drupal will use the previously defined menus.

To force Drupal to rebuild the menus, you just need to visit the modules page (the administration page showing the list of all installed modules), disable a module, and re-enable it. The last two operations are not strictly necessary; you would probably get the same effect if you click on the "Save" button present on that page without to enable or disable any module at all.
Drupal will call any implementation of `hook_menu()` and `hook_menu_alter()`, and it will grab the last menu callbacks defined from your module.

Alternatively, you can call menu\_rebuild() from code, or install Devel, which has a block containing a link that allows to force Drupal to rebuild the menu list it caches.
> 2 votes

# Answer
The problem is that `order` is not defined as a menu item. An easy way of fixing this would be to include it in the hook menu definition:

```
/**
 * Implements hook_menu().
 */
function order_menu() {
  $items = array();

  $items['order'] = $items['order/form'] = array(
    'title' => 'Order Form',
    'description' => 'Order multistep form.',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('order_form'),
    'access callback' => TRUE,
    'file' => 'order_form.inc',
    'type' => MENU_CALLBACK,
  );

  ...

}

```

You could use use the `MENU_DEFAULT_LOCAL_TASK` for the `order/form` menu item, but I believe it will produce a tab by default, which might not be what you want.

Remember to clear the cache after making these changes.
> 2 votes

---
Tags: 7, routes
---


# Question
Title: Testing installation profile with custom tasks
For a large project, we are using a code driven development workflow. We are using a custom installation profile to install and configure the contrib and custom modules used on the project. The ensure correctness of this profile, we need to test it like any other module.

Currently, we use a SimpleTest test case that looks like this which worked good so far.

```
class FooTestCase extends DrupalWebTestCase {

  protected $admin_user = null;

  public function getInfo() {
    return array(
      'name' => 'Foo Profile',
      'description' => 'Ensure that the Foo profile configure the site.',
      'group' => 'Foo',
    );
  }

  public function setUp() {
    $this->profile = 'foo';
    parent::setUp();
  }

  //Test methods ...
}

```

The site has to be multilingual, so in order to install and enable all the required language, I added a custom profile task using `hook_install_tasks`. The task works fine when executed from the browser. But it is not executed when DrupalWebTestCase::setUp\` is run. So we are unable to test its effect to ensure they are not lost whatever the refactoring our profile will go through in the future.

Since languages installation require translations loading, the task itself use batch processing.

I'm looking for both a way to have this particular task executed in `FooTestCase:setUp` and more generally to have all the (non interactive tasks) in my profile executed.

For reference, here is the code for the task

```
function foo_install_tasks($install_state) {
  return array(on
    'foo_install_import_locales' => array(
      'display_name' => 'Install additional languages',
      'display' => TRUE,
      'type' => 'batch',
      'run' => INSTALL_TASK_RUN_IF_NOT_COMPLETED,
    )
  );
}

function foo_install_import_locales(&$install_state) {
  include_once DRUPAL_ROOT . '/includes/locale.inc';
  include_once DRUPAL_ROOT . '/includes/iso.inc';
  $batch = array();
  $predefined = _locale_get_predefined_list();
  foreach (array('nl', 'de') as $install_locale) {
    if (!isset($predefined[$install_locale])) {
      // Drupal does not know about this language, so we prefill its values with
      // our best guess. The user will be able to edit afterwards.
      locale_add_language($install_locale, $install_locale, $install_locale, LANGUAGE_LTR, '', '', TRUE, FALSE);
    }
    else {
      // A known predefined language, details will be filled in properly.
      locale_add_language($install_locale, NULL, NULL, NULL, '', '', TRUE, FALSE);
    }

    // Collect files to import for this language.
    $batch = array_merge($batch, locale_batch_by_language($install_locale, NULL));

  }
  if (!empty($batch)) {
      // Remember components we cover in this batch set.
      variable_set('foo_install_import_locales', $batch['#components']);
      return $batch;
  }
}

```

# Answer
I typically find it best to leave your installation profile as bare bones as possible, and put tasks like this into hook\_enable of a site specific module. Similarly, any updates that need to be made should be put into `hook_update_N` functions in the same module, while updating the `hook_enable` implementation.

This makes it much simpler to test and has the added benefit of keeping all of your setup and updates in one place.
> 6 votes

---
Tags: 7, distributions, testing
---


title: Need a WYSIWYG plugin

text:
# Question
Title: Need a WYSIWYG plugin
Straight to the point, I need a WYSIWYG module for Drupal 6; here are the requirements:

* Easy to change the toolbar button
* Able to add custom style
* Able to upload image and put into content
* Able to upload flash and render it inside content
* Able to upload file and show it as download link inside content

Anybody familiar with Wordpress WYSIWYG editor? That is something like what I want.

# Answer
> 4 votes
If you are going to use WYSIWYG you should consider using WYSIWYG Filter to ensure that users do not include markup that you do not want to get through. Without the filter and full html text format enabled users can switch from full html or which other formats you have defined to plain text where they can add whatever markup they want and back to full html to by pass the plain text filter. With WYSIWYG filter you can ensure that bad markup or even corrupt js does not make it through the WYSIWYG editor.

Another way to ensure clean markup is to create your own text format and only enabling the WYSIWYG editors buttons that produce the same markup that you allow through your format.

elFinder is probably the best file manager out there at the moment. I find it's UI is much better than IMCE

# Answer
> 5 votes
Use the WYSIWYG module... TinyMCE allows for media to be added such as Flash, so you can use that plugin.

For files/images you can use the Insert module **OR** IMCE (along with IMCE Wysiwyg API Bridge) to add the images/files to the content.

Remember Google can be a wonderful thing ;)

# Answer
> 4 votes
In addition to WYSIWYG with whichever Javascript WYSIWYG library you want to use, you'll probably also want Linkit, Image Browser, etc., etc.

You should probably also make sure that you've got a good HTML cleanup configuration in your input formats and that your WYSIWYG configuration will only generate tags that other filters aren't going to strip out again. You'll also want to make sure that pasting "rich text" from other applications into your WYSIWYG will be treated correctly (cleaning up the junk from Word, normalising `style="font-weight:bold"` to `<strong>`, etc.)

Making a useful, reliable, "correct" WYSIWYG configuration requires more than just installing the modules.

# Answer
> 2 votes
I use WYSIWYG, CKEditor, IMCE, and the IMCE WYSIWYG Bridge. You can configure profiles that you assign to roles for various things like HTML filters, confine the user to an upload directory based on their UID (sites/default/files/%uid), and just a lot of other really awesome stuff.

Here is the guide that I found that finally put all of this together for me:

http://himerus.com/blog/himerus/inline-images-drupal-wysiwyg-api-tinymce-and-imce

---
Tags: 6, nodes, wysiwyg
---


# Question
Title: How to create a view to display a block of referenced nodes?
I have a node type, called "policy", that has a bunch of CCK fields, including a Node Reference type. This is configured to reference an unlimited number of nodes.

When the nodes are viewed, the list of referenced nodes appear at the bottom of the content. Ideally, I'd like to put these in a block on the side of the content.

I've tried writing a view that accepts an NID as an argument and displays the CCK field. This works in the Views configuration preview (displays expected results), but when I put this block on the side bar, and view a node, I do not see any results at all.

I do not have a relationship specified in the view - I'm not really clear on if I need to use it or not.

Thanks!

# Answer
When configuring the argument for the block, set it to "Provide a default argument", and configure that to use the nid of the node being viewed.
> 2 votes

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


# Question
Title: How can I setup Git/Drush dl/make caching of Drupal projects?
I'd like to setup the ability to have Drupal projects cached locally when I do a Git clone or Drush dl/make, so that if I happen to be offline or just to save bandwidth, when I Git clone/Drush dl/make a project that has previously been downloaded it will pull from the cache instead of from D.o., possibly after pinging D.o to see if there is a newer version (if online).

I'm sure I saw something about this once before, but haven't been able to track down the specifics.

# Answer
There is a blog post about locally cached git repositories here: http://randyfay.com/node/93
> 8 votes

# Answer
Drush 5 now has a `--cache` flag which builds up a cache automatically, just as described at http://randyfay.com/node/93.

We have started integrating Drush Make into Drush core and at that time, make will get Drush core's caching features (like what dl and updatecode have).
> 4 votes

# Answer
As the answer was only relevant to the Git, I did a little searching and came across an Issue in D.o. for Drush make that lead to a blog post on how to use Squid to cache Drush dl commands, the blog post is a tad broken due to the Geshi Filter module not running or working correctly, but the information seems like it will be valid. Still trying to wrap my head around it.
> 0 votes

---
Tags: drush, version-control
---


# Question
Title: How should I handle container form elements?
I have added some custom fields to the register user form and I'm discovered that they are sent back, packaged in a form element of type "container". My code needs to handle all kind of different custom register fields.

How should I parse these objects and extract the fields from them? Should I look into the arrays and what can I expect to find there?

I can't seem to find any good documentation on these objects.

Edit:

A regular fields received through user registration might look like this:

```
name
... (Array, 10 elements)
#type (String, 9 characters ) textfield
#title (String, 10 characters ) Username
#maxlength (Integer) 60
#required (Boolean) TRUE
#attributes (Array, 1 element)
class (Array, 1 element)
0 (String, 8 characters ) username
#default_value (String, 0 characters )
#access (Boolean) TRUE
#weight (Integer) -10
#fb_registration_field (String, 4 characters ) name

```

A form container looks e.g. like this:

```
field_birtyday
... (Array, 6 elements)
#type (String, 9 characters ) container
#attributes (Array, 1 element)
#weight (String, 1 characters ) 7
#tree (Boolean) TRUE
#language (String, 3 characters ) und
und (Array, 13 elements)
0 (Array, 12 elements)
#entity_type (String, 4 characters ) user
#bundle (String, 4 characters ) user
#field_name (String, 14 characters ) field_birtyday
#language (String, 3 characters ) und
#field_parents (Array, 0 elements)
#columns (Array, 2 elements)
0 (String, 5 characters ) value
1 (String, 6 characters ) format
#title (String, 8 characters ) Birthday
#description (String, 0 characters )
#required (Boolean) FALSE
#delta (Integer) 0
#weight (Integer) 0
value (Array, 16 elements)
#entity_type (String, 4 characters ) user
#bundle (String, 4 characters ) user
#field_name (String, 14 characters ) field_birtyday
#language (String, 3 characters ) und
#field_parents (Array, 0 elements)
#columns (Array, 2 elements)
0 (String, 5 characters ) value
1 (String, 6 characters ) format
#title (String, 8 characters ) Birthday
#description (String, 0 characters )
#required (Boolean) FALSE
#delta (Integer) 0
#weight (Integer) 0
#type (String, 9 characters ) textfield
#default_value (NULL)
#size (String, 2 characters ) 60
#maxlength (String, 3 characters ) 255
#attributes (Array, 1 element)
#theme (String, 25 characters ) field_multiple_value_form | (Callback) field_multiple_value_form();
#field_name (String, 14 characters ) field_birtyday
#cardinality (String, 1 characters ) 1
#title (String, 8 characters ) Birthday
#required (Integer) 0
#description (String, 0 characters )
#prefix (String, 42 characters ) <div id="field-birtyday-add-more-wrapper">
#suffix (String, 6 characters ) </div>
#max_delta (Integer) 0
#after_build (Array, 1 element)
0 (String, 30 characters ) field_form_element_after_build | (Callback) field_form_element_after_build();
#language (String, 3 characters ) und
#field_parents (Array, 0 elements)

```

# Answer
You should use `$form_state['values']` to handle submitted user data, not `$form`.
> 4 votes

# Answer
There is no good documentation on that form because it is dynamic, any module can implement hook\_form\_alter() and completely turn it upside down. In your example, the name is added directly by user.module while field\_birthday is a field and fields are built in a way that allows them to be displayed multiple times if necessary. That's why they are a container and only inside them is the actual form element.

Assuming you want to parse the actual form, and not the response, you have to go through the form recursively. The function element\_children() can help you with that. It returns the keys of all form elements below the one you passed in to that function.
> 0 votes

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


# Question
Title: How do I echo the node vocabulary in preprocess_page or in page.tpl.php so that I can test against it in Drupal 7?
I need to be able to echo the vocabulary that is associated with a node, but I need to echo it either in the preprocess\_page function in `template.php` OR somewhere in `page.tpl.php`. I can't seem to find how exactly this will work in Drupal 7. Does anyone know?

# Answer
If you want to output something on in the page structure (ie. somewhere in page.tpl.php), you *need* to output it as a block, Drupal's primary structural element.

In a module, define a `hook_block_info()` (or `hook_block()` in Drupal 6 and below), and implement it in this way:

```
/**
 * Implements hook_block_info().
 */
function mymodule_block_info() {
  return array(
    'node_taxonomy' => t('Taxonomy terms of the node')
  );
}

/**
 * Implements hook_block_view().
 */
function mymodule_block_view($delta = '') {
  if ($delta != 'node_taxonomy') {
    return;
  }

  // Get a node object form the URL (node/123).
  $node = menu_get_object();
  if (!$node) {
    return;
  }

  // Render the 'field_tags' field from the node object using the 'page' display.
  $rendered_field = field_view_field('node', $node, 'field_tags', 'page');
  if ($rendered_field) {
    return array(
      'subject' => t('Tags'),
      'content' => $rendered_field,
    );
  }
}

```

Or use Panels, which is precisely designed to build composite pages, and allows you to render the different elements of the node in different places.

Other approaches, especially those involving hacking the theming layer are breaking the principle of separation of structure and presentation.
> 3 votes

# Answer
Why don't you do it in node.tpl.php where $node is available? Just a `var_dump($node)` and it will work.

In page.tpl.php, however you can get node id at `arg(1)` (and arg(0) is 'node', the url is 'node/xxx'), use `node_load`:

```
var_dump(node_load(arg(1)));

```

Of course, you'll make sure that you are in a node page.
> 0 votes

# Answer
If you do it in a `MODULE_preprocess_page(&$variables)` the content of `$variables['node'] is a node object, when the page is associated with a node.`variables\['page'\]\['content'\]\` is the region with the main content of the current page; it is an array as requested by drupal\_render().

Using code similar to the following, you can dump the content of the taxonomy associated with the node, for debugging purposes.

```
function mymodule_preprocess_page(&$variables) {
  $element = array();

  if (!empty($variables['node'])) {
    $node = $variables['node'];
    if (!empty($node->field_tags)) {
      $element['#type'] = 'markup';
      $element['#value'] = check_plain(var_export($node->field_tags, TRUE));
      array_unshift(variables['page']['content'], $element);
    }
  }
}

```
> 0 votes

---
Tags: 7, debugging
---


# Question
Title: Adding a CDN feature for a new installation: now or later?
If you are setting up a Drupal 6 website from scratch, is it important to install a CDN module (or similar service) immediately? Or will adding such a feature be easy to do later on--even with multiple image files or static files already being used on the site domain?

# Answer
> 5 votes
Easy to add later. We usually do it right at the end. =)

To expand, it's easy anyway, but the CDN module makes it even easier: http://drupal.org/project/cdn

As described on the project page, CDNs work by taking files from your normal Drupal 'files' directory, either on demand or on creation (original pull or file conveyor) and in either case this can be done at the end - you can build your whole site, upload lots of files without it - it will all sort itself out when you hook things up.

The CDN module rewrites file links so you don't have to think about that either. And if you miss any, they'll still be there on your local server, everything will still work, and you can spot them in server logs and work out why they're still being served from local.

So yeh, it's cool. No need to worry about it right away.

---
Tags: 6, performance, cdn
---


# Question
Title: How to make a MENU_LOCAL_TASK on a user's profile only appear on their profile?
I use logic like this to place a tab on each user's profile page so users can view analytics from the usage of a WebApp:

```
  // maps a url to a sub-page of user's profile, url to user's Analytics-Management form
  $items['user/%user/ClientCompanyName'] = array(
    'title'            => 'ClientCompanyName',
    'description'      => 'Manage your ClientCompanyName services.',
    'page callback'    => 'drupal_get_form',
    'page arguments'   => array('_ClientCompanyName_mgmt_form'),
    'access callback'  => 'user_access',
    'access arguments' => array( 'access ClientCompanyName services' ),
    'type' => MENU_LOCAL_TASK,
  );

```

This works great for each user, but I do not want one user to be able to go to another user's profile and hit their link to get to that other user's private analytics data.

Currently, if a user tries to visit another user's analytics management page, they see an access denied page.

But I would like them never to even be given the link to that page. I tried writing my own 'access callback', but I can't figure out how to pass in the '%user' portion of the intended url so I can test that against the logged in user...

I like how one can use '%' symbols in the url, and then 'page arguments' can be used to reference those arguments in the url. Is it possible to do something similar with the 'access arguments'?

Essentially, I'm trying to achieve the same thing as the behavior of the 'edit' tab on a user's profile: only if the user is on their own profile page will that 'edit' tab appear on the profile. How do I get the same effect for my WebApp analytics page?

(I guess I could make my analytics page a MENU\_LOCAL\_TASK of the profile edit form... but I'd still like to know how to create a conditional MENU\_LOCAL\_TASK whose conditional is more then simply an user\_access() permissions test.)

# Answer
Instead of user\_access, define your own access callback function and then pass the user object to that.

So `'access callback' => 'yourmodule_analytics_access'` and `'access arguments' => array(1)`.

In that function, compare the user id *and* check the permission.

```
function yourmodule_analytics_access($account) {
  global $user;
  return $user->uid == $account->uid && user_access('access ClientCompanyName services');
}

```
> 6 votes

# Answer
I ended up using a custom access callback like this:

```
// this makes the analytics user profile tab's MENU_LOCAL_TAB conditional:
function _cex_mgmt_access($accessAllowed) {
  global $user;
  if (arg(1) != $user->uid)
    return false;
  return user_access($accessAllowed);
}

```

Where the `'access callback'` parameter in the MENU\_LOCAL\_TASK definition is set to `'_cex_mgmt_access'` rather than `'user_access'`.

I'm a bit uncertain about this method. It depends upon the menu module's logic that handles the MENU\_LOCAL\_TASK definition to be processed each time a user travels to any profile page. Doesn't that information get cached (if caching is turned on)?
> 1 votes

---
Tags: 7, routes
---


# Question
Title: Using CCK Date with Date Repeat on Calendar
I have a content type named `Event`. It has a field name `Date`, which uses the jQuery pop-up with `Repeat` options. It uses the To and From date, both of which are required. The time zone conversion uses the `Site time zone`.

On the Calendar view, I've modified it to use as the Argument, the Date field from the Event content type. This is also added to the Fields, as it's required to match the Argument. On Filters, I've got `Node Type=Event` and `Published=Yes`.

Now, I create an Event and set the Date field for `3/17/2011 03:00 pm` to `3/17/2011 05:00pm`. I then put on the Repeat a repeat for `Every` `Day` until `March 20, 2011`, with no exceptions or anything else.

Immediately after submitting it, I see that the node display only has repeats for `March 17, March 18`, and `March 19`. This is also reflected on the Calendar. But, then when I open the node in edit mode, it says the Repeat Until is set to `March 21` now. If I save it now, `March 20` shows up on the node display, but now the edit form shows `March 22`.

Any ideas what might be going on? I've tried playing with the time zone settings, and no luck. Any help would be appreciated!

# Answer
Here is a very recent issue thread that seems to match your problem:

http://drupal.org/node/1014664

The issue is very recent and it looks like a working patch has been rolled into the newest version of the module, so a quick update of the Date module, (specifically the Date-Repeat submodule) should fix you up.
> 2 votes

---
Tags: entities, datetime
---


title: Fields in page.tpl.php

text:
# Question
Title: Fields in page.tpl.php
I want to display in my page.tpl.php 3 custom fields form the latest content type added to my website.

I have a custom content type called "Articles" with three custom fields, field\_1, field\_2, field\_3.

How can I display on every page of my website those three fields from the latest content added to "articles"? I want to do this without using views.

# Answer
I don't have the exact answers for you, but I do have some directions to point you. Try something like this:

1. In template.php, in a THEMENAME\_preprocess\_page() function, construct a query to get the node ID of the most recently created node. Look up Drupal's Database API to see how to do this. (A more permanent solution would be to use a custom module for the query, but let's start at the theme layer to get this working.)
2. Do a `node_load()` to get the entire contents of that node, which will contain your three fields, and more.
3. Create variables (inside the `$variables[]` array) to hold the rendered content of your custom fields.
4. Use those new variables in page.tpl.php, or page-article.tpl.php
> 1 votes

# Answer
Since I'm going to assume you have some kind of religious opposition to the Views module- I would opt for the custom module method.

A simple module could create a block that can be displayed on any page you like.

I would start here, http://drupal.org/node/206753. We're talking 6.x right? Of course we are. Once you have the .info and .module file setup, you can skip down to Declaring Block Content, (http://drupal.org/node/206758), and then onto Generating content (http://drupal.org/node/206759 )... this is where it gets interesting...

```
function yourModuleName_block($op='list', $delta=0) {
  // set up the block
  $block = array();

  if ($op == "list") {
    // This is what it will be listed as in your list of blocks
    $block[0]["info"] = t('On This Date');
  }
  else if ($op == 'view') {
     $block['content'] = yourfunctionToGetNewArticalContent();
  }
}

```

Then create your function to return anything you want, For that you''ll want to take a look over here.. http://api.drupal.org/api/drupal/includes--database.mysql-common.inc/function/db\_query/6
> 1 votes

---
Tags: 7, theming
---


# Question
Title: Views Slideshow Output different in IE vs Firefox/Chrome/Safari
A site I'm working on is using Views and the Views Slideshow plugin to generate a tabbed panel on the site. We modified the output of the plugin to display link names instead of IDs, which worked great. The view set the link back to the node.

We modified the view itself to instead use a link that the user specifies on the node instead of linking back directly to the node itself. Cleared the cache and FF works fine. When I test in IE, it doesn't link anywhere (the anchor's href is actually empty).

I've got all the caching on Drupal turned off, deleted the cache in IE, rebooted... the module itself seems to be outputting different HTML based upon the browser. Any ideas on where to start looking? I'm digging through the module itself right now but I'm not seeing anything that stands out.

**Update**

What ended up happening was a module (not the one I was working on) was detecting IE and including javascript that was for IE only. This extra javascript ran before mine and mangled some of the tags I needed to work with.

# Answer
When browsers create different markup, the problem is most likely an error in the HTML, where IE is particulary bad at making broken HTML work.

Try comparing the actual source code for the page to see if it is the same.

If even the source is different it's most likely an issue with a reverse proxy or similar. Some are known to cause problems with IE with certain configurations.
> 2 votes

# Answer
Agreed, the answer is in the HTML source of the page (View Page Source). Regardless of the browser, they are all working with the same base HTML code which they then attempt to correct if they're not able to interpret correctly. FireFox tends to be more forgiving but the fact that it's not working in IE suggests that you have some type of typo.

Look at the HTML source around where the problem links are via "How do I view the source code of a web page?" -\> http://www.computerhope.com/issues/ch000746.htm. Silly things like typos or missing quotations can often be the root of the issue.

Remember, the problem is in *your* source not in the specific browser.
> 0 votes

---
Tags: 7, views
---


title: Drupal filters are not cacheable

text:
# Question
Title: Drupal filters are not cacheable
I have a Drupal 7 site with many custom filters. Everything works correctly, but not quick.
It looks as though the filter cache system does not work properly because the cache\_filter table is always empty. There is the issues in d.o. but it isn't replied.

# Answer
> 2 votes
The cache is used only when the input format is enabled to use it; this means that none of the input filters that are used by the input format disable the cache.

The code of check\_markup(), which the function that is called when an input format needs to be applied to a text, contain the following code.

```
$cache = $cache && !empty($format->cache);
$cache_id = '';
if ($cache) {
  $cache_id = $format->format . ':' . $langcode . ':' . hash('sha256', $text);
  if ($cached = cache_get($cache_id, 'cache_filter')) {
    return $cached->data;
  }
}

```

`$cache` is a parameter passed to the function, and `$format` is the variable containing the value returned by filter\_format\_load(); if `$format->cache` is `FALSE`, the filter cache will not be used.

In the case of the body content of a node, the function that is used to sanitize the body content (and the content of other fields) is \_text\_sanitize(), which invokes `check_markup()` without to use the fourth parameter (`$cache`), which by default is `FALSE`. This means that, whatever the filter is set to use the cache or not, the cache will not be used.

```
function _text_sanitize($instance, $langcode, $item, $column) {
  // If the value uses a cacheable text format, text_field_load() precomputes
  // the sanitized string.
  if (isset($item["safe_$column"])) {
    return $item["safe_$column"];
  }
  return $instance['settings']['text_processing'] ? check_markup($item[$column], $item['format'], $langcode) : check_plain($item[$column]);
}

```

This is different from what done by user\_comment\_view() (the implementation of `hook_comment_view()` that is used to filter out the signature of the user who wrote the comment), which passes the fourth parameter to `check_markup()`, setting it to `TRUE`.

```
function user_comment_view($comment) {
  if (variable_get('user_signatures', 0) && !empty($comment->signature)) {
    // @todo This alters and replaces the original object value, so a
    //   hypothetical process of loading, viewing, and saving will hijack the
    //   stored data. Consider renaming to $comment->signature_safe or similar
    //   here and elsewhere in Drupal 8.
    $comment->signature = check_markup($comment->signature, $comment->signature_format, '', TRUE);
  }
  else {
    $comment->signature = '';
  }
}

```

# Answer
> 1 votes
If cache\_filter table is empty, but memcache or APC is enable, then it's great ;)

Or as kiamlaluno pointed out, one of your filter disables cache (e.g. PHP filter) so that the whole format that uses that filter is not cacheable.

---
Tags: 7, caching, input-formats
---


title: Cannot install Open Atrium

text:
# Question
Title: Cannot install Open Atrium
I've been trying to install Open Atrium for at least 6 hours and cannot find a solution. There seems to be a permissions problem…

Here's where I'm at: I successfully installed a Ubuntu VM, and installed Drupal 6. I then downloaded Open Atrium, copied its contents into the `example.php` folder. I then went to the default folder and changed the settings file to `settings.php`, etc. Install Atrium launches through Firefox, but then says:

```
Forbidden

You don't have permission to access / on this server.
Apache/2.2.16 (Ubuntu) Server at example.dev Port 80

```

### Update:

I installed everything using the drush commands per quickstart tutorial. I created the `example1.dev` folder, then replaced its contents with Open Atrium. I then renamed the `Default.install.php` file to `install.php`, and created a `files` folder inside `default`.

I'm not sure why I'm having this problem, but it looks like a permission issue with the file folder. I can't figure out how to open up read/write permissions through Ubuntu. Any ideas?

I followed these directions verbatim, and wiped out the appliance and started over a few times as well. I'm at a loss. I think if I knew how to open permissions to Apache I'd be all set. Any ideas?

# Answer
You said you downloaded Drupal, then downloaded Open Atrium?

Open Atrium is a specialized version of Drupal, you install it standalone.
> 3 votes

# Answer
user581 I don't think OpenAtrium is your problem. I think you are just installing it incorrectly. Did you follow the instructions here?

https://community.openatrium.com/documentation-en/node/2428
> 2 votes

# Answer
Does not seem like a drupal issue at all. There is some documentation on what permissions drupal needs in order to run, the key part being:

> All the Drupal files (eg .php, .module, .css, .theme and images etc) will need to be able to be read by the webserver account. The 'files' is generally the only directory will need to be writable by the webserver account.

So ensure that the webserver user (normally www-data on Ubuntu using apache) has read access to the PHP files

*UPDATE*:

If you want this issue to be resolved by the community you will need to give me information, e.g.

* What distro and version of linux
* Version of apache
* Are you using mod\_php or fastcgi
* The webserver user and group
* current permissions (e.g. 640 for PHP, 770 for files dir etc)
* current user and group owners of the drupal installation
* Are you name-based virtual hosts or IP based?
* If you place a plain info.php file in the webroot with

\<?php phpinfo(); ?\>

in the contents - can apache read this?

* What about if you `chown www-data:www-data info.php` \- does this resolve the issue?
* What about if you `chmod 750 info.php` \- does this resolve the issue?

You probably should also refactor your question to remove open atrium as this is simply a distribution of drupal, at the moment if you will have troubles running any PHP files (i.e. drupal is not the issue here).
> 1 votes

# Answer
In your Apache configuration, are both the following lines included?

```
AddHandler php5-script .php
DirectoryIndex index.php

```

The `You don't have permission to access /` error will be shown if the `DirectoryIndex` line is missing or not set to include `index.php`.
> 0 votes

---
Tags: installation, distributions
---


# Question
Title: Avoid redirect to comment page if comment is invalid
I have configured comments to display in the node page, but if submit an invalid comment (e.g. without text in the comment field) I get redirected to the /comment/reply/ page. I would like to remain in the node page.

# Answer
> 7 votes
You can do this, by using `hook_form_alter` and then change the `$form['#action']` value to point to the current destination.

---
Tags: 7, comments
---


# Question
Title: How do I resolve the "Argument 1 passed to drupal_attributes() must be an array" error on my system_settings_form()?
I don't usually post specific questions like this, and ask for help on a specific issue but I am at the end of my rope wasting time way...

I have a simple D7 module as seen below, when I load the page (who's menu item is exactly where I want it to be) I get the following error:

> Recoverable fatal error: Argument 1 passed to drupal\_attributes() must be an array, null given, called in /path/to/site/public\_html/includes/form.inc on line 3106 and defined in drupal\_attributes() (line 2257 of /path/to/site/public\_html/includes/common.inc).

as you can see the form declaration itself is *very* simple, and everything runs peachy keen until the page load.

note, that I **have** looked at: 3106 in `form.inc` and the $element is populated but attributes doesn't exist - what am I missing???

```
<?php
/**
 * Implements hook_menu().
 */
function attach_images_menu() {

    $items['admin/structure/types/manage/%/attach/images'] = array(
        'title' => 'Attach: Images',
        'page callback' => 'attach_images_settings',
        'access arguments' => array('access administration pages'),
        'weight' => '10',
        'type' => MENU_LOCAL_TASK,
    );

    return $items;

}

function attach_images_settings() {
    //$content_type = arg(4);
    $form['attach_images_amount_'] = array(
         '#type'   => 'textfield',
         '#title'  => 'Amount',
         '#default_value' => variable_get('attach_images_amount_',1),
    );
  return system_settings_form($form);
}

?>

```

# Answer
> 12 votes
```
$items['admin/structure/types/manage/%/attach/images'] = array(
    'title' => 'Attach: Images',
    'page callback' => 'attach_images_settings',
    'access arguments' => array('access administration pages'),
    'weight' => '10',
    'type' => MENU_LOCAL_TASK,
);

```

This should be `'page callback' => 'drupal_get_form', 'page arguments' => array('attach_images_settings')`. (don't forget to clean the cache after making the change)

Also, form callbacks in Drupal 7 have a mandatory $form argument.

# Answer
> 3 votes
It's worth remembering that specifying 'drupal\_get\_form' in your page callback is no different than implementing your own custom built-from-scratch page callback, and calling drupal\_get\_form() in *it*.

---
Tags: 7, forms
---


# Question
Title: what can be removed when minimizing hook_views_default_views in a module?
I'm working on a new drupal 6.x module (currently in sandbox awaiting review - http://drupal.org/sandbox/sdague/1072704) which exports it's data via views. When I implemented hook\_views\_default\_views() I just used the export functionality on views for a few basic views to get things started.

That works, but those are both very verbose, and don't implement any i18n. Is there a standard way of trimming down the default values in those views so this becomes a bit more sane and maintainable?

# Answer
I find that the features module does a better job exporting the view. It adds an array of translatable strings. I haven't compared the verboseness of the views exported, but most they are probably the same. Most of the verboseness comes from defining fields. Some options might not be strictly needed - compared to the UI, but when importing/exporting things, it's better to be a bit over verbose, than to rely on default values.

With some practice, you can learn to spot the important stuff and ignore the rest.
> 1 votes

---
Tags: views, 6, hooks
---


title: How to adjust the display order

text:
# Question
Title: How to adjust the display order
The HTML structure is the following one:

```
   <div id="contentp">
     <p>.........</p>
     <p>.........</p>
     <div id="rate-node-18-1-1" class="rate-widget rate-widget-1 clear-block rate-processed">...</div>
   </div><!--contentp  end ----!>

```

The part between `<div id="contentp">` and `</div> <!--contentp end ----!>` is generated in node.tpl.php by the following snippet:

```
  <div id="contentp">
      <?php print $content; ?>
  </div>

```

The `<div id="rate-node-18-1-1">` part is generated by the rate module.

I want to put the `<div id="rate-node-18-1-1">...</div>` part outside of the `</div> <!--contentp end ----!>`.

How I should do it?

# Answer
> 2 votes
Since Fivestar actually appends its markup to the bottom of the node's content (instead of using Links, for example), its a bit more tricky.

Ideally you would create a seperate node template for your content type, ie: `node-story.tpl.php` or something like that (depends on your theme).

Once you have a node template you can safely edit, do the following at the top:

```
<?php
$my_node_content = $node->content['body']['#value'];
$my_fivestar_widget = $node->content['fivestar_widget']['#value'];
?>

```

Then, instead of `<?php print $content; ?>`, do: `<?php print $my_node_content; ?>`

This way, only your node's actual body content will be printed out.

Then, wherever you want, just print out the fivestar widget code!

Here's what it would look like using your markup:

```
<div id="contentp">
  <?php print $my_node_content; ?>
</div><!--contentp  end ----!>

<div id="my_fivestar_container">
  <?php print $my_fivestar_widget; ?>
</div><!--my_fivestar_container end ----!>

```

---
Tags: 7, theming, rating
---


title: NoSQL vs Other SQL Drupal Setups

text:
# Question
Title: NoSQL vs Other SQL Drupal Setups
What are the advantages of running NoSQL (ex MongoDB) over MySQL, PostGRE SQL or MSSQL in Drupal? Are the advantages gained from simply using the storage or does some Drupal configuration need to change?

# Answer
MongoDB can be used to store most or all your entities into fast, document-oriented storage. This type of storage scales way better then the standard SQL based storage we have in Drupal core (which is based on a "one table per field" schema).

In the current state of Drupal 7, you would have:

* The base table of the entity stored on SQL (ie. the users table, the node table, etc.)
* All fields stored in SQL
* The properties of the entities from their base tables duplicated in MongoDB

This allows fast querying on the entities on MongoDB, and the ability to add complex indexes that no Opensource SQL database support (including indexes across tables). At the same time, you don't lose interoperability because the base table of the entity is still stored in SQL and can thus be joined by modules that are still SQL-only (like Flag).

This type of fast querying is available thanks to the EntityFieldQuery mechanism, a way to build queries on entities, their properties and their fields in an abstract manner. The default implementation in core translate those queries to SQL, but the MongoDB module has a full-featured implementation that can satisfy those queries from MongoDB directly.

Thanks to the EntityFieldQuery backend for Views, you can easily leverage this power, by using the tools you are used to. The only downside is that relationships are not supported (but in practice you rarely need them anyway - and this can be worked-around by pushing additional data into the entity object and add exposing them as additional properties of the entity).

In a nutshell, as soon as query performance is a problem on your project, which happens as soon as you have a significant dataset (let's say starting at a few tenth of thousands of entities on a given entity type), MongoDB is a net gain for very very few drawbacks. Highly recommended.
> 13 votes

# Answer
MongoDB and similar are designed to store structured (hierarchical) data in a relatively flexible way.

For example in `Drupal 7`, when using `field_sql_storage`, every field gets it's very own tables. When you attach 10 fields to a content type, you end up with 10 tables in your database. When you load that node, `field_sql_storage` will execute a query per field and per node (or multiple nodes, when using `node_load_multiple`).

When you use mongodb\_field\_storage, you can store all fields of a node in a single document and get with a single query.

You can also store other things like watchdog, sessions, cache, blocks in *MongoDB*.

You still need MySQL however, *MongoDB* doesn't replace it (only for specific parts).

Another advantage is that it is easier with *MongoDB* to scale, you can add many servers to a cluster share the data between them.
> 7 votes

# Answer
The pros come with cons.

Drupal as a whole can't be switched to MongoDb, so you will have to support two databases and make sure they work well together.

Many modules will not be able to work with mongodb so you will loose interoperability.

Unless you have a pressing need (like part of your system is not coping with the number of request/or amount of data) I wouldn't switch. And even when you start approaching limits look at throwing hardware at the problem or tuning before switching.

I thought I had answered this before, there is a almost duplicate on SO
> 5 votes

---
Tags: 7, database
---


# Question
Title: How to call a Rules action settings form via drupal_get_form
So, I'm trying to embed the form I find at '/admin/config/workflow/rules/reaction/manage/commerce\_payment\_paypal\_wps/edit/3' - which contains the settings for the PayPal business, etc (from commerce\_paypal\_wps.module).

Looking in rules/ui/ui.controller.inc I can see it's called thus:

```
$items[$base_path . '/manage/%rules_config/edit/%rules_element'] = array(
      'title callback' => 'rules_get_title',
      'title arguments' => array('Editing !plugin "!label"', $base_count + 3),
      'page callback' => 'drupal_get_form',
      'page arguments' => array('rules_ui_edit_element', $base_count + 1, $base_count + 3, $base_path),
      'access arguments' => array('administer rules'),
      'load arguments' => array($base_count + 1),
      'file' => 'ui/ui.forms.inc',
      'file path' => drupal_get_path('module', 'rules'),
    );

```

I'm not entirely sure what extra things I should be passing into drupal\_get\_form('rules\_ui\_edit\_element') to make it render the form as it does normally.

How on earth do I get that rules action settings form to render either through drupal\_get\_form, or some other mechanism, so I can put it at the URL of my choosing, and make it look a bit more presentable to our clients?

# Answer
You must be using an old version of commerce to get an url like that. It was changed long ago to `dmin/commerce/config/payment-methods/...`

In `hook_menu`, the commerce\_payment\_ui module creates the path, where the rules forms should be located:

```
// Add the menu items for the various Rules forms.
$controller = new RulesUIController();
$items += $controller->config_menu('admin/commerce/config/payment-methods');

```

You could alter those if you want to change the url. You should however be aware that this url is also used elsewhere:

```
/**
 * Builds the payment settings page using the Rules UI overview table filtered
 *   to display payment method rules.
 */
function commerce_payment_ui_admin_page() {
  RulesPluginUI::$basePath = 'admin/commerce/config/payment-methods';

  ...
}

```

Since most of what Rules does, including creating these settings form is classed based, it wont exactly be easy to create the form. I haven't delved much into the Rules code, but I remember seeing public functions called

* `form`
* `form_validate`
* `form_submit`

I believe these are used to create the form, but how it ends up in the FAPI is beyond me. If all you want is to change the path, you could just use `hook_menu_alter` and for commerce, overwrite the `commerce_payment_ui_admin_page` function with your own to create the overview table.
> 1 votes

---
Tags: forms, commerce, rules
---


# Question
Title: What are the legal considerations to build a service like Drupal Gardens and earn profit from it?
I ask for your help to clarify a doubt I had on the usage and licensing of the Drupal platform to build a commercial project like Drupal Gardens.

Today, I have read both licensing and usage rules from the drupal.com and drupal.org, but I have found nothing that could give an straight answer to my curiosity about what will take both legally and economic to maintain a site 'like' Drupal Gardens. Being specific a service where people will pay to get a deployed Drupal instance.

# Answer
> 5 votes
The primary complication is the use of the Trademark "Drupal" in the product or service's name or domain. You'll need to contact the Drupal Association at http://association.drupal.org, or Dries Buytaert, the trademark holder.

If you're not interested in using the Drupal trademark as part of your product or service's name there shouldn't be any problem.

# Answer
> 1 votes
Since you will be using the drupal code ( GPL ) in SaaS model of deploying drupal sites for your customers there would be no legal issues. Like eaton said, trademark violation could be an issue you can read drupal trademark policy here - http://drupal.com/trademark

---
Tags: 7
---


# Question
Title: What all contributes to drupal page execution time?
I have a site I am investigating that has major performance issues, using memcache I was able to bring number of queries down both in number and total exectution time ( from 3 secs to 230 ms) but the page execution time is eluding me ( I am looking at values outputted by devel) my understanding is that page execution time = time taken for php to execute therefore I installed APC and I can see php opcode being cached and stats showing hits in APC control panel ( apc.php shipped with APC ) but my page execution time does not go down. So I think my question is two-fold:

* What all contributes to ( better slows down) page execution time? Is it just time taken to execute php?
* What approaches should I take to bring down page execution time. I tried APC but not much help

P.S number of modules used on this site is just enormous ( 168 ) but right now I am not in a position to make that recommendation, its more like a fire in the hole situation.

**Edit:** Output of running xhprof on local instance (recommended by mikeytown), this seems to be crazy I think the later results are due to thrashing? diff runs for the same url have drastic difference and its just too much resource usage. Also not sure why is it showing values which are not from today :| (I just installed xhprof on this laptop)

# Answer
> 4 votes
Get a cachegrind of your site. xdebug or xhprof can generate one. This will tell you what functions are taking the longest to run. Until you do this, its a bad guessing game.

# Answer
> 1 votes
EDIT: I misread the original post. 168 modules is a lot, and 300 to 700ms of SQL queries is *huge*. The more modules you will use, the more queries they will be as soon as modules does some.

Use aggressive caching while you can, cache everything, if it's not enough, try a reverse proxy cache. Using a CDN for files can greatly improve the whole thing. A reverse proxy cache can also help you by removing some auth cookies when hitting pages that does not needs it (then core will think user is anonymous for those and maximise caching).

---

The Drupal core dynamism make the whole dawn slow as soon as you have too many modules interacting at the same time.

I'd say, for example, if you use a lot of modules that loads data at hook\_node\_load() time instead of using fields, it will make a lot of queries while the field usage would have ensure caching efficiency.

Rendering can take a lot of time also, drupal\_render() (the rendering API sometime being called) is a nice piece of API (really useful) but also a bit slow. Switching to PDO (D7) and the full DBTNG (which is great by the way) also add non neglictable latency.

That said, core by itself is quite fast (but it does too much SQL queries, even with almost nothing installed), poorly coded modules often are the bottleneck.

APC can divide execution time per 2 or 3, depending on the code that runs. if you configure it well (enable all APC optimizations, the offical APC manual is well written and will guide you).

If you are on a box with a slow file system (network file system or slow hard drive) it can imply a visible impact on execution time. Drupal is made from *a lot* of small files, which forces PHP to do I/O on the FS each time it loads one of them (APC also helps a lot for that).

A misconfigured DBMS can also be quite an ugly bottleneck, if you are using MySQL think about doing fine tuning. If you are on a shared hosting, if it's not Drupal specific (or ready) DBMS and PHP stack will probably be misconfigured or non-tuned, which can lead to really slow sites.

Don't forget to activate all the caches. If your site is not authenticated user oriented, then activate the aggresive page caching (it really is amazing).

The more you'll have blocks, the more full pages will be slow, Views' module blocks will be a dawn bottleneck (depending on the Views plugins you use, OG's block can be a real pain) if you don't restrict their visibility on a per-page basis, or with custom PHP code (any other block also, always set your block visibility manually, greatly helps the framework by avoiding it to attempt to render empty blocks).

Avoid modules that uses hook\_init(), hook\_init() is being run on every page, even if you get a 403 or a 404, which slows down everything (it even slow down imagecache|style generation time, and 404 errors on files would be dawn slow just to tell you the file doesn't exist).

---
Tags: performance, caching
---


# Question
Title: The new version of my module depends on more modules than the old version ... how to ensure module users install them?
I am updating an existing module I have developed. The new version requires a "helper" module that the old version did not (fwiw, specifically "Nodereference Count"). How do I ensure that when people upgrade from the prior version of my module to the new version, they make sure to install the newly required helper module first?

Is there something I should put into hook\_update\_n function?

Thanks.

# Answer
You could use hook\_requirements(), which should allow you to display an error when the module is installed/updated.

Alternatively, if that doesn't work you can implement hook\_init() to run a check for the modules and react accordingly.

**Update:** I've just run into the same issue myself and here is the code that I have used:

```
/**
 * Implements hook_init().
 */
function MYMODULE_init() {
  if (!module_exists('ctools')) {
    module_enable(array('ctools'));
    if (!module_exists('ctools')) {
      drupal_set_message(t('MYMODULE has been disabled as the required !ctools module is not present.', array('!ctools' => l(t('Chaos tool suite'), 'http://drupal.org/project/ctools'))), 'error');
      module_disable(array('MYMODULE'));
    }
  }
}

```

This will try to enable the required module and if it is unable to do so it will display an error message to the user and disable the my module.
> 3 votes

---
Tags: updating
---


title: cck Nodereference for files

text:
# Question
Title: cck Nodereference for files
I am trying to create a node that has a single file attachment (using CCK filefield), and be able to reference that file by other nodes (possibly more than one node).

The application is such that there's a "forms library" that will have various documents refer to forms.

I have looked at FileField Sources, but I'm not clear if I change a file in node A, if the attached file in node B will reflect that change.

Additionally, we're finding related nodes based on taxonomy terms (http://drupal.org/project/relevant\_content), so it would be nice if I could refer to the node, but by clicking on the link to the node (via the node reference), the file opens.

I've looked at Custom Formatters (http://drupal.org/project/custom\_formatters) and Formatters 4 Node Reference (http://drupal.org/project/formatters4nodereference) as suggested by Attaching existing server files to filefield, but I don't seem to "get" the two modules, and neither of them are flush with documentation.

Is there a module for this, or am I looking at writing something?

# Answer
> 1 votes
You don't want FileField Sources, you want to use a Node Reference field on the node you want to reference the file on, and you want to change the display of the node reference field with either a Custom Formatter (that you'd need to write yourself) or a standard FileField via the Formatters 4 Node Reference field module.

To change the display of the Node Reference you would want to goto the Display Fields page on your Content Type and select the new Formatter from the dropdown.

A brief demo of what you could potentially do for this sort of system can be seen at: http://www.youtube.com/watch?v=qBXoN25guic

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


# Question
Title: How can I hook into the system Contact form Message Sent process and alter the HTML generated?
I have a Drupal site where I am using the sited-wide system Contact to allow visitors to send messages to the site owner. Once a visitor submits the form, the user is redirected to the home page and a sticky appears at the top reading:

**Your message has been sent.**

My question then, is it possible to change this message and add some HTML to the output? Ideally I would add some javascript to create a virtual page view for the Google Analytics account so that I can track it as a Goal Conversion.

I imagine this would be a hook\_ function sitting in my template file, but I'm relatively new to this process.

# Answer
Sure, just use hook\_form\_alter() and add a callback to $form\['#submit'\]. The easiest way to find your form's id is inspecting it using firebug. This article has a lot more detailed info: http://www.lullabot.com/articles/modifying-forms-drupal-5-and-6.

In short:

* Find the id for the contact form, "contact\_mail\_page" or something (notice how hifens turn to underscores)
* In a new custom module implement either: `yourmodule_form_alter($form_id, &$form, 'contact_mail_page')` or `yourmodule_form_contact_mail_page_alter($form_id, &$form)`
* Modify the contact form as you want using the $form variable passed by reference
> 6 votes

# Answer
The webform module might be more suited to your needs if it's just a general site wide form.
> 1 votes

# Answer
@shanabus, you're understanding of "write a hook for a module" is incorrect. The main goal of creating a custom hook for any existing module including a system module is to over-ride the behaviour. This is how you customise Drupal to a specific sites needs. You'll not edit the existing code but rather add new code that uses the "hook" system to add new/replacement functionality.

Typically a custom hook function lives in a custom module created specifically for the site by the author of the site. Consider it a place to store your site specific customisations that you'll not be sharing with the greater Drupal community. A classic use would be a hook\_form\_alter as Alex suggests above.

Consider looking at the hook API documentation for more details: http://api.drupal.org/api/drupal/includes--module.inc/group/hooks. This is often a concept that new Drupal developers struggle with so don't be discouraged if it takes some extra effort to get the concept figured out. We've all been here :)
> 0 votes

---
Tags: 7, forms
---


# Question
Title: Batch API and curl or file_get_contents() issue in Drupal 7?
Has anyone ever experienced issues with curl or `file_get_contents()` when using the batch API?
I'm trying to import nodes from a remote data source via batch API; I used file\_get\_contents() during one phase of development, but then it stopped working.

I can assure that neither curl or `file_get_contents()` is working, and that they work outside of batch API. Could it be related to how batch API makes its calls via AJAX? The really odd part is that it was working while I was trying to figure out how to get images into a field.

I know it's a really obscure question but I was hoping that someone else had experienced this before.

# Answer
> 2 votes
I think it isn't related to batch api.

Drupal has other HTTP client implementation - drupal\_http\_request()

# Answer
> 0 votes
Batch operations are interrupted every second. If the code is waiting for a reply from the remote server which doesn't reply, then the batch operation gets interrupted before it gets any result.

The code that interrupts the batch operations every second is contained in \_batch\_process():

```
// If we are in progressive mode, break processing after 1 second.
if ($batch['progressive'] && timer_read('batch_processing') > 1000) {
  // Record elapsed wall clock time.
  $current_set['elapsed'] = round((microtime(TRUE) - $current_set['start']) * 1000, 2);
  break;
}

```

---
Tags: 7, files
---


title: Window Title vs Page Title

text:
# Question
Title: Window Title vs Page Title
Can the Window/Browser title be set separately from the page title (which is displayed in an `<h1>`)?

I'd like to be able to do this in the most direct way possible from code, not using extra modules or configurations (unless that is the best route).

For example, I often use `drupal_set_title()` on a page definition. I'd love to call a similar function right next to this to set a slightly different version as the window title.

# Answer
The title set with `drupal_set_title()` is both the page title, and the browser window title.
If you are looking for a module that can change tHE window title, you can look at Page Title.

If you want to be able to do it from A CUSTOM module, you can implement `hook_preprocess_page(&$variables)` to modify the content of `$variables['head_title']`, which contains a modified version of the page title to use in the `<title>` tag.

```
function mymodule_preprocess_page(&$variables) {
  $variables['head_title'] = t("The new HTML title.");
}

```
> 6 votes

# Answer
You may want to checkout the Page Title project http://drupal.org/project/page\_title

Allows you to customize the page title on a per content or per node basis.

Some details from the module's project page:

> The word "title" is a bit overloaded. Every piece of content in Drupal has a title, and so does every page. The page title is the one found in the HTML head inside the tag. It is also used on SERPs (Search Engine Result Pages) and can greatly enhance your websites SEO (Search Engine Optimization).
>
> This module gives you granular control over the page title. You can specify patterns for how the title should be structured and, on content creation pages, specify the page title separately to the content's title.
> 3 votes

---
Tags: 7
---


# Question
Title: How to do a date countdown (to a future date)?
How would one go about doing a date countdown (something like this: https://www.mupromo.com/?kbid=4722). I know I'd need to create a block...and I have boilerplate code for that, but I was wondering whether there's a module that already does something similar...or any other pointers you can give.

# Answer
> 3 votes
The Countdown module has a drupal 6 & 7 version. This may work for you. Here is a quote about it (from the module's project page):

> Adds a block titled "Countdown" to count the days, hours, minutes, and seconds since or until a specified event. Can configure to just show days, or days and hours, etc.
>
> See also:

# Answer
> 2 votes
You might want to try the Javascript Timer module or the jQuery Countdown module. With either of these, you can add some code to the block to create your countdown.

Javascript Timer has a Drupal 7 version, but jQuery Countdown currently does not.

---
Tags: datetime
---


title: How should I use a field in views?

text:
# Question
Title: How should I use a field in views?
I have a CCK field that I want to use in a view. How can I do it?

# Answer
When you are in edit mode of your view:

1. you should have an option of adding fields
2. When you click on add field, you should see a drop down of all types of field available.
3. Choose Content from the drop down.
4. You should be able to see your cck field there, click add and review the settings for the display of the field.

I suggest you checkout this video to get overview of views - http://mustardseedmedia.com/podcast/episode9
> 6 votes

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


# Question
Title: How to set URL alias automatically for a content type WITHOUT using Pathauto? Which hook to implement?
Pathauto can do the job easily for all content types, but in my case I only have one content type URL that needs to be customized, and I would prefer to not install Pathauto and Token.

Can anyone advise me how to do?

# Answer
```
/**
 * Implements hook_node_insert()
 */
 function mymodule_node_insert($node) {
   if ($node->type == 'mytype') {
     $node->path['alias'] = 'mytype/' . $node->nid;
   }
 }

```

Additionally, you may add this code to hook\_node\_update()
> 12 votes

# Answer
See p. 149 of Pro Drupal Development, use hook\_insert(). When a new node is saved, hook\_insert() is called. This is the place to handle any custom processing of the node's content before the node is saved. Also look at p. 152-156 Pro Drupal Development which talks about all of the different hook\_node\_xxxx() functions.

I think using hook\_node\_insert() as suggested in the previous answer will result in a hook into *ALL* node creations which will not address your need to alter a specific content type.
> 1 votes

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


# Question
Title: How can I obtain the "latest" vid when on Revisioning's "View latest" tab?
I am using the Revisioning module to handle content revisions and I am creating a custom block that needs the vid of the node that the user is viewing to generate the appropriate content. I was trying to use menu\_get\_object() to obtain this and it works fine for a node with no revisions.

When I have a pending revision in Draft that I am looking at via the "View latest" tab, the node-\>vid I obtain from menu\_get\_object() is the vid of the "current" version, not the "latest". What would be the best way for me to obtain the vid of the version that is actually being displayed to the user?

# Answer
> 3 votes
I dug into the Revisioning module to see how they are doing the check and adapted it for use in a helper function in my module. I first load the node using `menu_get_object()` and then call the following:

```
function _get_correct_revision($node) {
  if (module_exists('revisioning')) {
    if (_revisioning_load_op($node, 'view') == REVISIONING_LOAD_LATEST) {
      $vid_to_load = revisioning_get_latest_revision_id($node->nid);
      $node = node_load($node->nid, $vid_to_load);
    }
  }
  return $node->vid;
}

```

# Answer
> 1 votes
The project page for revisioning says that node\_load will offer some extra attributes related to revisions and I think you are looking for:

```
$node->is_pending;

```

---
Tags: 7, nodes
---


title: Image field theming

text:
# Question
Title: Image field theming
In Drupal 6 Views, there was an option to display the path of that file for an image type field, which is not present in Drupal 7.
Where is it?

# Answer
> 5 votes
In Drupal7 the output is handled by the formatter. If you have a formatter which allows to output the filepath it will be used.

In core there is none so the Custom Formatters module will help you. Some more details about this module (from its project page):

> The Custom Formatters module allows users to easily create custom Field Formatters without the need to write a custom module. Custom Formatters can then be exported as CTools Exportables, Features or Drupal API Field Formatters.

---
Tags: views, entities
---


# Question
Title: Where can I find the save destination path for a filefield? (via code)
I have an image file field and I am attempting to write a little script that will programmatically scan my nodes and save images found in the body of my node into an image file field entitled `field_post_image`

I've been looking at the default process of what Drupal 7 + Image Field does and the example on SO found here: https://stackoverflow.com/questions/5129559/attaching-files-to-nodes-programmatically-in-drupal-7

I figured the best practice would be to save the images to the same folder as the file field destination in an effort to keep my /sites/default/files clean of orphaned files etc.

I've looked at both field\_info\_field and field\_info\_instance in the Field Info API and I can't seem to find the files destination (as configured in the Field UI)

Am I missing something and/or am I looking in the wrong place?

Thanks!

# Answer
It's part of the instance settings of the file field, but it supports tokens. You want to call file\_field\_widget\_uri($field, $instance), that will give you a URI you can use to save the file.
> 1 votes

---
Tags: 7, entities, files
---


# Question
Title: How to structure theme folder to make it more manageable?
So far, I've been able to put page, node, field and block templates in their own separate folders. My idea is that Drupal needs to find the main original tpl file (ie page.tpl.php) in a folder and will then look for the overriding files in that directory. If so, how do I structure a similar thing for my Views templates? Do I create a few folders and put the original files (view-fields.tpl.php etc) in each respective folder?

I'll try my own suggestion and will post back if it works, so that others can benefit from it.

# Answer
> 11 votes
I typically put all TPL's in a templates folder, further subdivided by categories such as views, node, page, etc.

Here's an example folder structure from one of my recent projects:

```
themename
- fonts
- images
- scripts
- styles
- templates
-- node
-- page
-- user
-- views

```

Basically, the only thing that goes into the root folder is the .info file, and the template.php file. Everything else is subdivided by category.

# Answer
> 1 votes
I put all my Views template files in the same folder. However you can separate them if you want. Your approach will work. Principle: if you override a template, you must override the base file, too, and put them in the same folder.

# Answer
> 1 votes
Drupal will search everything under your theme's root (the folder with the .info and template.php file) folder. Therefore your folder structure can be whatever you like, drupal will simply recursively scan your theme folder until it finds the template file its looking for. The Zen theme and its sub-themes have a nice folder structure as a starting point.

I would suggest:

```
themename
-fonts
-images
-js
-templates
-css
themename.info
templates.php

```

It comes down to personal preference in the end, as long as its structured and another theme developer could step in and find things its all good!

---
Tags: theming
---