# Question
Title: How can I implement a form into a DC view footer?
I am trying to make a shipping quote module for Drupal Commerce (DC) and I am trying to do it within the DC cart view footer by sending a form within a view.

I have done quite a bit of research and just can't seem to find the answer. The place I am now is trying to do it with a views handler. However, I can't even get the handler to show up in the footer add options.

My current .module code:

```
<?php
function MY_MODULE_form($form, &$form_state) {
  $form = array();

  //Zip Code
  $form['zip_code'] = array(
'#title' => '',
'#type' => 'textfield',
'#field_prefix' => t('Zip Code:'),
'#maxlength' => 5,
'#size' => 5,
  );

  //Shipping Select
  $form['carrier_select'] = array(
    '#type' => 'select',
    '#options' => array(
      'null' => 'Select Shipping',
      'ups_ground' => 'UPS Ground',
      'usps_priority' => 'USPS Priority'),
      '#ajax' => array(
      'callback' => 'MY_MODULE_form_callback',
    ),
    '#suffix' => '<div id="commerce_ups_ship_price"></div>',
  );

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

/**
 * Ajax callback triggered by select.
 */
function MY_MODULE_form_callback($form, $form_state) {
  require_once(DRUPAL_ROOT . '/sites/all/modules/commerce_shipping/modules   /MY_MODULE/includes/plugins/ups/fd_getrate.php');
  $commands = array();
  $commands[] = ajax_command_html('#commerce_ups_ship_price',    get_ups($form_state['values']['zip_code']));
  $commands[] = ajax_command_data('#commerce_ups_ship_price', 'form_state_value_select', $form_state['values']['zip_code']);
  return array('#type' => 'ajax', '#commands' => $commands);
}

/**
 * Implementation of hook_views_api
 */
function MY_MODULE_views_api() {
  return array(
    'api' => 3,
    'path' => drupal_get_path('module', 'MY_MODULE') . '/includes/views',);
}
?>

```

Plus .inc for the view handler:

```
class MY_MODULE_shipping_form extends views_handler_area {

  function option_definition() {
    $options = parent::option_definition();

    // TODO: Update with options

    return $options;
  }

  function options_form(&$form, &$form_state) {
    parent::options_form($form, $form_state);

    unset($form['empty']);

    // TODO: Update with options
  }

  function render($values) {
    return drupal_render(drupal_get_form('MY_MODULE_form'));
  }
}

```

Plus the .inc for views:

```
function MY_MODULE_views_data() {
  $data = array();
  // Define an footer handler for displaying shipping quotes.
  $data['MY_MODULE']['handler'] = array(
     'handler' => 'MY_MODULE_shipping_form',
     'title' => t('Shipping API Quotes'),
     'help' => t('Display a user input form to allow the retrieval of shipping quotes.'),
  );

  return $data;
}

```

On this last one I don't have a clue of what I am doing.

Anyone who can help me on this one?

FYI - I am using Commerce Kickstart + Views3

# Answer
> 2 votes
You might want to consider using the Commerce Shipping module to handle the integration to Drupal Commerce, it doesn't support adding the shipping quote form in the cart footer, but it would help in handling the actually shipping quote with commerce.

The problem you are facing is in the `hook_views_data`, you should do something like this:

```
function MY_MODULE_views_data() {
  $data = array();
  // Define an footer handler for displaying shipping quotes.
  $data['MY_MODULE']['shipping_footer'] = array(
    'title' => t('Shipping API Quotes'),
    'help' => t('Display a user input form to allow the retrieval of shipping quotes.'),
    'area' => array(
      'handler' => 'MY_MODULE_shipping_form',
    ),
  );

  return $data;
}

```

You need to define an area handler as shown above, that should let you select the form in the views UI.

---
Tags: views, 7, forms, commerce
---


title: problem about view module in drupal 7

text:
# Question
Title: problem about view module in drupal 7
I have created a view for a content type called "events," and in the view there are 2 contextual filters (by category and years).

what I want to do is to be able to view the result in 3 conditions:

1. only the year: http://example.com/events/2010
2. only the category ID: http://example.com/events/4
3. year and category ID together: http://example.com/events/2010/4

Now the problem is that in the second case, as the argument is considered a year.

How can I set the view to be able to use a URL as in the second case?

# Answer
> 2 votes
As @googletorp commented, the argument in the url have to keep a certain order if not Views won't know which kind it is. The recommended method for this is allowing a "wildcard" by providing an exception, in views you can configure this in the contextual filter options:
Then you simply put all instead of the year when not it's not available:
2- the category id alone : http://mydomain.com/events/all/4

---
Tags: views
---


title: render() and theme() fields

text:
# Question
Title: render() and theme() fields
I would like to assign some content from a node, lets say the *body* field, into a region. so I cannot theme this content in my *node.tpl.php*

In the `template_process_page(&$vars)` i can easily set `$page['my_region'] = HTML.`

with `$vars['node']->body` i can access to my body field dada. from there I would like to use the regular theme function to render the body field. to use `theme('field',$variables)` or `render($variables)` I need to bring the body-array from:

```
Array
(
    [und] => Array
        (
            [0] => Array
                (
                    [value] => TEXT
                    [summary] =>
                    [format] => full_html
                    [safe_value] =>  TEXT
                    [safe_summary] =>
                )

        )

)
```

to sth like:

```
Array
(
    [#theme] => field
    [#weight] => 1
    [#title] => Body
    [#access] => 1
    [#label_display] => hidden
    [#view_mode] => full
    [#language] => und
    [#field_name] => body
    [#field_type] => text_with_summary
    [#field_translatable] => 0
    [#entity_type] => node
    [#bundle] => article
    [#object] => stdClass Object
        (...)
    [#items] => Array
        (
            [0] => Array
                (
                    [value] => TEXT
                    [summary] =>
                    [format] => full_html
                    [safe_value] => TEXT
                    [safe_summary] =>
                )
        )
    [#formatter] => text_default
    [0] => Array
        (
            [#markup] => TEXT
        )
)
```

---

But I don't know how exactly. how can a generate my field with the second array-achitecture. if possible without more db-queries.

thank you for help!

# Answer
You are looking for `field_attach_view`

What you would need to do, with your loaded node is something like this:

```
$fields = field_attach_view('node', $node, 'full');
$body = $fields['field_body'];

```
> 5 votes

---
Tags: theming
---


# Question
Title: How do you remove the default Drupal 7 administration menu?
I have disabled the "Toolbar" module, and cleared the cache; yet, it persists.

How do I remove it?

# Answer
Weird, it just took time. I came back a few hours later and it was gone. Perhaps there are cache clearing issues in Drupal 7.
> 1 votes

# Answer
There's a permission in Drupal 7 labelled `Use the administration toolbar`. Try unsetting this permission from the account.
> 0 votes

---
Tags: 7, routes
---


title: dpm does not display form return values

text:
# Question
Title: dpm does not display form return values
I just enabled the devel module on Drupal 6 and using `dpm($form)` was showing values for me but it does not show values any more. What would mostly the issue here? Is there a way to see those values?

Thanks

# Answer
> 1 votes
Typical cases for why a `dpm(...)` doesn't show up:

* Cache: The `dpm()` is in some cached code and is not actually being executed.
* Access: You are viewing the page with a user that doesn't have access to see the debug messages.
* Ajax/etc: Some code clears the messages before they are rendered, in this case you can use `dd()` to print to a log file instead.

# Answer
> 1 votes
In say a validation function, to see both the `$form` structure and what the user has entered, use a devel debug statement like:

```
dpm(array('$form' => $form, '$form_state' => $form_state), "Validation debug");

```

The `$form_state['values']` array will contain the raw user entries you can then access and validate.

---
Tags: debugging
---


# Question
Title: How to make two vocabularies works as section and category for article?
So basically i want terms from first vocabulary to work as sections that users can add (movies, for example), and terms from second vocabulary to be fixed amount of categories (like actors, info, screenshots etc), that users can only choose from.

I already made two fields with both vocabularies, but they works separate (*site.com/section* and *site.com/category*). Obviously, i want path to look like *site.com/section/category*. Tried Pathauto, but it works in a different way and can't do such things.

Any suggestions?

# Answer
> 1 votes
I think you can use views with arguments to create this pages.

you should create links manually with `l('title', "/{$vocab1_term}/{$vocab2_term}");` in your .tpl.php files associated with this views

# Answer
> 0 votes
check this alternative way to custom urls like Pathauto make: http://www.drupalcoder.com/blog/how-to-create-url-aliases-in-drupal-without-path-module, you can custom your urls according your needs (but according the documentation, you must be careful with your customization to not lost performance)

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


# Question
Title: Listen and respond to ajax_command_replace()
I have a page where a block is dynamically reloaded when the user clicks a link. Rather than writing my own js, I'm trying to do this the Drupal way and using Drupal's own `ajax_command_replace()` like so:

```
function page_callback($type = 'ajax') {
    if ($type == 'ajax') {
    // Load block
    // ....
    $commands[] = ajax_command_replace('#block-watch-notifications', $output);
    $page = array(
       '#type' => 'ajax',
       '#commands' => $commands,
    );
    ajax_deliver($page);
}

```

And all this works just fine.

The problem is that I need to respond to this event on my page. The js event DOMSubtreeModified would work here if it were reliably implemented by browsers, but it's not.

However, jQuery's AJAX command also issues its own series of global events, including ajaxComplete. The problem is that, however Drupal is doing its AJAX magic, it isn't raising this event.

How can I listen for `ajax_command_replace()` having done its work on my page?

# Answer
The API documentation tells us that `ajax_command_replace()` is handled in javascript by `Drupal.ajax.prototype.commands.insert`. At the end of the javascript insert function, Drupal attaches behaviors to the newly added content, passing any settings set in `ajax_command_replace()`.

From this we know that you can add your own behavior and check for a specific setting you set to know that your acting on your content. This will allow you to do some action when the AJAX is "complete".

The other option is to register a Global jQuery AJAX Event Handler. These event handlers are fired for every single AJAX event on a page (assuming of course that jQuery is used for sending the request) and requires a lot of checking and rechecking to make sure you're acting on the request you want.
> 2 votes

