# Question
Title: Switching file system from private to public makes all inline image paths broken
I built a site with private file system initially, but now want to switch to public so that I can use performance enhancements like css and js minification as they are not available for private file systems.

The problem is that switching to public changes the file path and breaks all the inline image paths. Any ideas how to do this properly?

Just as an example, with private file system paths show as mysite.com/system/files/myfile.jpg this is what was stored by the body field for inline images. These change to mysite.com/sites/default..../myfile.jpg

# Answer
There's no miracle for that, you've to replace all path in the database. Fortunately MySQL has a replace function that will be useful for you.

First, you've to find every table/field that can contain inline image, if you're using Drupal 6, you'll look at `node` and `node_revision` for Drupal 7 it's more something like `field_data_body` and `field_revision_body`.

And finally you have to apply this query (for Drupal 7)

```
UPDATE field_data_body SET body_value = REPLACE(body_value, 'system/files/', 'files/');

```

Perhaps you should customize a query a little, but the main idea is there.
> 3 votes

---
Tags: media, files
---


# Question
Title: Attaching additional queries to webforms
I'd like to limit the ability of a form submission based on whether a user has submitted the form already.

So basically if a user has submitted a form, they can not submit again. I've already created the form using webforms, I just need to figure out how to limit the submissions now.

# Answer
Webform has already this option, that you can find in the Submission settings. Otherwise, if you need to check something more you still can use some Webform hooks.

But if you need more complex submission checking, the best way from my point of view is to add a `validate` callback with the help of hook\_form\_alter().

**Edit**

Here is an example how to use the hook\_form\_alter(); For it, you must install the module Devel before.

```
// First you have to create your module
// you will find more information about it
// here http://drupal.org/node/231276
function mymodule_form_alter(&$form, &$form_state, $form_id) {
  // To add your validate callback to any form, you must find
  // the right form_id before
  // the form_id is an id that identify the form
  // from all that drupal can generate.
  // My solution to find it quickly its to show
  // all form_id with the help of Devel
  dsm($form, $form_id);
  // This will show you a drupal_set_message with something like that
  // form_id_form => Array()…
  // When you found the form that you want add the validate callback you
  // change it like that
  if($form_id == 'the_form_id') {
    $form['#validate'][] = 'mymodule_myvalidate';
  }
}

function mymodule_myvalidate(&$form, &$form_state) {
  // Here you can see want you receive
  // by checking the content of $form_state
  // still with Devel, like that
  dsm($form_state);

  // You should see the values in $form_state['values']
  // After you can make your additional checks and retur errors like that
  if($error) {
    form_set_error('field_error', t("You can balbla"));
    return;
  }
}

```
> 1 votes

---
Tags: 6, webforms
---


# Question
Title: How to use Drupal to encapsule an external site
This is the scenario: I have a Drupal 6 site, and another website that doesn't use Drupal. This 'other site' is in the same server, and the same hosting account. I need Drupal to be over the other website with his theme, regions, blocks and sessions/roles/authentication. The other website must conserve its own system of session, authentication, content and their URLs (but like already said, the theme, blocks, regions, authentication, must come from Drupal).

**Update**: **iframe** is not an alternative (SEO issues).

**Update**: This guide Integrating third party applications seems useful, but certainly I do not know how to implement it.

# Answer
If you've, at least, any control on the second web site you can do it with dynamic includes. It works not so bad with the help of an own module.

The idea its to create a module that do a `file_get_content()` and return it to Drupal that gonna show the content.

But, for it your second web site should have relative paths between his pages, or you will make the change with a regex.

There an example module, no tested.

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

  $items['inc/%'] = array(
    'title' => t("Include"),
    'page callback' => 'mymodule_include',
    'page arguments' => array(1)
  );

  return $items;
}

function mymodule_include($path) {
  $http = 'http://example.com/';
  // Maybe check if the page is available
  // better to use drupal_http_request for that
  $content = file_get_contents($http . $path);

  // Perform any change in the content before to
  // send it for render.
  return $content;
}

```
> 2 votes

---
Tags: 6
---


# Question
Title: Create map that show user Location and last user's post
I don't know my question is cheap or good !:(

I want to create a map that shows on users location and last post like Azadnegar's map or Drupal.org front page. I know I should use openLayers, CCK, views but I can't build as well as Azadnegar! I want to know how create map like its map, I mean how can I config our modules. in this site get user location in registration form in list box,how create like it?

what map her use?How create views?or ...

please explain whit detail !

# Answer
> 2 votes
Once I had to do the very same thing and followed this good video by Drupal Therapy. It uses GMap (API 2) + Location modules instead of Open Layers, but if you're on D6 this is still a good solution. If you enable user-locations and node-locations functionalities in the modules page, you'll find predefined Gmap user/nodes location views. If you need to associate geographic information only on certain content types (and not to all nodes), you'd better enable location-CCK and just add and configure a location field to your desired content type, then create your Gmap view.

Hope it helps you to start with maps in Drupal.

---
Tags: views, 6, entities, location, javascript
---


title: Flag module views integration

text:
# Question
Title: Flag module views integration
Following an excellent suggestion, I added the Flag module to a website in order to allow users to store their favorite stories in a dedicated page. This seems to be working really nicely, but how do I now add the option to flag content as a field in a view?

# Answer
If you want to display a list of content a user has flagged - You want build your view as you would any other. Then you add a relationship to the view for the flag you wish to display.

If you wish to allow your user to simply add a flag directly from the view results, you would add a field to the view of the type "Flags: Flag Link". This will add the add/remove flag link to each result in your view.
> 7 votes

---
Tags: views, entities, 6, flags
---


# Question
Title: Taxonomy and Views - Creating a view based off of user selection
Been working with Drupal for a few weeks, and I have a question:

I have a large amount of content for content type X. I have built a view that returns certain fields from X nodes. Is there a way to build a user interface that will allow users to see all taxonomy tags for X and select a tag and then use that tag as a filter for the view?

For example, a user wants to see all results that are tagged "SEO." They will then see the views results for all nodes tagged with "SEO."

# Answer
> 0 votes
There are a few ways to accomplish this; i'll offer up my easy answer.

You can show all of the nodes associated with a taxonomy tag by adding the "Taxonomy: Term" filter (select the taxonomy term ID filter). Select your relevant vocabulary, and then select 'dropdown' for your Selection Type.

Click 'Expose' to show a dropdown box to your users. When a user selects a tag from your dropdown, your results will be filtered according on the Operator you have chosen.

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


title: Exposing archive view

text:
# Question
Title: Exposing archive view
I'm using an archive view which is in Views by default but just needs to be activated. It works great and is displaying the way I want it to, but I was wondering if there was an easy way for me to expose the view so I can allow users to filter content by month or within a month range (eg. from Janauary 2011 to May 2011)...?

# Answer
> 1 votes
You need a Date filter. If you have the Date module enabled, you can activate the Date Popup widget to allow users to easily select dates. (The popup may only work on the Page display, e.g. http://yoursite.com/archive)

Choose the 'Date: Date (node)' filter. Set the Operator to 'Is Between' and set the value type to 'An offset from the current time'. Using your example, you can use '-4 months' for the Min value and 'now' for the Max value.

Finally, click 'Expose' to show the date filter to your users.

---
Tags: 6, views
---


# Question
Title: Views 2 - Don't display results if user DOES NOT have a specific permission
I am trying to hide the results of a view from users who **have** a specific permission. For instance, Let's assume that a user has the permission "create page content". I would like for the view to show NO results to this user.

I can't restrict on roles because the user can have overlapping roles. Basically, I need the "Access" portion of views to work opposite of how it normally does.

I suspect I should be able to do this with the Global:Null argument validator, but I am having no luck. However I am assuming that has more to do with me weak php chops.

Thanks in advance.

# Answer
Hook\_perm to the rescue! I would suggest thinking the other way around: Grant access to the view's results if the user HAS a permission. Create a new permission and assign it only to the roles that may view the results.

In your custom module, add a new permission like so:

```
function mymodule_perm() {
    return array('can view results of my view');
}

```

Then in your view, change the 'Access' setting to your new permission.

You may run into problems if the roles that you're trying to exclude have the 'Access all views' permission (or a similar administrative views permission). If that is the case, you'll need to use a views hook to remove the results.

```
function mymodule_views_pre_render(&$view) {
  switch($view->name) {
    case 'the_view_name':
      if(!user_access('can view results of my view')) {
        $view->result = array();
      }
    break;
  }
}

```

I would flush caches in order to have this hook picked up by views.
> 1 votes

---
Tags: views, users
---


# Question
Title: How to remove unused tables in the database in Drupal 7
Is there an easy way to detect tables that are no longer used by my Drupal installation? I find it annoying that tables from previously used modules remain. I'll simply drop them using phpMyAdmin if not, but its a bit of a pain, and involves backing it up for obvious reasons! ;)

# Answer
I think Schema will tell you that. If a module leaves tables after uninstall, that's a bug, and you should open an issue.
> 5 votes

# Answer
After disabling and before removing the module run drush pm-uninstall 'modulename' in the terminal.(More info on drush)
Or through the website go to /admin/modules/uninstall.
The name of the module will still be found in the 'system' table, this can be deleted manually.
> 1 votes

---
Tags: database
---


# Question
Title: How do I enable modules in a Simpletest-Selenium test (Selenium module)?
I am using the Selenium module for Drupal, which is integrated with SimpleTest.

One thing I have not been able to do is to enable modules for the test cases. I am able to enable them on SimpleTest tests (using `setUp()`).

How do I enable modules in the Selenium Tests?

# Answer
It should work completely the same. You should be able to enable modules passing arguments to setUp().

Implementation of the setUp() method for DrupalSeleniumWebTestCase is

```
protected function setUp() {
  $modules = func_get_args();
  parent::setUp($modules);
  //...
}

