title: Views in English and Spanish

text:
# Question
Title: Views in English and Spanish
My site is in English and Spanish. My question pertains to the Similar by terms module and a custom view that on click shows random filtered by term nodes. How would I create an argument to show Spanish content when in Spanish mode, and English content when in English mode? I realize that I could simply filter nodes for Spanish.
How does the Similar by Terms module recognize the fact the page is in either English or Spanish, and display the appropriate language on click?

# Answer
I think you should not think about language and let Drupal handle it.

If you install locale module and configure it correctly you will gain what you need:

1. Install the Locale, Internationalization and Taxonomy translation modules. (The latter is optional.)
2. When adding a taxonomy term, select "Multilingual options-\>Per language terms."
3. When adding a content type, select "Workflow settings-\>Enabled."
4. when adding content, select language.
> 3 votes

---
Tags: views, 6, taxonomy-terms, i18n-l10n
---


# Question
Title: How to change the teaser for the front page articles
In my site : http://www.indiacustomercare.com front page(which is not displaying correctly) I want to show 200 words in teaser for each article. I've changed it in Post Settings but does not work.

What could be the reason?

# Answer
You need to Edit and Save again the articles to take effect.

I know can be painful if you have hundreds of nodes. If you google about it you will find scripts to do it like this http://befused.com/drupal/script-update-drupal-teasers

Or use the module retease http://drupal.org/project/retease

I advice you to take a database dump before testing these solutions, just in case.
> 2 votes

# Answer
With views module you can customize look of front page how ever you wish. You can style predefined "front-page" view or make your custom view and make front page of it.

In view, include field teaser (and title, post date etc.). Trim output of teaser to any number of characters you like and thats it. I like to exclude HTML tags from output as well so images, flash and such don't brake my layout

Hope this helps.
> 0 votes

---
Tags: nodes
---


# Question
Title: Drupal 7 list all the nodes that match a specific tag
is it possible to pass a specific url to Drupal7 that lists all the nodes that has a specific tag? i'm searching for something similar to "?tag=" used by wordpress.

I've already created tags and added the tag field to my nodes

Thanks

# Answer
> 1 votes
Tags are terms of a taxonomy vocabulary. Each term has its own page listing all the nodes for the term at `taxonomy/term/<tid>` where `<tid>` is the numaric term identifier. The Pathauto module allow automatic creations of cleaner aliases for these pages using patterns like `<vocabulary-name>/<term-name>`. So instead of being at `taxonomy/term/42` the page for the "Foo Bar" tag will be at `tags/foo-bar`.

---
Tags: taxonomy-terms
---


# Question
Title: Does  Drupal have an AJAX solution for search results, preferably with Apachesolr integration?
Specifically, I'm referring to being able to have the top 5 search results display as options in a drop down menu while the user types in a search query, somewhat similar to how node reference autocomplete works. It would be great to have such functionality work with Apachesolr.

# Answer
Depending on your needs, there are a couple of solutions. Probably the closest thing to Apple's Live Search feature is the Finder module. It does not integrate with Apache Solr at this time, however.

I would also keep your eye on the Inline Ajax Search module as Solr integration is on the roadmap. It might need some contributions to push integration through.

A third solution to try is the Apache Solr AJAX module. It might not fit exactly what you are trying to do, however it allows for inline refreshing of the page when queries are entered and filters are enabled.
> 6 votes

# Answer
Acquia offers a solution built on Solr. http://network.acquia.com/services/acquia-search
> 2 votes

# Answer
I would suggest installing the module http://drupal.org/project/apachesolr\_autocomplete, this out of the box will let you see Solr's keyword suggestions.

The next issue is showing nodes in the search results and not search terms, there is a hook called `apachesolr_modify_query($query,'apachesolr_autocomplete');` which will allow you to write a custom module to intercept the query as it goes to Solr and tell it to search for nodes and not search suggestions.

The remaining problem you have is simply down to theming the search results so that they look like the regular search.

There already are two theming functions avaliable:

* theme\_apachesolr\_autocomplete\_highlight
* theme\_apachesolr\_autocomplete\_spellcheck

Hope this helps.

At the end of the day you could write the entire module yourself without starting with the base module apachesolr\_autocomplete, but I feel it takes a lot of the heavy lifting off you and would be an advantage.
> 2 votes

---
Tags: 7, search
---


# Question
Title: Is there a module for limiting CCK select list options per role?
I notice we can define a custom php list for options widget in CCK.

Would love to limit allowed values per role?

What would be the easiest way?

Such a solution could replace a lot of other modules, like Workflow etc...

# Answer
You dont need a module, this is in core.

```
  $values = array(1|one, 2|two, 3|three);

  global $user;

  // Check to see if $user has the administrator role.
  if (in_array('administrator', array_values($user->roles))) {
    $values[] = 'special|special';
  }
  return $values;

```
> 2 votes

---
Tags: entities
---


# Question
Title: Force the module "legal" to show a "form_set_error" on path /user/register
I'm using the "legal" module version 6.x-8.5. This is a great module, but i think there's a `form_set_error()` message needed, to show the user which's trying to register, why registering cannot be applied, if he forget to click the required checkbox(es). I'm looking for a possibility to get this working. Does anybody know where to implement this function(hardcoded, if there isn't a other solution) in the module? I also tried to do this with rules forms, with this rule:

```
    array (
  'rules' =>
  array (
    'rules_register_ckeck_agb' =>
    array (
      '#type' => 'rule',
      '#set' => 'event_user_register_form_validate',
      '#label' => 'Register ckeck AGB',
      '#active' => 0,
      '#weight' => '0',
      '#categories' =>
      array (
      ),
      '#status' => 'custom',
      '#conditions' =>
      array (
        0 =>
        array (
          '#settings' =>
          array (
            'element' => 'legal[legal_accept]',
            'value' => '1',
                '#argument map' =>
            array (
              'form' => 'form',
              'form_state' => 'form_state',
            ),
          ),
          '#type' => 'condition',
          '#name' => 'rules_forms_condition_element_value',
          '#info' =>
          array (
            'label' => 'Form element \'legal[legal_accept]\' value check',
            'arguments' =>
            array (
              'form' =>
              array (
                'type' => 'form',
                'label' => 'Formular',
              ),
              'form_state' =>
              array (
                'type' => 'form_state',
                'label' => 'Form state',
              ),
              'element' =>
              array (
                'type' => 'string',
                'label' => 'Form element ID',
                'description' => 'ID of the form element to be targeted. Examples on the "Create Story" form: "title" for the title field or "body_field[body]" for the body field.',
              ),
              'value' =>
              array (
                'type' => 'string',
                'label' => 'Value(s)',
                'description' => 'Value(s) assigned to the form element. If the form element allows multiple values, enter one value per line.',
              ),
            ),
            'module' => 'Rules Forms',
          ),
          '#weight' => 0,
          '#negate' => 1,
        ),
      ),
      '#actions' =>
      array (
        0 =>
        array (
          '#weight' => 0,
          '#info' =>
          array (
            'label' => 'Set form error on element \'legal[legal_accept]\'',
            'arguments' =>
            array (
              'form' =>
              array (
                'type' => 'form',
                    'label' => 'Formular',
              ),
              'element' =>
              array (
                'type' => 'string',
                'label' => 'Form element ID',
                'description' => 'The element that should be marked. Examples on the "Create Story" form: "title" for the title field or "body_field[body]" for the body field.',
              ),
              'message' =>
              array (
                'type' => 'string',
                'label' => 'Nachricht',
                'description' => 'The message that should be displayed to the user.',
              ),
            ),
            'module' => 'Rules Forms',
          ),
          '#name' => 'rules_forms_action_set_error',
          '#settings' =>
          array (
            'element' => 'legal[legal_accept]',
            'message' => 'Please Confirm the...',
            '#argument map' =>
            array (
              'form' => 'form',
            ),
          ),
          '#type' => 'action',
        ),
      ),
      '#version' => 6003,
    ),
  ),
)

```

But this also does not the job, it should do. Does anybody know what I'm maybe doing wrong here? Thanx for all your suggestions. regards dennis605

# Answer
> 1 votes
I've posted my reply to you problem in the Legal issue you created.

I'll go over how you would create an additional validation that will throw a form\_set\_error()

Create a custom module with this

```
function example_form_alter(&$form, &$form_state, $form_id) {
    if($form_id == 'user_register') {
      $form['legal']['legal_accept']['#element_validate'] = array('_example_custom_field_validate');
    }
}

function _example_custom_field_validate($element, &$form_state) {
   if (empty($element['#value'])) {
     form_error($element, t('This is my custom message if `Terms & Conditions` is not checked off.'));
   }
}

```

If you don't see the message now, I am worried that you have error messages turned off.

---
Tags: 7, users, rules
---


# Question
Title: Is transaction support enabled by default?
I happen to read through the commented lines in settings.php under the "Database settings" (around line no. 45) the following text:

> Some database engines support transactions. In order to enable transaction support for a given database, set the 'transactions' key to TRUE. To disable it, set it to FALSE.
> Note that the default value varies by driver. For MySQL, the default is FALSE since MyISAM tables do not support transactions.

My databases array, auto-generated by Drupal Installer, is the following one:

```
$databases = array(
  'default' => array(
    'default' => array(
      'database' => 'test_db',
      'username' => 'root',
      'password' => '',
      'host' => 'localhost',
      'port' => '',
      'driver' => 'mysql',
      'prefix' => '',
    ),
  ),
);

```

Is it true that my site is not transaction aware until I add a key/value, `'transaction' => TRUE` (preferably after `'prefix' => ''`) to `$databases`?

# Answer
> 2 votes
Looking at `DatabaseConnection_pgsql::__construct()`, I noticed the following code:

```
  // This driver defaults to transaction support, except if explicitly passed FALSE.
  $this->transactionSupport = !isset($connection_options['transactions']) || $connection_options['transactions'] !== FALSE;

```

The code sets `DatabaseConnection_pgsql::$transactionSupport` to `TRUE` when the connection parameters don't contain the array index "transactions," which is one you should set in your settings.php file (it's not "transaction"), or when that array index is used in the connection parameters and it is not set to `FALSE`.

The same code is contained in `DatabaseConnection_mysql::__construct()`; in this case, the connection parameters (the ones set in the settings.php file) should be set not to use transactions only when the tables used are MyISAM.

```
  // This driver defaults to transaction support, except if explicitly passed FALSE.
  $this->transactionSupport = !isset($connection_options['transactions']) || $connection_options['transactions'] !== FALSE;

```

Also DatabaseConnection\_sqlite::\__construct() contains the same code.