# Answer
From what I can tell, Drupal behaviors are simply callback functions that are called in two cases: 1. when the page is loaded initially, and 2. when content is added/removed via ajax.

You add your callback function to the global js object `Drupal.behaviors` (US spelling), namespaced by your module's name. My module is called 'watch' so I attach my callback functions to `Drupal.behaviors.watch`. `Drupal.behaviors.MODULE_NAME` is itself an object and has two elements that may be named 'attach' and 'detach'.

'Attach' is called during the initial page load and whenever Drupal's ajax adds new content. 'Detach' is called when is Drupal's ajax removes content, either before adding replacement content or removing it forever.

For the record my javascript looked like this:

```
(function($) {
  Drupal.behaviors.watch = {
    attach: function(context, settings) {
      // This code is fired both when the page is 'ready'
      // in the jquery sense, and when new content
      // is 'attached' via Drupal ajax. The settings
      // values that are available to us here
      // are provided in the third parameter of
      // ajax_command_replace() as an associative array.
      // My new content is already part of the dom
      // so I can act on it here.
    },
    detach: function(context, settings, trigger) {
      // Example detach callback.
    }
  }
})(jQuery);

```

I'm guessing Drupal behaviors can be extended to include all sorts of other behaviors beyond attach and detach and is probably very flexible besides, but that's beyond me right now.
> 3 votes

# Answer
There is hook\_ajax\_alter: http://api.drupal.org/api/drupal/modules--system--system.api.php/function/hook\_ajax\_render\_alter/7 This works on php level, but if you do it there, you could search the commands and add your custom command if wanted.
> 1 votes

---
Tags: javascript, ajax
---


# Question
Title: How to remove the title from a youtube video when using D7 + media module?
When I add an youtube video to a "blog post" content type I automatically get youtube's title/url placed above the video (see screenshot below).

* I have Drupal 7.7 + Media 7.x-2.x-dev + Media Youtube 7x-1.x-dev installed.
* I have added to the "blog post" content type a new "video" field with type "multimedia asset" and widget "media file selector".

I would really appreciate any advice on how to remove or change this title.

# Answer
> 1 votes
*Concerns*:

Media v2 is not stable right now media 1 is fairly stable and will not give you the title problems you're seeing. You also should not be using the dev version for production sites, not only are they not stable, they will not show update and updating & flushing the database can be problematic.

*Uninstall v2*:

Also reverting media down is rather drawn out you need to disable sub media types (youtube at the least) then media, then file entity (media v1 comes with it's own entity\_file).

Then uninstall media and install v1.

*To answer your question*:

You might also check http://yoursite.com/admin/config/media/file-types and check the display filters for video. The other place where rocketeerbkw mentioned http://yoursite.com/admin/structure/types/manage/ (your content types machine name example: article/book) might be worth a look as well.

If you are keen on fixing the module I'd suggest installing devel and inspecting the elements, it's probably something in a .tpl somewhere.

# Answer
> 1 votes
It looks like that's the field label, which can changed on the manage display page (Structure \> Content Types \> Manage Display)

---
Tags: 7, media
---


title: Where to find Drush for Drupal 6?

text:
# Question
Title: Where to find Drush for Drupal 6?
I am trying to install and work with Drush for my Drupal 6.22 site. However, on the modele's page I can only find the module's tar.gz package for Drupal 7. nor can I find D6 package elsewhere. So appreciate your help.

# Answer
Drush is version agnostic. From the same page:

> It is valid to use the latest '7.x' (or master) no matter what your version of Drupal is. Drush is independent of Drupal version :)
> 4 votes

---
Tags: drush
---


# Question
Title: Attaching a view page display to a tab in a content type?
I've built a CSV exporter by heavily modifying a template file from Views Bonus Pack's CSV feed Views plugin that formats all the content in a particular view exactly how I want it.

Now, I just need to find some way of integrating it into the work flow. Ideally, on each "projectsheet" content-type node, there would be 3 tabs for admins: View, Edit, Export.

The exporter feed is attached to a Page display that's part of the view. If I set that page's path to something like "node/%/export", it usurps the default display of that node and the node becomes that view.

**How do I create a new tab, to which a Views Page display is attached, that's visible only in a certain content type and doesn't take over the default view of that content type?**

I'm using Drupal 6 and the Views UI; considering everything I've done is in Views UI as a template for Views Bonus Pack, I'd really like to not code a new module to achieve this (i.e., just use Views UI to accomplish it if possible).

Thanks!

# Answer
In the *Page settings* section of the Page display of your view:

Path: node/%/export
Menu: Menu tab, Title: Export

You'll probably have an argument in your view already. In that argument's configuration:

Validator: Node
Node type: projectsheet (or whatever node types to display tab for)
> 2 votes

# Answer
Have the same problem.

I wrote a simple module "Views node access" for d7 which allows you to bind a view page to a specified node type. The code is in http://drupal.org/sandbox/cezaryrk/1244456

It is independent from the argument settings.
> 1 votes

---
Tags: views, theming, routes
---


# Question
Title: How do I create a php page that has access to the Drupal API?
I would like to create a PHP page that executes Drupal API functions.

The page would be inside my Drupal 7 website, perhaps the theme directory, but I'm not sure where it should reside.

I would like this page to run a query to the database using the Drupal's database abstraction layer. Once the query is retrieved, I would like to run some other D7 API functions and finally print out a page.

The page should not be one of the default Drupal templates, but a new page, that simply has one single within it.

How can I achieve this?

**EDIT:** The correct way to do this is to implement `hook_menu()` inside a module. I'm trying to do this, but my approach doesn't work. This is what I'm doing:

* the profileBox.info file

```
name = PB
description = "Creates a callback to returnuid.tpl.php"
package = SDNN
core = 7.x
files[] = profileBox.module

```
* the profileBox.module file is installed and has the following code:

```
function profileBox_menu() {
  $items['returnunid'] = array(
    'title'=>'Example'
    'description'=>'examples'
    'page callback' => 'profileBoxGetit',
    'access callback'=>TRUE,
  );

  return $items;
}

function profileBoxGetit() {
  $stringit = "the string output";

  return $stringit;
}

```
* I created a returnuid.tpl.php file with some html code in it - just to test (not functional code)
* I then pointed my browser to \[root\]/?q=returnuid
* I expected to get the content of the `$stringit` variable, but I instead got an "access denied" error

This module actually messes up the Administration menu, which dissapears when the module is installed.

What am I doing wrong?

# Answer
> 4 votes
The correct way to "create a PHP page that executes Drupal API functions" is to create a module.

In that module, you implement hook\_menu() which allows you to tell Drupal that it should call a given php function for a specific path, for example 'yourmodule/somepath'. Inside that, you can then execute whatever PHP and Drupal API functions which you want.

See http://drupal.org/node/1074360 for more information.

# Answer
> 2 votes
Another approach is to create standalone file, just like index.php, and perform drupal bootstrap there. For example:

```
require_once './includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);
/**
Write your code here
use PHP core, drupal core and contrib functions
**/

```

---
Tags: 7
---


# Question
Title: Drupal Views argument menu - sending %! to end of URL
Im building this project managment site that uses organic groups to sort and name projects.

So I have example.com/project/6. Where 6 is the organic groups views argument of %1.

What I am struggling to do is be able to create links that send for example 'gallery' to the end of the URL so example.com/project/6/gallery would show the gallery for project 6.