```

So everything passed to it is passed to parent setUp method that should enable modules for you.
> 1 votes

---
Tags: 7, testing
---


# Question
Title: Drupal compress (gzip) files attached to pages. How to turn it off?
Drupal compress (with gzip) on the fly all files attached to pages during sending them to browser.
It takes too much time especially with PDF.

How to turn it off?

Drupal 6

edit:
Drupal do not compress pages on its own (option turned off), but apache does (output coming from php). And I want to stay it that way with exception of application/pdf (also output of php)

Is it possible?

edit2:
I couldn't change apache gzipping settings in .htaccess, but I was planning changing hosting. I've speeded it up a little and problem is gone now.

# Answer
The question here is one of Apache configuration, rather than Drupal.

I'd suggest checking out the Apache mod\_deflate documentation, which contains sample configurations to disable/enable compression in a variety of circumstances.
> 5 votes

---
Tags: performance, files
---


# Question
Title: creating a view showing nodes referenced from the currently selected node
I have a content type called shops and another called products. on creating a product content, one can type in the shops name, which is provided as an autocomplete node reference field. what i would like to achieve is to create a view showing products in a selected shop. how can i achieve this. I have tried to use reverse node reference module but its not working for me.

# Answer
> 0 votes
Reverse Node References is indead a good solution as it should provide what your are asking for. It's documentation describe how to use for that exact purpose: query children nodes referencing a parent node matching a filter.

Another solution is the Node Referrer module which will create a auto-populated fields on the parent content type with references to all the nodes referencing it. You can then build a view using this field to create a relationship to the children nodes.

---
Tags: views
---


# Question
Title: In drupal 7, How to override theme_pager?
I am using drupal 7 and zen theme. And am not able to override the theme\_pager using zen\_pager function in template.php. Any suggestion pls?

# Answer
> 12 votes
Implement all/selected of the following theme functions in your template.php:

changing 'theme' in each of these function names to short name of your theme.

# Answer
> 1 votes
If you are using Zen, you are probably writing a sub-theme. Inside its template.php you will have to prefix the `theme_pager` function with your sub-theme name, like `pretty_pager` if yout sub-theme is called "pretty".

Zen will clear the caches for you, but if it doesn't work, try clearing the caches manually. The Devel Themer module will help you check which theme function is being called.

---
Tags: theming, paging
---


# Question
Title: Elegant way to retrieve nodes by content type?
Of course I can do something like:

```
$results = db_query("SELECT * FROM {node} WHERE type = '%s'", $content_type);

while ($node = db_fetch_object($results)) {
    // ...
}

```

But is there a more elegant way maybe?

# Answer
Look at the node\_page\_default. You need just change condition in select query.
> 1 votes

# Answer
You can just use the Views module and add a filter on the content type.
> 2 votes

---
Tags: nodes, database
---


title: I need to pass a node id to a block

text:
# Question
Title: I need to pass a node id to a block
I am open to doing that with hook\_ module code (since i'm doing all my work in a custom module), and I'm open to doing that with Panels, which I'm using. I don't want to add PHP in the admin interface.

Thanks in advance.

# Answer
> 1 votes
Not quite a block, but you can do this with custom panel panes and pass it the `$node` being viewed. This is the cleanest way. I don't have a link handy for an overview on how to do this, though.

You can also do something similar using a view, and wiring up the relationships / arguments appropriately. You can then stick this view into a panel pane.

The hack is do do something like this in your block code

```
if (arg(0) == "node" && arg(2) != "edit") {
  $nid = (int) arg(1);
  if ($nid) {
    // do stuff
  }
}

```

---
Tags: 7, nodes, blocks
---


# Question
Title: How to update drupal 7.7 to 7.8 manually?
I found that there is a warning on my site saying that manual updates of Drupal core is required.

How can I do it safely?

# Answer
> 8 votes
See this article from the Drupal.org documentation under section "MINOR VERSION UPDATES".

> To update from one minor 7.x version of Drupal to any later 7.x version, after following the instructions in the Introduction section at the top of this file:
>
> 1. Log in as a user with the permission "Administer software updates".
> 2. Go to Administration \> Configuration \> Development \> Maintenance mode. Enable the "Put site into maintenance mode" checkbox and save the configuration.
> 3. Remove all old core files and directories, except for the 'sites' directory, the original install profile in the 'profiles' directory and any custom files you added elsewhere.
> 4. Download the latest Drupal 7.x release from http://drupal.org/project/drupal to a directory outside of your web root. Extract the archive and copy the files into your Drupal
> directory.
> 5. Re-apply any modifications to files such as .htaccess or robots.txt.
> 6. Run update.php by visiting http://www.example.com/update.php (replace www.example.com with your domain name). This will update the core database tables.
> 7. Go to Administration \> Reports \> Status report. Verify that everything is working as expected.
> 8. Ensure that $update\_free\_access is FALSE in settings.php.
> 9. Go to Administration \> Configuration \> Development \> Maintenance mode. Disable the "Put site into maintenance mode" checkbox and save the configuration.

# Answer
> 4 votes
In short :

1. Replace all the files with the 7.8-files (except the sites directory!) --\> this will take care of the file part
2. Run the update script (url/update.php). --\> this will take care of the database part

Since you haven't replaced the files-directory, all basic settings (settings.php) there should be ok.

That's the main principle in a minor update. Of course you always should take precautions like backups, and take care of all files outside the sites directory that might have changed.

For more info see : see http://drupal.org/node/1223018

---
Tags: 7, updating
---


# Question
Title: pass argument through url and use it in exposed filters in views
I have select box with taxonomy term ID's in it and when i change the term the respective content appears. This work well.

I am having the same term id's as click-able links on Left side block. I was thinking if i could pass a argument to a view from the URL and make the view content change as per the argument. Is it possible ?

# Answer
> 1 votes
Your're looking for "contextual filters". Add the Content: Has taxonomy term ID contextual filter. You can use taxonomy term names with this filter by adjusting Specify validation criteria settings.

Drupal 7 views contextual filters taxonomy name.

# Answer
> 1 votes
Yes, you can do this with two views two views.

Create the first view for the the block showing the term ids. It should be possible to change the links the way the second view expects them. May be you need some PHP do achiev this.

With the second view you expect the term id as a filter and show the appropriate information.

---
Tags: 7, views
---


title: Localisation of node published date

text:
# Question
Title: Localisation of node published date
I have a Drupal site and the standard language is Danish. However the date on the nodes is rendered in English. I can't figure out why.

If i put a date field in a content type it displays correctly following my custom date format.

Any suggestions on how to solve this?

# Answer
> 0 votes
Drupal provides a clean way of formatting dates any way you want throughout the entire site. Simply apply the settings that you're expecting for Danish:

Format dates in Drupal 6

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


# Question
Title: Why is INPUT field size different across platforms? OS X vs Windows?
I have a drupal created form where I have set the size of the form:

```
$form['myform']['#size'] = 22;

```

Now on my windows machine on Chrome / FF / IE / Safari it is a specific size, visually.

When I go to view the same form on my Macbook the same INPUT field is significantly smaller in Chrome / FF / Safari on OS X ??? Even though both obviously have the size = 22 setting?

Why is it not rendering the same size across all platforms??

# Answer
Size is the char amount that goes into the input field. If you want to style it, use CSS.

```
.inputbox{
  border: 1px solid #666;
  width: 210px;
  height: 30px;
  font-size: 1em;
}

```
> 1 votes

# Answer
There are differences in how the two platforms render content: THE WINDOWS/MAC FONT-SIZE PROBLEM. I'm afraid this is a long standing issue that many will say is the fault of Windows rather than the Mac due to how things are rendered on the two systems. If you're really keen on getting the best results in making your forms look consistent across browsers/platforms consider using css3: Design a Prettier Web Form with CSS 3.
> 0 votes

---
Tags: 7, forms, hooks, theming
---


# Question
Title: Adding a custom URL to the top of a view based on status of another field
Okay... so I have this crazy problem. Not really, but I can't figure out how to do it.

I have a view, that lists out a content type "request". When you click on the title, it links to that node (also displayed using a view).

So what I'm trying to do is this: When on a node whose content type is "request", I need to dynamically create a link that uses the title.

For example, if the Node is http://www.example.com/request/this%20is%20the%20title

Then I'd like a link to appear of this form: http://www.example.com/survey?request=this%20is%20the%20title

BUT ONLY if that node has a field\_type\_status of "closed"

Summary: Dynamically create a link using node's title using a view based on a field's status.

# Answer
Your question is actually several questions. I'd suggest that you break you problem down into smaller, more manageable questions otherwise the number of responses might be low.

For starters, a break down:

* "I need to dynamically create a link that uses the title" -\> Pathauto module.
* "I'd like a link to appear of this form": The format that the URLs appear in can be set in the Pathauto configuration settings for the node type.
* "BUT ONLY if that node has a field\_type\_status of "closed" -\> Hmmm, this might require some custom code. It's kind of a weird spec as it's considered good SEO to use Pathauto on all site content. Good luck with this one, perhaps someone else will help you with this one.
> 1 votes

---
Tags: views, 6
---


title: Expose views as JSON

text:
# Question
Title: Expose views as JSON
I'd like to expose data/views coming from 6.19 as json.

What I tried so far are the JsonRPC/REST service modules, but none of them worked for me.

# Answer
> 8 votes
Sounds that you need Views Datasource module:

> Views Datasource is a set of plugins for Drupal Views for rendering content in a number of shareable, reusable formats based on XML, JSON and XHTML.

---
Tags: views, 6
---


# Question
Title: How to get a week range as a Views filter - Thursday to Wednesday
I need to return nodes that have a date within a date range of Thursday to Wednesday. I have tried many different combinations, but none do the trick all the time.

The closest I can get is to set the Date From to: "Last Thursday" and the Date to, to: "Wednesday"

This works whenever the day isn't Thursday. As a demo: Today is Saturday 24th. The Filter would return everything from Thursday 22nd through to Wednesday 28th. Perfect! However on Thursday 22nd, it returns everything from Thursday 15th through to Wednesday 28th. A whole extra week of content I don't want!

Any ideas on how to combat this in Views?

# Answer
> 1 votes
I guess that `date` filter with `is between` option filter could be a possibility if you alter the query used by your View, using a custom php builded by you to calculate values (to use and send inside query) according the current day. see this article http://www.appnovation.com/using-hook-views-query-alter about how to use `query_alter` hook to alter the queries used by your view.

---
Tags: views, datetime
---


# Question
Title: Why am I urged to include my source files via files[] instead of using include_once?
What is the reason of using the .info file to declare the files used from the module, instead of including them at runtime?

# Answer
From Writing .info files (Drupal 7.x):

> Drupal now supports a dynamic-loading code registry. To support it, all modules must now declare any code files containing **class** or **interface** declarations in the .info file (...). When a module is enabled, Drupal will rescan all declared files and index all the classes and interfaces that it finds. **Classes will be loaded automatically by PHP when they are first accessed**.

So it only makes sense to add a file to the files\[\] array, if that file contains declarations of classes or interfaces and is not included manually (e.g. by calling module\_load\_include()).
> 5 votes

---
Tags: .info
---


# Question
Title: custom node template involving the use of quick tabs in drupal 7?
I have products that I want to display divided up into quick tabs. Originally I was thinking of using multiple views to do this, but then I realized that there has to be a way to do it using a node--product.tpl.php. the way they are divided up are as follows:

* One quick tab that has a basic image, title, and a little paragraph about the product.
* The second tab should have features of the product.
* The third should be a description of the product. the fourth should be files (images, and videos, and audio files, etc).
* And the last one is a tab for technicians of the product.

I want it so that I only have to use one CCK to do this, and it would be the content it's self, instead of multiple views put togeather in quick tabs. here is the kind of thing that I am looking for:

## 1. Product Tab:

>

---

## 2. Features Tab

> ---

**is this possible to do in a node--product.tpl.php?**

# Answer
Go forth and tabbify with Quicktabs 3.0 for Drupal 7 gives some good examples of how to add custom content to quicktabs.
> 4 votes

---
Tags: 7, theming, nodes, routes, blocks
---


# Question
Title: Have a profile field item from user registration show on a users page
I have created a new checkbox field through the core module 'profiles' called Billing Terms. It is visible on the user registration form.

I'd simply like an asterisk `*` next to the users name on their profile page if the Billing Terms checkbox is ticked. Actually it doesn't have to be an `*` but rather anyway to signify that the Billing Terms checkbox was ticked.

Any help or helpful links would be greatly appreciated.

# Answer
One way you can do this is if you have a custom template in your theme for user profiles. Creating a custom user profile template

Basically, you can overwrite the entire layout of the user profile this way. And then, you can output profile fields however you like by simply printing them. For instance:

```
<?php print $account->CHECKBOX_FIELD_NAME; ?>