```
  // This driver defaults to transaction support, except if explicitly passed FALSE.
  $this->transactionSupport = $this->transactionalDDLSupport = !isset($connection_options['transactions']) || $connection_options['transactions'] !== FALSE;

```

In short, the drivers used by Drupal always set the transaction support to `TRUE`, and users should set it to `FALSE` when they are using MyISAM tables, or they don't want to enable the transaction support.

# Answer
> 0 votes
First things first, your database requires the InnoDB engine as MyISAM tables do not support transactions.

From the sounds of the README you then need to add the key to the array as you suggested above.

More information on transactions in general http://drupal.org/node/355875

---
Tags: 7, database, i18n-l10n
---


# Question
Title: What's the best way to maintain templates for standard pages and a front page?
I’m developing a new Drupal 6 theme with a custom front page. My standard `page.tpl.php` has the entire HTML structure (as it should), including the doctype, HTML head, and HTML body.

When I make `page-front.tpl.php`, though, I have to duplicate `page.tpl.php` and modify it, meaning that whenever I need to make changes to the standard page template (add Javascript, modify CSS, etc.), I have to replicate all those changes in the front page template.

What’s the best way to avoid all this duplication? What’s the best way to keep the main page structure uniform? Create a custom function that spits out the HTML head? Put everything in separate PHP files (header.php, footer.php, etc.) and include them in the two template files?

# Answer
> 3 votes
To avoid duplication, creating separate PHP files might work, but the best answer is to you do everything in your `MYTHEME_preprocess_page(&$variables)` function, in your template.php file.

```
MYTHEME_preprocess_page(&$variables) {
  if($variables['is_front']) {
    //set variables to X
  }
  else {
    //set variable to Y (or just leave them)
  }
}

```

Now you probably won't even need page-front.tpl.php

Also, if you are using page.tpl.php and/or page-front.tpl.php you do have the variable $is\_front available

# Answer
> 2 votes
Not sure exactly what you are trying to do different, but my suggestion would be to use Panels.

When you do this, your `page.tpl.php` can stay pretty generic, mainly header footer stuff, and then you can have different panel layouts for your different HTML layouts.

Another options is to do things like

```
<?php if ($is_front): ?>
  <p>I'm on the front page.</p>
<?php else: ?>
  <p>I'm not on the front page.</p>
<?php endif; ?>

```

inside `page.tpl.php`.

Also remember that the `body` normally has class on it called `front` when it is the front page, and `not-front` otherwise. This can help a lot with targeting CSS and/or jQuery.

# Answer
> 2 votes
I was doing the very same thing and after few attempts with the page-front.tpl.php method, I discovered that the best and most flexible solution for me was the front page module, where you can set several types of home page:

1. full - sets the arbitrary HTML code of the whole page, if you want it to be completely different from the theme
2. themed - sets the arbitrary HTML code just for the content, while the rest of the page will follow the active theme
3. redirect - sets a URL that replaces the home page

In full and themed types you also have an option to insert PHP code too within your HTML and enable its execution - extremely flexible!
You can also set custom home pages by roles and set temporized content for people not visiting your site for a certain period of time.
Hope it can help.

---
Tags: theming
---


# Question
Title: filter with taxonomy-term-alias instead of term-ID?
I've my view filtered by taxonomy term ID.

http://aelasoca.cat/web/

(in the main menu I've links to taxonomy ID's 3 to 8). How can I filter with the taxonomy term alias instead of it's ID ??

(not sure if it's the same issue as in: Views, Taxonomy, Block and Context... What am I doing wrong? )

# Answer
1. Create a new Taxonomy:Term ID contextual filter.
2. Under the form "When the filter value IS in the URL..." select the option "Specify validation criteria".
3. Select "Taxonomy Term" as the validator.
4. Select which of your vocabularies you'd like to use.
5. Under "Filter Value Type" select "Term name converted to term ID".

That should do it. If you have multiple-word taxonomy terms, you should allow the contextual filter to convert dashes in the URL into spaces for the term name. If you have unusual characters in your taxonomy terms, see this post for tips.
> 24 votes

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


# Question
Title: page-new.tpl.php shows page not found in browser title
The page displays fine, however; the browser tile shows `Page Not Found | main title of site`.

How can I apply a proper title to this custom page when another page controls the header ?

# Answer
This will set the title in the actual browser window:

```
function MYTHEME_preprocess_page(&$variables) {
  drupal_set_title(t('Custom title'));
}

```
> 1 votes

# Answer
Inside your template.php

```
MYTHEME_preprocess_page(&$variables) {
  $variables['title'] = t('custom title')
}

```

use the `t` function for translation
> 0 votes

---
Tags: theming
---


# Question
Title: which version is this cache_set function belong to?
The function I have commented out is in Drupal 5.x and I've seen a lot. I want to know which Drupal version the function I haven't commented out belongs. This is the function that I have seen on the site that I am working on. I am about to replace the site by Pressflow. But I met some problem with cache\_set function. Serialized seems a new column and this function is so different. So I really don't know which version of Pressflow in 5.x that I can use for my site...

```
/*
function cache_set($cid, $table = 'cache', $data, $expire = CACHE_PERMANENT, $headers = NULL) {
  $created = time();
  db_query("UPDATE {". $table. "} SET data = %b, created = %d, expire = %d, headers = '%s' WHERE cid = '%s'", $data, $created, $expire, $headers, $cid);
  if (!db_affected_rows()) {
   print_r($data);
    db_query("INSERT INTO {". $table. "} (cid, data, created, expire, headers) VALUES ('%s', %b, %d, %d, '%s')", $cid, $data, $created, $expire, $headers);
  }
   //mysql_query("INSERT INTO tbj_cache_views (cid, data,created, expire,headers) VALUES ('aaa', 'adsfadfasdfdffa', ".$created.", ".$expire.", NULL)");
}
*/
function cache_set($cid, $table = 'cache', $data, $expire = CACHE_PERMANENT, $headers = NULL) {
  $serialized = 0;
  if (is_object($data) || is_array($data)) {
    $data = serialize($data);
    $serialized = 1;
  }
  db_lock_table($table);
  db_query("UPDATE {". $table ."} SET data = %b, created = %d, expire = %d, headers = '%s', serialized = %d WHERE cid = '%s'", $data, time(), $expire, $headers, $serialized, $cid);
  if (!db_affected_rows()) {
    @db_query("INSERT INTO {". $table ."} (cid, data, created, expire, headers, serialized) VALUES ('%s', %b, %d, %d, '%s', %d)", $cid, $data, time(), $expire, $headers, $serialized);
  }
  db_unlock_tables();
}

```

# Answer
That looks like the D6 cache\_set().

Pressflow versions are API compatible with the Drupal versions. So if your site is D5, you should use Pressflow 5.

Mixing up Drupal 5 and Drupal 6 code is a recipe for disaster. So if you are doing this stop. Pressflow 5 cache.inc includes this...

```
function cache_set($cid, $table = 'cache', $data, $expire = CACHE_PERMANENT, $headers = array()) {
  $headers = serialize($headers);
  $created = $_SERVER['REQUEST_TIME'];
  db_query("UPDATE {". $table. "} SET data = %b, created = %d, expire = %d, headers = '%s' WHERE cid = '%s'", $data, $created, $expire, $headers, $cid);
  if (!db_affected_rows()) {
    @db_query("INSERT INTO {". $table. "} (cid, data, created, expire, headers) VALUES ('%s', %b, %d, %d, '%s')", $cid, $data, $created, $expire, $headers);
  }
}

```

This is probably what you should use.
> 2 votes

---
Tags: caching
---


# Question
Title: Indexing all pages of a website in Google
I use Google CSE on my website, which contains upwards of 5000 stories. Naturally, I would like all of this content to be indexed in Google. Many of these stories will not be linked elsewhere on the site... can they still find their way into Google's search index?

Thanks!

# Answer
The XML sitemap module will generate a file which can be submitted to google, and other search engines to tell them about all of your content.
> 4 votes

---
Tags: 6
---


# Question
Title: Hide body on node edit if user can't access input format
The default behaviour is that a user can't edit a node when they don't have access to its current input format, even if they do have the edit content type permission. I'd like to just hide the body field in those situations. Does anyone know of a contrib that does that? (I'm only interested in the body field, but a more general solution would be cool too.)

# Answer
You could do it, but it would require some work.

1. Use hook\_menu\_alter to change the access function used for node edits
2. Create your own access function that is similar to core's access control, but allow users that doesn't have the filter permission to edit the node.
3. Use hook\_form\_alter to hide the body field if the user can't use the selected filter
4. You're done.

You have to be very careful about doing this, as if this isn't done right, it could potentially open for security holes.
> 1 votes

# Answer
Not really an answer, but there is AFAIK no way to change this without hacking core.

The check for this is directly in node\_access() and can't be altered.

What you are trying to do is btw how it works in Drupal 7, see the corresponding issue.
> 2 votes

# Answer
In the end I didn't create a custom edit function, I followed googletorp's idea while trying to mitigate against the issues Berdir described. In case anyone's interested there's a module here.
> 0 votes

# Answer
You can use content permission in CCK.
> 0 votes

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


# Question
Title: ubercart invoice generation to allow user to request funds withdrawal
I have a site where user purchases some service and once the service is received by the purchased person, i should allow the service provider to raise a invoice order to request funds.

what are the modules that i should use to achieve this

# Answer
If you are implementing the "service" as part of your site, you can attach the "services" to the user by assigning permissions to the "service" to a role, then create a content type, enable it as product and attach a "feature" to a product to enable the role for a limited amount of time (if this is your business model).

This would use CCK (to define the product) + Ubercart (for setting up the shop and attaching Product + feature to product) as well as Permissions (to your "service") and Roles (to apply to the permissions).

I hope this has been of some help!
> 1 votes

---
Tags: 6, ubercart, commerce
---


title: Form API to Database

text:
# Question
Title: Form API to Database
I have been reading Form API Quickstart Guide. I understand how it all works, but I don't understand how to save the data entered into the forms into my own database Drupal style. Or am I supposed to use good old standard PHP to connect to the database to insert the data as required?

Is there a similar page to the form API quickstart page showing how to integrate a module with a database?

# Answer
> 4 votes
Connecting to the database and writing your own SQL, outside of the Drupal framework, while possible will put you in the dark ages. Drupal handles a lot of the heavy lifting and abstraction for you. If you are used to writing your own PHP to do DB queries it can be tempting to go with what you know. but in the cases where you need to use custom queries use the Drupal DB API like Berdir suggested.