I am trying to create a global menu where all items would work for any organic group you may be within. So if you were within project 5 (http://example.com/project/5) the same menu item of 'Gallery' could be used to display example.com/project/5/gallery.

I have tried with all normal drupal menu methods but %1 is never accepted. The main thing is to be able to send for example '/gallery' to the end of the URL, or use any other method to achieve this.

Hope I have explained myself correctly.

Many thanks in advance.

# Answer
> 1 votes
Each segment of the URL is it's own argument. So to get `project/6/gallery` you would have two arguments.

The first argument `%1` (which you already have) is the organic group, the second argument `%2` would be (I assume) a content type argument.

---
Tags: routes, views
---


# Question
Title: How do I create a "quick post" bookmarklet for use with Drupal 7?
I'm trying to create a bookmarklet. This is not working:

```
javascript:window.location="http://domain.com/node/add/content_type?title="+encodeURIComponent(document.title)

```

The Prepopulate module is not ported for D7. Any recommendations?

# Answer
Out of the box, Drupal 7 doesn't support form population from the URL. Just like Drupal 6. That's why the Prepopulate module exists. Prepopulate is about 100 LoC, porting it to Drupal 7 is probably the best option. The effort has been started, see issue #935990.
> 3 votes

# Answer
As Pierre noted, the Prepopulate module is your way to go. I just installed it for Drupal 7 and it seems stable enough (works for the post title and body, anyway). The `USAGE.txt` that comes with it includes some info on using it for a bookmarklet for exactly this purpose.

However, I found that the code offered there didn't work for me: I had to change the variable name used for the body text from `edit[body_field][body]` to `edit[body][und][0][value]`. My guess is that this is because the site was previously upgraded from Drupal 6 to 7, but I can't say for sure.

Not to self-promote or anything, but I just published a long blog post about this, including the gotchas I found (like the variable name for the body field) and the version I wound up using: http://www.drupaldork.com/2011/08/mimicking-wordpress-press-bookmarklet-drupal-7

UPDATE September 11, 2011: I just released the QuickPost Bookmarklet module to add a frontend to make it easier to customize your bookmarklet. It requires Prepopulate, but it seems to be reasonably stable at this point—at least, for simple usage like this.
> 2 votes

---
Tags: 7, javascript
---


# Question
Title: How to determine which element has called (triggered) the AJAX callback function?
For example:

```
/** FIRST FIELDSET **/

$form['fieldset_1']['enabled'] = array(
  '#type'        => 'radios',
  '#options'     => array(1 => t('Enable'),
                          0 => t('Desable'),
                          ),
  '#ajax'    => array('callback' => 'my_ajax_callback',
                      'wrapper'  => 'my_wrapper_1',
                     ),
);

$form['fieldset_1']['myChangebleField'] = array(
  '#type'   => 'whatever',
  '#prefix' => '<div id="my_wrapper_1">',
  '#suffix' => '</div>',
);

/** SECOND FIELDSET **/

$form['fieldset_2']['enabled'] = array(
  '#type'        => 'radios',
  '#options'     => array(1 => t('Enable'),
                          0 => t('Desable'),
                          ),
  // Now I am calling the same callback function but assigning a different wrapper
  '#ajax'    => array('callback' => 'my_ajax_callback',
                      'wrapper'  => 'my_wrapper_2',
                     ),
);

$form['fieldset_2']['myChangebleField'] = array(
  '#type'   => 'whatever',
  '#prefix' => '<div id="my_wrapper_2">',
  '#suffix' => '</div>',
);

function my_ajax_callback($form, $form_state) {

/**
 *  How do I figure out which of the element "enabled" was the caller?
 *
 *  In that way I could do something like:
 **/
   switch($caller){
     case 'fieldset_1':
       // do stuff...
       break;
     case 'fieldset_2':
       // do stuff...
       break;
     // ...
   }

   return $form[$fieldset]['myChangebleField']
}

```

As seen in the example above, how do I figure out which of the element "enabled" was the caller?

Having two callback functions is not an option as the form elements will be constructed in a dynamic way and I won't actually use a switch statement in the callback function as shown in the example.

Cheers,

# Answer
Got it!!! This guy here `$form_state['triggering_element']` does the trick.
> 8 votes

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


# Question
Title: Setting up the ideal multiple repository Drupal Site version control with a DVCS
I have an upcoming project that will use Drupal, and I've been toying around with repository setup ideas in my head for a bit now and while I've come up with a wishlist, I don't know how to actually set up a source control repository this way. While I'm using Drupal for this, hopefully this setup could be extensible to other CMS systems.

Ideally, I'd be using Mercurial/Kiln since that's what my shop uses, but I'd rather have an ideal workflow than use that particular too.

Here are the features I think are important

1. Drupal core should be a working copy from their repository, so that I can update it easily
2. Site specific configuration will be exported from the Drupal DB to files using Features/Strongarm, so the repository should have a sub repository that controls all of the configuration that is not part of Drupal Core
3. Part of this project might involve writing custom modules. These should also have a separate repository or sub-repository so that they can be managed without interfering with site-specific configuration
4. I'd like to avoid storing code from Drupal Core in my own VCS, since it's already managed by the initial checkout used for item 1.

Is there some combination of ignore settings, submodules/subrepositories, or other configurations that can yield a setup like this? If not, what are my best alternatives? Or perhaps am I approaching the problem wrong, and there is some well-known workflow that solves these kinds of problems?

# Answer
A general workflow when it comes to Drupal is to clone the core repository and use it as the base for your local repository. Then, you'd create a separate branch specifically for your custom site, so as not to disturb the core branches.

Next, you'd add each module you'd want to use as a submodule off of this branch: this allows you to track specific versions of modules while still having the flexibility to easily upgrade them in the future.

Then, you'd set up an exclusion plan for user-generated content and your settings file. Generally, this would include:

* `sites/SITENAME/files`
* `sites/SITENAME/settings.php`

Finally, when you want to upgrade third-party content:

* With core, you'd pull the latest changes and rebase your custom branch
* With contrib, you'd navigate to the specific module's directory, pull the latest changes, and commit the new submodule hash to your custom branch.

The problem is, this works really, really well... if you use git. As Drupal has standardized on git, it's just a matter of linking to the correct drupal.org repositories and pulling when necessary.

If you're using a different VCS, submodules aren't really going to help unless you want to spend the time to convert each and every drupal.org repo for the modules you're using to whatever VCS you want to use. That's a lot of work, especially for a one-off project.

Alternatively, you could follow the above workflow, but instead of setting up a repo for each and every contrib module, you could set up one private repository called contrib, and manually add updates to contrib there. This way, you can keep contrib code separate, but you spare yourself having to maintain potentially dozens of custom repositories that do nothing other than duplicate drupal.org repositories.
> 7 votes

---
Tags: version-control
---


# Question
Title: How to use term id in content paths using path auto?
How can I use term id instead of term name in path auto?I have a category field in my content type named "field\_article\_category" and there is a token \[node:field\_article\_category\] for it but it is replaced by term name not term id.is there anyway to get term id instead of term name?

# Answer
The token you should use for the taxonomy term ID is *\[node:field\_article\_category:id\]*.

I have a "Categories" vocabulary, and this is the list of the tokens associated to that vocabulary for the nodes.

If you install the Token module, apart from having more tokens available, you will also have a list of the available tokens, from which I have taken the previous screenshot. The list is available after the fields to set the patterns for the automatic aliases, in the "Replacement patterns" fieldset.

I have noticed that out of four vocabularies I associated with content types, only two are listed as tokens; in my case, thought, I don't see all the tokens for that vocabulary, which is different from your case, where you seem to see only part of the tokens associated with a vocabulary.
> 2 votes

# Answer
You likely need the Entity tokens module from http://drupal.org/project/entity for now. We are working on adding the more detailed field tokens into Drupal 7.
> 3 votes

# Answer
in the '**Automated alias settings**' of Pathauto you will find the section '**Taxonomy term paths**', there is a sub-section called '**Replacement patterns**'. Here you will find several patters. The pattern `[tid]` is the pattern used to show the unique ID of the taxonomy term.

I hope have understood well your question.
> 1 votes

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


# Question
Title: How can I convert character entities to display as 'normal' characters in Drupal?
I have a customised module that imports items from feeds accessed via a third-party API. The items are used to create nodes for each instance. All the content appears to be importing correctly, but the feed includes character entities like '&amp' in some of the text imported. I've checked the CSVs being imported and the character entities are already in the feed content, so it isn't the module that's causing normal characters to be converted to character entities.

I'd like to know how I can get Drupal to convert the character entities to display as normal characters. Is there a module or setting that can do this?

# Answer
Edit your import module to http://php.net/manual/en/function.html-entity-decode.php the text before importing.
> 1 votes

---
Tags: 6, nodes
---


# Question
Title: How do I add a clearing DIV to the bottom of a region?
In the eternal mission to care about Internet Explorer, I have a template region which needs a clearing `<div<`, since I think that ":after" and "overflow:hidden" tricks don't work so well in IE. (I'm currently not able to test this as I'm on a Mac without a virtual machine.)

Is there any region preprocess trick, or anything equally clean, in order of adding a clearing `<div>`? I'd prefer not to use Javascript, or add an entire block for this purpose, if it is possible.

# Answer
I would find a common class for your region(s), and add in the clearfix rules. With kosher HTML and CSS, I don't recall the last time this didn't work in IE for me.
> 3 votes

# Answer
Drupal already has built in clearfix classes you can use. For Drupal 7, use `clearfix`. For Drupal 6, I believe it is `clear-block`.
> 1 votes

---
Tags: 6, blocks, theming
---


# Question
Title: How to use mysql queries in Action in a Triggered Rule?
I created a triggered rule. The action will 'fill a field'. To get the value for this field I need to get a value saved in sql database. Then I check to set the value using php and create this code:

```
$result = mysql_query("SELECT field_codigo_value FROM content_type_inmuebles_en_venta SORT BY field_codigo_value LIMIT 1");
$value = mysql_fetch_array($result);

return array(
  0 => array('value' => $value )
);

```

But I get this error message:

> warning: mysql\_fetch\_array() expects parameter 1 to be resource, boolean given in /Applications/MAMP/htdocs/drupal6multilingual/sites/all/modules/rules/rules/modules/php.rules.inc(107) : eval()'d code on line 2.

# Answer
First off, you should be using the drupal SQL coding conventions:

**db\_query** instead of **mysql\_query**
**db\_fetch\_array** instead of **mysql\_fetch\_array**

I would structure the query like so:

```
$query = "SELECT field_codigo_value
          FROM content_type_inmuebles_en_venta
          SORT BY field_codigo_value
          LIMIT 1";

$result = db_query($query);

return $result;

```

You should know that triggered rules allows you to pull a value out of the database without writing a custom query. We need a bit more context as to how this node is related to your triggered rule, but I would guess that you can load the node that you just created or load a referenced node to the node that you just created and then use the available tokens to fill in the CCK field that you need filled in.
> 1 votes

---
Tags: database
---


# Question
Title: Reducing attached items within node.tpl.php
I have multiple images attached to a content type that I have set up with fancybox. Currently when viewing that node, all images are displayed. I only want to show the first image, then the rest within gallery mode.

I an struggling to figure out how to limit the diplays within (node.tpl.php) to only show the first attaced image.

# Answer
> 2 votes
I like the Gallery Formatter module for my galleries. It's the Colorbox module is nicely integrated with galler formatter to give you a cool lightbox popup. Gallery Formatter will use the first image in your multi-value CCK image field as the first slide image, so you can drag the order of the images in the node form into the order you want them to appear in.

If you want to display the first image of your multi-value CCK image field separate from your gallery (like in a view that gives a preview of each gallery), I would first create an ImageCache setting that you want to use to display that image, and then output that image in your node template like so:

```
<?php print theme( 'imagecache', '[your_image_cache_preset_name]', $node->field_gallery_images[0]['filepath'] );?>

```

---
Tags: nodes, media
---


# Question
Title: how to import some content to a new site?
**site A** powered by drupal 6 whch has a content type `news`. there are many articles under it.

**site B** is a new site. which powered by drupal 6 too. now i only want to import those articles in **site A** to **site B**. how do i do? thank you.

# Answer
The deploy module can move nodes between Drupal sites. For advanced uses there's also migrate.
> 3 votes

# Answer
Export the content from site A using views + http://drupal.org/project/views\_bonus to create a CSV of all the news items you need.

Then use the feeds module to import the CSV into site B.

Both modules have a good amount of documentation.

Thanks Reece
> 0 votes

---
Tags: 6
---


# Question
Title: How can I display a block only when a node meets a particular condition?
I have a block that allows a site visitor to query an external calendar, but it will only work for certain nodes.

How can I set it up so that I can i) indicate whether or not a node has calendar data available for the node and ii) if it has calendar data available, display the block and if it hasn't got calendar data available, the block is not displayed?

Someone suggested to me that I use Workflow to do this, but I've not been able to figure out how Workflow would help me set this up.