```

This will allow anyone visiting the profile to view the results.

If you wish to display this to only users of a specific role, you would want to wrap the above code in an *if* and check what the viewing users role it. For example, something like this

// Check to see if $user has the administrator role. if (in\_array('administrator', array\_values($user-\>roles))) { CHECKBOX\_FIELD\_NAME; ?\> } ?\>
> 1 votes

---
Tags: users
---


# Question
Title: Comment author name = user name by default?
My website can only be accessed by authenticated users. How can I automatically make the author's name the user's name without giving users the option to input anything else in the name field?

# Answer
If you go to the permissions table, located at admin/user/permissions you will find a permission that allows you to disallow users from changing their own name it is called **change own username**

If you are manually creating users, this should work well for you because they will have the name you created for them and they will not be able to change it. However, if the users create their own accounts, one option for you to consider is the Real Name Module
> 1 votes

# Answer
Well, correct me if I'm wrong, but from what I know (and based on a check I've just done in D6 sandbox) logged-in users do not have option to change their name, they see their username displayed in normal text instead of form textfield. So that's exactly the behavior you're looking for?
> 1 votes

---
Tags: 6, users, comments
---


# Question
Title: slideshow module where editor can upload images
I am looking for a JQuery slideshow module, where an editor can upload images from Drupal, without having to go into the code or through ftp. I imagine this module already exists.

# Answer
There are many options, but I am rather fond of Views Slideshow

It allows you to create a slideshow from a view. What is nice is this basically means the possibilities are endless. Plus, it allows your user to easily upload images, assuming of course you have created a content type they can use.
> 0 votes

---
Tags: 7
---


title: Add additional button to login form

text:
# Question
Title: Add additional button to login form
```
Drupal 7

```

I am trying to add a new button or link to my log in form. The button would simply link to another page outside of the drupal framework. I am looking at the `form_alter` hook but I am not sure if I completely understand how to implement my update.

do I have to update the template.php page?

The form is the login form on the front page. Any help would be great.

I am pretty sure I need something like the following :

```
<?php
$form['preview'] = array(
  '#type' => 'button',
  '#value' => t('Preview'),
  '#weight' => 19,
);
?>

```

But I need to add the link. request.php to the button so when clicked it will go to request.php. Also I am not sure where to add this code and how to direct it to my log in form.

# Answer
You cannot alter a form from a theme's template.php file. You need to create a custom module for that. In this module, you can alter the login form in an implementation of the `hook_form_alter()` or `hook_form_FORM_ID_alter()` hooks.

Without some JavaScript, you will not be able to submit the form to a separated URL. What you can do, in your module, is to provide an dedicated validation or submit handler for you button. In this handler, you can redirect to your external URL using `drupal_goto()`.

Something like:

```
MODULE_form_user_login_alter(&$form, &$form_state) {
  $form['foo'] = array(
    '#type' => 'button',
    '#value' => t('Foo'),
    '#submit' => array('MODULE_user_login_foo_submit'),
    '#limit_validation_errors' => array(),
  );
}

MODULE_user_login_foo_submit($form, &$form_state) {
  drupal_goto('/path/to/request.php', array('external' => TRUE));
}

```
> 8 votes

---
Tags: forms, hooks, users
---


# Question
Title: Highlight the argument passed in the exposed filters
I have a view page like http://localhost/drupal/myviews, which looks like in the following screenshot:

I pass arguments to this page using a URL like http://localhost/drupal/myviews/voc3; the page looks like in the following screenshot:

So all this works fine. When the argument is passed within the URL, can I highlight that argument in the exposed filter?

# Answer
I was able to create a solution for a regular Taxonomy: Term ID (no depth) filter, so this may not be applicable for you (the filter with depth was behaving erratically for me).

This code will set the dropdown element to the term provided in the argument, and will defer to the dropdown selection if one is chosen.

Add this to your custom module and then flush caches:

```
function mymodule_form_views_exposed_form_alter(&$form, &$form_state) {
  if($form_state['view']->name == 'name_of_view') {
    if(!isset($_GET['tid'])) {
      $arg = arg(1);
      if(isset($arg)) {
        $selected_value = array_search($arg, $form['tid']['#options']);
        if(isset($selected_value)) {
          $form_state['input']['tid'] = $selected_value;
        }
      }
    }
    else {
      $form_state['view']->args = array();
    }
  }
}

```

You can try changing every instance of 'tid' to 'term\_node\_tid\_depth' if you are going with a Taxonomy With Depth filter (use a dpm($form) to verify the filter name).
> 2 votes

---
Tags: 7, views
---


title: Undefined error for field image

text:
# Question
Title: Undefined error for field image
I am using a custom image field in one of my content types, which I am accessing using the following code.

```
if ($content['field_heading']) {
  print render($content['field_heading']);
}

```

Everything is fine, except that in administrative area I am seeing this error message:

> Notice: Undefined index: field\_heading in include() (line 4 of tridz7\sites\all\themes\tridz\node.tpl.php).

What could be the reason? Is there any workaround?

# Answer
Probably you have nodes where the "field\_heading" field has not been set, or you didn't enable the field in output tab on content type section.

Try this code:

```
if (!empty($content['field_heading'])) {
  print render($content['field_heading']);
}

```
> 4 votes

# Answer
Drupal errors "Notice: Undefined index: profile in...".

Basically the particular above notice is created when PHP tries to access the index of an array, where the variable is not holding an array. Check that 'field\_heading' has a value assigned to it in the `$content` array.

If this is your development server, you'll also want to disable displaying warnings. The link above also details how you can do this at the PHP/server level; you can also disable the error reporting to the screen on a production site in Drupal.
> 1 votes

---
Tags: 7, media
---


# Question
Title: Warning: Cannot use a scalar value as an array
```
function theme_test($form) {

  $output = '';

  foreach($form['field'] as $key => $val){

    $output .= '<div class="test">';
    $output .= drupal_render($val['uid'. $key]);
    $output .= '</div>';
    unset($key,$val);
  }

  return $output;

}

```

When I run this code, I get the following warning message:

> Warning: Cannot use a scalar value as an array in theme\_test()

How do I resolve this, and what is the reason behind this warning?

# Answer
> 1 votes
There's somehting funky happening on this line:

```
$output .= drupal_render($val['uid'. $key]);

```

$val is not an array, you'll need to rethink your PHP code. Do a Google search for "Warning: Cannot use a scalar value as an array" and you'll see a bunch of cases where other users are dealing with the same issue. As an example:

PHP : Cannot use a scalar value as an array

EDIT:

Looking at your code again, this line looks suspect:

```
unset($key,$val);

```

You're in a loop that is using these values. Applying an unset could result in the issue in addition to the point I made above.

---
Tags: theming
---


title: Wrapping a field value with <p>

text:
# Question
Title: Wrapping a field value with <p>
I am using the Drupal 7's Bartik theme.

It wraps with `<p>` the content-type fields that are set as "long text," but not the fields that are set as "text."

Where do I change this so that it wraps every field with `<p>`?

# Answer
> 0 votes
```
node--<content-type>.tpl.php

```

Check out the discussion for how to active template suggestions at the theme level: Drupal 7 page template suggestions.

---
Tags: theming
---


# Question
Title: Adding content to a page through a module
I just want to echo some words when a certain node comes up.

Currently however it doesn't echo within the content section, but above the header.

How do I get my module to echo the words at the top of the content section?

# Answer
If the content is always static then you can look into adding it to a theme template file (by creating a subtheme).

Or you could add some php as part of preprocess\_node in template.php to append/prepend the text to the content/body array.
> 1 votes

---
Tags: 6, nodes
---


title: Apply a filter to a view

text:
# Question
Title: Apply a filter to a view
I have some code:

```
 http://mysite.com/node/1/edit
 <?php echo "Hello World!"; ?>

```

I have a content that processes it:

```
 http://mysite.com/node/1
 Hello World!

```

I have a view that displays the code based on context:

```
http://mysite.com/node/1/code
[[php]]<?php echo "Hello World!"; ?>[[/php]]

```

How do I apply Syntax Highlighter or Geshi to the output of a view to get it looking pretty?

# Answer
> 1 votes
what if you try to call directly the Syntax Highlighter or Geshi libraries to be readed from view templates? here is an example of Geshi (http://qbnz.com/highlighter/geshi-doc.html#basic-usage) and here another with Syntax Highlighter (http://alexgorbatchev.com/SyntaxHighlighter/manual/demo/) Is only a suggestion (not tried).

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


# Question
Title: custom module page -- i need it to use a predefined panels page layout
I've got this:

```
function foo_menu() {
    $items = array();
    $items['facadmin/directory'] = array(
        'title' => 'Faculty & Staff Directory',
        'page callback' => 'foo_facstaff_directory',
        'access callback' => TRUE,
        'type' => MENU_CALLBACK,
    );
    return $items;
}