However often there are ways to use forms, without having to write your own database methods. Depending on what you want to do with the data there are several options.

Webform may be what you are after. Which will allow you to create custom forms with simple data management at the back end. Again fairly simple to implement but in this case you won't have the overhead of new nodes and the data is easily exportable.

In both of these cases you can use hook\_form\_alter to customize the form if you wish.

# Answer
> 3 votes
Yes, there is, see Database abstraction layer.

In short, Drupal 6 provides a simple database abstraction (much better in D7), but apart from that you have to use standard SQL, with a few specialities like wrapping table names in curly braces.

You could also check out drupal\_write\_record(), which allows to save a single record in a table.

# Answer
> 1 votes
If you do need to manually update a table, the Form Example and Database Example in the Examples Project will get you going.

---
Tags: 7, forms
---


# Question
Title: Existing module for logged in user image upload
I'm looking to build an image upload website. The only feature needed is the ability for logged in users to upload images.

Is there an existing module for this?

I could just build a custom module for a form; but i wanted to find a decent module to build this before investing time into it.

Required:

* Image upload restricted by user role
* Each Image upload becomes either node

Some wants:

* Image cropping

# Answer
You can make that in different ways, you can use the media module to create image galleries, remember if you use that module installing Styles
> 0 votes

---
Tags: 7, media, files
---


# Question
Title: How to change the duration of user access?
By default Drupal keeps users logged in 2.000000 seconds, i modify in settings.php at the line:

```
ini_set('session_cookie_lifetime',2000000);

```

It is right ?

# Answer
Yes. You are correct. Changing these settings will change the session time for logged in users.
> 1 votes

---
Tags: 7, cookies
---


# Question
Title: Limiting table rows viewed in CCK Table Field
I'm using Drupal 6. The node has been created with 10 rows.

I'm looking for ways to make the table content viewed on the front page with 5 rows, where it has "more" link to the full node.

It can be PHP code to be placed in the block, or any other ways. Any suggestion are welcome including modification on other modules.

# Answer
You need to focus on node template.
Override or create a tpl of your content type e.g. `node-type.tpl.php`
User $node object to access all your cck fields.

Also care about `$teaser` and `$page` flags to get the state of your node.

If $teaser is true then render 5 items from $node object. If $page is true then render all your items.
> 1 votes

---
Tags: entities, theming
---


title: Override theme_node_preview

text:
# Question
Title: Override theme_node_preview
I'm using a custom theme but **Seven** as administration theme.

How can I override the theme function '`theme_node_preview`'?

Notice that `theme_node_preview` is called in the node form, and it's shown in an overlay. So it's part of the admnistration theme.

* I tried to used the generic `phptemplate_` prefix but this way of overriding theme functions was removed for Drupal 7.
* I tried `seven_node_preview` from a module and also from the `template.tpl.php` of my custom theme, but didn't work.
* I don't want to create a subtheme of Seven only for this.

# Answer
> 5 votes
I know you explicitly stated that you don't want to create a subtheme of Seven, however short of hacking the core Seven theme or messing with the theme registry (which I explain below against my better judgement) this is the simplest way to accomplish what you are trying to do. The amount of overhead to do this is incredibly small and requires only three files. Simply create a folder named something like "mytheme" and add an empty "mytheme.css" file in addition to a "mytheme.info" file with the following code:

```
name = My Theme
description = Custom subtheme of Seven.
core = 7.x
base theme = seven
stylesheets[all][] = mytheme.css

```

Then add a template.php file and override the theme hook similar to below:

```
function mytheme_node_preview($variables) {
  // Do custom stuff here.
}

```

All done. This is the "Drupal way" of doing theme hook overrides.

Again, it is against my better judgement to post the code below. If you absolutely have your mind set on not creating a subtheme, you can implement hook\_theme\_registry\_alter(). Did I mention that this solution is hacky and the hook is pure evil? :-) In a custom module named "mymodule", do the following:

```
function mymodule_theme_registry_alter(&$registry) {
  $path = drupal_get_path('module', 'mymodule');
  $registry['node_preview']['file'] = 'mymodule.module';
  $registry['node_preview']['theme path'] = $path;
  $registry['node_preview']['function'] = 'mymodule_node_preview';
  $registry['node_preview']['includes'] = array(
    $path . '/mymodule.module'
  );
}

function mymodule_node_preview($variables) {
  // Do whatever you need to do here.
}

```

Use the snippet above at your own risk.

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


title: How to embed two views into a block

text:
# Question
Title: How to embed two views into a block
I have two views that are block displays. I'm trying to embed these views in a block. When I include the block nothing is displayed. If i add "test" to $block\['content'\] it displays test in the block body.

Here is my code ($gid is an organic group id as an argument to the block):

```
  case 5: // Create Mugshot block
    $viewName = 'display_most_wanted';
    $display_id1 = 'block_1';
    $args = array($gid);
    $wanted = views_embed_view($viewName, $display_id1, $args);

    $display_id2 = 'block_2';
    $convicted = views_embed_view($viewName, $display_id2, $args);

    $block['subject'] = 'CWPA OG Mugshots';
    $block['content'] = $wanted . $convicted;
    break;

  default:
    // Throw an error
    break;
}

return $block;

```

# Answer
> 2 votes
Your problem is the arguments are not getting passed properly

```
function views_embed_view($name, $display_id = 'default') {
  $args = func_get_args();
  array_shift($args); // remove $name
  if (count($args)) {
    array_shift($args); // remove $display_id
  }

  $view = views_get_view($name);
  if (!$view || !$view->access($display_id)) {
    return;
  }

  return $view->preview($display_id, $args);
}

```

So you want `$wanted = views_embed_view($viewName, $display_id1, $args[0], $args[1], $args[etc]);`

Also from the Creator of Views

> You either want:
>
> views\_embed\_view('viewname', 'page\_1', 1, 2, 3)
>
> or
>
> views\_embed\_view('viewname', 'page\_1', '1+2+3')
>
> depending on if you have a single argument expecting multiple nids or multiple arguments each expecting a single nid.

# Answer
> 3 votes
It seems like instead of rendering the views programmatically you could also leverage the Views "Attachment" display . The allows you to attach a view to another display, in other words render one view after another. The "block\_1" display of the view you posted above would be the main view displayed as a block, and then you would change the "block\_2" display to an attachment and configure the settings similar to the image below.

This would eliminate the need to create custom code to display both views in a block.

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


# Question
Title: Adding autocomplete to title field of node form
I created a small custom module to help users while creating a specific content type. Basically the module just adds the autocomplete feature to the title field to show possible duplicate nodes to the user while filling out the form for "on-the-fly" feedback.

The problem is that the autocomplete only works for users with the permission 'Administer nodes'. Is this normal or am I doing something wrong? If it is normal, is there another way to achieve these results without handing out that permission?

Custom module:

```
<?php
/**
 * Implementation of hook_menu()
 */
function duplicates_menu() {
  $items = array();
  $items['duplicates/check'] = array(
    'title' => 'Check for duplicates',
    'page callback' => 'duplicates_check',
    'access callback' => TRUE,
    'type' => MENU_CALLBACK,
  );
  return $items;
}

/**
 * Implementation of hook_form_alter()
 */
function duplicates_form_alter(&$form, $form_state, $form_id) {
  if ($form_id == 'company_node_form') {
    $form['title']['#autocomplete_path'] = 'duplicates/check';
  }
}

/**
 * Check for duplicates
 */
function duplicates_check($check) {
  $duplicates = array();
  if ($check) {
    $results = db_query('SELECT title FROM {node} WHERE type = "company" AND LOWER(title) LIKE LOWER("%%%s%%")', $check);
    while ($dupes = db_fetch_object($results)) {
      $duplicates[$dupes->title] = check_plain($dupes->title);
    }
  }
  print drupal_json($duplicates);
}

```

# Answer
Avoid a custom implementation and use the Unique Field Module. Once this module is enabled, it adds a 'Unique field settings' section to each content type's administration page for specifying which fields (Including node title) for that content type must be unique.The administrator may choose whether the fields must be unique among all other nodes, among nodes of the same content type, or of the same language. You can also set it to display the nodes that match the title.
> 2 votes

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


# Question
Title: How to translate blocks content (created with views module) in drupal 6?
I created blocks with views, my question is this: When you select a language, even the block content ( created with views )applies to me translated ?

# Answer
You can add a filter to your view, under the `Node translation` group that will make your view filter out nodes that don't belong in the default or current language.

**Edit** You may need the i18n views module to see some of the options in the screenshot.
> 2 votes

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


# Question
Title: Where does Feeds cache the source and how do I disable this cache feature?
I've found out that Feeds caches the sources. Even when I change the content of the source, emptying the imported items and reimport, it imports the old items.

Where does Feeds store this cache and how do I disable this cache feature?

I need to disable this caching feature because I am dealing with sources which change often.

# Answer
I've posted this issue on Drupal before. Basically it's a problem that they are working on.

http://drupal.org/node/1156062
> 1 votes

---
Tags: feeds
---


# Question
Title: share field template between node display and views
Is there an easy way to share the same field template for both node display and views output?

Perhaps this requires a template.php template\_files candidate addition?