# Answer
I would use the PHP visibility settings to display the block on a node's page if a cck value in that node has some value, assuming that this cck field's value is an indication of that node containing calendar data. Once you've created the block that you want to display (or not display) add the following code to the "Page specific visibility settings" in the block configuration menu:

```
<?php
$node = node_load( arg(1) );

if ($node && $node->type =="[your_content_type]" && $node->field_has_cal_data[0]['value'] =='Yes'){
return TRUE;
}

return FALSE;

?>

```

This is assuming that the url is built like "content/name-or-id-of-node".
> 1 votes

---
Tags: 6, nodes, blocks, workflows
---


# Question
Title: Filtering a View that is output as a Block
I have a view which has a page display and a block display. The block display has Use Ajax enabled so the filters show up. When I output the block display to my template using:

```
<?php print views_embed_view('list_disciplines', 'block_1'); ?>

```

It outputs correctly, and shows the filters. The problem is when I submit the filters form it redirects me to the path I have set up for the page display, and doesn't use ajax at all.

Any ideas?

# Answer
> 1 votes
Ok finally dug up my answer.

http://drupal.org/node/386388

In summary, the scripts for ajax views cannot be added if you embed your view in a page template. You either have to create the view in preprocess\_page or in a node template file.

---
Tags: views, 6, ajax
---


# Question
Title: Create rule to e-mail only someone who has combined roles
This is for a Drupal 6 install.

In rules there is an IF statement available of "If user has roles" and this can be set to be either an "and" statement or an "or" statement.

Within DO is an option to send an e-mail to everyone of a selected role.

I'd like to combine the selector of "if user has roles" using the "and" portion with the DO action of send e-mail to everyone of a selected role.

The site is currently using workflow & revisioning. Using Node Privacy Byrole I've assigned certain parts of the website to a specific department for editing.

Then using Workflow Access I've set up authors, editors, and publishers to limit the actions someone in a department may take on a node.

So there may be a user who is in the department role of "Marketing" and is also an "Editor." Then there may also be someone who is in "Marketing" who is also a "Publisher."

I'd like to notify say the Marketing Publisher (2 different roles) when a post changes workflow state, then have the Marketing Editor notified when a post changes to a different workflow state.

The workflow state is already available as an IF statement within rules, I just need to figure out how to create the DO statement to allow me to send e-mails based on this combination of roles.

# Answer
Two solutions come to my mind:

1. Write a module that provides the action you require. See the Developer Documentation for Rules for how this is done.
2. Write a module that adds users to the role "Marketing Publisher" whenever he as both the role "Marketing" and "Publisher". The module would only have to implement hook\_user($op = 'update') and hook\_user($op = 'insert').
> 2 votes

---
Tags: workflows, rules, actions
---


# Question
Title: View Module : How to display list of Taxonomy terms with record count
I cloned the default Glossary view and changed it a bit to look like something as following:

A (3) C (7) D (10) E (12) ...

But instead of Alphabets, how do I make it show taxonomy terms, for example:

General Knowledge (24) Inspirational Stories (20) Current Issues (10)

Appreciated...

# Answer
> 2 votes
### Drupal 7

With View 7.x-3, you first remove the "Content: Title" contextual filter, and then you add the "Content: Has taxonomy term ID" one.

In the dialog for the settings that appear once you select the context filter, you set the options as in the following screenshot. There are two displays: "Page," and "Attachment"; the first screenshot is for "Page."

The result is the following view; the first screenshot show the output when none of the links have been clicked on.

### Drupal 6

In Views 6.x-3, the used terminology and the user interface change, but the steps to follow are similar.

Also in this case, there are two displays, which have the same name used in Views 7.x-3; differently from Views 7.x-3, the display to change are the default one, and "Attachment."

You first remove the "Node title" argument, and add the "Taxonomy: Term ID" argument; the first image is for the default display.

In the latter display, the argument will be displayed as list by default; I didn't change it.

**Important:** There are two similar contextual filters/arguments, where in one appears the word "depth"; the difference is that this last contextual filter/argument shows all the node where the taxonomy term is the select one, or one of its children. You should use this one, if the vocabulary is organized hierarchical, and for example, the taxonomy terms are "Porsche," "Porsche \>\> Carrera," and "Porsche \>\> Cayenne"; in this case, selecting "Porsche" will show also the nodes using "Porsche \>\> Carrera" and "Porsche \>\> Cayenne."

# Answer
> 1 votes
Use Term Node Count and forget about cloning the glossary view. Then make a taxonomy term view adding terms and term node count as a fields

---
Tags: views
---


# Question
Title: Active trail not producing expected results
I'm writing a very simple module to alter the active trail on specific pages. Observe.

```
function alter_breadcrumbs_menu_breadcrumb_alter(&$active_trail, $item) {
  if (substr($item['href'], 0, 4) == 'user') {
    $num_crumbs = count($active_trail);
    $people = array(
      'href' => 'people',
      'title' => t('People'),
      'localized_options' => array(),
    );
    $active_trail[] = $people;
  }
}

```

The profile page by default has the breadcrumb 'Home'. I have a directory page that has a list of users with links to their profile pages. This page is located under /people. So, on the user page, I want the breadcrumbs to look like 'Home \> People \> John Smith'.

I expect the code above to produce 'Home \> People', but it doesn't. Instead, it produces 'Home \> jsmith \> People'. It puts in jsmith instead of John Smith because John Smith is derived from custom first and last name fields, but the crumbs currently just take the user's username by default, so ignore that fact for now. What it comes down to is I don't understand why it's pushing on the username crumb and the People crumb, rather than just the People crumb. Any insight would be helpful.

Cheers.

# Answer
It looks like your adding $people to the end of the array, you have to insert it in second place, using http://php.net/manual/en/function.array-pop.php you can do something like this (untested):

```
$name = array_pop($active_trail);
$active_trail[] = $people;
$active_trail[] = $name;

```
> 1 votes

# Answer
```
$breadcrumb = array();
$breadcrumb[] = l($breadCrumbTitle, $linkPath);
drupal_set_breadcrumb($breadcrumb);

```
> 1 votes

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


# Question
Title: Getting the $user object of a logged out user based on a username and setting its status
As mentioned in the question here Using user\_load() and user\_save() to change the status of a logged out user, I want to be able to access the $user object of a logged out user based on a username and set the user status to active with user\_save().

As advised, I put my code in a custom module and implemented hook\_menu() with a page callback. However, I still don't fetch $user.

**UPDATE:** I've managed to get what I wanted: I'm indeed fetching the $user object by a username passed as a parameter and I manage to change the user's status. BUT, i'm not doing this the proper way. Here's the code inside mymodule.module:

```
<?php
function mymodule_user($op, &$edit, &$account, $category = NULL) {
  switch ($op) {
    // set user's status to blocked upon registration
    case 'insert' : {
      user_save($account, array('status' => 0));
      break;
    }
  }
}

function mymodule_init() {
  // needed due to Drupal's menu caching. Otherwise, mymodule_menu() won't be called
  menu_rebuild();
}

function mymodule_menu() {
  $account = user_load(array( 'name' => $_REQUEST['user'] ));
  user_save($account, array('status' => 1));
}

```

As you can see, I implement hook\_menu() but there's no page callback. A working page callback would solve me 2 issues:

1. I would like the user activation functionality to be available only from a specific page in Drupal and i'd like to restrict access to that page.
2. Performance - currently, the menu\_rebuild() is called on each and every page request on Drupal.. not pleasant at all :)

**When I tried putting a page callback in the mymodule\_menu() function and debugged the code, I saw that the page callback wasn't even fired.** Here's what my initial code looked like:

```
function mymodule_menu() {
  $account = user_load(array( 'name' => $_REQUEST['user'] ));
  $items['auth'] = array(
    'page callback' => 'mymodule_page',
    'page arguments' => array($account),
    'access callback' => TRUE,
    'type' => MENU_CALLBACK,
  );
  return $items;
}

function mymodule_page(&$account) {
  menu_rebuild();
  user_save($account, array('status' => 1));
}

```

Why isn't my page callback function fired with this code? How can I tell Drupal to rebuild the menus or to clear the menus cache only for a certain page?

Avner

# Answer
> 1 votes
What is wrong in your code is that the implementation of `hook_menu()` is gathering the arguments for the callback, when that hook is only called in specific moments (as I reported in my previous answer).

Rather than doing as you do, I would rather use the following code:

```
function mymodule_menu() {
  $items['auth/%user'] = array(
    'page callback' => 'mymodule_page',
    'page arguments' => array(1),
    'access callback' => TRUE,
    'type' => MENU_CALLBACK,
  );
  return $items;
}

function mymodule_page($account) {
  user_save($account, array('status' => 1));
  drupal_goto('<front>');
}

```