```

Which then does this:

```
function foo_facstaff_directory() {
    $content = foo-make-html();
    $page = array();
    $page['#markup'] = $content;
    return $page;
}

```

I'd like this page to use a predefined panels template, but when I set 'facadmin/directory' as a selection rule, it doesn't do the smart thing automatically and just dumps the html into the content region -- no panels.

Help?!?

# Answer
I made a custom block and put that into a standard layout instead.
> 1 votes

---
Tags: 7, panels
---


title: Cannot see a Custom Block in Drupal 7

text:
# Question
Title: Cannot see a Custom Block in Drupal 7
I'm trying to create some blocks with custom content in Drupal 7, but I cannot see them anywhere (Structure\>Blocks)

* I'm using Drupal 7
* I have **successfully activated the module**
* Cache is not activated

Here is the code:

**bcndevcon.info**

```
; $Id: bcndevcon.info,v 1.0.0.0 2011/02/09 10:11:15 BcnDevCon Exp $
name = "Custom BcnDevCon Modules"
description = "Custom BcnDevCon Modules In Code"
core = "7.x"
package = "Custom BcnDevCon Modules"

```

**bcndevcon.module**

```
<?php

function bcndevcon_blocks_info() {
    $blocks['my_custom_block'] = array(
        'info' => t('Custom Block Name'),
    );

    $blocks['my_custom_block2'] = array(
        'info' => t('Custom Block Name 2'),
    );

    return $blocks;
}

/**
 * Implementation of hook_block_view().
 */
function bcndevcon_blocks_view($delta='') {
  $block = array();
  switch ($delta) {
    case 'my_custom_block':
      $block['subject'] = t('Custom Block Name');
      $block['content'] = bcndevcon_contents();
      break;
  }
  return $block;
}

/**
 * custom html block
 * @return string
 */
function bcndevcon_contents() {
  return '
    </p><div class="body">
      Hello World, this is a example custom Block
    </div><p>
  ';
}

?>

```

Any suggestions?

# Answer
Not sure if this is a typo just in the question... but you have your hooks defined as `hook_blocks_*` with an extra `s` at the end of the word `block` which shouldn't be there.
> 1 votes

---
Tags: 7, blocks
---


# Question
Title: In the specific page.tpl.php adding an include file
I was recently asked to create a blank page without a header and footer. I implemented that following this comment. Now the issue is that the team for whom I've created it do not want the html, body tags either that show up in view source! They have directly included a php file in the specific page-simple.tpl.php . I know this is not the right approach. If someone could point out the issue doing it this way and another approach if possible. I'd really appreciate it.

Thanks.

# Answer
> 0 votes
Try create a custom module and use module\_load\_include() it might be a better approach than the standard PHP include() then include the custom php.

---
Tags: theming
---


# Question
Title: Is there an hook to modify programmatically the thumbnail shown from the video module?
I'm using the video module and i need to show a different thumbnail if the user who is watching the node is a guest or a logged on user (if the user is a guest i want to display a standard thumbnail). Is there an hook to do this?

# Answer
> 2 votes
you could just modify the template to show a different thumbnail for anonymous users. You can use the Theme Developer module to find the right template to modify.

---
Tags: 7, files
---


# Question
Title: Webform 6x 3.11 - custom code to determine value of webform field
I intend to pass a predetermined NodeID into a webform through URL querystring like so:

```
www.mysite.com/forms/my-form?nid=43

```

On the webform, one of the field values must be calculated by getting the Node Title based on what the *nid* is. I want to use a textfield, so that it can be one of the values submitted in the email. Can this be achieved?...because from what I see, the "default value" box only allows for a few tokens and no custom code. Furthermore I don't want to pass in the NodeTitle directly in the querystring for 2 reasons:

1. It will contain spaces and therefore will not be URL encoded, and
2. I want to avoid people tampering with the querysting

Here's hoping some drupal guru can come to my rescue! thanks in advance!

# Answer
> 3 votes
We had exactly the same issue when we were developing a custom job application online form, and we wanted to pass in the job details into the webform in question. How we solved it:

* Created (job application) webform node
* Created links to the webform node above in the form of /apply-online?n=17
* Created custom node-856.tpl.php (856 happened to be the node of the apply online webform) to
    + first validate the nid as a valid job
    + validate that the job is published
    + validate that the job had not closed
    + format the additional fields into the webform such as title, position etc etc
    + stop any URL tampering
* Created a custom webform validation hook to ensure that only published nodes of type 'job' were allowed to ever be submitted (to stop any form tampering)

Sample code for the validation hook:

```
/**
 *  Implementation of hook_form_alter()
 *  This function is used to add an extra validation function to the apply online webform
 */
function site_profile_form_webform_client_form_856_alter(&$form, &$form_state)  {
  $form['#validate'][] = 'site_profile_validate';
}

/*
 *  Implementation of hook_validate()
 *  Doesn't exactly validate the webform as that's done in another validation function
 *  This takes the nid from the job_url field and turns it into a url.
 */
function site_profile_validate($form, &$form_state) {
  global $base_url;

  $nid = $form_state['values']['submitted']['job_url'];
  $node = node_load($nid);
  $job_url = $base_url . url('node/' . $nid);
  $form_state['values']['submitted']['job_url'] = $job_url;

  //need this to stop the form losing the nid argument in the url
  if (empty($form_state['values']['submitted']['cv']['_fid']) || empty($form_state['values']['submitted']['cover_letter']['_fid']) || empty($form_state['values']['submitted']['completed_application_form']['_fid'])) {
    drupal_goto('apply-online', array('n' => $nid));
  }
}

```

Sample code for the node-856.tpl.php:

```
  // job's apply online node ID = 856, this template was made to theme this
  // particular page

  $job_nid = $_GET['n'];
  if (!is_numeric($job_nid)) {
   drupal_access_denied();
   exit;
  }
  $job_node = node_load($job_nid);
  if ($job_node->type != 'job') {
    drupal_access_denied();
    exit;
  }
<div id="node-<?php print $node->nid; ?>" class="node<?php if (!$status) { print ' node-unpublished'; } ?>">

  <h4><?php print t('Job Title'); ?></h4>
  <p><?php print $job_node->title; ?></p>
  <h4><?php print t('Vacancy Number'); ?></h4>
  <p><?php print $job_node->field_number[0]['value']; ?></p>
  <h4><?php print t('Closing Date'); ?></h4>
  <p><?php print $closing_date; ?></p>
  <h4><?php print t('Job Summary'); ?></h4>
  <p><?php print $job_node->teaser; ?></p>

```

Hope this helps

# Answer
> 1 votes
Here is a short howto I wrote on getting custom code to run with Webform. It details writing a custom module, copying the Webform template to match the nodeID, and adding custom javascript/jquery for form processing.

http://docs.quantact.com/drupal-webform-custom-php-code

---
Tags: 6, webforms
---


# Question
Title: How do I load templates within templates?
Ok so I am writing a custom module and am trying to undestand how Drupal manages theming output.

I have registered my theme function, ie

```
mymodule_theme() {
    return array(
        'mylist' => 'templates/mylist-template',
        'arguments' => array('data'=>NULL)
    );
}

```

The mylist-template contains a HTML table with a heading row, such as:

```
<table>
    <tr>
        <td>ID</td>
        <td>Name</td>
    </tr>
    <?php print $rows; ?>
</table>

```

As you can see here I want to output x number of rows using another template file such as list-rows.tpl.php, ie:

```
<tr>
    <td>1</td>
    <td>My Name</td>
</tr>

```

How do I achieve this? At the moment I have a menu item with my table function, let's say:

```
 function mymodule_table() {
     $output = theme('list','');
     return $output;
 }

```

This works fine but im not sure how I would implement my rows

# Answer
You need to (properly) define two theme hooks. One for your table, and the second for your rows. Then, in the preprocess function for your table, you can call the row template for each row in your data array, something like:

```
function MODULE_theme() {
  return array(
    'mylist' => array('arguments' => array('data' => array())),
    'mylist_row' => array('arguments' => array('id' => NULL, 'name' => NULL)),
  );
}

function MODULE_preprocess_mylist(&$variables) {
  $rows = array();
  foreach ($variables['data'] as $item) {
    $rows[] = theme('mylist_row', $item['id'], $item['name']);
  }
}

```

If you want to display a nice and themed table, you don't need to implement your own theme hooks using templates, the table theme hook provided by core should be fine. It is a complete and flexible solution for most table output needs.

```
function MODULE_table() {
  $header = array(t('ID'), t('Name'));
  $rows = array(
    array(1, 'foo'),
    array(2, 'bar'),
    array(3, 'foobar'),
  );
  return theme('table', $header, $rows),
}

```
> 3 votes

---
Tags: theming, 6
---


title: Strict Grid system

text:
# Question
Title: Strict Grid system
I need to setup data in a grid system. The grid itself will be 10\*10 and each position in the grid should only contain a single node. I am guessing I will be using VIEWS to great effect to output the grid. But, I still have the following issue:

So, my thoughts are to create a custom content type called 'ITEM'. **Each time an ITEM is created, I need a way to position it within the grid. For instance, if the first ITEM is to be positioned in \[ROW:1, COLUMN:1\], how can I (i)represent that as part of the node data and (ii)enforce it so that if another user tries to place a second ITEM in the same position, it will not be allowed.**

# Answer
> 2 votes
My first approach would be to use Nodequeue and create a view for each row. Or, use Nodequeue with a tableless grid using the Advomatic tutorial.

---
Tags: theming
---


# Question
Title: Using to user_profile_form being used on a page thats not /user/#/edit
I've found the post How to display one of Drupal's default forms which talks specifically about this issue. however I wanted to post comments on it to get more info, It didn't seem to let me. Mabey I missed a button somewhere.

Anyway, I have section of my Drupal 7 site for all account and user stuff. /my/ This is a portal so to speak, /my/account is a menu handler that originally called `drupal_get_form('user_profile_form', $user);` Everything works, except when trying to upload, My profile is customised with a field to upload a file and field to upload an image.

Neither field works, it just returns errors. after the ajax kicks in.

Using the method found in the above linked post my entire form refuses to save and gives me validation errors. Thew above link mentions that custom callbacks and/or validators may have to be added due to referencing issue so i was hoping that someone could point me in the direction of what those custom things are.

Thanks.

# Answer
> 3 votes
You're likely using `module_load_include()` to include modules/user/user.pages.inc.

However, you need to use form\_load\_include() whenever you attempt to load, build, process, and render a form that is defined and constructed in an entirely different include file.

`form_load_include()` requires to pass the `$form_state` in order to record the file to include (and automatically load it later, if needed). This needs to happen before the form structure is cached (which happens directly after invoking the constructor).

In order to do that, you can resemble what drupal\_get\_form() does, and inject the needed `form_load_include()` prior to building the form, like this:

```
$form_id = 'user_profile_form';
$form_state = array();
$form_state['build_info']['args'] = array($user);