# Answer
Might have to do this: CCK Formatters, hoping there may be an easier way. Here is a quote about CCK Formatters (from the module's project page):

> This package is a collection of add-on formatters for various CCK fields. Each provided sub-module in this package should be a self-contained single formatter.
>
> CCK fields support an arbitrary number of "formatters", swappable code that renders a field. In Drupal 6 these are essentially theme functions, although in Drupal 5 they are not always. It is possible for any module to define new formatters for field types it doesn't define itself, which creates a very powerful way to extend and theme a field in any of the myriad ways that a field can appear.
>
> This module is an "incubator" for new field formatters. Because each formatter may have its own development cycle, there will probably not be stable releases of the entire suite. If a specific formatter gets particularly popular or requires a more full-featured release cycle, it should likely be spun off to its own project.
> 1 votes

---
Tags: entities, theming
---


# Question
Title: Smart paging rendering pager different from the Devel model
I am on Drupal 7 and I have the Smart Paging module enabled. When theming my module, I want the page numbers to appear as regular links. This seems to be the natural behavior. Here is the HTML available on the Devel module on the render section for \[smart\_paging\]:

```
<div class="smart-paging-pager">
    <h2 class="element-invisible">Páginas</h2>
    <div class="item-list">
        <ul class="pager">
            <li class="pager-current first">1</li>
            <li class="pager-item"><a href="/node/178/devel/render/pagina/0/1" title="Ir para a página 2" class="active">2</a></li>
            <li class="pager-item"><a href="/node/178/devel/render/pagina/0/2" title="Ir para a página 3" class="active">3</a></li>
            <li class="pager-next"><a href="/node/178/devel/render/pagina/0/1" title="Ir para a próxima página" class="active">próx ›</a></li>
            <li class="pager-last last"><a href="/node/178/devel/render/pagina/0/2" title="Ir para a última página" class="active">fim »</a></li>
        </ul>
    </div>
</div>

```

The problem is that the links to the pages 1, 2, 3... are being replaced with a select list box with the options Page 1, Page 2, Page 3. I don't know how to change that behavior and make the links render as... links, exactly the way the HTML is showing.

I am using the Omega theme and I know it is not the theme replacing my pager because if I switch to another theme, the same change is applied to the pager... Do you know where I can configure the pager display? Do I have to go to template.php? Thank you.

# Answer
I found the solution: go to the Smart Paging settings page and uncheck "Use javascript pager as progressive enhancement for Drupal native pager"... as simple as that...
> 1 votes

---
Tags: paging, theming
---


# Question
Title: View: taxonomy_term, additional display of type page
I have two main content types with different vocabularies for tagging them.

I have enabled default Drupal view, "taxonomy\_term".

I need two different displays: unformatted for content type A and table for content type B.

Content type A works ok, because it is using the default page display of this view.

I created another page display in this view with a filter to the proper vocabulary and node type.

Path is the same: taxonomy/term/%

But I am getting "Page not found" for taxonomy terms for content type B.

Could somebody help?

# Answer
You can only have one page display on a particular path.

If you want to display two views on one url there are a number of ways you can do it.

Have one display page as you have, then have the second view as an attached view.

Or

Display the second view as a block and use context to display it on the same url
> 2 votes

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


# Question
Title: Individual CCK Imagefield promote-to-front
At the moment, my view creates a gallery of images by fetching all images across multiple node types. What I need is a way to indicate which images should be used in the gallery. So, instead of my view simply displaying all images, I want the client to indicate which image they want to "promote" to the gallery.

Can anyone help please?

# Answer
> 1 votes
Here is another option, that will work for sure. May need to do a bit of reconfiguring with your current imagefields.

* Download latest version of CCK 3.x.
* Install multigroups module (currently this module is stable)

On the selected content type:

* Add on/off checkbox featured field (set limit to 1)
* Add Image field (set limit to 1)
* Encapsulate theses 2 fields in a multigroup (set limit to unlimited)
* Create view that will filter on featured field

# Answer
> 1 votes
So, in my example scenario, I needed to indicate which individual image(s) are to be part of my gallery.

My node/1 contains a cck imagefield with unlimited uploads and currently holds 5 images. Of those 5, I want 2 of the images to be part of a gallery on a seperate page.

So, in the global settings of cck imagefield configuration, there is the 'list field' area with 2 radio button options. By default it is set to 'disabled'. I enabled it. Now, in the node there will be a check box next to each one of the image uploads. I check the images I want in my gallery.

In the view that generates my gallery, in the filter area, each imagefield exposes a 'list' option for your cck imagefields. It's options are 'true' of 'false'. I make sure it is set to true.

This way I now how granular control over my image displays.

I trust that will help someone out there!

# Answer
> 0 votes
Probably you have to add checkbox field to all content types for indicate image to promote.

# Answer
> 0 votes
You have 2 options

Option 1: In your view, you add a filter for

```
Node: Promoted to front page
Whether or not the node is promoted to the front page.

```

Set value is 1. Now all nodes promoted to the front page will be in the gallery

Option 2: You create a cck field that is a single on/off checkbox. Featured Image Go back to your view and add a filter for this new cck field.

---
Tags: views, media
---


# Question
Title: Create a vocabulary with terms that are linked to a content type
I need to create a vocabulary with this "twist": the taxonomy terms of the vocabulary are the titles of the article based on a specific content type.

This means that if I create, modify, or delete an article based on the content-type "vocabulary," the relative term in the vocabulary should be added, modified, or deleted.

Imagine I have the content type "Cars." I create different articles, one of which is "Ferrari 456", and another one is "Volkswagen Golf." I want a vocabulary called "cars" with a term for each article (e.g., one for "Ferrari 456", one for "Volkswagen Golf").

# Answer
* When you are creating a new node, you call taxonomy\_term\_save(), passing as argument the taxonomy term object `$term`, and using the node title for set `$term->name`, and the vocabulary ID to set `$term->vid`.
* When you update a node, you first you load the taxonomy term with taxonomy\_term\_load\_multiple(), as in `taxonomy_term_load_multiple(array(), array('name' => trim($name), 'vid' => $vid))`, change `$term->name`, and save the taxonomy term with `taxonomy_term_save()`.
* When you delete a node, you first load the taxonomy term with `taxonomy_term_load_multiple(array(), array('name' => trim($name), 'vid' => $vid))`, and then delete it passing `$term->tid` to taxonomy\_term\_delete().

The functions I reported needs to use the vocabulary ID; this means that the module you are writing needs to save in a Drupal variable the ID of the vocabulary it created, or to ask to the user the vocabulary name for the vocabulary that needs to be used. In the second case, and in the case the module stores the vocabulary name, code similar to the following one should be used to get the vocabulary ID:

```
$vocabulary = taxonomy_vocabulary_load_multiple(array(), array('name' => trim($name)));
$vocabulary = reset($vocabulary);
$vid = $vocabulary->vid;

```

The code needs to be changed for Drupal 8, as the conditions (the second parameter of `taxonomy_term_load_multiple()`, and `taxonomy_vocabulary_load_multiple()`) will be removed in Drupal 8.
> 0 votes

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


# Question
Title: Theme Views exposed filters, how to add count?
For example in the case of filtering by taxonomy terms, I would like to add the node count next to each term in the exposed filter block. Already using Better Exposed Filters module as it allows to use checkboxes instead of select list.

Is there a way to do this? I can make a nice list of the terms with node counts using aggregation, but I can't think of an easy way to use ajax that way. :-)

# Answer
What you are asking for is what is called faceted search.

If you want to have this feature you should think about using a search database that supports this, like Apache Solr. The problem is that it otherwise is going to be very heavy and complex to make, especially with views making the query for you. If you were to make this feature yourself with MySQL, it would probably be easier to code the entire page yourself, and add the facets for the terms in your custom form.

In Drupal 7 the search api module comes with support for Apache Solr and can do facets on both MySQL and Solr. It also have views integration.

For Drupal 6, you can use the Apache Solr Search integration module, which creates an API integration with Solr, making it easier to create facets with Solr. Use this would probably require that you custom made the entire form.
> 6 votes

---
Tags: ajax, views
---


# Question
Title: What can I do to improve the size of csv file that can successfully be imported via Feeds and Commerce Feeds
I am using Feeds and Commerce Feeds to import product lists into my Drupal Commerce store. I'm finding I have to keep the csv files really small for the import to succeed? As soon as the file is too big (the exact threshold size does not seem to be consistent) the system generates a 403 error as follows:

```
An AJAX HTTP error occurred. HTTP Result Code: 403 Debugging information follows. Path: /batch?id=260&op=do StatusText: Forbidden ResponseText: Access denied

```

The file that resulted in this error was 577kB.

The only way around the problem is to have multiple csv files. These all have to be maintained and updated individually, which is very inefficient.

What can I do to improve this state of affairs?

# Answer
The `403` HTTP code translates to access denied, which doesn't points to a problem in the size of the CSV file. Since it's using the batch API, which splits up the job in smaller chunks, it doesn't look like that it is the size of the file that is the problem. You should investigate the watchdog (dblog) and see if you can find the root cause.

This is the best answer I can provide with this limited information.
> 2 votes

---
Tags: feeds, commerce
---


title: Custom Testimonial page

text:
# Question
Title: Custom Testimonial page
I need to make a testimonial page, which include 3 parts.

1. text on the above
2. video testimonial which have the owner name and his image
3. text testimonial which have the owner name and his image

I am new at Drupal and using Drupal 7 for start things.

I made 2 content types, first for video testimonials the second for text testimonials

Now I am confused how i will proceed to plan things up.

Thank you for the help in advance

# Answer
> 1 votes
You can do this in many ways. But i suggest that you do it with panels.

In this video tutorial you can see exactly how you can do what you asked for.

You can spice up your testimonial page by adding views displaying random testimonials.

---
Tags: views
---


# Question
Title: How can I customize the node/add form for a content type?
How can I add some help text above the form used to create a node of a specific content type? What is the best way to do it in Drupal 7?

# Answer
Just throw a custom block in there with your instructions and set to display on /node/add/get-a-quote (Keep it simple)
> 2 votes

# Answer
On the content type edit/creation page there is a field labeled **Explanation or submission guidelines** with a help text of:

> This text will be displayed at the top of the page when creating or editing content of this type.

Simply put your instructions for the content type form in that field and save your changes.

Example:
> 6 votes

---
Tags: nodes
---


title: Sync free tagging vocabulary

text:
# Question
Title: Sync free tagging vocabulary
I've a content type article, where user can create new terms to a vocabulary through free-tagging for example content, color and so on . When the user creates a new content, he can add new terms to the categories. Now I'd like to provide the new created terms also to be available in my forum vocabulary, so user can discuss about this terms in the forum. I've assigned the vocabulary to my article and to my forum. But that alone does not work the way, I'd like to. In the meanwhile I'm using the Taxonomy Manager for just copying the terms from the 'article' vocabulary to the 'forum' vocabulary. But that's not the best solution for me, cause I've to manually do this for every added term. It would be great, if this could happened 'on the fly', some kind of automatically.
Can anybody please help me to get this working? Please also let me know, if the problem is not getting clear to you. Thanx for your suggestions.

# Answer
1. Assign the same vocab to both content types.
2. Install the Tagging module
3. Now the fields should have auto suggest for the fields, as the user types
> 1 votes

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


# Question
Title: What css framework is better between 960gs and Blueprint?
For a new project what is better for drupal between Blueprint and 960gs? I usually prefer 960gs, but for you?

# Answer
I haven't used 960gs, but used to use Blueprint. Blueprint worked fine if I was always making 960px width templates. But, now I veer away from those CSS sizers. They're too constricted in what you can accomplish. Also, I always prefer to size the CSS with a min-width:960px and max-width:1200px. So many of the screen res. are 15" and 17" now. You can't really accomplish much beyond the scope of 960px with Blueprint and, I'm assuming, 960gs.
> 1 votes

---
Tags: theming
---


title: views... two random nodes to vote on

text:
# Question
Title: views... two random nodes to vote on
I'm trying to use views to show two random nodes for voting on. I would use something like: filter: Node:terms(with depth), fields:Node body/ title, Sort criteria:GLOBAL:random. Now, how can I render two random nodes for voting? Would I have to render them on a custom page-"newpage".tpl.php? I'm thinking if I used a custom template I would make two 50% regions, have them float left/right, have one height:150px region footer for the voting(below the nodes), then maybe use "popups" so it looks cleaner? Any ideas on this? For starters, I'm not sure how I would generate "2" random nodes and have them render in the appropriate "left/right region". Thank you.

# Answer
Just create them as blocks and place them on a static page together in any region you wish. (Keep it simple)
> 1 votes

---
Tags: views, 6
---


# Question
Title: Using hierarchical select to display a particular section of content
I have a content type called "Results" that displays the results of a particular game. I am using the Hierarchical select module for my taxonomy terms that include Year, Game and League.

My goal is to create a view that only displays a Result content type that matches the terms selected in the exposed Hierarchical Select module. I currently have the view working, but it is displaying all the Results content type.

# Answer
> 1 votes
As far as drupal 6 views 6.x is concerned. You need to ensure you are saving the taxonomy heirarchy as additional terms in the database. Ensure also you are saving the entire lineage from the view. Finally Add a filter with Taxonomy: Term ID and leave this using default values.

(1) Ensuring you are saving the taxonomy heirarchy as additional terms:

-edit your "Results" content type, go to manage fields and edit the heirarchical field. Somewhere on this page you will see 'Save values additionally to the core taxonomy system (into the 'term\_node' table).'

(2) Ensure you are saving the entire lineage:

-on the same page as above follow the link to oonfigure this heirarchical select on a separate window.. 'Due to limitations of CCK, there is a separate form to configure this Hierarchical Select widget's settings'

(3) Go back to views and add that filter I mentioned above.

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


title: Customizing custom modules

text:
# Question
Title: Customizing custom modules
We are planning to implement custom features (in the form of newly developed modules) on top of a standard Drupal7 installation. This "standard" Drupal installation may include some contribution modules such as organic groups. This extended Drupal installation will be provided to different clients each of which may require custom theming and some (minor) customisation of the custom features mentioned above.

What I am wondering about is the deployment and code maintenance architecture. Coming from an object oriented background my initial reaction was to propose a layered architecture along these lines:

```
------------------------
Client Customization Modules
----^ ^ ^ ^ ^ ^ ^ ^-----
Generic Self-created Modules
----^ ^ ^ ^ ^ ^ ^ ^-----
  Contribution Modules
----^ ^ ^ ^ ^ ^ ^ ^-----
      Drupal Core
------------------------

```

Meaning the custom main extension modules ("Self-created Modules") would be overwritten/overloaded wherever the respective client requires individual changes using a second custom layer of "Client Customization Modules". From my point of view this is benefitial as it allows for the generic "Self-created Modules" to remain identical for all clients so bugfixes can easily be performed on a single, central svn location.

Now a colleague argued heavly against such an approach, saying having a 4th module layer which basically overwrites hooks of the 3rd layer would be extremely bad practice in Drupal development as it raises the application complexity and makes debugging virtually impossible.

The alternative would be to create redundant copies of the "Generic Self-created Modules" layer for each client and directly customize these instances. While this is surely possible, a bugfix or change to the generic functionality would then not be possible anymore in a central location, so this approach seems quite dirty to me.

Is it really considered bad practice, or heavily advised against, to customize ones own custom modules by "hooking custom hooks" in a way proposed above?

# Answer
> 2 votes
In Drupal, most of the customization is not done by overriding existing code but rather by extension or alteration. Most contribution modules and Drupal core provides extension points (hooks) and configuration variables. Your custom modules (*self-created* and *client customization*) should re-use these hooks and configurations.

For your *self-created* modules, you can use the Features module to easily export *configurations* into code. To customize your features at the *client customization* level, you can choice to either use alteration hooks or to re-write part of the Features-generated code to make it customizable via in-DB configuration. See http://developmentseed.org/blog/2009/jul/09/development-staging-production-workflow-problem-drupal and http://www.archive.org/details/CodeDrivenDevelopmentUsingFeaturesEffectivelyInDrupal6And7 for more information on the Features module. Also, the Kit Specification provides information on how to build re-usable features modules (with Features)., see also http://funnymonkey.com/building-features-for-install-profiles and http://nodeone.se/blogg/an-alternative-way-of-structuring-features-for-distributions.

# Answer
> 0 votes
It should be fine, but do your performance tests, of course.

How extensive are those customizations? Can you use Drupal variables or database tables to control your layer 3 behaviours?

If you can get away with mostly the same module codebase for the different sites, you can use a multisite setup to simplify maintaining the codebase for those sites while allowing site-specific modules for sites that need more extensive customizations.

---
Tags: 7
---


title: How to enable "Menu primary tabs"?

text:
# Question
Title: How to enable "Menu primary tabs"?
I want to enable Menu Primary tabs in my site, but I can't find how to enable them. Any suggestions please?

# Answer
1. Under Menus \> Primary Links \> (select items to enable by checking the menu items)
2. Check to ensure primary links are specified in the blocks by visiting 'Blocks' configuration.

Is this what you're looking for?
> 1 votes

---
Tags: routes
---


title: Change Template for a Content

text:
# Question
Title: Change Template for a Content
I'm using Drupal (version 7) for the first time and I have two content types, Landing Page and Article Page, each with their own templates page--landing\_page.tpl.php and article\_page.tpl.php respectively. The only reason I have two content types is because each content type needs to be displayed differently on the website.

I have several contents of the type Landing Page which I would like to display with the page--article\_page.tpl.php template. So now I have the troublesome task of manually converting each of these content types to Article Page.

Is there a more effective way for a user to select the template he wants to use for a content instead of changing content types?

# Answer
I ended up using "template suggestions" feature of drupal 7. Now I only have one content type called Article Page. I added a custom field to it called `field_template`, which takes the name of the template i want to use not including the `page--` prefix and not including the `.tpl.php` suffix. So if field\_template has the value 'landingpage', then the template will be 'page--landingpage.tpl.php';

Then in my `~/sites/all/themes/THEMENAME/template.php` file, I wrote the following function

```
function THEMENAME_process_page(&$variables) {
  if (array_key_exists('node', $variables))
  {
        if($variables['node']->field_template['en'][0]['value'])
        {
        $variables['theme_hook_suggestions'] = array('page__'.$variables['node']->field_template['en'][0]['value']);
        }
        else
        $variables['theme_hook_suggestions'][] = 'page__'. $variables['node']->type;
  }
}

```

Replace THEMENAME with the name of your theme.
> 1 votes

---
Tags: theming
---


title: Displaying the filefield file's size

text:
# Question
Title: Displaying the filefield file's size
How can I get the filesize (eg, 2.12 MB) of a FileField upload?

I tried this from a views row template but I get an error message (*function.filesize\]: stat failed for ..filename..*):