In this way, Drupal will automatically get the user ID, and pass to the page callback the user object for that user. `drupal_goto()` is necessary as the page callback is not showing any output; you can redirect the user to any pages you want. (I chose "`<front>`" because it's a path that is always defined, in Drupal). If you need to use a username, then you need to use a loader function that loads a user object knowing the username. As in Drupal there cannot be two users with the same username, it should avoid the user being acted upon is not the desired one.

```
function mymodule_menu() {
  $items['auth/%mymodule_username'] = array(
    'page callback' => 'mymodule_page',
    'page arguments' => array(1),
    'access callback' => TRUE,
    'type' => MENU_CALLBACK,
  );
  return $items;
}

function mymodule_page($account) {
  user_save($account, array('status' => 1));
  drupal_goto('<front>');
}

function mymodule_username_load($name) {
  return user_load(array('name' => $name));
}

```

The code defines a new wildcard argument; if "%wildcard" is the name of the wildcard, then Drupal will look for the `wildcard()` function that needs to return `FALSE` in case of error; in that case, Drupal will return the "page not found" error (404).

**Important** I used the same value you used for "access callback," but **it is not something that should be done**, in this very specific case.
The reason is that the menu callback alters a user account; imagine what should happen if a user with a blocked account could do if he knows of this URL: He could enable his own account very easily. This is because the entry "access callback" you are using is saying "everybody can access this menu callback," which also means that Google, or any other search engine could enable a user just visiting the URL the search engine has found in some way.
In general, the rule is to restrict the access to a menu callback that alter some data, which includes also the case the menu callback deletes data.

---
Tags: hooks, users, database
---


# Question
Title: Theming book navigation block to generate drop-down menus
I have a 3 level deep book navigation block. I'd like to change the menu tree HTML output in the following way: For each level of the tree, create a li and inside it put an anchor tag with the active-trail link for that level, and afterwards a ul with the rest of the siblings for that level.

```
<li>
    <a href="#" class="active-trail level[x]">Level[x] active trail link</a>
    <ul style="display:none;">
        <li><a href="#">Level[x] sibling1</a></li>
        <li><a href="#">Level[x] sibling2</a></li>
        <li><a href="#">Level[x] sibling3</a></li>
        <li><a href="#">Level[x] sibling4</a></li>
    </ul>
</li>

```

The order of sibling links appearance should be according to their corresponding node weight.

I thought this could be done via the theme\_menu\_link() function but I can't seem to find a way to pass the current item's depth to the function.

What function do I have to work with in order to achieve what I'm after? Can someone offer some guidance?

Thanks, Avner

# Answer
> 1 votes
There is a specific theme function, which is used from the Book module for outputting its own block of links to book pages. I am not sure if it suits your case, but you can always use that code to build your own theme function.

The theme function is called from book\_block(), using the following code:

```
  if (variable_get('book_block_mode', 'all pages') == 'all pages') {
    $block['subject'] = t('Book navigation');
    $book_menus = array();
    $pseudo_tree = array(0 => array('below' => FALSE));
    foreach (book_get_books() as $book_id => $book) {
      if ($book['bid'] == $current_bid) {
        // If the current page is a node associated with a book, the menu
        // needs to be retrieved.
        $book_menus[$book_id] = menu_tree_output(menu_tree_all_data($node->book['menu_name'], $node->book));
      }
      else {
        // Since we know we will only display a link to the top node, there
        // is no reason to run an additional menu tree query for each book.
        $book['in_active_trail'] = FALSE;
        $pseudo_tree[0]['link'] = $book;
        $book_menus[$book_id] = menu_tree_output($pseudo_tree);
      }
    }
    $block['content'] = theme('book_all_books_block', $book_menus);
  }

```

The theme\_book\_all\_books\_block() function is empty, because the theme is using a template (book-all-books-block.tpl.php); as far as I can see, there isn't a preprocess function for that template file.

---
Tags: 6, theming, navigation, nodes
---


# Question
Title: hook_init() is not working in my custom module
In my custom Drupal 7 module I am using `CUSTOM_MODULE_NAME_init()` function. But it is not triggered while page execution. Any suggestions?

# Answer
> 6 votes
Hook implementations are cached in Drupal 7. After implementing a new hook, you need to clear the cache. See What method is used to clear caches in the Drupal? for ways to do that.

# Answer
> 3 votes
1. Make sure that the module is enabled (don't laugh, I forget that sometimes).
2. Make sure that the page is not served from cache. Use hook\_boot if you need to perform setup tasks for cached pages.
3. Use a debugger to step through the execution. hook\_init is invoked at the end of \_drupal\_bootstrap\_full.

# Answer
> 2 votes
As reported in the documentation for hook\_init(), the hook is not invoked on cached pages. This means that, if the content of a page is found in cache, the hook implemented by your module is not invoked.

> This hook is run at the beginning of the page request. It is typically used to set up global parameters which are needed later in the request. when this hook is called, all modules are already loaded in memory.
>
> **This hook is not run on cached pages.**
>
> To add CSS or JS that should be present on all pages, modules should not implement this hook, but declare these files in their .info file.

---
Tags: hooks
---


title: Customizing/theming a created view

text:
# Question
Title: Customizing/theming a created view
I searched a lot on net, but did not find proper answer for the customizing / theming a view that is created. I have created a view like one in screenshot . I wanted to change the way the pagination appears and some cosmetic changes for it. So whats the best way to do it.

# Answer
Use the unformatted style, instead of the table style. Then use CSS in your theme and you can style it any way you want. Should you want to change the html (I hardly ever need it), try rearranging the view or using the suggested templates.
> 1 votes

---
Tags: views, theming
---


# Question
Title: How do I find the user ID  knowing the username, when using drush?
That would be much more handy to use Drush rather than executing a SQL query to find a user ID. So I am wondering what drush command can be used that takes a username, and returns the equivalent user ID.

# Answer
> 3 votes
Try user-information.

---
Tags: drush
---


title: "current-page:title" when adding a node

text:
# Question
Title: "current-page:title" when adding a node
I have a node-type with an image field. while uploading a file I would like to put it in a node-specific directory which is named after the node title. while using tokens, there is no `node->title`, while I am creating the node, so the `current-page:title` is the `node->type` I am trying to add. so this works only when adding files to an existing node.

my solution-idea:

1. should I restrict adding files before the node is already created? the node should be created unpublished.

are there other solutions / a shorter way e.g. a two-step-edit-form?

# Answer
You will need FileField Paths. See ImageField Tokens for tokens in default values for alt and title attributes as well.
> 1 votes

---
Tags: tokens, files
---


title: Cache problem: update node

text:
# Question
Title: Cache problem: update node
I am running a Drupal 7 website with "Cache pages for anonymous users" and "Cache blocks" enabled. Both "Minimum cache lifetime" and "Expiration of cached pages" are set to 1 day.

When I update a node, for example, edit a picture, and visit that page as an anonymous user, the new picture isn't being displayed. When I manually clear the cache the page is displayed as it should be. It's like the cache isn't cleared after the node is updated.

Extract of the API:

modules/node/node.pages.inc

```
function node_form_submit($form, &$form_state) {
  $node = node_form_submit_build_node($form, $form_state);
  $insert = empty($node->nid);
  node_save($node);

  // Do stuff...

  // Clear the page and block caches.
  cache_clear_all();
}

```

Notice that the function cache\_clear\_all is called after the node is saved, regardless if the node needs to be inserted or updated.

Further inspection of the API reveals the following:

modules/node/node.module

```
function node_save($node) {

  ...

    // Save the node and node revision.
    if ($node->is_new) {
      drupal_write_record('node', $node);
      ...
    }
    else {
      drupal_write_record('node', $node, 'nid');
      ...
    }

    ...

    // Clear the static loading cache.
    entity_get_controller('node')->resetCache(array($node->nid));

  ...
}

```

Again, everything seems to be as it should be. The cache is cleared using the Entity API (`public DrupalDefaultEntityController::resetCache(array $ids = NULL)`).

Nothing seems to be wrong in the code. Maybe the code doesn't clear all of the necessary cache?

# Answer
The problem is that you have a *minimum lifetime* of *1 day* set. This means `cache_clear_all()` will not remove entries with a lifetime of less than a day. Try setting this to 1 hour, or something more acceptable for your site (eg, how long between new content or edited content, and when an anonymous user needs to see the content).
> 3 votes

# Answer
You can use `db_delete()` to clear the db table "manually" regardless of minimum lifetime.
> 0 votes

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


# Question
Title: How can a node appear in different places?
This is the kind of planning-stage question that I tie myself up in knots with...

A film site has main nav headings for Comedy, Fantasy, Kids etc. Each menu item displays a listing View of content type 'Film' tagged with the relevant taxonomy terms.

For example, 'Harry Potter' film is tagged as Fantasy and Kids, and appears on both listing pages.

If the user goes to the Fantasy section and clicks on 'Harry Potter' to view the full node, it needs to appear within the Fantasy section.

To achieve this, I am thinking of using another View to display the node content in the correct section (so the user never gets to the actual node). Or maybe I can do something with Panels. Or perhaps some kind of dynamic menu management?

I just have that familiar feeling that there has to be a cleaner way with Drupal?

# Answer
You can do this pretty easily with views...just build a view with different page or block displays that filters nodes by the different tags (a.k.a. Taxonomy Terms). You can manually build a menu that provides links to the different pages that correspond to each tag.
> 1 votes

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


title: Disable Timezones in User Account

text:
# Question
Title: Disable Timezones in User Account
How do you disable Timezone from being edited in a User account? Is there a config setting I can turn off?

# Answer
Visit `index.php?q=admin/config/regional/settings` to configure whether users are able to set their own timezone.
> 34 votes

---
Tags: 7, users
---


title: Setting default parent item in Drupal 6

text:
# Question
Title: Setting default parent item in Drupal 6
In Drupal 7 it is possible to set a **default parent item** at admin/structure/types/manage/article/edit.

Where is this option in Drupal 6?

If it isn't possible to do this in Drupal 6, is there a contributed module that will achieve this?

# Answer
> 3 votes
Node Menu Parent is the module you need to achieve this:

> The Node Menu Parent module gives us an extra option under the content type settings to choose a specific parent menu item per content type.

---
Tags: 6, routes, nodes
---


# Question
Title: How do I delete all the user's posts, using drush?
I frequently need to delete all comments/posts of a particular abusive user. It takes a hell of time to accomplish this with a browser. It would be great if someone could tell me how to do it using drush.

# Answer
> 3 votes
You could run something like this via `drush php-script`:

```
<?php
global $user;
$user = user_load(1);
$result = db_query("SELECT nid FROM {node} n INNER JOIN {users} u ON n.uid = u.uid WHERE u.name = '%s'", 'alice');
while ($row = db_fetch_object($result)) {
  node_delete($row->nid);
}
?>

```

There's also http://drupal.org/project/user\_delete.

---
Tags: drush, comments
---


# Question
Title: Multiple Field Widget instances on the same page, validation problem
I have multiple instances of the same field widget attached to different entity forms on the same page. On validating one of these forms, when I set form\_set\_error($field\_name, '...'), every one of these widgets get highlighted. Is there a way to get around this somehow?

# Answer
Check out the API page for form\_set\_error. This bit should help you out:

> $name The name of the form element. If the #parents property of your form element is array('foo', 'bar', 'baz') then you may set an error on 'foo' or 'foo\]\[bar\]\[baz'. Setting an error on 'foo' sets an error for every element where the #parents array starts with 'foo'.

In your case you'll just want to make sure that the parent item is different for each instance of that field, then set the error with `form_set_error($parent_name . '][' . $field_name, '...')`
> 1 votes

---
Tags: entities
---


# Question
Title: hook_nodeapi() is great on nodes, but what can I use on non-node pages?
I'm building a module that needs to do stuff wherever the user is browsing, but I used `hook_nodeapi()`, which is ordinarily great but it is not coping with non-node pages (such as views, and user profile pages). Does anyone have any idea on which hook should I run in such circumstances?

# Answer
You have three options:

* hook\_init() This hook is not run on cached pages - though CSS or JS added this way will be present on a cached page.
* hook\_boot() Only use this hook if your code must run even for cached page views.
* hook\_exit() This hook is run at the end of each page request. It is often used for page logging and printing out debugging information. Only use this hook if your code must run even for cached page views.

Performancewise, you will want to avoid `hook_boot()` and `hook_exit()`, since they will run regardless of caching. Having one module that implements those hooks brings the familiar warning on the performance page, "The following enabled modules are incompatible with aggressive mode caching and will not function properly: …"

If all you need to do, is add some Javascript, static HTML, or CSS, `hook_init()` is the best option: the JavaScript and CSS you add will be added to the cache and be present.

If, however, you need to run actual PHP that is not needed for the rest of the request, e.g. to write a record in a database, or log a line to some file, then `hook_exit()` is the best option: it will only be called after the page is already served.

If you need to run some setup: e.g. establish a connection with a service, perform access-check and such, then `hook_exit()` is the best option.
> 2 votes

---
Tags: hooks
---


title: Article page in Drupal

text:
# Question
Title: Article page in Drupal
Usually the articles in a drupal installation are published on the front page, but what I would like to do is to create a menu link to show all articles (instead of the front page)?

# Answer
> 5 votes
You need Views.

With Views you can make highly customizable lists of content. I suggest you use Drupal 7 and Views 3, because its easier to make a View in it than in the version 2. If you are using Drupal 6 try Simpleviews, which will let you create Views very easily too.

I make this suggestions because as a newcomer the full Views interface can be a bit daunting. Have a play around and good luck!

---
Tags: nodes
---


# Question
Title: How do I find out the user name and password for an existing account?
MY site was created and maintained from a developer I cannot contact, and I need to know the username/password the developer used to access the site.

How can I achieve this?

# Answer
If you have access to the database you can change the password with a simple query. If you want to save one step from having to go to the MD5 website you could also use the MySQL built-in function with something like this:

```
UPDATE `users` SET `pass` = MD5('mynewpassword') WHERE `uid` =1;

```

**Note:** That only seems to work for Drupal sites \<= version 6.x. If you are using version 7.x the MD5 hash will not work (I'm guessing it uses some sort of salt string on it). To reset the password on version 7.x you can just change the email address of the admin user to your email address with a query like this:

```
UPDATE users SET mail = 'myemail@mywebsite.com' WHERE uid = 1;

```

Once that is done you can go to the normal login page and just request a password reset, and it will be sent to your email address.

Reference: https://superuser.com/questions/104482/how-do-i-take-control-of-a-drupal-installation-on-my-web-space-without-the-admin
> 4 votes

---
Tags: users
---


title: Node/add within a block?

text:
# Question
Title: Node/add within a block?
Is it possible to have a block that shows the node create page for a content type, and which would disappear once the node has been created?

# Answer
You can use Panels to display a node create form anywhere you like. With a bit of extra config, you could probably make it disappear when a node exists. Panels allows you to set visibility rules to determine whether to show content.
> 2 votes

---
Tags: 6, blocks
---


title: Problem installing a module

text:
# Question
Title: Problem installing a module
When I try to enable a module I get

```
Fatal error: Call to undefined function modulename_cron() in /home/modulename.install on line 17

```

In modulename.install I have

```
function modulename_install() {
  db_query('ALTER TABLE {node_revisions} ENGINE = MYISAM');
  db_query('ALTER TABLE {node_revisions} ADD FULLTEXT `similar` (`title`, `body`)');
  modulename_cron();
}

```

module\_cron() is definitely defined in my modulename.module file. What could cause this problem and how could I fix it?

# Answer
Have a look at the documentation for hook\_install. It says:

> Note that functions declared in the module being installed are not yet available. The implementation of hook\_install() will need to explicitly load the module before any declared functions may be invoked.
> 1 votes

---
Tags: 7
---


# Question
Title: create bilingual language site with drupal 6
i want to build a multi-language site (Chinese and English). From the documentation, I know I should install the Internationalization module, so i installed it, but there are some parts on my site that are not translated.

1. There are some parts as the following in every page (the Chinese version):

```
<h1><a href="<?php print $base_path ?>" title="<?php print t('Home') ?>">测试公司</a></h1>

```

How do I translate *测试公司* when English is the set language?

1. On every page's top right part, there are some parts as the following:

```
<div id="topnav">
  <a href="#" onclick="return setHomepage();">设为首页 |</a><a href="#" onclick="return addCookie();"> 添加收藏  |</a><a href="http://example.com/" class="zh"> 简体中文</a><a href="http://example.com/en" class="en"> English</a>
</div>

```

How do I translate *设为首页*, *添加收藏* and *简体中文* to English, when the user access http://example.com/en?

I know I can put that content in a block, then translate it, but it's too weird.

Is there a simple way to get that?

**ps:** why this one that i can't translate(english--\>chinese)? the code is used to alter the conntact form . `$form['mail'] = array( '#title' => t('E-mail'), '#type' => 'textfield', .` when i searched the `E-mail` in the translate interface, i can't find it,but when i changed `E-mail` to `test`. then i can search it. why? thank you.

# Answer
> 0 votes
You must use the  function on all text if you want translate it directly throw the admin panel.

---
Tags: 6
---


# Question
Title: In what cases should I personally sanitize input & output when using the Database Abstraction Layer
I'm trying to get a clearer sense of where security vulnerabilities on my site may lie. At no point in my code do I ever query the MySQL database directly; I always use the Database Abstraction Layer (db\_query(), etc). Under what circumstances may this not provide sufficient protection against SQL injection attacks?

I am using Drupal 7.

# Answer
If you use `db_query()` all the time without directly inserting variables, but using the arguments.

For example this is right: `db_query("SELECT * FROM {node} WHERE nid = :nid", array(':nid' => $nid));` it's perfect, you don't have to care about something else (except critical bug directly in Drupal).

On the other hand, if you do it directly: `db_query("SELECT * FROM {node} WHERE nid = $nid");` you expose your site to SQL Injection.

From my own experience, Drupal alone (without other modules) is very secure and many times we tried to hack it with professionals.
> 2 votes

---
Tags: 7, database, security
---


title: Drupal $custom_theme caching issues?

text:
# Question
Title: Drupal $custom_theme caching issues?
I have a `hook_boot()` module that detects certain circumstances and changes the theme using `$custom_theme` to a specific theme. All works good, however if Drupal has a cache of the page that page will be served regardless of the fact it is not the correct theme.

Is there anyway to force drupal not to use and caches for that specific theme? Or is there a way to force drupal to keep two caches? One for each theme?

I am using Drupal 6 btw.

# Answer
> 0 votes
From my point of view, the better way is to use your own cache system, but don't worry is nothing very complicate.

Copy the includes/cache.inc and put it somewhere in sites/all/libraries or whatever you want. After in your settings.php you've to add `$config['cache_inc'] = 'sites/all/...';` and Drupal will replace is own cache system by yours. This file contains three functions, clear\_cache\_all, cache\_set and cache\_get. Here the idea is to add the name of your theme before all `$cid`.

I never tried it, so I'm not sure if you can have access to this informations, but you can try .

---
Tags: 6, caching, theming
---


# Question
Title: How do I automatically do an SQL insert when creating a new node?
When creating a new node of a certain type, I want an SQL insert to be made at the same time. The insert operation needs to use the node ID from the node just created, such as `INSERT INTO my_own_db (nid) VALUES ('last inserted node id')`.

# Answer
You've to create your own module and after use a hook\_node\_insert you'll receive a $node object with all informations you need.
> 5 votes

---
Tags: nodes, database
---


title: how do I use overlays in d7?

text:
# Question
Title: how do I use overlays in d7?
Does Drupal 7 have built-in functionality for using jquery overlays? I would like to do some confirmation screens and form-wizard type stuff with them.

# Answer
Have you checked: How to Add a jQuery UI Dialog to Drupal 7?

There is also Drupal 7 jQuery (Popup e ui.dialog), in Italian.
> 2 votes

# Answer
Personally I use jQuery tools.

http://flowplayer.org/tools/

Integrating with Drupal is just a matter of adding a line to your theme.info file, i.e.

`scripts[] = js/jquery-tools1.42/jquery.tools.min.js`
> 0 votes

---
Tags: 7, modal-dialogs
---


title: Content type within content type?

text:
# Question
Title: Content type within content type?
I have such a situation:

I have 4 content types:

city (name) cinema (name, city\_ref, hall\_count) movie (name, description) session (movie\_ref, cinema\_ref, hall\_number, date\_time)

city\_ref, movie\_ref, cinema\_ref are connecting content types with Node Reference module.

After that with Views and EVA I can aggregate some movie listings, etc.

What I want to do is to make site content manager register multiple sessions while entering a movie description, i.e.:

there are number of cities and cinemas created and fixed. But the number of movies may change and content creator opens the form and enters name of the movie, description and then has something like multiple sessions: in the same form content admin can enter session, which automatically has reference to this movie, add reference to the cinema, hall number, date AND (if needed) he could ADD additional session with the same duplicated info, but maybe different hall number/cinema and date.

How could it be solved? Is there any way to connect those content types to make it a bit easier to enter all the data and still have all the relations working?

# Answer
> 1 votes
This sounds like the kind of thing to Node References and the Node Relationships module in D6 or the References module for D7. Both of those suggest other related modules that might helpful as well.

---
Tags: views, nodes
---


# Question
Title: What's the best way to get the email of the author of a referenced node
I'm looking to use a combination of Mailhandler with either Rules or Notifications. When a volunteer creates a "note" (a node that references another node), I want to notify the author of the referenced node. The use case here is a volunteer helpdesk where a volunteer logs a note on a ticket, and the ticket's author receives an email.

It seems like a custom token to locate the ticket author's email would be useful in either situation. Is that the right approach? If so, are there any code samples of creating a D7 token that does something like this?

# Answer
> 5 votes
With Rules:

1. Create a new Rule that reacts on event *After saving new content*.
2. Add a condition *Content is of type* to the rule and select the *note* content type in the content types section.
3. Add an action *Fetch entity by id* to the rule.
    1. As entity type, select *Node*.
    2. In the *Identifier* section, press button *Switch to data selection* (unless you already see an input field labeled *Data selector*).
    3. From the *Data selectors* section, find the selector that references the ticket that is associated to the note. Copy that value into the *Data selector* input field.
    4. In the *Fetched entity* section, set the variable label to "Referenced ticket" and the variable name to "referenced\_ticket"
    5. Save the action.
4. Add an action *Send mail* to the rule. You can now use *referenced-ticket:author:mail* as data selector for the recipient.

---
Tags: 7, tokens
---


# Question
Title: How do I change the default configurations for the node options?
I want to change some default configurations for the node options; for example, the authoring information has 'Authored by' field which is defaulting to auto-complete authors. I want to change this to a drop down instead.

Is there a module that can do this? I learned that editing a module is not advisable, and I cannot find modules that can override default configurations anywhere.

# Answer
Unfortunately in that case, I guess that you should do your own module and use hook\_form\_alter()
> 1 votes

# Answer
Editing a module is not advisable; every time you update the module to resolve issues that have been fixed in the module by other users or from the maintainers, you would lost your customizations. If the change can be useful for somebody else, and not just for you, you can propose a patch that could be accepted, and implemented by the module maintainer.

If the change is not interesting for anybody else, or the change aims to resolve an issue that you only have, then you can create your own custom module that alters the form created by another module.
In Drupal almost everything implemented by a module can be altered: You can alter the theme function defined from another module, or you can alter the form implemented by another module, in the same way you can change the tokens implemented by another module (Drupal 7), or you can alter the file where some hook implementations are looked in (still in Drupal 7).

In this case, you can alter the form using hook\_form\_alter().

```
function mymodule_form_alter(&$form, &$form_state, $form_id) {
  if (isset($form['type']) && isset($form['#node']) && $form['type']['#value'] . '_node_form' == $form_id) {

    if (isset($form['author']['name'])) {
      $form['author']['name']['#type'] = 'select';
      $form['author']['name']['#multiple'] = TRUE;

      // This is not strictly necessary, as the autocomplete is not used with the field
      // we are using.
      unset($form['author']['name']['#autocomplete_path']);

      $form['author']['name']['#options'] = mymodule_build_name_options();
      $form['author']['name']['#default_value'] = $node->name ? $node->name : t('-none-');
      $form['author']['name']['#description'] = t('Select %option for %anonymous.', array('%option' => t('-none-'), '%anonymous' => variable_get('anonymous', t('Anonymous')))),
    );
  }
}

```

`mymodule_build_name_options()` should return the list of the available usernames in an array, such as `array("username 1", "username 2", // …)`.

"mymodule" is the short name of the module you create.
> 1 votes

---
Tags: nodes
---


# Question
Title: Change Field Order of Content Type in the database
I'm using drupal 7. The drag drop interface to re-order fields for a content type seems to be buggy. When I ADD a new Content, i noticed that Translation Settings is always appearing in the middle of my custom defined fields. I go to Structure\>Content Type\>MyContent to re-arrange my fields, but no matter how I sort the fields, when I go back to Add My Content, Translation Settings always appears between the 27th and 28th custom defined field.

So I'm thinking of making this change in the database somewhere. Does anyone know which tables I should be looking at?

# Answer
Yes, I saw this too. The `language` form element was added by locale module in code. If you want to change the weight of this element you can create your hook `HOOK_form_node_form_alter()` and add `#weight` for `$form['language']`.
> 1 votes

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


# Question
Title: Drupal 7 js compression generating 6 files
I'm using drupal\_add\_js and drupal\_add\_library to add some js to my site. But when I turn on the drupal js compression, drupal is aggregating the files but it's generating 6 files and Yslow is saying that it's too much files. Is there any way to force drupal to aggregate more the files? It'd be great if drupal 7 generates only 2 or 3 files per page.

# Answer
Surprisingly, the larger number of files can actually *save* bandwidth on subsequent requests, something that YSlow doesn't take into account. Aggregating everything into a single giant file is really only optimal for visitors that load a single page and no others.

I wrote an article explaining the details in Drupal 7: Taking control of CSS and JS aggregation.

To reduce the number of files, you can try the Core Library module. The article above also has some example code that will group the files together using `hook_css_alter()` and `hook_js_alter()`.
> 1 votes

---
Tags: 7, javascript
---


# Question
Title: How can I limit the taxonomy terms of certain nodes?
I have a content type that can have unlimited taxonomy terms. However those taxonomy terms should be unique to each node ID. Since the user will create the taxonomy terms, should I write a "nid" field with each taxonomy term, or is there a better way?

# Answer
Write a module that implements hook\_node\_validate. The implementation of that hook can check the integrity of the term associations by calling taxonomy\_select\_nodes and report any inconsistencies by calling form\_set\_error.

Beware of the limitations of taxonomy\_select\_nodes:

> This function requires taxonomy module to be maintaining its own tables, and will return an empty array if it is not. If using other field storage methods alternatives methods for listing terms will need to be used.
> 2 votes

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


# Question
Title: Loading a form via AJAX with drupal_get_form()
I am trying to load a form via ajax, here is the code i use:

JS:

```
bigPopupBut.click(function () {
        jQuery.ajax({
            url: "http://site/group_create",
            dataType: "html",
            success: function (data) {
                bigPopup.append(data);
            }
        });
})

```

The group\_create is a PHP script that returns me a form, here is the code i used:

```
$node_type = 'group';
    $form_id = $node_type . '_node_form';
    $node = new stdClass();
    $node->uid = $user->uid;
    $node->name = $user->name ;
    $node->field_city['und']['0']['value'] = $user->field_city['und']['0']['value'];
    $node->field_country['und']['0']['value'] = $user->field_country['und']['0']['value'];
    $node->type = $node_type;
    $node->language = LANGUAGE_NONE;
    $node->path = '';
    node_object_prepare($node);
    $return=drupal_get_form($form_id,$node);
return $return;

```

The Problem i have is that the PHP callback doesn't just return me the form, but a whole page, with headers, body, so when i append it with JS i get a duplicate of the whole page in my bigPopup DIV.

What am i doing wrong ? how could i just get the form without the surounding page?

Thanks all for the help.

# Answer
Try just to do `echo render($return); exit();`.

Otherwise, you should change de delivery callback from the path of your page, and I'm pretty sure that exists one one Drupal for Ajax.
> 4 votes

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


# Question
Title: How to upload images via CKeditor 6.x - 1.3?
is there any way to one click upload images with a CKeditor? Found this https://drupal.org/project/ocupload but sadly - its for 7.x version of Drupal :(

# Answer
Have you tried IMCE it can be attached with a number of WYSIWYG editors like FCK Editor, CK Editor, Tiny MCE
> 1 votes

# Answer
Can you upgrade to ckeditor-6.x-1.5. There you can use plugins for the CKeditor. One of the plugins is the IMCE button. This allowes you to skip the image dialog and upload a file. It still isn't a one click upload, but it's better than the normal IMCE upload.

Add the following line to your ckeditor.config.js \['Link','Image','IMCE'\],

for the toolbar you are using.

Good luck
> 0 votes

---
Tags: wysiwyg
---


# Question
Title: Rotor banner, Toggle the display of an image banner and rotor banner view based on view results
Within the page node is a field for an image that is the page's banner image. We also use Rotor banner to do rotating banner images in the same location. Since I have a default banner set for the page, pages can't have an empty banner field. If a rotor banner view exists, both the page's banner and the rotor banner display stacked on top of each other.

How can I test to see if the rotor banner view has any results and determine whether or not the field banner for the page should display or not? If there is a rotor banner to display, I want to hide or remove the field banner from display.

Both the field banner and rotor banner are living as blocks in the same region. I would like to come up with something for the "Page specific visibility settings" for the blocks, but I'm thinking I will have to do it some how within the theme.

I can't figure out how to see what nodes have been loaded other than using Firebug. If I could access those nodes in a variable accessible to the block or the theme, I could detect if there are rotor items loaded.

Does anyone have any ideas?

# Answer
> 0 votes
Okay, here's my solution:

I added `display:none;` to my CSS for the block that displays the CCK banner image field. In the rotor block view's Empty Text, I added `display:block;` for that CCK banner image field. Seems like a bit of a hack, but it works. Thanks for all of your help.

# Answer
> 1 votes
You can display the image field of the node if the rotator banner is empty by outputting that field into the Empty Text field of the view that you are displaying. So you would only need the view's block in the region that you have both blocks currently. Make sure you have PHP input enabled in your empty text.

If the banner content is exclusive to that node's page, you can add a Node Reference CCK to the banner content type and tie the nid argument in views the the node reference field by adding that node reference field as a relationship in your view.

---
Tags: views, blocks, theming
---


# Question
Title: Customizing User Profile - adding lots of extra parameters retrieved from my own database tables
I would like to **customize the User Profile so that I could display very much extra parameters that the user can set - and display them for users that watch other user's profiles; but these parameters would come from my own database tables**.
I have to create a dating site, where users can set their own parameters like eye color, hair color, height, etc.

I already made a class from which these data can be retrieved and set, I just have to build it in the User Profile - or I could also place it anywhere else, but I thought it would be a more comfortable way to display these among other user parameters - and even set them when the user is watching his/her own profile.

**Besides, I will have to make a page where users can search for their "future partners" depending on the different parameters that the users select** (for example someone looks for a user with blue eyes and blond hair, or anything else :D) - my own queries would run and search for given users.

What do you suggest? Should I make a module? Or should I override my template files? What would be a nice solution? How would You do that in Drupal 6?

I hooe I could clarify what I would like to do, if something isn't quite clear, please ask!
Thanks in advance!

# Answer
Don't put business logic into template files. Override the template files to present the information differently, not to calculate the information in the first place.

Profiles can be extended with the built-in Profile module or with Content Profile module. The latter uses nodes as profile categories, which means you can use CCK fields. You can also write your own profile module. For for this, you have to implement hook\_user. You need to react to at least the following values for `$op`:

* **categories** to provide your own profile categories,
* **form** to show the form for editing items of the categories you provide (in case the *$categories* parameter is one of values you returned via **categories**),
* **delete**, **insert**, **update** to persist changes to the user,
* **view** to show the profile information for your categories.

For the matching, I suggest custom views handlers. Use the Advanced help module to access the developer documentation that comes with views.
> 1 votes

---
Tags: 6, entities, database, users
---


title: FileDepot upload file sizes restriction

text:
# Question
Title: FileDepot upload file sizes restriction
I am using the filedepot module. With this module I am able to upload files. I want to allocate space for "uploading files" to individual registered users basing on user roles.

Is it possible? How do I do it?

# Answer
> 1 votes
I don't believe that is possible with filedepot without patching the module. However it **is** readily available within the IMCE module if you are able to change modules. From the project page:

> * Basic file operations: upload, delete
> * Image(jpg, png, gif) operations: resize, create thumbnails, preview
> * Support for private file system
> * Configurable limits for user roles: file size per upload, directory quota, file extensions, and image dimensions
> * Personal or shared folders for users
> * Permissions per directory
> * Ftp-like directory navigation
> * File sorting by name, size, dimensions, date
> * Tabbed interface for file operations
> * Keyboard shortcuts(up, down, insert(or enter), delete, home, end, ctrl+A, R(esize), T(humbnails), U(pload)).
> * Built-in support for inline image/file insertion into textareas
> * Multiple file selection(using ctrl or shift)
> * Ajax file operations
> * Themable layout using tpl files

For a better idea of what you are looking at, take a look at a screenshot of filedepot.

Everything you need is already built in to IMCE.

---
Tags: files
---


title: How to search by taxonomy terms

text:
# Question
Title: How to search by taxonomy terms
I created a taxonomy called `tags`. I added terms to the vocabulary list.

Then I created a content type called News Item. You can apply tags to News Items.

I created a view to list News Items.

How do I set up a search box that let's people search News Items by tags? they should be able to search by multiple tags. So if the search words are "tutorial learning-resource", then show all news items that have both the tags tutorial and learning-resource.

How do I do this?

# Answer
If I understand well, I think that you can do this with Views, so you can **expose** a **filter** related with `Taxonomy: Term ID` related with your Vocabulary. Remember that you can use the operator 'Contains' if you want to be more laxed in the search.
> 2 votes

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


# Question
Title: How can I sort the search results alphabetically?
I would like to sort the search results alphabetically in Drupal 6.
How can I do that?

# Answer
> 1 votes
You can use the search results of Views, Then you can expose a filter related with you are looking for, and assign the sort condition alphabetically. If you want to expose the sort condition, you can do this with views 3, and with views 2 using the hook query\_alter().

Remember that you can use the operator 'Contains' if you want to be more laxed in the search.

---
Tags: search
---


# Question
Title: How do I add a hyper-link as a content type field?
I want to add a link as a content-type-field, so that it shows up under all the nodes of that content type.

This is because I do not want a link to a taxonomy-term; I want a link to the view I have created for that content type.

# Answer
> 1 votes
For this case you should use one of these (or both) hooks hook\_node\_view and hook\_view

# Answer
> 1 votes
You could use the Link field module, but for your use case, yvan's answer is correct and probably more suitable.

# Answer
> 1 votes
If I understand well, an alternative could be creating a copy of node template. Inside your theme directory, create a copy of file node template node.tpl.php, and rename this copy according your Content Type, for example, if machine name of my content type is `my_content_type`, then:

`node-my_content_type.tpl.php`

and adding your custom field in the place that you want, using the machine name of your field, for example, if your field is a cck field, and the machinename is `respective_field_name`, then :

```
  <div class="content clear-block">
    <?php print $content; ?>
  </div>
  <?php echo $node->respective_field_name[0]['value']; //this is the new line near to $content variable ?>

```

---
Tags: views
---


# Question
Title: Content dependent on the IP of the viewing user
Is there any drupal module for implementing such behaviour? I want to display content especially selected for the user, based on her localisation/IP.

**Can you propose some solution?**

For example, for a side bar I would like to have a set of filters:

* in case of IP in mask xx.xx.xx.xx display side bar A
* in case of IP in mask yy.yy.yy.yy display side bar B
* in case of any other IP display default side bar

# Answer
I think that this depend that you are looking for. See this information if you want to hide a block according certain conditions http://drupal.org/node/134425 (you can custom your php using $\_SERVER\['REMOTE\_ADDR'\] to get IP address)

If you want to show or hide whole sidebar, I think that you can make this in template.php (in your theme), adding with php your IP condition, and according the result of condition, set (and/or unset) regions. See this for more/related information http://drupal.org/node/539488
> 1 votes

# Answer
Domain Access might also be what you're looking for.
> 0 votes

---
Tags: nodes, i18n-l10n
---


title: Save own fields in database

text:
# Question
Title: Save own fields in database
i've altered a form by adding my own fields. they're not part of the node. i'm wondering which hook to use, to save these fields in the db.

i guess hook\_nodeapi is the right one, but the form variable only gets transfered in the 'validate' $op, and it doesn't seem right to save data in the validate operation.

So how would i go about that?

# Answer
When you alter a node editing form, the fields you add *are* part of the node and can be accessed using the **$node** argument of **hook\_nodeapi**. Save your data when **$op == 'insert'** and **$op == 'update'**.

If you do not want your fields to become part of the node, write a form submit handler and add its name to the **$form\['#submit'\]** array. The submit handler should remove all your fields from **$form\_state\['values'\]** (in addition to whatever was intended when adding the field to the form).
> 2 votes

# Answer
with CCK module http://drupal.org/project/cck you can add your own fields to your content types, and each field will be stored in the database. CCK is a common module to create your own custom fields easily, see the documentation http://drupal.org/node/101723, .
> 1 votes

---
Tags: 6, forms, nodes
---


# Question
Title: Admin's node set to published by default?
I currently have nodes set to unpublished by default because I want to approve user submitted content before publishing it live. However, admins should have their nodes published by default. How can I accomplish this?

# Answer
Assuming Drupal 6.

Define a hook\_form\_alter function in your custom module and set the '#default\_value' of the status element to TRUE. This will only run if the user has the correct permission. This way, nodes can also be unpublished by unticking the 'Published' checkbox.

```
function mymodule_form_alter(&$form, &$form_state, $form_id) {
    if (user_access('administer nodes')) { // or other permission
        $form['options']['status']['#default_value'] = TRUE;
    }
}

```

Now your admin's nodes will be automatically published.

Thanks to andy for his comments.
> 3 votes

---
Tags: 6, nodes, workflows
---


# Question
Title: "#markup" form element can't have children
I have my form, but any child of the "#markup" element will not appear when the form is being rendered.

```
$form['html'] = array(
  '#type' => 'markup',
  '#markup' => '<h2>My Heading</h2>',
  '#tree' => true,
);

$form['html']['element'] = array(
  '#type' => 'textfield',
  '#title' => 'Foo',
);

```

In this example the "element" form field will not be rendered.

Is this a Drupal bug, or do I need to do something specific?

# Answer
Not being able to use "#tree" with a "#markup" element seems a bug of Drupal, as the reference page for the form API reports that "#tree" is supported by the "#markup" element.

As workaround, you can also use the "#prefix" property, as in the following code:

```
$form['html']['element'] = array(
  '#type' => 'textfield',
  '#title' => 'Foo',
  '#prefix' => '<h2>My Heading</h2>',
);

```

If it is not rendered as you expect, then you can simply remove "#tree" from your code, which doesn't seem to be needed, if all you want is to render the `<h2>My Heading</h2>` tag before the form fields. The form API renders the elements following the order they appear in the array; if you want to alter the order, you can use the "#weight" property.

```
$form['html'] = array(
 '#type' => 'markup',
 '#markup' => '<h2>My Heading</h2>',
);

$form['html']['element'] = array(
  '#type' => 'textfield',
  '#title' => 'Foo',
);

```
> 9 votes

---
Tags: 7, forms
---


# Question
Title: Adding class to form element via hook_form_alter for views exposed filter is not working
I have a Views exposed filter, for which I am trying to add a class via `hook_form_alter()` with the following code:

```
$form['price']['#attributes'] = array('class' => array('price-hide'));

```

Outputting the form array with devel shows that this is adding the attribute fine; however I can only assume there is another `hook_form_alter()` running after my module that is wiping my attributes, as other attributes are being added, and mine never make it to the HTML output.

I've tried moving from `hook_form_alter()` to `hook_form_views_exposed_form_alter()` since I remember that hook running at a different time than `hook_form_alter()`; however, this doesn't seem to make any difference.

# Answer
> 3 votes
Did you check the actual markup after the page is rendered with Firebug or something to see for sure if another module's hook\_form\_alter() is overriding yours? If that is indeed the case then an easy way to get around is it by increasing your module's weight so hook\_form\_alter() in your module is called after other modules.

```
db_query("UPDATE {system} SET weight = 20 WHERE name = 'my_module'");

```

EDIT: I should say that this code should go in `hook_install()` and you should then reinstall your module to get the weight set properly.

---
Tags: 7, forms, views
---


title: SEF URLs in Drupal 7.7?

text:
# Question
Title: SEF URLs in Drupal 7.7?
I've enabled Clean URLs which has tidied my URLs up a bit, however I need them completely rewritten for SEO purposes. For instance my 'blog' content type should be '/blog/blog-entry/' rather than 'node/etc'.

I've looked around but I can't find a stable solution for 7.7 ? Either a module or hook function in my theme would be fine

Thanks in advance

# Answer
> 2 votes
Go get pathauto http://drupal.org/project/pathauto With pathauto you can set up automatic path aliases to do exactly what you want. It will basically allow you to set up patterns for how to build token based paths for new pages at the time of their creation. It's one of the most widely used Drupal modules and is an absolute necessity for any site.

Also, once it's enabled and you've set up your paths the way you want them you can regenerate existing aliases in bulk at the content overview page.

---
Tags: uri
---