// Load user.pages.inc and ensure it is automatically reloaded if
// this form is rebuilt via AJAX or other means.
form_load_include($form_state, 'inc', 'user', 'user.pages');

$form = drupal_build_form($form_id, $form_state);

```

More details:

Normally, Form API automatically takes over the include file to load (if any) from the menu router item definition in `hook_menu()`.

In your case, your custom `'my/account'` menu router item is not directly related to `user.module`, nor `user.pages.inc`, so the system does not know that this include file is required to build the form, especially when the form is submitted and rebuilt via AJAX — which happens on yet another system path/menu router item, namely `'system/ajax'` (which, by default, would only know about an include file of your `'my/account'` menu router item, if any).

In turn, Form API gets a request to rebuild `user_profile_form`, but the form constructor function user\_profile\_form() is not defined, because `user.pages.inc` was not loaded, since the cached $form\_state does not contain a pointer that the file needs to be loaded.

---
Tags: users, forms
---


title: how to style navigation sub-menu?

text:
# Question
Title: how to style navigation sub-menu?
I need to display dash (-) in front of each sub-menu element. For example, the output should be

```
<ul class="menu clearfix">
  <li class="first leaf"><a title="" href="/">Home</a></li>
  <li class="expanded active-trail"><a class="active-trail active" title="" href="/about-us">About</a>
  <ul class="menu clearfix">
     <li class="first leaf"><a title="" href="/process">- Process</a></li>
     <li class="leaf"><a title="" href="/process-101">- Process 101</a></li>
     <li class="last leaf"><a title="" href="/compnay">- Compnay</a></li>
  </ul></li>
  <li class="last leaf"><a href="/content/useful-links">Useful Links</a></li>
 </ul>

```

I tried the following:

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

  if ($element['#below']) {
     $sub_menu = drupal_render($element['#below']);
   }

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

```

# Answer
> 0 votes
You can do this with CSS

```
ul.menu ul.menu li a:before {
  content: "- ";
}

```

Or, you can do something similar with `list-style-image` or a `background-image`.

Keeping stuff like that out of markup makes things cleaner.

---
Tags: theming, routes, navigation
---


# Question
Title: Update node multi value field programatically
I am trying to update a node with a standard multi value text field programatically with the following:

```
$node = customfunctionreturnsnode();
$node->field_scores['und'][$dayof]['value'] = $total;
node_save($node);

```

More info: `$dayof` is a custom variable, that can be from 1 - 28. `$total` is numerical value that is determined elsewhere in the code.

Eventually the field will have 28 values, but they might not get entered in the 'correct' order. So I would like to be able to have my code above select which delta to add it to. Also, the values could get updated, so this will allow me to update the correct value.

It seems to work, and the db shows the right delta. But when I add a new value the previous delta resets to 0. The new delta has the correct value, but when I add another one the second value's delta goes to 1... and so on.

I checked, and the delta field is not an auto-increment table... but I'm not really sure where to look from here. I couldn't find anyone else that has this issue. Am I doing something wrong?

Thank you for you time.

# Answer
I think I found a solution. I used hook\_node\_presave to check if a value was set, ad if not to set it to -1 for the 28 fields I have. Maybe not the most elegant (I would love to hear if there is a more drupally way to do this) but it works.

```
function mymodule_node_presave($node) {
if ($node->type == 'mynodetype') {
for ($i = 0; $i < 29; $i++) {
if (!isset($node->field_scores_a['und'][$i]['value'])) {
 $node->field_scores_a['und'][$i]['value'] = -1;
}
if (!isset($node->field_scores_b['und'][$i]['value'])) {
 $node->field_scores_b['und'][$i]['value'] = -1;
}
if (!isset($node->field_scores_c['und'][$i]['value'])) {
  $node->field_scores_c['und'][$i]['value'] = -1;
}
}
}
}

```
> 3 votes

---
Tags: 7, entities
---


# Question
Title: How to edit fields' values in the hook_node_load function?
In the `hook_node_load` function I want to alter a field's value. I printed the node variable and got the following structure for the field:

```

    [field_myfield] => Array
        (
            [und] => Array
                (
                    [0] => Array
                        (
                            [value] => 1316760775
                        )

                )

        )

```

So I should write something like `$node->field_myfield[und][0]['value'] = 'sth'`. My site has 2 available languages, and \[und\] will be changed when language is changed. How can I alter the field value for all languages?

# Answer
> 1 votes
The $node object will have its language in a language variable. So, create another variable to work with like `$lang = $node->language;`; then you can write `$node->field_myfield[$lang][0]['value'] = 'sth';`, where the language will be dynamic with the $node object.

# Answer
> 2 votes
I'd go with entity\_metadata\_wrapper(), see this blog post for more info on that.

```
$node = node_load(323);
$wrapper = entity_metadata_wrapper('node', $node);
$wrapper->title = 'New title for the node';
$wrapper->save();

```

It works for any property: title, fields, author, etc.

---
Tags: 7, hooks, nodes
---


# Question
Title: Edit node link in view redirects to false URL
I have a view with a list of nodes and their associated edit links. The nodes can be categorised/filtered so I use an argument\* in the view that I set manually on the content template of the pages to display the view (different pages should show different sets) -- there is no correlation between this argument and the path to the pages containing the view. This works fine except that every edit link in the view redirects to a path that is a combination of the page's internal path and some string identifier that depends on the page being shown but isn't the page's title. On node/6 the link looks like `edit?destination=nodeIdentifierF6`. I've confirmed the number at the end corresponds to the node's ID and it is always preceeded by a capital F. My guess is that `Identifier` is really meant to be `%` and that Views substitutes some argument I'm not sure where comes from.

Is there a way to fix this, or a different approach altogether (e.g. using filters in a way that allows me to control the node sets dynamically), short of creating a whole template for this minor annoyance?

*Actually there are two arguments plus the three from the Views Or module, but I'm assuming it doesn't consume arguments, and the other argument has a default value and shouldn't be used. Using filters would be more appropriate, as users shouldn't have control over what set of nodes to display anyway, but I couldn't find a way to adjust filters dynamically, and the alternative seems to be to create n idental views but for this filter. I am mentioning this in case it's important.

**22/9 Update:** This appears to be related to `drupal_get_destination()`, which returns an encoded path (`/` =\> `%2F`). For the view in question the `%2` part must then be interpreted as an argument placeholder and substituted. I am no closer to a solution to the problem, unfortunately.

# Answer
> 0 votes
I ended up including the node ID and generating the edit link myself, with the catch that I can't hide the field for underprivileged users because it can never be empty (just prints an empty string in that case). It's an acceptable solution but I'd prefer to se the built-in method.

---
Tags: views, 6
---


# Question
Title: How do I hide/remove a views menu tab from some pages?
I created a page view with Page Settings for the path being equal to: node/%/content/recentnews

I also set the Page Settings menu to have a menu tab.

How does that system decide what pages will display the menu tab?

I have one page where the menu tab is displayed, but I don't want it to be shown on that page. Is there some way to remove/hide it?

Thanks, Greg

# Answer
There are two factors to consider when determining whether the tab is displayed:

* The parent menu item
* The result of the access callback

You probably cannot do much about the parent menu item, because this points to the generic `node/%node`.

You can, however, influence the result of the access callback by configuring how to validate the argument. This allows you for example to display the tab only for nodes of a certain content type. Of course you will have to configure the view to hide the view/display 404 if the argument does not validate.

A fancier validation would be possible if the validation configuration dialog would allow you to enter PHP code. I don't know if this is the case, so you might have to look for a different solution.
> 1 votes

---
Tags: views
---


# Question
Title: How to add field classes from within template_preprocess_node
During `template_preprocess_node` I would like to be able to dynamically add classes to specific field wrappers.

Is this possible or does `template_preprocess_node` run after `template_preprocess_field`? I would much prefer to use `template_preprocess_node` if possible as the class relies on other fields.

I've tried adding:

```
$vars['content']['field_name']['classes']
$vars['content']['field_name']['classes_array']

```

but neither seem to take effect.

Were I to do the same within `template_preprocess_field` then I apparently would add classes to `$classes_array` which would automatically flatten into `$classes`, however these values don't appear to be available, or at least provided, to `template_preprocess_node`?

EDIT:

After investigation, it seems `template_preprocess_node` does run first, however it doesn't seem to have access to `$classes_array` as it appears in `template_preprocess_field`.

# Answer
> 3 votes
Ok my somewhat dirty solution was to pass a classes array from `template_preprocess_node` to `template_preprocess_field`:

```
function template_preprocess_node(&$vars){
  if(!isset($vars['content']['field_name']['classes_array'])){
    $vars['content']['field_name']['classes_array'] = array();
  }
  $vars['content']['field_name']['classes_array'][] = 'custom-class';
}

function template_preprocess_field(&$vars){
  if(isset($vars['element']['classes_array'])){
    $vars['classes_array'] = array_merge($vars['classes_array'], $vars['element']['classes_array']);
  }
}

```

If there's a more 'official' way to do this, please feel free to enlighten me and I'll re-award the answer :)

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


# Question
Title: Using variable_set with associative array
I use checkboxes in a form to capture a users selection as:

```
$form['mbo_block_config']['livembo_classes_details'] = array(
                '#type' => 'checkboxes',
                '#title' => t('Class Details'),
                '#description' => t('Choose class details to display.'),
                '#options' => $details,
                '#default_value' => variable_get('livembo_classes_details', array('c_id','c_cd_name')),
                '#required' => TRUE,
                );

```

The available options are stored in $details which is an associative array:

```
$details = array(
          'c_id' => t('Class ID'),
          'c_cd_name' => t('Class Name'),
          'c_cd_description' => t('Class Description'),
          'c_l_name' => t('Location: Name'),
          'c_l_city' => t('Location: City'),
          'c_l_full' => t('Location: Full Address'),
          'c_l_phone' => t('Location: Contact Number'),
          'c_s_FullName' => t('Staff: Name'),
          'c_start ' => t('Class Start Time'),
          'c_end' => t('Class End Time')
          );

```