```
// this correctly gets the result
// /sites/example.com/files/CIRS_manual_test.pdf
$file_field = '/' . $field->original_value;
print "<a href='" . $file_field . '">Download chapter as pdf: ';
print filesize($file_field) . '</a>';

```

I've tried using the full path /www/..., but get the same error message. I know the path is right because I'm able to load it in my browser.

# Answer
> 5 votes
Are you talking about getting the actual filesize or just formatting the size?

If the first, you can add a relationship to the `{files}` table in your view so that you can pull in the `filesize` column. IIRC, you add a relationship to the fid and then you will see File: Size in the fields. This will not work, though, if you manually overwrite the files via SFTP, etc.

You are getting the error because of the difference between the web path and the actual filesystem path.

# Answer
> 3 votes
Drupal has an API function for that: `format_size`

---
Tags: views, 6, files
---


title: Register Page Themeing

text:
# Question
Title: Register Page Themeing
I just found out the template for themeing the register page is **page-user-register.tpl.php**.

But, how do I change the labels on the textfields etc?

For instance, I want to rename the **E-Mail** label to ... somethingelse :-)

# Answer
Here is a good tutorial to change all the user pages. http://drupal.org/node/350634. For E-Mail edit the $variable\['form'\]\['x'\]
> 3 votes

# Answer
Another route to take: Use the code below in the template.php file of your theme. Be sure to change "YOURTHEME" to the name of your theme. If `YOURTHEME_theme()` already exists you need to add to the returned array. Change "Something Else" to whatever you want the label to be and **clear the cache** or you won't see the changes.

```
function YOURTHEME_theme($existing, $type, $theme, $path) {
  return array(
    'user_register' => array(
      'arguments' => array('form' = NULL),
    ),
  );
}

function YOURTHEME_user_register($form) {
  $form['mail']['#title'] = t('Something Else');

  return drupal_render($form);
}

```
> 1 votes

---
Tags: theming, users
---


# Question
Title: Recover the field from one Drupal page to another
What I want to do is recovering the avatar picture the Avatar Selection module generates, and present it elsewhere in my Drupal installation, specifically in pages where it is not appearing.

I have been referred to the `dsm()` function, but not being a programmer, I am utterly lost with this. I haven't got a clue.
I know that I need to know the field's name, where the picture is showing and then I can render it, but while I know all this, I have no clue as how to do it or if this is all I need.

I haven't found (or haven't understood) any `dsm()` tutorials out there.

# Answer
> 2 votes
First off, `dsm()`. You have to install a devel module. In you code if you do `dsm($user)` then it would show you a nice user interface of the $user object/array

The location to the user picture (or avatar) is in your $user-\>picture object. If $user array is not available, then you can do `global $user;`

---
Tags: 6, nodes
---


title: Theme for mobile devices

text:
# Question
Title: Theme for mobile devices
I want parts of my site to be accessible to Android, iPhone and other mobile platforms. Is there a particular theme I should start with, or anything I should look for in a theme besides it being clean and simple? Would I be better off creating a theme from scratch?

# Answer
The Omega theme is a grid based theme that will allow the developer to use a shared CSS file and three different CSS files for different screen resolutions. This way the same site can be served to different devices without having to do a ton of work to make it look nice on all of them.
> 4 votes

# Answer
Honestly, iPhone and Android devices don't need special mobile sites, they just need a bit of thought put into the layout, and that was what I assume you're after judging from your question.

If you really want a specific theme for mobile devices then I'd recommend just starting with one of the many Drupal base themes, and trying to keep it simple. Keep it 1 column, avoid `position:fixed` like the plague because the iPhone doesn't do it. Avoid `:hover` wherever you can for the same reason.