I use variable set `variable_set('livembo_classes_details', $edit['livembo_classes_details']);` which works fine, however it flattens the array and changes the keys to values as per:

```
Array ( [0] => c_id [1] => c_l_phone [2] => c_l_name )

```

How can I retain the key/value format in the array as originally specified? For example:

```
Array ( [c_id] => t('Class ID') [c_l_phone] => t('Location: Contact Number') [c_l_name] => t('Location: Name') )

```

# Answer
> 4 votes
The problem is not variable\_get()/set(). It stores whatever you pass to it as a serialized array.

However, what you are saving are the *keys* of your array, because that's what is passed from the browser when submitting the form. This is also what is expected in the #default\_value so it needs to be like this.

When accessing the information, all you need to do is get the intersection of your $details and the selected keys like this:

```
$selected_details = array_intersect_key($details, array_flip(variable_get('livembo_classes_details', array('c_id','c_cd_name')));

```

I would recommend to add a helper function which returns $details if you haven't already, so you can re-use that definition and a second helper function which contains the above code.

---
Tags: 7, forms
---


title: How to theme a list based field

text:
# Question
Title: How to theme a list based field
I have a text field attached to my node. The user can add an unlimited number of values.

I want to out put all the values as a HTML list in my node.tpl.php file.

Contemplate module suggests to use the following code to out put the field:

```
<?php print $node->field_body_list['und'][0]['safe_value'];?>

```

This, however, has two problems: 1) It only outputs the first value of the field. 2) It uses UND, which is apparently bad.

I have tried using theme developer, but it doesn't produce any code that I can use in my node.tpl.php file.

Any help would be greatly appreciated it.

# Answer
> 2 votes
It's easiest to stay out of `node.tpl.php` for this one and instead use a field specific template file.

You'll need two copies of `/modules/field/theme/field.tpl.php` in your theme folder. The first is an exact duplicate with no changes and the same filename. The second you should rename to `field--field-body-list.tpl.php`. Consult Drupal 7 Template Suggestions if that filename doesn't work for you.

In `field--field-body-list.tpl.php` I would change the div with `class="field-items"` to `<ul>` and the div with `class="field-item"` to `<li>`.

---
Tags: entities, theming
---


title: Organic groups & views

text:
# Question
Title: Organic groups & views
So... I created a few groups and a new content-type. The problem is that I don't know how to display content linked to a certain group using a path like: "/\[-content-type\]/\[group-name\] (using views, of course). As far as I know it has something to do with contextual filters, but that's where my knowledge ends.

Thanks for any help.

# Answer
> 1 votes
take some time and watch these very informative new videos: Modules Unraveled Kudos to Brian Lewis aka bjlewis2

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


# Question
Title: Print taxonomy term name in node.tpl.php
How can I print the taxonomy term name in node.tpl.php?

The following prints the name as a link, but I just want to print the name as text so I can make it a `<div>` class.

```
<?php print $terms ?>

```

# Answer
```
$term = current($node->taxonomy);
echo '<div class="some-class">' . $term->name . '</div>';

```
> 2 votes

---
Tags: 6, theming
---


# Question
Title: Display several user blog entries at once
I use Blog 7.7 core module to display site updates at http://preferans.de/blog/1

However only 1 news item is always displayed at that link.

Is there maybe a way to change that amount?

I've tried looking around, including **admin/content/book/settings**

# Answer
you can create a "view" to display a list of blogs. In Views you can specify how to layout those blogs, how many to show, in what order, etc. NoneOne has a great screencast about learning views
> 1 votes

---
Tags: 7, nodes
---


title: View item list ranking

text:
# Question
Title: View item list ranking
I have a view with a list of nodes of a certain type sorted by a custom field.

Is there any way to put a ranking number on the output of a view?

Thanks!

# Answer
I Assume you just want a row counter (1, 2, 3…). Just add the field "Global: View result counter".
> 2 votes

# Answer
If I understand well your question, in `Format` of your View settings, select `HTML list`. and in the settings of this `HTML list` select `Ordered list`
> 1 votes

---
Tags: views
---


title: Filtering in views

text:
# Question
Title: Filtering in views
I have a view with a list of nodes of a certain type. I would like to add a filter in the HTML in order to reduce the amount of items in the list.
Every item has a Term Reference field, I would like to add a checkbox for each term in order to do this.

Is there any way to do this?

# Answer
> 3 votes
If I understand well your question, in your filter criteria of your View configuration, you can select the option `Expose this filter to visitors, to allow them to change it`.

---
Tags: views
---


# Question
Title: Is there a module to hide URL path settings by content type?
Eg. I'd like to let the client see the URL path settings fieldset for Page but not for Slide.

I'm happy to implement it myself, just wondered if someone else already had.

# Answer
> 1 votes
I don't believe there is anything out there at the moment (perhaps my search wasn't extensive enough either), but you can hide the URL path settings fieldset yourself easily with one line of code:

```
<?php $form['path']['#access'] = FALSE; ?>

```

# Answer
> 0 votes
Here's a sandbox module to automate Laxman13's answer for fieldsets in general (including *URL path settings*).

---
Tags: 6, path-aliases
---


title: AJAX JSON Views

text:
# Question
Title: AJAX JSON Views
In Drupal 7 how can I get Views data encoded as JSON? There's the built-in `http://yourdrupal/views/ajax` URL that will return the View data as HTML. For instance it will return:

```
   {
      "command":"insert",
      "method":"replaceWith",
      "selector":".view-dom-id-1",
      "data":"...a bunch of HTML here...",
      "settings":null
   }

```

The `data` is correct but it's formatted as HTML - how can it be formatted as JSON instead?

# Answer
> 9 votes
Check out views\_datasource. It allows to specify a views display of type 'JSON'.

---
Tags: 7, views, ajax
---


title: DSM output intermittently shows up

text:
# Question
Title: DSM output intermittently shows up
For some reason my DSM output is only occasionally showing up. Nothing significant is changing on the template I'm calling it from. It will show up, then on refresh go away, and randomly re-appear 10 refreshes later.

Any idea what can cause this behavior?

# Answer
Especially in templates files, `dpm()` doesn't show up, I'm not sure about the cause but I guess it's because the `drupal_set_message()` function is called earlier. So while working on templates I prefer using `kpr()`, it works the same way but print directly the krumo message into the page instead of using `drupal_set_message`.
> 3 votes

# Answer
Does the page have any 404 errors? (You can check the browser's console, or your server's access\_log). Sometimes 404 pages can eat the dsm() messages, see http://drupal.org/node/885896.
> 0 votes

# Answer
`dpm()` uses `drupal_set_message()`, which actually stores the message into the `$_SESSION` variable, and it's fetched from there on the next full page refresh. So any AJAX changes may not pick up things that have been written, and also the `$_SESSION` contents are occasionally destroyed by buggy behavior especially during logout.
> 0 votes

# Answer
You can find all the details about dsm() and kpr() here
> 0 votes

---
Tags: 6, debugging
---


# Question
Title: How to remove a help text from the registration form?
I'm writing a custom function to now allow spaces and other special characters for the username on the registration form.

How can I remove the text "Spaces are allowed; punctuation is not allowed except for periods, hyphens, apostrophes, and underscores." on that page?

# Answer
> 2 votes
I figured it out:

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

  if (!($form_id == 'user_register_form')) {
        return;
  }

  $form['account']['name']['#description'] = 'Username has to be between 5-20 characters long and can only contain letters and numbers.';
}

```

---
Tags: 7, theming, users
---


# Question
Title: Conditional PHP works in Node Template but not in Views Custom Fields
This code in my node template checks a CCK field and prints some text dependent on the value:

```
<?php if ($node->field_stock[0]['view'] == 'No' ) : ?>
<div id="out-stock-my"><h2>Out of Stock</h2></div>
<?php endif; ?>

```

How can I do something similar with Views Custom Field's PHP filed type? Thanks

# Answer
If 'm not mistaken you are trying to move this logic out of your tpl.php template file by using views custom field.

You first need to get the name of the accessible fields with this code.

```
<?php print var_export($data, TRUE); ?>

```

Then you should be able input in the custom field something similar to this.

```
<?php if ($data->field_stock == 'No' ) : ?>
<div id="out-stock-my"><h2>Out of Stock</h2></div>
<?php endif; ?>

```

There is more info here http://drupal.org/node/467190.
> 3 votes

# Answer
in templates of views you can seek/use the id of the node (nid).

for example, in this case I will use views-view-unformatted.tpl.php

```
<?php
$nodeIdItem = $view->result[$id]->nid; //get the id of the current item, in this case using $view->result inside the view results loop.
$node = node_load($nodeIdItem);
?>
<?php if ($node->field_stock[0]['view'] == 'No' ) : ?>
<div id="out-stock-my"><h2>Out of Stock</h2></div>
<?php endif; ?>