These sites that are designed to look like apps are more often than not annoying, especially if mobile devices are automatically redirected. You'd be much better off directing your time into something like Responsive Web Design, so your mobile visitors get the same content with a better layout.
> 3 votes

# Answer
For themes, as well as iUI, there's Nokia Mobile and the simplistic Mobile.
Use this module to set a mobile theme (i.e. only used by mobile devices): Mobile Theme.
> 2 votes

# Answer
Definitely agree with Paul Jones, these mobile devices don't need special mobile sites. I think that your website and all your content should be available as well on mobile devices as on desktop. It also seems a lot of overhead, creating and maintaining seperate themes.

A better solution would be an adaptive theme that doesn't scale to specific devices like some modules or themes do, but that adapts to screen sizes, with things like media queries, flexible grids and flexible layouts.

Something like this: http://drupal.org/sandbox/kristofo/1086306 Also check out this group: http://groups.drupal.org/responsive-web-design
> 2 votes

# Answer
I would also suggest checking out jQuery Mobile UI which is developed by Jason Savio. I attended his session at the Design 4 Drupal Boston 2011 and it definitely looks very promising. Apart from that, I dont see any other native jQuery Mobile module for Drupal 6.
> 2 votes

# Answer
iui is available as a showy theme for the mobile platform, and with modules linked from that page you can have the theme automagically changed when the page is viewed from a mobile device.
> 0 votes

# Answer
If you want a completely separate mobile theme you can use the Mobile Tools module with the Fusion Mobile theme.

If you just want a responsive theme I would give 320 and up a look.
> 0 votes

# Answer
jQuery Mobile looks great to me, though a full Drupal module is still in it's early stages.
> 0 votes

---
Tags: theming
---


# Question
Title: is using non English words for paths recommended?
I'm working on a Drupal site which has a non-english language.I want to change the paths to something better than node/\[nid\].Nodes also have a non-english title and I want to set the path to content/\[node-title\].does it cause any problem?does it affect on SEO?

# Answer
I use transliteration module in combination with pathauto module to transliterate any characters in my node title beyond ASCII 128 and automatically create friendly urls for each of my nodes.

This combination works really well! :)

Whether it is actually necessary or advantageous to remove unicode characters from your site's URLs is a subject on which I'm sure there would be many different opinions.

The Russian Wikipedia doesn't transliterate, but if you need to send your site's url's in an email, then things can quickly get out of hand and look ugly: http://ru.wikipedia.org/wiki/%D0%97%D0%B0%D0%B3%D0%BB%D0%B0%D0%B2%D0%BD%D0%B0%D1%8F\_%D1%81%D1%82%D1%80%D0%B0%D0%BD%D0%B8%D1%86%D0%B0

I have no experience if unicode characters in URLs affect SEO.
> 1 votes

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


# Question
Title: How to remove the default "Anonymous" from comment author name?
In the comment form field (core comment module) I would to leave the comment author name empty, in order to encourage commentators to come up with original epithets.

What's the easiest way to do it?

# Answer
I see a few of ways this could be done:

1. Custom module - someone has even written it for you - http://drupal.org/node/240610#comment-1096024
2. Using string overrides \- change Anonymous to \[empty string\]
3. Remove it from the comment module - Content management -\> Content types and click edit for your node type and enable "Anonymous posters may not enter their contact information"
4. Use javascript - someone has also written this as well - http://drupal.org/node/240610#comment-2051378

I would probably opt for option 1 as this provides greater flexibility in altering the forms to suit other requirements in the future
> 1 votes

# Answer
`hook_form_alter()`

http://api.drupal.org/api/drupal/modules--system--system.api.php/function/hook\_form\_alter/7

Allows you to hook in to and alter any form, including setting the default text to empty. Here's some more help on what the valid elements are:

http://api.drupal.org/api/drupal/developer--topics--forms\_api\_reference.html

Best way to start is to determine the form ID by creating a `mymodule_form_alter()` function and printing out the `$form_id` using `print` so it appears at the top of the page. (Or better still, use the devel module to print it out in a Drupal status message). Once you know the form ID, you can add an `if` to make sure you only act on that form and then alter the array to remove the default value you don't want.

Look at pretty much any module for an example implementation. Many modules use this hook. I can't think of any specific example off the top of my head, but there are loads.

EDIT: Here's a good Lullabot blog post on the matter... there's not much different between Drupal 6 and Drupal 7 in this regard, AFAIK: http://www.lullabot.com/articles/modifying-forms-drupal-5-and-6
> 3 votes

# Answer
Just a note for those who decide to go with a custom module, but get *Anonymous* in the *Name* input box for no apparent reason, and their `hook_form_alter` (or `hook_form_comment_form_alter`) is okay.

Make sure to remove the `comment_info_name` cookie, which the `comment`'s module Javascript uses to store the previously used name. It took me some time to find out...

It's all covered in one place here: http://jan.tomka.name/blog/how-remove-anonymous-name-comment-form
> 2 votes

# Answer
This is the kind of simple tweak that I'd do with JavaScript.

```
$(document).ready(function() {
    var editbox = $('#edit-name');
    if (editbox.val() == 'Anonymous' {
        editbox.val('');
    }
});

```

Pop that somewhere in your theme and the name field is cleared when the page is loaded.
> 1 votes

---
Tags: forms, comments
---


# Question
Title: How to modify a cck field of Node A when Node B (referenced from Node A) is modified
Drupal 6 Question:

I have two content types - a Property and a Task. The Task content type has a CCK Node Reference field that references the Property node it belongs to. When I modify a certain field in the Property node, I need to automatically update the "field\_task\_status" within it's referring Task node to "Complete".

I've been able to accomplish this with Rules 1 and VBO, but It seems like building a multitude of VBO views and triggered rules just to handle switching the Task node's status to "complete" or "pending" is a bit overkill.

Is there a more efficient way of doing this through a small custom module? I've heard that VBOs are heavy on the server, and I don't want to run into problems with the VBOs bogging down site.

I was initially thinking that I could write a query to get the nid of the referring Task node, and use that to load that Task and subsequently modify the value of its "field\_task\_status" ... I'm not a developer by trade, but I can put the code together if I have some idea of where to start.

Edit: Here's my attempt at coding a custom module, it's not getting me what I want...am I even close?

```
function mymodule_task_updater($property)
{
 $task_id =db_result( db_query(
 "SELECT tn.nid FROM content_type_task_notification tn,
 content_field_property_reference p, node n
 WHERE  n.nid=p.field_property_reference_nid
 AND tn.field_task_notice_type_value='Realtor Assignment'
 AND  p.field_property_reference_nid='%d' ", $property->nid ));

 $task = @node_load( $task_id );

if($task && $property->field_realtor_reference[0]['value'] == NULL)
   {
    $task->field_task_notice_status[0]['value'] = 'Pending';
    node_save($task);
   }
}

```

# Answer
Ok so I've got it working the way I want...let me know if this is the best way to do this. Everything seems to be working correctly with the following code:

```
  module_load_include('inc', 'node', 'node.pages');
/**
 *  Implements hook_nodeapi()
 */

 function MYMODULE_nodeapi(&$node, $op, $a3 = NULL, $a4 = NULL) {
  switch ($op) {
    case 'insert':
    case 'update':
    //check for correct type
      if (  $node->type == 'property' ) {
        MYMODULE_task_complete($node);

     }
      break;
  }
}
function MYMODULE_task_complete( $node)
{
    $result =db_result(db_query(
   "SELECT tn.nid
   FROM content_type_task_notification tn, content_field_property_reference p
   WHERE  tn.nid=p.nid AND tn.field_task_notice_type_value='Realtor Assignment'
   AND p.field_property_reference_nid='%d' ",  $node->nid));

   $task =  node_load( $result );

    if($task )
    { // We need this here or else the system will just create a blank node

         if($node->field_realtor_reference[0]['uid'] )
        {
        $task->field_task_notice_status[0]['value'] = 'Complete';
        node_save($task);
         }
       else
           {
       $task->field_task_notice_status[0]['value'] = 'Pending';
       node_save($task);
        }
        }

   }

```
> 0 votes

# Answer
If you are careful you can use hook\_node for this. You can check when node type property is saved, and load alter and save the task.

Make sure you put guards in place otherwise it is easy to end up with recursion.
> 2 votes

# Answer
Try this. Add this inaddition to your MYMODULE\_task\_updater function.

```
/**
 *  Implements hook_nodeapi()
 */
function MYMODULE_nodeapi(&$node, $op, $a3 = NULL, $a4 = NULL) {
  switch ($op) {
    case 'insert':
    case 'update':
      //check for correct type
      if ($node->type == 'property') {
        //check if certain field is modified
        if ($node->field_certain_modified_field['value'] == 'something different' ) {
           MYMODULE_task_updater($node);
        }
      }
      break;
  }
}

```

EDIT:

For Drupal 7 hook\_nodeapi() has been replace by hook\_node\_update() & hook\_node\_insert. You will have to add the same code in both MYMODULE\_node\_update & MYMODULE\_node\_insert function.
> 2 votes

---
Tags: entities
---


title: Field level permissions in Drupal 7

text:
# Question
Title: Field level permissions in Drupal 7
What is the best way to create a piece of content with multiple fields... allowing users to edit the content as a whole yet blocking the ability to edit.

The setup I have is a piece of content that has 3 fields: Body, PDF, SWF... and a "Selector" (List Text) that's tied via dependancy. So the user chooses BODY, PDF or SWF and that's what available to edit and shown on the page when live.

What I want to do is add a PHP field... that's either:

* greyed out (unable to edit) if your not admin...
* doesn't show up in the Drop Down list... Can't select it if you can't see it
* Shows up on the drop down, but the field doesn't show up in the editor without permissions.

I hope I'm making sense... I can provide an example if needed.

# Answer
> 3 votes
For Drupal 7, check out http://drupal.org/project/field\_permissions.

> The Field Permissions module is a drop-in replacement for the Content Permissions module shipped with CCK.

So for Drupal 6, use the Content Permissions module shipped with CCK

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


# Question
Title: How to publish referenced nodes at the same time node is published?
I have a product content type and a review content type. A user can create a product node and then several users can review it. There is a node reference field in the review content type that links the product type using the node reference url widget.

The user can create and edit the product node but it is not published. However, there are links from the node reference url widget that allows for reviews to be attached that get published immediately. Now I have views on other pages with reviews that link to an unpublished node. This doesn't work.

How do I allow for reviews to be made but are not published if the product is unpublished and published if the product is published? Are there techniques using Rules?