```
> 1 votes

---
Tags: 6
---


# Question
Title: How do I use "IGNORE" in a database query?
I would like to run a query similar to `INSERT IGNORE INTO the_table (nid, language) VALUES (8, 'Chinese')`, but I cannot find any documentation on how the "IGNORE" statement works with the Drupal DB API.

Does anyone know how to achieve that?

```
db_merge('the_table')
  ->key(array('nid' => 8, language' => Chinese))
  ->fields(array(
      'nid' => 8,
      'language' => Chinese,
  ))
  ->updateExcept('nid','language')
  ->execute();

```

Would the code above be the equivalent of my initial query ?

**EDIT:** updateExcept method doesn't exist, no idea why it s still in the documentation

# Answer
What you want is a MERGE query with no UPDATE part. Something like this should work:

```
db_merge('the_table')
  ->key(array(
      'nid' => 8,
      'language' => Chinese,
  ))
  ->insertFields(array(
    'nid' => 8,
    'language' => Chinese,
  ));
  ->execute();

```
> 4 votes

# Answer
db\_insert() does not support `IGNORE` because this is not SQL standard but a mysql-specific extension. db\_merge() is not what you want I think, because it either INSERTS or UPDATEs a row. There are two possible ways to work around this:

* You can simply use db\_query() and pass a query string to it. However, this means that your code/module only works with MySQL and can not be used with PostgreSQL. This might be OK for a custom module for a specific site, but I would nevertheless strongly recommend to chose option 2 below. For a contributed module, this is wrong, obviously.
* The only clean way out of this is that you first need to check if such a row already exists with a normal SELECT query and if not, execute a normal INSERT query. Note that this method might be prone to concurrency issues, if two requests happen at the same time. You could work around that with a transaction and blocking write access to that table, but this might on the other hand slow down performance...
> 1 votes

# Answer
Instead of using IGNORE, I think you'll be interested to `db_merge()`, which adds or updates your data according to the query you execute.
> 0 votes

---
Tags: 7, database
---


# Question
Title: How can I get newly created node of a certain type?
I understand I could use `hook_nodeapi('insert')` in Drupal 6 (Drupal hook fired after node created), but this seems to have changed in Drupal 7. What would the equivalent of that in Drupal 7?

# Answer
> 3 votes
The equivalent of `hook_nodeapi('insert')` in Drupal 7 is hook\_node\_insert().

```
function hook_node_insert($node) {
  db_insert('mytable')
    ->fields(array(
    'nid' => $node->nid,
    'extra' => $node->extra,
  ))
    ->execute();
}

```

# Answer
> 0 votes
In Drupal 7, several hooks that previously allowed modules to do a group of related operations, with a $op argument, were split into individual hooks for each operation.

See node.api.php.

---
Tags: 7, hooks, nodes
---


# Question
Title: View items content type as css class in view template
I have a view which outputs node titles from various content types, what I need is to theme the view template so one of the css classes for each row in my view is the item's content type. How would I do that?

EDIT: I tried to add the code below in the view template file but it doesn't seem to output any code:

```
<ul class="<?php print $fields['type']->content ?>">

```

In fact I even tried outputting it as a regular field but it simply seems to be ignored:

```
<?php print $fields['type']->content ?>

```

# Answer
You need to adjust the template (tpl) file that's being used to generate the markup for the Views output. I think everything you'll need as well as a bunch of related and equally important info can be found here: Mustardseed -\> Views Theming
> 2 votes

---
Tags: views, nodes, theming
---


title: Multi-language site

text:
# Question
Title: Multi-language site
I'd like to build a multilingual site and I am quite new to drupal, I was wondering if I could proceed in the following way:

I could tag my entries with the world "english" and "italian", then I could display pages only with such tags to filter my site...

Generally speaking, would I be able to filter my site by tag?

Would this option be feasible? What would be the best solution to my problem?

Many thanks for any answer!

Alex

# Answer
Use the native Drupal internationalization functionality. You can then configure how nodes of different languages are shown, but by default they are found at \[lang\_code\]/node/123 - eg fr/node/123.

You can alter Views to only show content to users in their specified language. User language can be a configurable option or can be autonegotiated based on browser headers.

Internationalization is a big, difficult topic, which I'm sure you're beginning to realise as you work on your site! i18n module is a good place to start, as it provides many useful add-ons which extend the core Drupal i18n functionality.
> 2 votes

# Answer
What version of Drupal are you using? As "cam8001" suggests, internationalisation is a huge topic, fortunately Drupal has some substantial functionality to help you out. Take a look at these resources to get a summary of the topic:

Perhaps most importantly know that multilingual support in Drupal has several different modules to create the functionality of a typical multilingual site. Which ones you choose to use is dependent on your needs.
> 1 votes

---
Tags: 7, i18n-l10n, taxonomy-terms
---


# Question
Title: Using ENTER key to submit default Drupal 7 Search doesn't not return results: Why?
I have a design provided by the customer, where the search block form has no SUBMIT button. It is expected the user just hits the "enter" key.

Users can type keywords into the search box, and when they press "enter," the form is submitted. The problem is that the form is submitted always with "#default\_value" and never with the keywords typed into the input box.

On the advanced search page/results the search does work.

Does anyone know why this might be?

We have hidden the submit button via a CSS call of `display: none`.

# Answer
> 1 votes
Are you using the `<form>`'s submit event rather than the `<input>`'s click event to respond to the form submission? Check out this working example on jsFiddle.

```
$("#form").bind('submit', function(e) {
    var $div = $("<div>Transmitting</div>").appendTo('body');
    $.ajax({
        url: '/ajax_html_echo/',
        data: {html: $("#html").val() },
        type: 'POST',
        success: function(data) {
            $div.html("Received: "+data);
        }
    });
    return false;
});

```

---
Tags: 7, forms, search
---


# Question
Title: Module for extracting information from remote site?
I want to give user better experience when filling in forms. They are prompted to fill information about some product, like price, description, image, etc...

My idea is that I'll let them just copy & paste URL to (for example) amazon and the website will itself pre-fill all the fields (price, description, ...).

So I would basically need set of regular expressions per field, per remote site. This is not a problem, I can cover 90% of our user daily used websites. If this mechanism fails, then user still will be able to fill the information manually.

My problem is that I cannot find any drupal module that is capable of doing something like this. Does anyone know how to (simply) achieve this goal? Or do I have to write a module for this?

# Answer
> 1 votes
I think that Feeds XPath Parser and Example Web Scraper could be a guidance to your needs.

# Answer
> 0 votes
I don't see how your approach would really work as it would require the scraper to be authenticated as your user with the target site.

It may be worth looking into OAuth or Facebook Connect to streamline your registration process.

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


# Question
Title: Print a text if a view result is equal to a certain value
In a template file, how can I use PHP to print some text if a view has a certain value?

The view uses the node ID, so I guess this argument needs to be passed to the view (as it would be if the view was embedded onto the page).

Here is my attempt:

```
<?php
  $view = views_get_view('hide_weight_2');
  if ($view->execute_display('default', $args) == 'Yes' ):
?>
  <h1>Result of view was yes</h1>
<?php endif; ?>

```

# Answer
If I understand well your question, I guess that you can make this in a rough way from a template View. Inside this template file you can add the respective conditional to show your text.

Here is the part of views-view-unformatted.tpl.php when each result is printed:

```
<?php foreach ($rows as $id => $row): ?>
  <div class="<?php print $classes[$id]; ?>">
    <?php print $row; ?>
  </div>
<?php endforeach; ?>

```

Then, you can parse `$row` to catch the respective value and print a message. You can use preg\_match() to match the value For example, instead of `<?php print $row; ?>` you could use:

```
<?php
  if (preg_match("/(here text to match)/i", $row)) {
    print "Aha!:" . $row;
  }
  else {
    print $row;
  }
?>

```

I guess you can improve this seeking per target fields.
> 0 votes

---
Tags: views, theming
---


# Question
Title: How to Bi-directional link two nodes from different content type?
Hello i am new to Drupal. I have used Joomla for very long time and some wordpress.

I want to link 2 or more nodes bi-directional. Meaning that if i link A to B, B must be also linked to A.

I will give you a simple example:

Lets say i want to make a Lyrics site. Where i will have 2 content types.

* 1) Artist / Band
* 2) Song Lyrics

The **Artist / Band** type will have information about the artist with maybe a photo and textaera for description.

The **Song Lyrics** will have the actual song lyrics (textaera).

Finally i want to link the Song Lyrics to an Artist / Band. So when i view the Lyrics page it will link to the Artist page. And when i go to the artist page it will link to all the lyrics that are available for that artist.

How can i do this in **Drupal 7**? Can i do it with the Core, or do i need to install additional Modules?

# Answer
Also check out these modules (quotes included are from their project pages):

* References Module:

> ... provides D7 versions of the 'node\_reference' and 'user\_reference' field types, that were part of the CCK package in D6, at functional parity with the D6 counterparts.
* Entity Reference:

> Provides a field type that can reference arbitrary entities:
>
> + A generic entity reference field
>     + Four widgets:
>         - Two implemented on top of the Options module (Select and Radios/Checkboxes),
>         - Two autocomplete widgets (one with one text field per entry, one tag-style with comma-separated entries in the same text field)
>     + Two formatters:
>         - A "Label" formatter, with optional link that displays the label of the referenced entity (the node title, the user name, etc.)
>         - A "Rendered entity" formatter, that renders the references entity using a configurable view mode
>     + Integration with Views (for both forward and backward references)
>     + Integration with Entity Metadata (and as a consequence with Search API and the like)
>     + Integration with Devel generate
>     + Integration with Feeds and Migrate (\>= 2.3) for painless data import
* EVA: Entity Views Attachment

> ... provides a Views display plugin that allows the output of a View to be attached to the content of any Drupal entity. The body of a node or comment, the profile of a user account, or the listing page for a Taxonomy term are all examples of entity content.
> 1 votes

# Answer
While still new and with rough edges, the Relation module will be the right module for that job.
> 3 votes

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


# Question
Title: How do I create a block for my heartbeat activity?
I have a heartbeat activity and a message template. I'm able to log the activities using `heartbeat_api_log()`, but how do I show the activities in a block?

I'm using Drupal 7.

# Answer
heartbeat has views integration. Just built a view and add it to a block.
> 1 votes

---
Tags: blocks, heartbeat
---


# Question
Title: How can I customize the way my taxonomy terms are displaying?
I have been searching all over the place for some help on this.

I currently have my tags displaying for each node like such: tag,tag,tag

Now I would like them to display a little cleaner and more appealing to my visitors. So what I would like to do is have them display like such: tag \ tag \ tag

Now from what I have read, I need to target the field API? and use a preprocess function to alter what the array is spiting out? Please correct me if I am wrong.

This seems like an easy task to complete but I just can't seem to find a solution.

Thanks in advance

# Answer
Indeed a preprocess function is what you're looking for, I suspect in D7 this will help:

```
function MYTHEME_preprocess_html(&$variables) {
if(arg(0)=='node' && is_numeric(arg(1))) {
    $node = node_load(arg(1));
    $results = taxonomy_node_get_terms($node);
    if(is_array($results)) {
        foreach ($results as $item) {

```

In terms of D6, node-taxonomy.tpl.php and page-taxonomy-term.tpl.php should put you on the right path.
> 1 votes

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


title: Gmap does not work on iPhone

text:
# Question
Title: Gmap does not work on iPhone
I am using the Gmap module to display a map on the page; however, it works on the PC, but not on the iPhone.
I checked the iPhone debug console, and got the following error:

> Drupal.gmap \[undefined\] is not an object

Could anyone please suggest me the way to solve this problem?

# Answer
> 0 votes
I fixed the problem; it was caused by the JavaScript file. This is what I have tried:

1. Open the file of "/sites/all/modules/gmap/gmap.module"
2. Find the function "\_gmap\_doheader()"
3. Find the line begin with "drupal\_set\_html\_head('
4. Move it to the second line of \_gmap\_doheader(), so it may look like:

```
function _gmap_doheader() {
  drupal_set_html_head('<script src=xxx
  static $gmap_initialized = FALSE;
  // …
}

```
5. Upload the file to /sites/all/modules/gmap/
6. Flush all caches

# Answer
> 2 votes
So your solution hacks the module code. Do the community a favour and submit your change to the issue cue for the module so that everyone can share in your success or even better roll a patch for the authour to apply to the module code.

---
Tags: google-maps
---


title: Date #return_value to ordinary time()

text:
# Question
Title: Date #return_value to ordinary time()
So I have included a date field in my custom block form and would like to use the date.

However it is saved as an array which I am finding a little difficult to work with:

> The format for "#default\_value" and "#return\_value" is an array with three elements with the keys: 'year', month', and 'day'. For example, `array('year' => 2007, 'month' => 2, 'day' => 15)`

What is the best way of getting this "date array" into something I can use strtotime() on? Am I missing some Drupal way of allowing me to format this nicely into a string?

What I have working seems to be very long winded and static:

```
$startDate = variable_get('start_date', NULL);
if (isset($startDatea)) {
  $startDate = $startDatea['month'].'/'.$startDatea['day'].'/'.$startDatea['year'];
  $startDate = date('Y-m-d', strtotime($startDate));
}

```

I am sure there must be a nicer way.

# Answer
> 0 votes
For what it's worth you have a typo in your sample code, $startDate is being referenced as $startDatea - note the extra "a". As for a shorter version, try:

```
$startDate = variable_get('start_date', NULL);
$startDate = date('Y-m-d', mktime(0,0,0, $startDate['month'], $startDate['day'], $startDate['year']);

```

I suspect not jumping from numeric to string and then back again might save you a few cycles at the PHP layer.

---
Tags: 7, forms, datetime
---


# Question
Title: How to change to default Localization Client language to translate
Localization Client allow me only to translate from English to one of others languages.

It is possible to translate from language x to English too?

# Answer
> 1 votes
No.

The reason is the way the Drupal translation system is built. Original strings (defined in modules) must be written in English. This means all translation will be from English to X-language.

# Answer
> 1 votes
The Locale module (in core) will detect your t() strings and provide an interface for translations. Handbook page explaining it in summary can be found here: Translating a site interface to different languages (Locale core module).

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


# Question
Title: Calculated field returns undefined index
I'm trying to average all of the fivestar ratings I have for a node using a computed field. But i'm struggling to simply access the other fields using entity!

In the body of the node, this works fine:

```
$test1 = $node->field_ae_stimclasswrk[und][0]['average'];

```

In the computed field area, this doesn't work:

```
$entity_field[0]['value'] = $entity->field_ae_stimclasswrk[$entity->language][und][0]['average'];

```

Instead, when I save the node, I get this index error:

> Notice: Undefined index: und in eval() (line 2 of...

It must be something syntax, but I'm completely out of ideas.

Here is the field info:

```
    [field_ae_stimclasswrk] => Array
        (
            [und] => Array
                (
                    [0] => Array
                        (
                            [user] => 80
                            [average] => 80
                            [count] => 1
                        )

                )

        )

```

# Answer
> 1 votes
`$entity->language` is the same as und so try using:

```
$entity_field[0]['value'] = $entity->field_ae_stimclasswrk[$entity->language][0]['average'];

```

---
Tags: views, entities
---


title: Link to my story content type D7?

text:
# Question
Title: Link to my story content type D7?
I have added many content to content type story. How will I link to the page that shows all the nodes with their teaser? What will the link be?

# Answer
If your contents are promoted to front page, they will be shown on front page.

If you want to see your content in a seperate page or block you should create a *View* from your contents, with the Views module
> 2 votes

# Answer
Drupal does not quite work like that; lists are not automatically created. You can use the Views module to create the list.

Views can output the data as a table, fields etc. Set the filter by type on the content drop down to 'story'. By creating a view type page you can also set the custom URL.
> 1 votes

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


title: Download Confirmation Form

text:
# Question
Title: Download Confirmation Form
I would like to add a confirmation page for downloads.
How can I achieve it?

# Answer
Not easily because you are going direct to the path.

You could do it in a similar manner to sites such as sourceforge which show you the confirmation page first and use JavaScript to open the download. This method should also have a direct link option incase JavaScript is disabled.

The best way of doing this would be to add a menu hook which shows the message and then links to the path. You would need to add a .htaccess to capture the page downloads and perhaps pointing it to /download-confirm?link=(Base64 encoded link).
> 1 votes

---
Tags: cookies, files
---


# Question
Title: Validate based on existing CCK field value?
I have a content type with an address field in it. My client has requested that when saving, the site should check whether another node (of the same content type) already has that address.

I.e., I want the content type to validate if and only if the address being given hasn't been used.

How do I do this? Using Drupal 6, by the way.

# Answer
You should be able to use hook\_nodeapi for this!

In this example I'm assuming the node type is *blah*

In a custom module just write something along the lines of:

```
function mymodule_nodeapi(&$node, $op, $a3 = NULL, $a4 = NULL) {
  if ($op == 'validate' && $node->type == 'blah') {
    $sql = db_query("SELECT bl.field_address
           FROM {content_type_blah} bl
           WHERE bl.field_address = '%s'", $node->field_address)

    if ($sql != '') {
        form_set_error($node->field_address, t('This address is already being used'));
    }
  }
}

```

That way, before a node is saved (during the validation) it runs an SQL query to see if the address field is duplicated anywhere else on any other node with the type *blah*. If it is, then it throws an error on the form field! You will need to tweak the query dependant on your table names etc.

I'm only writing that code from the top of my head, and I've not tested it (sorry) but it should definately be a starting point! I may have the $node-\>field\_address part wrong!

If all else fails, put a `die(print_r($node));` after the `if ($op == 'validate'...` line and you can get the right part from that!

Hope this helps :)

References:

http://api.drupal.org/api/drupal/developer--hooks--core.php/function/hook\_nodeapi/5 http://api.drupal.org/api/drupal/includes--form.inc/function/form\_set\_error/6
> 1 votes

---
Tags: entities, 6
---


# Question
Title: How to assign ImageCache setting to an imagefield in content type
For a self-created node type called 'Event' I added an image field. Got all the modules going ImageCache, Imagefield, IamgeAPI, …. under sitebuilding\>ImageCache I made a setting called 'agenda-full-node-thumbnail' (agenda is dutch for calendar by the way) I intended to assign this setting to the image field in Node type 'Event' and succeeded. But now I forgot how I did this.

The problem now is, since I put the site online, my pictures fail to reside in the directory /sites/default/files/imagecache/agenda-full-node-thumbnail and hence giving me a broken image link on my webpage.

Maybe I need to rename the path since I put it online, but can't figure out how I went about making this Imagecache setting and making it work for my Node type to begin with. And that's where I've been stuck for a couple of hours and it's driving me completely nuts.

# Answer
> 1 votes
in order to work, imagecache relies on a tmp folder that needs to sit on your server. While developing local the tmp directory is located under the local webserver directory obviuosly and that needs to be changed when you go online. Administer » Site configuration - then file system is where you change it do a directory that is compatible with a server on your host. Setting the permissions to 777 then allowed imagecache to store the necessary image files and solved my issue.

# Answer
> 0 votes
Take a look at the handbook on drupal.org -\> Troubleshooting Imagecache

Note the section title "What can go wrong? No images in the imagecache directory" Go through the list of items that will guide you to making sure any of the common issues are not the problem. If you don't figure it out then come back and poke us again with any more details you figure out.

Good luck, imagecache in the bomb!

---
Tags: 6, media
---


title: Taxonomy term as node css class

text:
# Question
Title: Taxonomy term as node css class
Kind of similar to my previous question, but apparently doesn't work the same way: is there an easy way to use a taxonomy term or a token as node css class to theme different pages?

# Answer
> 5 votes
Edit you node-type.tpl.php for this.

```
<?php
    foreach($node->taxonomy as $term){
            $term_classes[] = $term->name;
    }
?>

```

And print those classes in your node content wrapper.

```
<div class="content <?php print implode(' ', $term_classes); ?>">
    <?php print $content ?>
</div>

```

---
Tags: 6, nodes, taxonomy-terms, theming
---


# Question
Title: how to programmatically set a group audience
I am trying to programmatically add the group audience widget to a custom form (without using OG field setting) and set it to a default value.

Would anyone know of a way to do so?

---

Well after one week of investigation i still haven t find an answer. I gotta say i am really dispointed by OG module, the documentation is so poor and the maintainer doesn't really help improving this. A real shame such a module isn't more documented

# Answer
First in your .install when creating your content type, add:

```
og_create_field(OG_AUDIENCE_FIELD, 'node', 'bundle_name_of_your_content_type');

```

Then when you need to assign a fresh new content of your content type to an existing group, you can do it in two ways:

1) Found it http://drupal.org/node/1249396#comment-4885442 and thanks to tenken

```
$node = node_load($nid);
$values = array(
  'entity type' => 'node',
  'entity' => $node,
  'state' => OG_STATE_ACTIVE);
og_group($gid, $values);
node_save($node);

```

2) Maybe less sexy

```
$node = node_load($nid);
$node->group_audience['und'][0] = array(
  'gid' => $gid,
  'state' => OG_STATE_ACTIVE,
  'created' => mktime());
node_save($node);

```

Cheers
> 5 votes

# Answer
Assuming you are using Drupal 6, there is an API function named og\_form\_add\_og\_audience() that you can leverage to add the audience widget to your custom form. It is important to note that you will probably have to process the data yourself through a custom submit handler.
> 0 votes

---
Tags: 7, forms, organic-groups
---


# Question
Title: One view to do everything or a different view per page?
If I need to display the last 10 nodes created on my front page regardless of content type and need to do the same in my sub-pages but need to filter by specific content type, is it easier to create several different views or to create one view that does all of that? If I need to create one view, how would I restrict different pages to specific content types?

# Answer
Personally, I create a view per content type and set up decent defaults and then have displays to handle the different uses. Special pages and other one offs (like the home page in your case) have specific views.

I find this approach better handles changes that may come down the line.
> 3 votes

# Answer
You could possibly have one view for the home page that displays everything, and then another view that uses the current node type as an argument?

Assuming that is that when you're on a *blog* node type (for example) you want to display the most recent *blog* type nodes.
> 1 votes

---
Tags: 6, views
---