# Answer
> 1 votes
I would look into rules. This should be a simple problem solve with them. If not here is how you would code it in a custom module

Drupal 6:

```
/**
 *  Implements hook_nodeapi()
 */
function MYMODULE_nodeapi(&$node, $op, $a3 = NULL, $a4 = NULL) {
  switch ($op) {
    case 'presave':
      //check for correct type
      if ($node->type == 'review') {
        if ($node->field_product_node_reference[0]['value']) {
           $product = node_load($node->field_product_node_reference[0]['value']);
           if ($product->status == 0) {
             //product is unpublished, set review to unpublish
             $node->status = 0;
           }
        }
      }
      break;
  }
}

```

Drupal 7: hook\_nodeapi() has been change. Create MYMODULE\_node\_presave($node). Use the same code.

# Answer
> 1 votes
Rules Views Bulk Operations is being worked on which will hopefully allow a change in a node trigger, through a Views argument, a VBO reaction that will, for example, unpublish a set of referenced nodes.

However, I just needed to hide Reviews in Views that were spread around the website. This is done by using the Relationships content: reference and adding a filter content: published that uses the referenced node relationship to test if it's published.

The reviews will always remain published. They can be viewed if people know where to look which doesn't make a difference. However, now an anonymous user doesn't land on the front page sees a view with a new review that links to a product which isn't published resulting in a page not found error.

---
Tags: nodes, rules
---


# Question
Title: difficult to understand drupal hook menu function
I am new to drupal.I can't understand how drupal hook menu works.I visit the drupal site and try to read documentation.but it is too difficult to understand.can you please tell me a good tutorial so that I can understand how they work.thanks in advance

# Answer
For me the best way to get a solid understanding on Drupal **quickly**, was to purchase some video tuition. By watching just a couple of these paid downloads, I had a good understanding on the basics.

Most tutorials step you through building your first custom module, explaining what everything is, why it is required and how it works into the overall structure.

A number of companies offer this type of product, and this one is a freebie from one site to introduce the Drupal menu system, including hook\_menu()
> 3 votes

---
Tags: routes, hooks
---


# Question
Title: How to get CCK optionsfield value, if I have the key for that value?
I have a CCK select list where I defined key|value pairs.

When I execute a node\_load for that node, I only get the key (in my case an integer) stored in Drupal.

How can I get the value of that key easily? Is there a Drupal function?

something like, cck\_value('field\_name',$key) ?

# Answer
> 1 votes
Node\_load will return fully-populated node object.

Value of cck fields in node object are usualy accessed in this way:

```
 $my_node_object = node_load($nid);
 $myVar = $my_node_object->field_your_field_name['0']['value']

```

You can see what $node object contain if you do

```
dsm($my_node_object); // Devel module must be turned on

```

Hope this helps.

# Answer
> 0 votes
Found this meanwhile http://www.mugginsoft.com/content/getting-allowed-values-cck-field

---
Tags: entities
---


# Question
Title: How do i use views with a custom entity?
I defined a custom entity with a few bundles. Is it possible to display these using Views? How do I do that?

# Answer
If you used entity API module, then this is done pretty much out of the box, see my blogpost on Integrating entities with Views for more details.

If you didn't use entity API module or don't want to, you can make the views integration yourself using `hook_views_data`.
> 10 votes

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


# Question
Title: How do I Improve Drupal 7 Forum Performance?
I am working on a website that has 60k+ forum topics and it is extremelly slow. The problem is that the core forum module uses the following query

```
SELECT ncs.last_comment_timestamp AS last_comment_timestamp
, ncs.last_comment_uid AS last_comment_uid
, CASE ncs.last_comment_uid WHEN 0 THEN ncs.last_comment_name ELSE u2.name END AS last_comment_name FROM node n
INNER JOIN users u1 ON n.uid = u1.uid
INNER JOIN forum f ON n.vid = f.vid AND f.tid = '22'
INNER JOIN node_comment_statistics ncs ON n.nid = ncs.nid
INNER JOIN users u2 ON ncs.last_comment_uid = u2.uid WHERE  (n.status = '1') ORDER BY last_comment_timestamp DESC LIMIT 1 OFFSET 0

```

I saw that this query was the problem because after running the top command I saw that mysql was consuming 150%+ CPU so I ran a show full processlist that showed that the query above was always in the following state

```
Copying to tmp table    SELECT ncs.last_comment_timestamp AS last_comment_timestamp, ncs.last_comment_uid AS last_comment_uid, CASE ncs.last_comment_uid WHEN 0 THEN ncs.last_comment_name ELSE u2.name END AS last_comment_name\nFROM \nnode n\nINNER JOIN users u1 ON n.uid = u1.uid\nINNER JOIN forum f ON n.vid = f.vid AND f.tid = '22'\nINNER JOIN node_comment_statistics ncs ON n.nid = ncs.nid\nINNER JOIN users u2 ON ncs.last_comment_uid = u2.uid\nWHERE  (n.status = '1') \nORDER BY last_comment_timestamp DESC\nLIMIT 1 OFFSET 0

```

The result of the explain command is

```
id      select_type     table   type    possible_keys   key     key_len ref     rows    Extra
1       SIMPLE  f       ref     PRIMARY,tid     tid     4       const   30030   Using index; Using temporary; Using filesort
1       SIMPLE  n       eq_ref  PRIMARY,vid,node_status_type,uid        vid     4       drupal.f.vid    1       Using where
1       SIMPLE  ncs     eq_ref  PRIMARY,last_comment_uid        PRIMARY 4       drupal.n.nid    1
1       SIMPLE  u2      eq_ref  PRIMARY PRIMARY 4       drupal.ncs.last_comment_uid     1       Using where
1       SIMPLE  u1      eq_ref  PRIMARY PRIMARY 4       drupal.n.uid    1       Using where; Using index

```

Any ideas what to do to improve the performance here ?

Thanks

# Answer
If you remove statistics then things should fly. From my understanding drupal statistics does not scale well
> 1 votes

# Answer
Rather vague question that likely is very system specific, but the first thing you can try is tuning your database server. If you were running D6, then you could try using DB Tuner, but apparently this doesn't have a D7 version.

A lot of the module is based on MySQL Tuner, which will examine a live database and give suggestions on parameters to adjust.

I would also read the resources in the answers to https://drupal.stackexchange.com/questions/1715/what-would-the-optimal-mysql-configuration-for-a-drupal-7-site-be
> 0 votes

# Answer
The `ORDER BY` forces MySQL to store the selected rows in an internal temporary table to sort them before returning the result set. If this result set is more than MySQL can handle in memory, the temporary table has to be stored on disk. Obviously, this severely impacts performance.

The maximum size for in-memory temporary tables is the minimum of the `tmp_table_size` and `max_heap_table_size` values. You could try and increase these values in `my.cnf` and see if it speeds execution up. `mysqltuner` will give you valuable hints here.

It looks to me that the statement goes through a lot of (database) effort only to return a single result row. Optimizing it could yield a significant performance gain. Unfortunately, I don't have the time just now.
> 0 votes

---
Tags: database, performance, nodes
---


title: comment per page settings

text:
# Question
Title: comment per page settings
How can I change "Default comments per page" array to my own. What hook I need to use, if it needed? `hook_form_FORM_ID_alter(&$form, &$form_state)` with `FORM_ID = node_type_form`

$form doesn't contain this value

# Answer
Drupal pulls the number of comments per page from `variable_get('comment_default_per_page' . $node->type)`. Its default is 50. To change this go to content type X -\> edit, then save.

To change the 50 to something else, you can create you own custom module and have this code

```
function example_form_alter(&$form, &$form_state, $form_id) {
    if ($form_id == 'node_type_form' && isset($form['comment'])) {
        $form['comment']['comment_default_per_page']['#default_value'] = 70;
    }
}

```

If you want to change it somewhere else, then I recommend calling `variable_set('comment_default_per_page' . $node->type, 'MYVALUE')`. See below where it is hard-coded inside comment.module & comment\_form:

```
$form['comment']['comment_default_per_page'] = array(
  '#type' => 'select',
  '#title' => t('Default comments per page'),
  '#default_value' => variable_get('comment_default_per_page_'. $form['#node_type']->type, 50),
  '#options' => _comment_per_page(),
  '#description' => t('Default number of comments for each page: more comments are distributed in several pages.'),
);

function _comment_get_display_setting($setting, $node) {
  global $user;

  if (isset($_GET[$setting])) {
    $value = $_GET[$setting];
  }
  else {
    // get the setting's site default
    switch ($setting) {
      case 'mode':
        $default = variable_get('comment_default_mode_'. $node->type, COMMENT_MODE_THREADED_EXPANDED);
        break;
      case 'sort':
        $default = variable_get('comment_default_order_'. $node->type, COMMENT_ORDER_NEWEST_FIRST);
        break;
      case 'comments_per_page':
        $default = variable_get('comment_default_per_page_'. $node->type, 50);
    }
...

```

and inside `comment_render($node, $cid = 0) {`

```
$comments_per_page = _comment_get_display_setting('comments_per_page', $node);

```
> 4 votes

# Answer
The default comments per page is stored and changed on the content type itself. In D6 it was stored using `variable_set()` but I'm not sure if this is the case for D7.
> 0 votes

---
Tags: comments
---


title: SQL function with EntityFieldQuery

text:
# Question
Title: SQL function with EntityFieldQuery
Is there a way to use SQL functions with the `EntityFieldQuery` class?

What I am trying to do is something similar to the following code:

```
$query_user = new EntityFieldQuery;

$query_user
->entityCondition('entity_type','user')
->fieldCondition('MD5(user+pass)',null,$user_token,'=')

```

The interesting part is the `EntityFieldQuery::fieldCondition()` call. Obviously this it isn't working, otherwise I would not ask this question.

# Answer
> 2 votes
No. The whole point of EntityFieldQuery is that it is SQL-agnostic, so you can switch from MySQL to MongoDB for example, and it still works.

# Answer
> 0 votes
The first parameter to fieldCondition is expecting to be the field you want to query. So unless you have a field called `MD5(user+pass)` this won't work. You can't query with arbitrary SQL like that.

Read the documentation linked above about how to use the method. This is generally a good place to start when things don't work, to check if you can do what you are trying to do.

From the doc:

> public EntityFieldQuery::fieldCondition($field, $column = NULL, $value = NULL, $operator = NULL, $delta\_group = NULL, $language\_group = NULL)
>
> $field Either a field name or a field array.

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


# Question
Title: How do I create additional fields in module.install?
I am creating a module in the ".install" file, using the following code:

```
// if not exists, create new content type
if (!node_get_types('type', 'houses')) {
  $info = array(
    'type' => 'houses',
    'name' => t('Houses'),
    'module' => 'node',
    'description' => t('Manager Houses'),
    'locked' => FALSE,
    'custom' => TRUE,
  );
  $info = _node_type_set_defaults($info);
  node_type_save((object)$info);
}

```

It creates a new content type, but how do I create additional fields (e.g. text, nodereference)?

# Answer
> 3 votes
Instead of creating the node type and fields by hand in code, you should use the features module which does the same thing, but has support for a bunch of other things as well, like reverting changes made to what is saved in code.

# Answer
> 1 votes
Have a look at programmatically created cck fields. Also see Creating a Compound Field Module for CCK in Drupal 6.x and Programmatically add CCK field to content type.

---
Tags: nodes, entities
---


# Question
Title: Form API file upload field default value implementation using AJAX/AHAH
Apologies for the long explanation. I have a form built using the From API that is used as a profile for users. It allows users to upload a CV/resume type file for themselves and it is mandatory to upload a file or the user cannot complete the form.

Uploading and saving the files are no problem, but I run into problems when the user tries to update their form. The file input type in the Form API doesn't have a `#default_value` option (understandably) which means that when the user comes to edit the form, there are two problems.

The first is that it shows a blank file upload field and the user is expected to upload a file again (as the field is mandatory). This is confusing for the user and means that more than one file can be assigned to a user. The second is that the user does not have an option to remove their file and add a new one to replace it.

What I would like to do is write a function that checks to see if the form is being accessed by a logged in user, checks if that user has a file associated with them and displays the field appropriately. If a file exists, display the name of the file and a link to remove it instead of showing the file upload field.

I could do most of this no problem, but the extra part I would like and can't do is for the "Remove file" link to be an AJAX call that would delete the user's file and then display the file upload field dynamically. Has anyone done something like this before?

# Answer
Unfortunately, depsite the vast amount of answers posted to this question, there was no easy way to do this. In the end, I had to check when the form was being displayed if the form already had content, and if so, if the form had a file attached. I then displayed a different value rather than the form field and made a validation workaround due to the fact that the file upload was mandatory.

My advice to others with similar problems: if you're using this as an user profile field, avoid FAPI and stick to CCK and Content Profile. Although it can be a pain sometimes, all of this functionality is already taken care of.
> 0 votes

---
Tags: 6, forms, ajax
---


# Question
Title: How to populate nodes with imagefield programmatically?
I'm trying to do a mass import of images to drupal nodes in D7 and ended up with lots of funny entries in the table {files\_managed}.

This is the code I use:

```
  chdir('/path/to/drupal/root');
  define('DRUPAL_ROOT', getcwd());
  require_once DRUPAL_ROOT . '/includes/bootstrap.inc';
  drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);

  $node = node_load(123);

  $dir = '/path/to/files';
  if ($handle = opendir($dir)) {

    while (false !== ($file = readdir($handle))) {
      $file_ext = pathinfo($file, PATHINFO_EXTENSION);

      switch ($file_ext) {
        case 'jpg':
        case 'gif':
        case 'JPEG':
        case 'jpeg':
        case 'png':
          $name_explode = explode("_", $file);
          $image_location =  $dir .'/'. $file;

          $file_temp = file_get_contents($image_location);
          $file_temp = file_save_data($file_temp, 'public://' . $file, FILE_EXISTS_RENAME);
          $node->field_ep_image = array(
            $node->language => array(
              0 => array(
              'fid' => $file_temp->fid,
              'filename' => $file_temp->filename,
              'filemime' => $file_temp->filemime,
              'uid' => 1,
              'uri' => $file_temp->uri,
              'status' => 1
              )
            )
          );
        break;
      }

    }

    closedir($handle);
  }

```

What is the correct way to populate an imagefield programmatically in D7?

# Answer
> 2 votes
You only need to store the fid on the node, the rest of the file data is stored in the files table.

So

```
$node->field_ep_image = array(
   $node->language => array(
     0 => array(
       'fid' => $file_temp->fid,
     )
   )
 );

```

should be fine.

You could also use the entity API module, which simplifies this for you:

```
$node_wrapper = entity_metadata_wrapper('node', $node);
$node_wrapper->field_ep_image = $file_temp->fid;

```

If you are getting funny values you might want to check your file handling, are the files save in the files table as expected?

# Answer
> 2 votes
I don't have the exact answer to your question, but you could check how other modules do it. Devel Generate for instance (part of Devel) can populate image fields. Check out devel\_generate\_fields() in devel\_generate.fields.inc and image\_devel\_generate() in image.devel\_generate.inc.

Hope that helps.

---
Tags: 7, media
---


# Question
Title: Drupal commerce: Purpose of utilizing different product types?
I'm trying to figure out product types in Drupal commerce. Why would you want to use more than one product type?

Couldn't you just use one product type?

I could see that different product types have different fields. Is that the primary reason?

Or is it because there an ease of use for utilizing product types in views?

# Answer
Different set of fields should be the main reason for different product types. In my opinion, it is the same reason which puts us in the position of creating new content types.

Different set of fields might seem trivial, but if you are using rules/triggers to do different things to a unique set of fields, then that's altogether a different feature.

Hope this explains the difference.
> 4 votes

---
Tags: nodes, commerce
---


# Question
Title: Does $form_state['redirect'] require a rebuild?
I'm working on a multi-step form, and one of the last steps is a confirmation page with a 'Continue' and 'Cancel' button. If they hit cancel, I want it to go to a whole other page.

I have a custom submit handler for the cancel button, but the functionality doesn't appear to be working. I have:

```
function hook_form_cancel_submit($form, &form_state) {
  drupal_set_message('Cancelled');
  unset($form_state['rebuild']);
  $form_state['redirect'] = array('another/page');
}

```

I don't want the form to be rebuilt after cancellation, but then I wonder how my redirect would get triggered, since it exists only in `$form_state`?

# Answer
Form generation reports the following text:

> `$form_state['redirect']` is used to redirect the form on submission. It may either be a string containing the destination URL, or an array of arguments compatible with `drupal_goto()`. See `drupal_redirect_form()` for complete information.

The function drupal\_redirect\_form() is called by drupal\_process\_form(), which calls it after executing the form submission handlers with form\_execute\_handlers().

```
if ($form_state['submitted'] && !form_get_errors() && !$form_state['rebuild']) {
  // Execute form submit handlers.
  form_execute_handlers('submit', $form, $form_state);

  // ...

  // If batches were set in the submit handlers, we process them now,
  // possibly ending execution. We make sure we do not react to the batch
  // that is already being processed (if a batch operation performs a
  // drupal_form_submit).
  if ($batch = & batch_get() && !isset($batch['current_set'])) {
    // ...
  }

  // Set a flag to indicate the the form has been processed and executed.
  $form_state['executed'] = TRUE;

  // Redirect the form based on values in $form_state.
  drupal_redirect_form($form_state);

  // ...
}

```

In short, the form is not rebuild, before redirecting the user to a new page. The `$form_state` array that is passed to `drupal_redirect_form()` is the same array passed to `form_execute_handler()` (the difference is that the form handlers can add or alter values contained in `$form_state`).
> 7 votes

# Answer
Use `drupal_goto()`

```
function mymodule_form_cancel_submit($form, $form_state){
  drupal_goto('destination_path');
}

```
> 1 votes

---
Tags: 7, forms, redirection
---


# Question
Title: How can I do the dynamic select in Drupal 7 forms?
I work with drupal 7. In the following code I call the function players() which returns array of values for option. This values were defined beforehand by hand. How can I load it dynamically from the database?

```
 $form['officers']['officer'] = array(
'#title' => t('Select the officer'),
'#type' => 'select',
'#description' => t('Please, select the officer'),
'#options' => players(),
'#multiple' => FALSE,
'#empty_value' => ' ',
'#empty_option' => '- None -',

);

```

For example in the "Text Field" there is property #autocomplete which defines a path where Drupal’s automatically included JavaScript will send HTTP requests using jQuery.

```
 $form['team_name'] = array(
'#title' => t('Name'),
'#type' => 'textfield',
'#description' => t('Please, insert your name'),
'#autocomplete_path' => 'autofillform/teamname' ,

);

```

And i created the module which handles it.

```
<?php
function autofillform_menu() {
$items['autofillform/teamname'] = array(
'title' => 'Example autocomplete',
'page callback' => 'autofillform_teamname',
'access callback' => TRUE,
'type' => MENU_CALLBACK,
 );
 return $items;
 }
 function autofillform_teamname($string){
 $matches = array();
 $result = db_query("SELECT name FROM users where lower(name) like '".$string."%'  LIMIT 10");
 foreach ($result as $user) {
 $matches[$user->name] = check_plain($user->name);
  }
 print drupal_json_encode($matches);
 return;
 }

```

Are there any possibility to do the same with "Select" ?

# Answer
You need to focus on #ajax option. That will look like

```
$form['officers']['officer'] = array(
  '#title' => t('Select the officer'),
  '#type' => 'select',
  '#description' => t('Please, select the officer'),
  '#options' => array(),
  '#multiple' => FALSE,
  '#empty_value' => ' ',
  '#prefix' => '<div id="officer-wrapper">',
  '#suffix' => '</div>'
  '#empty_option' => '- None -',
  '#ajax' => array(
     'callback' => 'path/to/callback/handler',
     'wrapper' => 'officer-wrapper',
     'method' => 'replace',
     'effect' => 'fade',
  ),
);

```

In the submit handler you will have change the form element for `#options` and render to post back using `drupal_json_output`.
> 1 votes

---
Tags: forms, javascript
---


title: Access denied hook_menu Drupal 7

text:
# Question
Title: Access denied hook_menu Drupal 7
I am trying my first module on Drupal 7 on the behalf of experience on Drupal 6.

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

  $items['mypage']=array(
    'title'=>t('Title'),
    'page callback' => 'drupal_get_form',
    'page arguments' => array('custom_work_mypage_view'),
    'access arguments' => array('access content'),
  );

  return $items;
}

```

Upon accessing my page, I get access denied. What am I missing here?

# Answer
> 8 votes
Revised:

Your code looks right

3 Things could be the problem

1. 'mypage' could be a banned link.
2. you don't have access to 'custom\_work\_mypage\_view' form.
3. Clear your cache. Without the 'access argument' line you will get access denied. If you added it then save your file, you will still get access denied until you clear your cache.

My gut feeling is #3.

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