# Question
Title: Administrator users can add records, end users can view them
How can the administrator users add few records into the database (through a form), and how can the end users view them in the front end?

1. Administrator users will be adding records of training classes, through a form in an administration panel.
2. The end user will be viewing the list of training classes in the front end, in a block.

How to achieve these tasks?

# Answer
here in short all the steps for the simplest solution I can think of:

1. depending on your content (needed fields...) you may need to create a new contentype (YOURCONTENTTYPE)(maybe using the CCK module (drupal6))
2. make sure the roles are set correctly (e.g. admin can create and view this content, authenticated only view...) via `admin/user/permissions`
3. create a block (node-)view with the views module where you filter by YOURCONTENTTYPE and sort by date
4. modify the visibility setings of this block via `admin/build/block` or in the view itself
5. admin can create content via `node/add/YOURCONTENTTYPE`

But it really depends on what exactly you want to do.
> 3 votes

# Answer
In Drupal, there isn't a flag that set a page as administration page, and a tag that set a page/block for end users.

What makes a page for administrator users is the permission that users needs to have to see that page. A settings page requiring the users to have the permission to administer users is considered an administration page; the same is true for a setting page requiring the permission "administer content type," or "administer nodes."

If you have a page that needs to be seen only from administrators, then you need to use an existing administration permission, or implement a module that implement the specific permission that you need.
A block implemented by Views can use the permission implemented in other modules as well, and you can set the permission users need to have to view a block (or in general, a view) created with Views.
> 1 votes

---
Tags: views, forms
---


title: Views 3 Relationship Handler

text:
# Question
Title: Views 3 Relationship Handler
I am trying to write a relationship handler for Views 3 in Drupal 7, but am failing even to begin.

Basically, I have a bunch of nodes of various types all with the same field attached to them. This field is a reference field linking off to a Civicrm contact - but that's not important, as essentially these fields just contain integers.

Now, let's say I have a node of content type 'story', and its reference field contains the integer, oh, let's say 55. In addition, there are nodes of content type 'news' which also contain the reference ID 55.

I want to build a block view, that sits on the story page, that reads in the node's nid as its argument, and then through a relationship it discovers all other nodes that contain the same reference integer as itself.

(In my head, the sql looks something like: `SELECT n.nid FROM node n INNER JOIN node n2 ON n.reference = n2.reference` \[Assuming, for the sake of simplicity, the field data is kept in the node table\]).

How do I create a Views handler that caters for this relationship? The only documentation I can find is the views api, which is for version 2 and not 3, and besides is utterly unhelpful. Reading various module's views handlers is not helping either, and views tutorials on the web are almost non-existent.

# Answer
Are you really sure you need a relationship handler for this?

In general the default relationship handler is already quite flexible because it uses the default join class which is really powerful.

There are some use cases for relationship handlers, for example the relation module, but this module does some vodoo stuff.

So back to the problem. It might be enought if you define 'relationship' with the right field and base field.

PS: There is a big reason why there is no documentation about api=3 because the difference to api=2 isn't big at all.

Here is an example how to define a relationship.

```
  $data['node_revision']['vid'] = array(
    'relationship' => array(
      'handler' => 'views_handler_relationship',
      'base' => 'node',
      'base field' => 'nid',
      'title' => t('Content'),
      'label' => t('Get the actual content from a content revision.'),
    ),
  );

```
> 8 votes

---
Tags: views
---


# Question
Title: very bad thing of output the vocabulary in drupal 7
I created four vocabularies for the "article" content type.
I want to output the vocabulary which belongs to the node; when I used `print render($conetent['field_vocab'])`, it output the vocabulary, but the HTML structure is too bad; more useless `<div>` and classes make me crazy. In order to remove them, I output it like this:

```
$content['body']['#object']->field_vocab['zh-hans'][0]['taxonomy_term']->name;

```

It's too long, and it makes me crazy too. If the vocabularies contain more than one taxonomy term, it only prints one.

Is there a better way to output the vocabulary?

# Answer
What you are looking for is what is called field formatters. It is essentially theme function for themes, and can be used to render the same field in \['form'\] ways. You can create a custom field formatter where you render the output of the field how you want.

To read more about fields and formatters see: http://drupal.org/node/707832
Or you can checkout this step by step guide on how to create a field formatter.

Another option would be to simply overwrite the theme function (That can be done with any theme function) used for the default field formatter, which would then effect all of the fields across your site.
> 3 votes

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


# Question
Title: Custom field widget with text field formatter?
I'm trying to create a compound field in Drupal 7 that combines and image field, text field and a textarea field.

I've successfully done this but I'm now trying to add text format option to the textarea and I'm having problems getting it working.

It seems that when I change the widget's `textarea` field into a `text_format` field Drupal expands that field into two fields `value` and `format` (see: filter\_process\_format), this means that when the node displaying the field is saved it stores the array into the database and not the field value.

Here is my widget:

```
/**
  * Implements hook_field_widget_form().
  */
function MYMODULE_field_widget_form(&$form, &$form_state, $field, $instance, $langcode, $items, $delta, $element) {

    $elements = image_field_widget_form($form, $form_state, $field, $instance, $langcode, $items, $delta, $element);

    foreach (element_children($elements) as $delta) {
        foreach ($elements[$delta]['#process'] as $key => $process) {
            if($process == 'image_field_widget_process') {
                unset($elements[$delta]['#process'][$key]);
            }
        }
      $elements[$delta]['#process'][] = 'MYMODULE_widget_process';
    }

    return $elements;
}

/**
 * Element #process callback function.
 *
 * @param array $element
 * @param arrayreference $form_state
 * @param array $form
 * @return array
 */
function MYMODULE_widget_process($element, &$form_state, $form) {

    $element = @image_field_widget_process($element, $form_state, $form);

    $item = $element['#value'];
    $item['fid'] = $element['fid']['#value'];

  $instance = field_widget_instance($element, $form_state);

    $settings = $instance['settings'];
    $widget_settings = $instance['widget']['settings'];

    $element['title'] = array(
        '#type' => 'textfield',
        '#title' => 'Title',
        '#default_value' => isset($item['title']) ? $item['title'] : '',
    );

    $element['text'] = array(
        '#type' => 'textarea',
        '#title' => 'Text',
        '#default_value' => isset($item['text']) ? $item['text'] : '',
    );

    if($instance['settings']['text_processing']) {
      $element['text']['#type'] = 'text_format';
      $element['text']['#format'] = isset($item['format']) ? $item['format'] : NULL;
      $element['text']['#base_type'] = 'textarea';
    }

    return $element;
}

```

The field value in the database is "Array" and not the string the user entered. If the field is set to a normal textarea the field value is stored correctly.

I'm guessing this is something to do with the structure of the widget but I can't work it out and the documentation is non existent.

# Answer
I recently needed to create a widget for file field, that among other things needed to be able to handle multiple uploads via plupload.

Anyways, during the process of getting everything to work, I discovered the `#value_callback` attribute that you can put on a form item. It allows you to change the data of the submitted data and extra extra infomation, like fid of a file.

This isn't documented yet, but you can take a look at it's use in the file module. There is an issue for this on the Drupal issue tracker, but no good patch has been created with some document example yet.

I'm not sure if this would be a good case for the use of `#value_callback`, but it seems to me, that it could be of good use in this case.
> 2 votes

---
Tags: 7, entities
---


# Question
Title: Display a field of a node that is referenced on another node via a relationship
I have two content types, "Stores" and "Offers." In the "Offers" content type, there is a CCK node reference field type that references the "Stores" nodes. So essentially, I create a store and if the store has an offer, I create the "Offer" node and select the store with which it is associated.

I have a view (a default glossary view) that displays a list of stores. I would like to display the node titles of any offers that are associated with it but I can't figure out how to do it.

I have tried to add a relationship on the node reference field then add a field that uses the relationship but the result just appears blank.

# Answer
> 0 votes
I finally went with something similar to Stefan's answer. I created a module using `hook_views_pre_render` that checks the correct table against the node id to see if there are any related nodes. The code is shown below.

```
<?php

/**
 * Implementation of hook_views_pre_render()
 */
function gretna_views_pre_render(&$view) {
    // Select the right view
    if ($view->name == 'stores_list') {
        // Check how many results there are
        $count = count($view->result);
        // For each result (reason we don't use foreach is every result is duplicated twice)
        for($i = 0; $i < $count; $i++) {
            // Get the nid for this row
            $nid = $view->result[$i]->nid;
            // Check to see if the node has any related offers
            $result = db_query("SELECT nid FROM {content_type_store_offers} WHERE field_offer_store_nid = %d", $nid);
            $result = db_fetch_array($result);
            // If not false, the row has offers
            if ($result !== FALSE) {
                $view->result[$i]->users_uid = "Yes";
            }
            // Else it doesn't
            else {
                $view->result[$i]->users_uid = "No";
            }
        }
    }
}

```

# Answer
> 1 votes
In your view style template you can access the node reference value, load the related node and then do whatever you need with that. You don't need a relationship for this approach.

---
Tags: views, nodes
---


# Question
Title: Show only unread content; remove item once read or option to remove items
I require a view which only shows unread content or provides functionality to remove items listed in the view once the node has been accessed. Alternatively a "x" button to remove the items manually for users.

So for example a view would show article's 1, 2, 3 & 4.

Once I had visited article 1 & 4 the view would now only show 2 & 3.

# Answer
> 1 votes
You can filter nodes exactly this way (a node filter called timestamp I think).

I'm not sure what the best way would be to solve the "x" button thing. Maybe add an extra binary field to the contenttype which you set via ajax (triggering a function you defined via "page callback" in hook\_menu()) when clicking the "x". Then you have to add this field to your views filter as well.

Edit:

Instead of an extra CCK field you could also insert data into the `history`-table (uid, nid, timestamp) of drupal and pretend the user has already viewed the node. This way you would only need first views filter.

---
Tags: views
---


# Question
Title: View of nodes grouped by tag including not tagged elements
My feature includes custom code, some views, content types and a taxonomy vocabulary.
An overview page should list all contents grouped by their taxonomy term (tag). The first group should be "not tagged".

How do I add the "not tagged" group?

# Answer
not really sure how you're getting your lists, you mention custom code, and views.... if you just need a list of nodes that have no taxonomy term:

```
$nodes=db_query('SELECT * FROM node AS n LEFT JOIN taxonomy_index AS ti ON n.nid=ti.nid WHERE ti.nid IS NULL')

```

will give you that.

you could add a join to the taxonomy\_term\_hierarchy table and a WHERE clause to determine if the node has a term associated that is part of your vocabulary
> 1 votes

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


# Question
Title: How to display specific forms in drupal 7?
I need to display the system login form and the system registration form on the same page but different panels (not tabbed like the default). I don't want to build a form from scratch using the forms api. I want to pull the accrual forms from the system and use them. The result should be much like the home page of facebook before you login, on the same page you can either login or sign up. I want to do all this from code, not from a module but from the page.tpl.php file. I have a special function that will display a completely different page for the home page.

# Answer
> 5 votes
I would recommend using blocks with conditional views instead of hard coding this into your template file, but if that's really what you want to do, you basically just need to use drupal\_render and drupal\_get\_form in the appropriate places in your template file i.e.:

```
Login:
<?php print drupal_render(drupal_get_form('user_login')); ?>
 - OR -
Register:
<?php print drupal_render(drupal_get_form('user_register_form')); ?>

```

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


# Question
Title: Module development - integrating custom content types
I want to create a module which would need custom content types from the cck module. I know in the .info I can say a dependency is the cck module.

How can I best have the module create the content type? I want this to be easily distributed rather than when I put it on a website I have to also create the content type using cck.

# Answer
> 3 votes
One way is to create an export of a CCK content type to use in the module. For an example of this method see How to create a CCK content type and fields from a module.

Another exported CCK example

---
Tags: 7, entities
---


# Question
Title: Several field templates or on node template?
Try to figure out when field templates are the wrong approach...

I've been told and agree that you should ultimately avoid creating node templates and try to process things before they hit the theming layer. I believe this because you alway want to add more room for theming later, and data changes should stay with the proper entity... at least a field template if not template preprocess, nodeapi, etc.

So... if I have a node type that's requiring I end up with 3-5 field templates, to do some logic on the display of links vs. text, add standard suffix text, etc. **When do I throw in the towel and just do it all in the node template because that's the right thing to do?**

Maybe I just need contemplate?

Your thoughts?

# Answer
I would never recommend Contemplate to someone who needs true control over the output.

Here is what I usually do:

I make php stuff and logic stuff on the node\_preprocess, only sending to node.tpl variables ready to be echoed, or arrays to be foreach'ed and then printed, in the case of cck fields with multiple values.

And I never run functions of any type on node.tpl.php. If you need to run a function, run it on preprocess!

Using this approach my templates become faster, as they can take take a little more advantage of the internal template caching system, and also, my node.tpl.php gets REALLY easy for me and others to understand it.
> 2 votes

---
Tags: entities, theming
---


# Question
Title: ImageCache or different CCK image fields?
I'm setting up a website with lots of different image presets (probably up to five or six), so basically depending what page and what view my story teasers end up in they will have different dimensions, however, the web publishers need to have as much control as possible over the way the photos are cropped and resized. Is it better to use ImageCache or have different CCK image fields and have the publishers crop the images to their liking in an external image editor such as photoshop and then upload all of the presets to Drupal so the story can automatically display the right preset depending on what page and view displays it?

Also, is it possible to set up different presets for ImageCache depending on which view displays the image? Finally, it doesn't seem to me that imagecache offers cropping functionality per se. Am I correct?

# Answer
> 2 votes
Imagecache can crop. Exact or relative dimensions.

And yes, you can choose the preset for an image field in views. It is very easy. And you can manipulate it with code, but that would be much more complex. I don't think you need this.

If you **really** need the publishers to manipulate the image **on the node edit form**, just use IMCE. It integrates with Imagecache, so they could use that.

But the more you can automatize the process, the better.

So try to allow your publishers to send images the way they like (only being bigger than the minimum size you will ever use), and then you use imagecache dynamically to crop and resize the images the way you want over all the places on your site.

---
Tags: media
---


title: Change content types

text:
# Question
Title: Change content types
Is it possible to change node content types? I have a bunch of story nodes and I would like to create several content types and reassign each story to a different content type. Is there a way to automate this either through the drupal administration area or the database?

Thanks! Jane

# Answer
It is possible with Node Convert.

> Node Convert adds a menu tab "Convert" on the node view page, i.e. node/1/convert, which gives the ability of converting the node from it's current node type, to another node type. Also it gives the ability of transfering all the custom cck field values of the current node type, to the destination cck fields, or discard them. As of 5.x-1.4 you can bulk convert many nodes of the same type, to another one that can be accesed in Administer-\> Content -\> Convert Nodes.
> 3 votes

---
Tags: entities, nodes
---


# Question
Title: put the code into the template.php file?
```
<div class="meta">
  <?php
    echo  $submitted;
    $common = $content['body']['#object']->field_fenlei['zh-hans'];
    foreach($common as $vocab){
      echo  l($vocab['taxonomy_term']->name,$vocab['taxonomy_term']->uri['path']);
    }
  ?>
</div>

```

This code is the one I wrote for node.tpl.php, and it's too bad. Is there a way to put the code into the template.php file? How do I do?

# Answer
> 5 votes
It's fine to put code in template.php, but do not print or echo there. All print or echo code should be in template files (.tpl.php). If you need to prepare variables for output in a template file, alter a preprocess function (eg. THEMENAME\_preprocess\_page if you need them in page.tpl.php), add your variables to the $variables array (eg. `$variables['greeting'] = 'Hello!';` and print those variables in the template file (`print $greeting;`).

So for this example it would be something like:

```
function THEMENAME_preprocess_node(&$variables) {
  $common = $variables['content']['body']['#object']->field_fenlei['zh-hans'];
  $term_links = '';
  foreach($common as $vocab){
    $term_links .= l($vocab['taxonomy_term']->name,$vocab['taxonomy_term']->uri['path']);
  }
  $variables['fenlei_term_links'] = $term_links;
}

```

Now you can access the output with the variable $fenlei\_term\_links in your node.tpl.php:

```
<?php print $fenlei_term_links; ?>

```

In general you might want to use something like http://api.drupal.org/api/drupal/includes--theme.inc/function/theme\_links or http://api.drupal.org/api/drupal/includes--theme.inc/function/theme\_items

# Answer
> 1 votes
In template.php:

```
function THEME_preprocess_node($vars) {
  $node =& $vars['node'];
  if (!empty($content['body']['#object']->field_fenlei['zh-hans']) {
    foreach($content['body']['#object']->field_fenlei['zh-hans'] as $vocab){
      $vars['common'][] = l($vocab['taxonomy_term']->name, $vocab['taxonomy_term']->uri['path']);
    }
  }
}

```

In node.tpl.php:

```
<div class="meta"><?php
  print $submitted;
  print implode('', is_array($common) ? $common : array());
?></div>

```

---
Tags: theming
---


# Question
Title: Why does boost turn off standard caching?
When you enable the Boost module, it disables the standard Drupal caching (as at http://drupalperformanceblog.com/drupal-performance-tips), but it only reports boost as being incompatible with "aggressive" caching, and allows you to turn it back to "normal."
Does boost turn this off because it's unnecessary, or because it's actively harmful? Or does it not matter anyway?

(See also Is it redundant to use the "boost" module if varnish is used? with reference to using multiple caching systems.)

# Answer
> 6 votes
It's the System module that disables the aggressive caching when there is a module that implement hook\_boot() or hook\_exit().

The explanation is reported in the description text that appears in the form field to choose the type of caching.

> The normal cache mode is suitable for most sites and does not cause any side effects. The aggressive cache mode **causes Drupal to skip the loading (boot) and unloading (exit) of enabled modules** when serving a cached page. This results in an additional performance boost but can cause unwanted side effects.

The code that executes that verify is the following one (system\_performance\_settings()):

```
  $problem_modules = array_unique(array_merge(module_implements('boot'), module_implements('exit')));
  sort($problem_modules);

  if (count($problem_modules) > 0) {
    $description .= '<p>' . t('<strong class="error">The following enabled modules are incompatible with aggressive mode caching and will not function properly: %modules</strong>', array('%modules' => implode(', ', $problem_modules))) . '.</p>';
  }

```

Boost only changes the content of a Drupal variable with `variable_set('cache', CACHE_DISABLED)`; as it does it in its implementation of hook\_enable(), it will disable the normal caching all times it is enabled. The reason for disabling it is reported in a comment before the code that changes that variable: "Forcibly disable Drupal's built-in SQL caching to prevent any conflicts of interest."
That means the module disables it just to avoid that both Drupal and Boost use their own cache, with the result of obtaining data from a cache that is then replaced with the content of another cache.

It could have been a better idea to hide the cache selector when Boost is enabled. In that way, users could not enable the cache that Boost disables when it is enabled.

As side note, `hook_boot()` has been removed from Drupal 8, and `hook_exit()` is probably going to be removed from Drupal 8 too. What I reported here for Drupal 6/7 will not be anymore true for Drupal 8.

---
Tags: caching
---


# Question
Title: Seeking iPhone/iPad JavaScript/jQuery libs, techniques & tutorials
Client wants iPad & iPhone support for a webapp that has at least one form where DOM elements are dragged around on a (Raphael) Canvas (JavaScript rendered graphic).

Currently, the touch-unfriendly interface to drag items around uses mouse-hover and other mouse states to handle the drag-items interface. I know I'll need a completely different approach for touch screen devices, and am wondering if any fellow Drupal developers have posted their breadcrumbs as they faced this.

Drupal 6 or Drupal 7 does not matter, since this is at the JavaScript layer unless the possible solution requires jQuery only available in Drupal 7.

# Answer
> 1 votes
The only thing that I know of that's close to what you want is on Eric London's Drupal blog where he talks about themes and redirects for mobile versions of Drupal websites. I'd be interested in knowing more about this too, sorry that I couldn't be of more help.

---
Tags: theming
---


# Question
Title: Drush: difference between pm-update pm-updatecode
What's the difference between pm-update and pm-updatecode? I reviewed this in the Drush documentation, but they sound the same.

# Answer
> 3 votes
`pm-update` also runs the `update.php` script to take care of any database schema changes that a module may need (same as `drush updatedb`), `pm-updatecode` doesn't. Under many/most circumstances, you can just run `pm-update`.

---
Tags: drush
---


title: Content profile title token

text:
# Question
Title: Content profile title token
I need a content profile title token. I downloaded this small module, but it works only for text\_field and I need a title.

# Answer
Did you try the Content Profile Tokens module? It is a sub-module of content profile 1.x.

Your content profile title could be a node title or a CCK field; the token \[title\] or \[field\_titlefieldname-raw\] will provide the value you expect.
> 1 votes

---
Tags: tokens, users
---


# Question
Title: Form API: Show/Hide/Select option based on a previous option
> **Possible Duplicate:**
> Easiest method for conditional fields in a form

Essentially I have 2 select fields on a form:

**EDIT**: I should mention, this is an entirely custom form built with Form API, I'm not modifying a core/contrib form.

* Type

+ Global
    + Regional
* City

+ Any
    + London
    + New York
    + Paris
    + LA

If Type:Global is selected, then the City field is hidden and City:Any is selected.

If Type:Regional is selected, then City is revealed, City:London selected and City:Any hidden.

Is there a Drupal or Form API compliant method to achieve this or is it simply a case of loading a JS file with drupal\_add\_js and writing entirely custom JS?

If it's simply custom JS/JQuery no need to write it out for me, I can handle that, but I would like to try and stick to the standard and best practices if there are any for my problem.

Thanks!

# Answer
You can solve this problem using AHAH on your Form API. The module AHAH Helper may be very useful for you... take a look there...
> 1 votes

---
Tags: forms, javascript
---


# Question
Title: What's the functional difference between the "disabled" and "external" caching setting?
I've seen the answer elsewhere that "External lets you use varnish, etc" but what are the internal differences between external and no caching? Does external actually cache anything, or is there a difference in headers sent?

# Answer
> 1 votes
There is like you say a difference in the headers that drupal send out. I've based this answer on Drupal 6 since it seems from the text you quote that this is the version you are referring to.

Anyways, in `bootstrap.inc`, drupal will call `drupal_page_cache_header_external` when external cache is turned on. I posted the function below since I couldn't find it on api.drupal.org

```
/**
 * Set HTTP headers in for downstream caching.
 *
 * The headers allow as much as possible in proxies and browsers without any
 * particular knowledge about the pages. Used for the external caching mode.
 */
function drupal_page_cache_header_external() {
  // Get headers set in hook_boot(). Keys are lower-case.
  $hook_boot_headers = drupal_get_header();

  $max_age = variable_get('page_cache_max_age', 0);
  drupal_set_header('Cache-Control', 'public, max-age=' . $max_age);
  drupal_set_header('Last-Modified', gmdate(DATE_RFC1123, $_SERVER['REQUEST_TIME']));

  // HTTP/1.0 proxies do not support the Vary header, so prevent any caching
  // by sending an Expires date in the past. HTTP/1.1 clients ignores the
  // Expires header if a Cache-Control: max-age= directive is specified (see RFC
  // 2616, section 14.9.3).
  drupal_set_header('Expires', 'Sun, 11 Mar 1984 12:00:00 GMT');

  // Allow HTTP proxies to cache pages for anonymous users without a session
  // cookie. The Vary header is used to indicates the set of request-header
  // fields that fully determines whether a cache is permitted to use the
  // response to reply to a subsequent request for a given URL without
  // revalidation. If a Vary header has been set in hook_boot(), it is assumed
  // that the module knows how to cache the page.
  if (!isset($hook_boot_headers['vary']) && !variable_get('omit_vary_cookie', FALSE)) {
    drupal_set_header('Vary', 'Cookie');
  }
}

```

# Answer
> 1 votes
External caching is just a caching system that doesn't use the database tables used by Drupal to cache data, or doesn't use any table in the database used by Drupal. Example of external caching systems includes APC, eAccelerator, Memcache/Memcached, Varnish, XCache, or even a system that uses files instead of database tables.

All those systems surely cache data, or there would not be any difference between using them, and disabling the cache completely. The only difference with the standard Drupal cache system is where the data are cached.

---
Tags: caching, 6
---


title: getting node items by taxonomy

text:
# Question
Title: getting node items by taxonomy
I can get a list of node items by content type, using the following query:

```
$query = db_select('node', 'n');
    $query->condition('n.status', NODE_PUBLISHED);
    $query->condition('n.type', 'slider');
    $nids = $query
        ->fields('n', array('nid'))
        ->orderBy('changed', 'DESC')
        ->range(0, 4)
        ->addTag('node_access')
        ->execute()
        ->fetchCol();
    $nodes = node_load_multiple($nids);

```

I want to filter this output further with taxonomy. How can I do this?

# Answer
> 1 votes
You need to use the `EntityFieldQuery` instead of the `SelectQuery` that `db_select` uses. You should do something like this:

```
$query = new EntityFieldQuery();
$result = $query
  ->entityCondition('entity_type', 'node', '=')
  ->entityCondition('bundle', 'slider', '=')
  ->fieldCondition('fieldname', 'tid', $tid)
  ->propertyOrderBy('changed', 'DESC')
  ->range(0, 4)
  ->addTag('node_access')
  ->execute();

```

The results will be an array of objects containing the nid and vid.

Read more about the `fieldCondition`

# Answer
> 0 votes
```
$query = new EntityFieldQuery;

$entities = $query
  ->entityCondition('entity_type', 'node', '=')
  ->entityCondition('bundle', 'slider', '=')
  ->propertyCondition('status', NODE_PUBLISHED, '=')
  ->fieldCondition($field, 'tid', $tid, '=')
  ->propertyOrderBy('changed', 'DESC')
  ->range(0, 4)
  ->addTag('node_access')
  ->execute();

$nodes = entity_load('node', array_keys($entities['node']));

```

`$field` contains the name of the taxonomy term field; `$tid` is the taxonomy term ID for which the list of nodes is filtered.

---
Tags: taxonomy-terms
---


# Question
Title: What is the default value for $operator in condition()?
Basing on `QueryConditionInterface::condition()`, the default value for `$operation` is `NULL`, while Conditional clauses says its default value is `'='`.

What is the default value? Does it change basing on the datatype of `$value`, for example it's `'IN' for array and` '='\` for integers and strings?

# Answer
QueryConditionInterface is just that, an interface. The actual class used is DatabaseCondition.

In DatabaseCondition:condition(), it does set the default operator:

```
if (!isset($operator)) {
  if (is_array($value)) {
    $operator = 'IN';
  }
  elseif (!isset($value)) {
    $operator = 'IS NULL';
  }
  else {
    $operator = '=';
  }
}

```
> 3 votes

---
Tags: database
---


title: Setting up and enabling Google CSE

text:
# Question
Title: Setting up and enabling Google CSE
Is it possible to fully set up and enable Google CSE module before a website is launched? Or would I have to wait until it's launched and submitted to Google's search engine?

# Answer
> 3 votes
You can set it up now but it would be much use until your content is fully indexed by Google

# Answer
> 0 votes
Sort of doable question to answer. The answer is specif to the site that you are building. I would set up Google CSE module when I think my site has adequate contents and almost ready to go live.

---
Tags: 7, search
---


# Question
Title: Helper to get the raw value of a node field?
I wonder if something "core" already exists that gives me the raw value of a field inside a node. For that matter I wrote this little helper, but it seems too strange not to be able to do it with a core function:

```
function mymodule_get_node_field($node, $name, $lang = 'und', $key = 'value') {

  if (substr($name, 0, 6) != 'field_') {
    $name = "field_{$name}";
  }

  if (!is_object($node) || !isset($node->{$name}) || !isset($node->{$name}[$lang])) {
    return null;
  }

  return $node->{$name}[$lang][0][$key];
}

```

# Answer
The only thing I know is field\_get\_items().

Your function makes a lot of assumptions that don't work for a core function.

* Not all fields are prefixed with field\_, only those created through the UI. body for example not.
* Some fields have multiple values, your function only returns the first.

If you want a function that makes these assumptions, you could write a simple wrapper for field\_get\_items() that takes care of that.
> 1 votes

---
Tags: 7, entities
---


# Question
Title: How to get rid of CKEditor and recover access to admin pages?
**I can't access anymore to many module's admin page (especially CONTENT : bueditor, wysiwyg, smileys. And MEDIA : IMCE or Imagepicker) since I uninstall CKEditor.** I don't know if that's exactly linked but since then, when I go to `admin/config/content/` I get "Advanced Forum", "Text Format", and "CKEditor" even if I've uninstalled it.

Of course, when I click on "CKEditor", I get a normal PHP error :

`Fatal error: require_once() [function.require]: Failed opening required '*****/sites/all/modules/ckeditor/includes/ckeditor.admin.inc' (include_path='.:/usr/lib/php5') in *****/includes/menu.inc on line 501`

**BUT if I try to force access, like typing admin/config/content/bueditor or admin/config/media/imce, I'm redirected to admin/config/content/ or admin/config/media**

P.S.: I'm on D7.

# Answer
> 1 votes
I have to ask, did you properly uninstall CKEditor? As in disable the module first (in admin/modules) and then uninstall (admin/modules/uninstall)?

It sounds like you just deleted the folder without uninstalling it properly...

---
Tags: wysiwyg
---


title: Node pagination

text:
# Question
Title: Node pagination
I was wondering if there was a way in Drupal to create previous/next links between about 100 nodes of a specific content type. I know there is a pager module, but that allows you to break one node up into several pages, but I can't figure out a way to achieve that result between all of the nodes in one content type.

# Answer
Why not use Views?

You could create a View that displays one full node of your content type and add a pager to it.
> 4 votes

---
Tags: nodes, paging
---


# Question
Title: Is there a tool to covert any template to drupal 7 theme?
Is There any tool to convert any template (wordpress, joomla, static html/css etc) to a drupal theme

# Answer
Nope! :)

There is, however, a nice page full of information to convert Drupal 6 themes to Drupal 7: link
> 2 votes

# Answer
I don't think there is an easy way to convert a "template" into a Drupal theme. At least not something that is going to do all of the heavy lifting for you. If you are new to Drupal, start with a base theme, such as Fusion, Adaptive Theme, Omega or Zen and that will give you a good start. And depending on the complexity of the theme, you can sometimes get away with doing just css.

Themeing also just got easier in 7. I have recently been experimenting with pure css themes and its works nicely and keeps it lightweight.
> 1 votes

# Answer
As far as I know, there is no easy process to convert a custom html/css project into a Drupal theme. One of the reasons is that a Drupal theme needs to have files that describe how specific blocks look like, Views etc and that's not something that you can easily automate: someone knowledgeable needs to do the conversion.

However, if you have some time and you would like to try some things out this podcast, helped me a lot when I started theming back in Drupal 6.

The basic ideas remain the same, but a slideshow that I found about some of the new things in D7 theming, can be found here.

Ideally, you want to watch the whole podcast that I mentioned above, and then, after getting the idea of Drupal Theming in general, you can check the slides for some more D7-specific information.
> 0 votes

# Answer
I think there is not such tools of converting form Drupal x to Drupal 7. Theoretically, the process is not so complicated (depends of your theme practically) you can do it yourself following the suggestion of @Alex.

However if the question is to convert form WordPress, Joomla and other themes to Drupal there are nice tools to create a Drupal theme such as Artisteer and maybe it will convent also.
> -1 votes

---
Tags: 7, theming
---


# Question
Title: How can I make the Book Navigation also show the Summary of the Child Page?
Currently the Book module will create a navigation of links to each of it's children pages. I need that navigation to also include a teaser or summary from the child page.

This is for Drupal 7.

# Answer
--- Potentially not the best solution -----

I haven't tried this but looking at api.drupal.org I think you should be looking at overriding `template_preprocess_book_navigation` the variables processed in this preprocess are used in book-navigation.tpl.php ( u are interested in changing output of $tree which is an unordered list by default) I think you can override the preprocess for book\_navigation and use a different callback for `$variables['tree']` instead of book\_children. Your new callback would be based on book\_children but additionally load teaser for those child pages.

I myself would like to see a better solution for this coz sometimes core design decisions are not what we need and would like to know if there are better solutions other than overriding theme engine and replacing a call to a core function with a custom one ( in this case book\_children ) Let me know if you find a better solution or if this works.

Needless to say this will affect output of all book pages where book-navigation.tpl.php is used.

Cheers
> 1 votes

# Answer
I think you could also do this by using the custom\_pagers module, but I'm not 100% sure how the book module works in terms of navigation. You can override the c\_p theme function that displays the pager links and implement the teaser within.

Here's an example - note that it is pretty expensive as it includes node\_load's for each page either side of the current one (page left/right, as it were):

`function phptemplate_custom_pager($nav_array, $node, $pager) {
 if (is_numeric($nav_array['prev'])) {
 $prev = node_load($nav_array['prev']);
 }
 if (is_numeric($nav_array['next'])) {
 $next = node_load($nav_array['next']);
 }`

`$prevlink = '' . (($prev) ? l(t('â~@¹ ' . $prev->title), 'node/' . $prev->nid) : ' ') . '';
 $nextlink = '' . (($next) ? l(t($next->title . ' â~@º'), 'node/' . $next->nid) : ' ') . '';
 return '' . $prevlink . $nextlink . '';
}`

Sorry the code doesn't seem to want to align correctly...!
> 1 votes

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


# Question
Title: Drupal 7 - field template - $item - img tag
In drupal 7 theme, I have the following file:

field--field\_photo.tpl.php clearfix"\> \>: \> $item) : ?\> "\>

Inside render($item) lies an image with img tag How I may deconstruct this item, so that I write my code with img tag? The reason is just that I want to add a class to this img tag. thanks

The path to the images are save in public:files format

# Answer
I usually use Devel module to figure out things like this. Install and enable Devel, then add something like this to your field template file:

```
<?php kpr($item); ?>

```

This will show you all the contents of $item (arrays and objects). Then you can just print the part that you want (the img tag in this case), wrapped in the extra class.
> 2 votes

---
Tags: theming
---


# Question
Title: How do I modify the content of a select list field?
I have a content type with a Node Reference field, so the user can select from a list of node titles. I need to filter out some nodes from the list (those that have a date field older than the current date).

I know that hook\_form\_alter() can be used to modify the display and validation of form fields, but probably not change the query that the field uses. So I think I need to write some kind of preprocess function for this field, that does a second filter on the contents?

Any pointers on how to do this would be great - thanks.

# Answer
Have a look at Restricting node reference values to owner

As described there, you can select a view as the source for the node reference selection. In that view, you can apply whatever conditions you want to that list.
> 0 votes

---
Tags: 7, forms, nodes
---


title: Detection of form refresh and callback!

text:
# Question
Title: Detection of form refresh and callback!
How is it possible to detect if the page, in which the form is, is refreshed and to detect if only the form is refreshed?

I tell you the whole thing: I'm building a module. The form in this module has ajax-ed elements. When the form is first loaded (or when the page containing the form is refreshed) a database query is executed (filling up the form), that is the thing i want. But when an ajax-ed element is triggered the query is executed again, and i don't want that.

How is it possible to stop the execution of this query when an ajax callback is executed?
The form is in an .inc file and called by the .module file via `drupal_get_form()`.

# Answer
You can use `$form_state['triggering_element']` to find out if and by which element a form was submitted.

That said, I am not sure if what you want to do is possible. When rebuilding the form, you will have to provide all valid form elements and options for them *again*.

If that query is slow, you might be able to use the caching system instead (That is, unless these options are personalized for the current user).

But maybe I didn't exactly get what you meant, so try it..
> 1 votes

---
Tags: 7, forms
---


title: Problem with cURL

text:
# Question
Title: Problem with cURL
I've run into a strange issue.

I have a few simple lines CURL code for calling an api service. This code runs perfectly fine when running outisde of Drupal (in php file in browser and cli), but when the file is included within Drupal (after the bootstrap), it operates deferentially.

Under normal condition, the result returned by the API service has many results, but when run within Drupal, it only returns one result.

I suspect Drupal is changing a setting that CURL is using, which is changing how the API is understanding the call.

Does anyone know what the problem might be caused by?

The code below is derived from our api class files written within a common library. We plan to use these in the future in other PHP projects.

Here is the code:

```
$params = array(
  'domain' => array(
    'www.domain1.com',
    'www.domain2.info',
    'www.domain3.in.th',
    'www.domain4.com',
    'www.domain5.in',
  )
);

$ch = curl_init();
curl_setopt_array($ch, array(
  CURLOPT_URL => 'http://api.postrank.com/v2/domain/activity?appkey=123456&format=json',
  CURLOPT_HEADER => false,
  CURLOPT_CONNECTTIMEOUT => 30,
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_SSL_VERIFYPEER => false,
  CURLOPT_POST => true,
  CURLOPT_POSTFIELDS => http_build_query($params)
));
$response = curl_exec($ch);
$err = curl_errno($ch);
curl_close($ch);

print_r($response);

```

# Answer
> 1 votes
The answer was that Drupal changes the *&* in a querystring to *`&`* and the remote API service only processed the argument separator *&* and not *`&amp`*. So naturally, when it splits the post data up, it got only the first parameter in the array correctly.

---
Tags: http-request
---


title: Autocomplete JavaScript module

text:
# Question
Title: Autocomplete JavaScript module
I have created a custom autocomplete function. The autocomplete field is populated with user name and last name from the content profile.

It is possible that there will be few users with the same name and last name. How I can pass content type ID to Drupal autocomplete, and add this ID to a hidden form field, so I can be more accurate?

I don't want to put the content type ID straight to autocomplete field, so I need some callback to current implementation.

# Answer
Thanks to @googletorp advice the solutions is so easy and I want to share it with others. All I need was to overwrite two Drupal autocomplete object functions: found and select.

My autocomplete works on content profile fields. I pass nid of selected profiles to JS:

PHP:

```
function messagi_autocomplete($string) {
  global $user;

    $cache = cache_get('messagi_auto_complete_'.$string);
    $items = array();

    if ($cache) {

        $items = $cache->data;

    } else {

        $sql = "
              SELECT
                n.nid AS id
              FROM
                node as n
              WHERE
                n.type = 'profile'
              AND
                u.status = 0
          ";
          $result = db_query($sql);
          $disabled = array();
          while($obj = db_fetch_object($result)) {
              $disabled[] = $obj->id;
          }

          $items = array();
          $sql = "
                        SELECT
                    profile.nid AS nid,
                    profile.field_profile_name_value AS name,
                    profile.field_profile_surname_value AS surname
                  FROM
                    content_type_profile AS profile
                  WHERE
                    lower(profile.field_profile_name_value) LIKE lower('%s%%')
                  OR lower(profile.field_profile_surname_value) LIKE lower('%s%%')
                  LIMIT 10
          ";
          $result = db_query($sql, $string, $string);
          $sql = NULL;
          while($obj = db_fetch_object($result)) {
            if (! in_array($obj->nid, $disabled)) {
                  $key = check_plain($obj->name).' '.check_plain($obj->surname);
                  $items['nids'][$key] = (int) $obj->nid;
                  $items[$key] = $key.', '.check_plain($obj->venue);
            }
          }
            if (! empty($items)) {

                cache_set('messagi_auto_complete_'.$string, $items, 'cache', 1000);

            }
          $disabled = NULL;

    }

  print drupal_to_js($items);
  exit();
}

```

JS:

```
$(document).ready(function() {    if
    (Drupal.jsEnabled) {
            Drupal.jsAC.prototype.found = function (matches) {
              if (!this.input.value.length) {
                return false;
              }

              var ul = document.createElement('ul');
              var ac = this;
              for (key in matches) {
                var li = document.createElement('li');
                //to avoid of showing nids object in the select list
                if (key !== 'nids') {
                    $(li)
                      .html('<div>'+ matches[key] +'</div>')
                      .mousedown(function () {
    ac.select(this); })
                      .mouseover(function () {
    ac.highlight(this); })
                      .mouseout(function () { ac.unhighlight(this); });
                    li.autocompleteValue = key;
                    $(ul).append(li);
                } else {
                 //add all nids to prototype
                    Drupal.jsAC.prototype.nids = matches[key];
                }
               }
                //rest of the code
              }
            };

            Drupal.jsAC.prototype.select = function (node) {
              //get selected value nid and put it on form hidden field
              $('#edit-nid').val(Drupal.jsAC.prototype.nids[node.autocompleteValue]);
              this.input.value = node.autocompleteValue;
            };
} })

```

I hope this help somebody in the future. Thanks for the others advice to this code.
> 3 votes

# Answer
If you want to use the default Drupal autocomplete, your best bet it to add the id to the autocomplete and then use additional custom JS to move the id into a hidden field.

The other solution would be to overwrite the prototype functions created by Drupal and add extra handling there.
> 2 votes

---
Tags: 6, javascript
---


# Question
Title: Theming the node edit forms  to open them within Lightbox
I'm trying to display all the node edit forms neatly within Lightbox, without any of the excess content I don't want: no sidebars, footer, header, nothing but just the content. So I created a page-node-edit.tpl.php file.

I have two problems daunting me, but for now I'll only mention the first since its more important.

From any page, clicking on the "edit" link for the node doesn't activate the Lightbox like it should; instead, it clicks through the link as normal.
With jQuery in the header I added a "del" attribute for the Lightbox to the links, but the box still doesn't activate. I tested the Lightbox on a link I hardcoded into the page, and it activated just fine. For elements generated by Drupal, like the node edit link/button the problem seems to be timing.

I think the "del" attribute needs to be built with the page, with the link, rather than appended onto it. The catch is, the link lacks an id and class, so I don't see how the `hook_alter_link()` function can help me.

I'm willing to try anything. Perhaps someone has opened a node/edit form within Lightbox before.

# Answer
> 1 votes
Seems like you just need to disable the default action for that link, i.e. force the link to return `FALSE`.

```
$("a").click(function() {
  $(this).lightbox;
  return false;
});

```

Obviously, you'll need to change the target from "a" to the specific edit link.

# Answer
> 2 votes
If installing one or 2 additional module is an option then you can check Popups API (Ajax Dialogs). When I last checked, the module had functionality of opening forms in popups, which you can theme. I also feel that, in the way Drupal form API works, there is more to done then just adding classes and JavaScript to make Drupal forms work in Lightbox.

# Answer
> 1 votes
If you have Theme developer enabled, Lightbox will not work.
Theme developer should not be kept enabled, but enabled when necessary to get the necessary information; once you don't need it, you should disable it.

Some versions of the Devel module, had a link to enable or disable that module; I didn't check the latest version of Devel, and the link could not be present anymore.

---
Tags: theming, nodes
---


title: What are the different types of hooks?

text:
# Question
Title: What are the different types of hooks?
In an old blog post, Larry Garfield refers to "registry-style" hooks and hook\_nodeapi type hooks.

When it comes to breaking down the different types of hooks, there doesn't seem to be any documentation. There is the big list of hooks and Tim Plunkett found two defgroups dealing with hooks, but there doesn't seem to be a formal breakdown of what different types of hooks we have.

What would such a breakdown look like?

# Answer
I would group them in three, four groups, but there is no technical/internal difference between them. All are just functions that are called because of naming conventions.

1. Info hooks. Hooks that provide information about something, typical examples are hook\_entity\_info(), hook\_field\_info(), hook\_hook\_info() but also hook\_permission(), hook\_menu(), hook\_theme(), etc. Many of these have a `_info` suffix but don't necessarly need to. These hooks can be called any time and the returned information is often cached (static cache or persistent cache) or stored to specific tables (e.g. `hook_menu()`).
2. Reactive/Action hooks. I just invented that name, but these are hooks which are called when something specific happenend like hook\_init(), `hook_node_save()`, `hook_user_save()`, hook\_node\_view() and so on.
3. Alter hooks. Hooks that can be used to change something provided by other modules, exist for almost any info hooks (e.g. hook\_menu\_alter() or hook\_entity\_info\_alter()) and also some action hooks (e.g. hook\_node\_view\_alter()).

There is also a forth group but those are actually not really hooks and they are one of the main reasons for the typical confusion about hooks. They are often referred to as "Callbacks". This are "Hooks" which are only called for a single module, which owns something. Typical examples include node type callbacks (hook\_submit, hook\_view, hook\_form, ...), many field hooks (e.g. hook\_field\_load()) but also hook\_block\_view(). There are plans to remove these and replace with something else (oop based) or rename them to something else than hooks.

I assume there are also some hooks that can't be correctly put in any of these groups or are a mix of those groups. If so, that might be a sign that they should be redesigned. If someone knows any examples, I can add it here.

Disclaimer: This is not official but how I see it. Use with caution. ;)
> 7 votes

# Answer
One way to split them up is in terms of input and output: 1) input-only, 2) output-only, 3) input-output, and 4) no input, no output.

There's not a lot of #1, since nearly anything that happens could have some sort of response. The only examples I can think of are delete hooks, e.g. hook\_file\_delete(), hook\_comment\_delete(), where the hook gets the deleted object, but that object is already deleted, so there's no reason for a response.

The "registry-style" hooks would be #2, output only. They just feed data into a central registry and don't take any input. hook\_menu() and hook\_help() are examples.

hook\_nodeapi() was #3, but now it's broken up into different functions like hook\_node\_presave() -- still #3 -- and hook\_node\_delete() -- which is now #1. This is the most common group. Many of the examples explicitly have the word "alter" in the hook name, e.g. hook\_form\_alter().

Something like hook\_init() would be #4. Beyond general notification of an event, there's no input nor output.

That's a pretty arbitrary break-down though. You could easily argue for breaking up #3 into hooks where the output has the same structure as the input (alter) vs. hooks where the output has a completely different structure (call-response). Or you could combine #1 and #4, since the function call itself is a type of input, so the difference is just in level of detail.
> 0 votes

# Answer
Reading Larry's blog post, I don't think he meant to say that there are only two kinds of hooks (registry-style and nodeapi-style). As far as I know, there are no official types of hooks defined. Basically, all hooks are technically similar, but there is a difference in what they to and when they do it.

Hooks can be invoked anywhere between the initial http request and returning the output. Most hooks are meant to influence that (usually html) output one way or the other (call them 'normal hooks' if you like), like hook\_init for example.

Some hooks are *not* meant to affect the output directly, but they add to or alter a registry that is being stored in the database. This is what Larry calls registry-style hooks. They are not invoked often, but build a persistent list of values that can be used over and over again. Storing it in the database as a registry improves performance. This is what hook\_menu and hook\_theme do, among others.

The 'nodeapi-style' that is mentioned in the blog refers to hooks that bundle a bunch of subroutines in a single hook implementation. In D6, an implementation of hook\_nodeapi can respond to multiple events, like saving a node, viewing a node and deleting a node. This type of hook no longer exists in D7; for instance the single hook\_nodeapi has been replaced by hook\_node\_insert, hook\_node\_view, hook\_node\_delete and a bunch of similar hooks.
> 0 votes

---
Tags: hooks
---


title: How do I move a site to another server?

text:
# Question
Title: How do I move a site to another server?
I'm having troubles migrating a Drupal 5 site. I don't have direct access to the original site, but I've been given the Drupal source files and a dump of the database.

When I upload the database to my local server and alter the settings file to connect to the database I can access the first page, but nothing else (eg: nothing within the admin area). When I click on any other link I get a generic HTML file with just one string of text in it. I can't even tell how the file is being generated, it's the oddest thing.

I'm really thrown off because I move Drupal 6 sites all the time, and although I do run into all sorts of problems related to file paths, a few search/replace queries in the database seem to fix most of those problems

So I'm wondering **if there is something specific to Drupal 5 that I should be doing** (but that I'm not aware of). Perhaps the database is corrupt?

I'm at a loss here!

# Answer
> 5 votes
Just thought I'd give an update: this problem actually had to do with Clean URLs, once I migrated the site, I had to disable Clean URLs directly in the database since I couldn't access any of the sub-pages of the website so I couldn't get to the admin area, then I replaced the custom htaccess I got from the remote server with an htaccess from a fresh Drupal 5 installation, and that basically solved it! Wow, what a relief, thought I was going to go crazy trying to figure this one out!

---
Tags: migrations, 5
---


# Question
Title: How do you resize a form element in a block?
I have two blocks, one with a search forum(using drupal finder module) and an email invite module, and for some reason both input forms go outside the blocks borders.

Both are giving me two different problems. The finder module's search bar is going beyond the block borders but the entire email invite block is outside the borders.

How do you adjust the size of blocks?

# Answer
Set the #size and #cols (textarea) attributes of the different form elements as appropriate. You can do that with a hook\_form\_alter() implementation if they're not your forms.

Additionally, you can also use CSS, using the #attributes property.
> 1 votes

---
Tags: 7, blocks
---


title: what's inside the includes folder?

text:
# Question
Title: what's inside the includes folder?
I made a pretty dumb mistake..I was copying a library called ZendGdata to the includes folder within drupal and thought I copied all the files wrong so I deleted the folder and recopied the sub folder I wanted. Right after, I got a white screen of death.

I did a bit of research and realized the problem and restored the files from the orginal drupa install, but I'm wondering if there's any problem with it(the site works right now). Is there any customized code or anything of that nature in the the /includes folder that will effect me later?

# Answer
> 3 votes
No, the /includes does not (if you haven't hacked core) contain anything personalized. That folder contains code that doesn't belong to a (core) module.

The correct place for libraries is sites/all/libraries, see http://drupal.org/project/libraries.

---
Tags: files
---


# Question
Title: Logging into Drupal from an external application
I am currently using the services module and some custom code to delete, login and edit drupal users from an external application. I can currently login as a user on the external application but I am only logged on in the code and not the actual browser. Meaning that I can perform actions with the authenticated account in the code but when I visit my drupal website through the browser, I am not logged in. I want my users to be logged into drupal when they log into my external application. How can I do this?

# Answer
> 2 votes
You can use the form API to write a custom function for validating authentication. Something like this (this is from Drupal 7, but for 6 you have the same logic and the API is not very different). The code here is from a module I've wrote to authenticate users from an IP.Board (a forum software) database:

```
<?php
/**
 * @file
 * Allow Drupal 7 to use IP.Board members table for authentication
 *
 * Some code is based on this nice tutorial http://www.touchnoc.com/node/86
 */

/**
 * Alter the user login block form
 */
function ipbridge_form_user_login_block_alter(&$form, &$form_state) {
  _ipbridge_user_login_form_alter($form, $form_state);
}

/**
 * Alter the user login page
 */
function ipbridge_form_user_login_alter(&$form, &$form_state) {
  _ipbridge_user_login_form_alter($form, $form_state);
}

/**
 * Change the validate callback
 */
function _ipbridge_user_login_form_alter(&$form, &$form_state) {
  $k = array_search('user_login_authenticate_validate', $form['#validate']);
  $form['#validate'][$k] = 'ipbridge_authenticate_validate';
}

/**
 * Custom validation
 */
function ipbridge_authenticate_validate($form, &$form_state) {

  // try normal validation first
  user_login_authenticate_validate($form, $form_state);
  if ($form_state['uid'] !== FALSE)
    return;

  // still here? Try to find the user in IP.Board
  $name = $form_state['values']['name'];
  $pass = $form_state['values']['pass'];

  $records = db_select('ibf_members', 'u', array('target' => 'ipb'))
  ->fields('u', array('member_id', 'name', 'members_pass_hash', 'members_pass_salt', 'email'))
  ->condition('u.name', $name, '=')
  ->execute();

  if ($records->rowCount() == 1) {

    $ipbUser = $records->fetchObject();

    // this is how IPB generates the pasword hash
    $hash = md5(md5($ipbUser->members_pass_salt) . md5($pass));

    if ($hash == $ipbUser->members_pass_hash) {

      // based on Drupal's user_external_login_register (that function doesn't set the email address)
      $account = user_external_load($name);
      if (!$account) {

        $userinfo = array(
          'name' => $name,
          'mail' => $ipbUser->email,
          'pass' => user_password(),
          'init' => $name,
          'status' => 1,
          'access' => REQUEST_TIME,
        );

        try {
          $account = user_save(drupal_anonymous_user(), $userinfo);
        } catch (Exception $e) {
          drupal_set_message(t('Are you trying to login using an IP.Board username that was previously registered in Drupal? Caught exception: ' . $e->getMessage()), 'error');
        }

        if (!$account) {
          drupal_set_message(t("Error saving IPB account."), 'error');
          $form_state['uid'] = FALSE;
          return;
        }
        user_set_authmaps($account, array("authname_ipbridge" => $name));
      }

      $form_state['uid'] = $account->uid;
    }
  }
}
?>

```

---
Tags: 6, users, services
---


title: Get the parent items of a menu item

text:
# Question
Title: Get the parent items of a menu item
How can I get the parent items of a menu item for a view? I added a Global: null argument in the view and I need to get the parent items of this view. The view is set to belong to a menu in admin/build/menu-customize/primary-links.

I tried these in the argument to examine the parent items: $menuParent = menu\_get\_active\_trail(); dsm($menuParent);

However, it's not resulting in the output I hoped. I tried to look for a right function in http://api.drupal.org/api/drupal/includes--menu.inc/group/menu/6 but I get confused with all these functions: menu\_tree, menu\_tree\_data, menu\_get\_ancestors etc.

I am using Drupal 6.

# Answer
> 2 votes
There is not an easy way to get the parent of a specific menu item. The problem is that a path can be in many menus so you need to not only know the path of the item whose parant you want to find, but also which menu to look for them.

The `menu_links` table hold the info and with a few queries you could find info about the parent. If you actually want to change anything in the menu being printed, that's a completely different story, and can be quite tricky in Drupal 6.

To get menu item you could do something like this:

```
$path = 'foo';
$menu = 'bar'
$mlid = db_result(db_query("SELECT plid FROM {menu_links}
          WHERE link_path = '%s'
          AND menu_name = '%s'";, array($path, $menu)));

$menu_item = menu_get_item($mlid);
// $menu_item is now the parent menu_item of the menu in bar with path foo

```

---
Tags: views, routes
---


# Question
Title: Can I specify the location of a .tpl.php while using preprocess hooks?
If I override the template file using the code below, can I specify the location of `page-ajax.tpl.php`? I wanted to leave page-ajax.tpl.php inside my module's directory rather than to place it inside the current theme's folder.

```
function my_ajax_preprocess_page(&$vars, $hook)
{
    if (isset($_GET['ajax']) && $_GET['ajax'] == 1)
    {
        $vars['template_file'] = 'page-ajax';
    }
}

```

# Answer
It has to be in either the module defining the theme function or the active theme, unless you want to make override in the theme registry.

Drupal provides a hook: hook\_theme\_registry\_alter that allows you to alter the theme registry and thus also where Drupal would look for template files. Messing too much with this tends to make it blow up into your face, as you alter some default Drupal behaviors.
> 1 votes

---
Tags: theming
---


# Question
Title: Why is there a <p> tag where I didn't add it?
I put the following code into the bock content box and set the input type to *Full HTML*; then I enabled it on page--front.tpl.php. When I viewed the HTML source, I saw the `<a>` label contained a `<p>` tag.

```
  <ul>
      <li><a href="addons.html"><img class="floatleft" src="images/Panel-index03_108.jpg" /><p><strong>test</strong><br/>
      Fujia Chanpin 01</p></a></li>
       <li><a href="addons.html"><img class="floatleft" src="images/Panel-index03_108.jpg" /><p><strong>test</strong><br/>
      Fujia Chanpin 01</p></a></li>
      <li><a href="addons.html"><img class="floatleft" src="images/Panel-index03_108.jpg" /><p><strong>test</strong><br/>
      Fujia Chanpin 01</p></a></li>
      <li><a href="addons.html"><img class="floatleft" src="images/Panel-index03_108.jpg" /><p><strong>test/strong><br/>
      Fujia Chanpin 01</p></a></li>
      <li><a href="addons.html"><img class="floatleft" src="images/Panel-index03_108.jpg" /><p><strong>test</strong><br/>
      Fujia Chanpin 01</p></a></li>
      <li><a href="addons.html"><img class="floatleft" src="images/Panel-index03_108.jpg" /><p><strong>test</strong><br/>
      Fujia Chanpin 01</p></a></li>
      <li><a href="addons.html"><img class="floatleft" src="images/Panel-index03_108.jpg" /><p><strong>test</strong><br/>
      Fujia Chanpin 01</p></a></li>
    </ul>

```

For example, for the last list item, the output was the following.

```
<a href="addons.html"><img src="sites/all/themes/cpanel/images/cPanel-index03_108.jpg" class="floatleft"><p><strong>tsdet</strong><br>Fujia Chanpin 01</p><p></p></a>

```

Why is there a `<p>` tag where I didn't add it?

# Answer
> 4 votes
For not getting the paragraph tags, you need to use an input format that does not include the *Lines and paragraphs break automatically* setting.

Check to see if *Convert line breaks into HTML* input format is enabled in admin/config/content/formats/full\_html, and disable it. You can still add `<p>` and `<br>`, but Drupal will not add them automatically for every line break present in the text.

---
Tags: 7, blocks
---


# Question
Title: Form State in the field instance settings form
How do I access the global form state of the field instance settings form. hook\_field\_instance\_settings\_form only takes two arguments - instance and field.

Use case - Ajax refresh of an options list

# Answer
> 2 votes
You can't access it directly, what you can do it use `#after_build` which will be called with the `$form_state`, but this will happen at a later step.

---
Tags: entities, ajax
---


title: Menu links not working in IE

text:
# Question
Title: Menu links not working in IE
When I click on certain links in menu in IE a page with error message "Internet Explorer cannot display this page" appears. Other browsers are OK.

Problem is with these two links
"http://localhost/?q=calendar"
"http://localhost/?q=user/login"

Do you know what is wrong?

thank you

# Answer
To give any meaningful answer you need to describe your problem better. I did notice that your urls seem to lack your site name

`http://localhost/?q=calendar` vs `http://localhost/drupal?q=calendar`

This can happen if you don't create the urls with the l/url function regardless of browser being used.
> 1 votes

---
Tags: routes
---


# Question
Title: Restrict permission to custom modules in drupal
I am using drupal 6, and I have created a custom module. This module consists of a form that can be used for adding records to the database.

But I saw that the link to this form (`http://localhost/drupal/my_module/form`) is accessible to all the users, even anonymous users.

I want to restrict the access to this module and form from all the normal users. I want only the administrator to access it.

I have created a role called Administrator and permitted my module only for the administrator. It still doesn't work.

How can I restrict the access to my custom module ?

# Answer
> 8 votes
1. Declare a permission with hook\_perm(). It is recommended to somehow use your module name in the permission or something unique to your module to avoid conflicts (there is no namespacing, permission names are global).
2. In your hook\_menu() implementation, add `'access arguments' => array('permission name here')`. Since the default access callback is user\_access(), the menu system will call `user_access('your permission name')` to check if the current user has access to that menu item. See hook\_menu() documentation for more information. You can also use `user_access()` directly in your code, if you want to check permissions somewhere else; for example for blocks, you can use that function directly.
3. Then, you can create whatever roles you want to and give them the permissions of your module at admin/user/permissions. The important distinction here is that permissions are controlled in modules (which can be more or less generically written) while roles and the permissions they have are site-specific.

Then, make sure to rebuild the menu (by using devel.module or saving the modules form) and you should be good.

---
Tags: 7, users
---


title: process form in popup window

text:
# Question
Title: process form in popup window
I have a custom module in Drupal and I also have a custom table for storing the details of seminars, such as name, description, date and location.

I am showing the names of the seminars in a left sidebar block; when the user clicks on a seminar name, I want to show its other details (description, location, etc.) in a form (which include a "Submit" button) in a popup modal box.

When the user clicks on the submit button, the user will be joined in the seminar (inserted into database).

How can I use JavaScript/AJAX for this scenario and process form in popup, without refreshing the page?

I have included the jQuery library in my module file using `drupal_add_js()`; I also installed the Chaos Tools Suite module.

# Answer
> 2 votes
I would suggest you to have a look at Chaos tools suite; the module brings an example for a modal form inside a modal window right with it (AJAX example).
It should be not to hard to integrate that, if you're already working on a custom module.

All I've said is valid for Drupal 6; I haven't looked into cTools in Drupal 7.

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


# Question
Title: Image styles not generated with Drupal 7 on IIS 6
I've developed a site that uses various image styles to export images to an iPhone (linked from a XML export document). This worked perfectly fine on my own development server with Linux/Apache.

The site is now currently hosted on a shared hosting environment, which uses Windows/IIS6. (yeah, strange; it is not my decision as you can assume ;).)

The problem now is that the image\_style URLs for new images (existing images work) lead to a 404 error page, which is directly served by IIS. However, clean URLs worked fine out of the box and "normal" 404 pages are displayed by Drupal.

So, an URL like http://example.org/does\_not\_exist shows the typical site not found error, served with Drupal but http://example.org/sites/default/files/styles/command\_image/public/Chrysanthemum\_0.jpg shows the IIS 404 page.

The site is using the public file system for these images and the path is correct; it does work fine for existing images, which I uploaded together with the rest of the site during the initial deployment on that server.

Do you have any idea?

# Answer
Ok, I figured it out.

The problem was that there were two .htaccess files. One in the top level, that contains most of the configuration and one in sites/default/files, which is security related (avoid execution of php files and similar) and contains just this:

```
SetHandler Drupal_Security_Do_Not_Remove_See_SA_2006_006
Options None
Options +FollowSymLinks

```

Now the difference seems to be that in Apache, both files seem to be combined (the one in sites/default/files inherits everything from the top-level one). This does not happen with the ISAPI\_Rewrite module that seems to handle the Apache/IIS .htaccess compatibily.

I fixed this by copying the content of the top-level directly into the file in sites/default/files, below the existing content. Additionally, I had to change the RewriteBase so that it included the index.php file in the correct directory.

The header of the changed .htaccess file now looks like this:

```
# From the original .htaccess file, do not remove.

SetHandler Drupal_Security_Do_Not_Remove_See_SA_2006_006
Options None
Options +FollowSymLinks

#
# Apache/PHP/Drupal settings:
# (copied from /.htaccess)
#

Content of the top level .htaccess file here comes here...

```

And the part that I changed now looks like this:

```
# Modify the RewriteBase if you are using Drupal in a subdirectory or in a
# VirtualDocumentRoot and the rewrite rules are not working properly.
# For example if your site is at http://example.com/drupal uncomment and
# modify the following line:
RewriteBase /YOURFOLDERHERE

```

So when Drupal is installed in a sub directory, insert your folder name. If not, you can leave this part commented out.

I found this thanks to the (unecessarly long) blog post at http://www.caspianit.co.uk/imagecache-wrong-path/

Note: Simply deleting the .htaccess file in sites/default/files *did* work too, however, that removes the security relevant SetHandler setting. I however doubt this has any effect in IIS anyway...
> 3 votes

# Answer
Is /sites/default/files/styles/command\_image/public/Chrysanthemum\_0.jpg present on the file system? If so, there may be a permission issue while fetching the image. If not, there may be a permission issue while generating and writing the image. Are there any errors in the Drupal log page?
> 1 votes

---
Tags: iis, media
---


# Question
Title: Is there a better way to make a user profile tab using a view?
I have created a question node type using CCK and would like to show all of the questions which users create on a tab on their profile page.

The way I have done this feels a little indirect. I have:

1. Created a view which lists all of a user's questions and made a block to display it.
2. Configured the block so that it only displays on the right path ("user/\*/questions").
3. Created an entry in hook\_menu for this path. Used a page callback which calls a function which creates an empty page (see below).

Is there a more direct way to do this by, e.g., attaching the view directly to the profile page?

The code in `hook_menu()` is:

```
$items['user/%/questions'] = array(
  'title'            => 'Your Questions',
  'description'      => 'User Questions',
  'page callback' => 'answers_blank_page',
  'access arguments'  => array('create question content'),
  'type'     => MENU_LOCAL_TASK,
  'weight' => 9,
);

```

The page callback is simply:

```
function answers_blank_page () {
  return '';
}

```

# Answer
There isn't any need to use a custom module for this: The Views module already allows you to associate a URL to a view and make the view appears as a menu tab.

The following screenshots are for Views 7.x-3.x-dev, but the settings are present also in previous versions of the module.
Under "Page settings," there are two options: "Path" and "Menu." The screenshots shows the settings used for a view implemented by a third-party module (the Flag module), whose view is shown as menu tab.

>

>
> 4 votes

# Answer
Create a new page view, and then configure it to provide a menu item, specifically a tab, at path user/%/questions.
> 3 votes

# Answer
It should work just by creating a page display, setting the path appropriately; no need to do the tricky steps you used.

Edit: you must also specify a menu item for the display.
> 1 votes

---
Tags: views, users
---


title: Can't print fields in a view template

text:
# Question
Title: Can't print fields in a view template
I'm overriding drupal /blog path with a views. Created a new view page display and set path to blog. Created views-view-unformatted--blog-page.tpl and trying to output view fields this way:

```
<?php
print $fields['title']->content;
print $fields['body']->content;
?>

```

But all what i get is nothing, tried to output `<?php print 'Hello, world!'; ?`\> == it outputs Hello,world. But i can't print Views fields...

PS in another view display - printing fields this way works perfectly. Blank fields affects only blog page view display

# Answer
The template you have overwritten looks like this (in Drupal 6):

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

```

As you can see, it's purely used to print out the rows in the view; you should instead use one of the other templates available, if you want to alter the fields. Take a look at the theming information button in the UI that will give you a complete list with previews.
> 2 votes

---
Tags: views, theming
---


# Question
Title: How do I change the style used by the "Archive" view to show the dates?
By default the "Archive" `views` module displays the dates as "May 2011." I want to change them to "2011 year May."

How do I do that? Is it possible?

`from the instructions of googletorp`: i made the following but it's not work. what's wrong with my code?

1. created a module named `customviews`. which have files(`customviews.info`, `customviews.module`, `customviews.views.inc`)
2. `customviews.module` has code:

```
    <?php
      function customviews_views_api(){
        return array('api'=>2);
      }

```

function customviews\_views\_data\_alter(&$data) { // Set the argument to the handler you named above. $data\['node'\]\['created\_year\_month'\]\['argument'\]\['handler'\] = 'custom\_handler'; }
3. `customviews.views.inc` has code

```
 <?php
   class custom_handler extends views_handler_argument_node_created_year_month {
     function construct() {
       parent::construct();
       $this->format = "Y year M month";
     }
   }

```

i have cleared the cache.

i put the **function customviews\_views\_data\_alter(&$data)** into the .module file. it's still can't work. what's wrong with it?

# Answer
> 1 votes
Views haven't supplied an easy way of doing this, but it is possible. To do this you would have to create your own handler and make views use that:

### 1. Creating own handler

```
class custom_handler extends views_handler_argument_node_created_year_month {
  function construct() {
    parent::construct();
    $this->format = 'F Y'; // Write your custom format here.
  }
}

```

### 2. Making view use your custom format

```
function module_name_views_data_alter(&$data) {
  // Set the argument to the handler you named above.
  $data['node']['created_year_month']['argument']['handler'] = 'custom_handler';
}

```

Update.

1. The custom\_handler class or whatever you choose to call it need to go in it's own file. For Drupal 7 the standard is to put it in a dir called handlers which is located in the dir that you specify with `hook_views_api`, and add the file as include in the .info file (Look at the views module for reference).
2. For the module\_name\_views\_data\_alter you need to replace module\_name, with the name of your module.
3. Clear cache.

---
Tags: views
---


# Question
Title: Fatal error undefined function taxonomy_get_tree()
I want to write a module that makes a select search form based on taxonomy terms. (with hierarchical select boxes) This is on drupal 7.0 and status is up to date. The form is made and Ajax is properly working with testing values. But now I need to find a way to fill up my select boxes with taxonomy terms, wanted to use the function taxonomy\_get\_tree (modules/taxonomy/taxonomy.module, line 836) and received the message:

```
Fatal error: Call to undefined function taxonomy_get_tree()

```

When I've put the function from modules/taxonomy/taxonomy.module in my own module I receive the message:

Fatal error: Cannot redeclare taxonomy\_get\_tree()

Should it be that I have to hook my module in any kind of way with the taxonomy.module file, or ar there other ways to achieve my goal?

This is on a mymodule.module file placed in drupal7/sites/all/sitename/modules/custom/mymodule/mymodule.module

The code is like

```
$tree = taxonomy_get_tree(6, $parent = 0, $max_depth = NULL, $load_entities = FALSE);
print_r($tree);

```

I'm unable to approach all functions in the taxonomy.module page...

# Answer
If your module depends from another one, and you are getting an error about a function defined from that module not being present, then you should change the weight of your module to a higher value.

In Drupal, modules are loaded basing on their weight (first the lighter modules, and then the heavier modules), and on the short module name; user.module is loaded after taxonomy.module, if both the modules have the same weight.

Instead of using `drupal_load('module', 'taxonomy')`, you should change the weight of your module in hook\_install() or hook\_update\_N() with `db_query("UPDATE {system} SET weight = 10 WHERE name = 'your_module_name'")`, or `db_update('system')->fields(array('weight' => 1))->condition('name', 'actions_loop_test')->execute()` in Drupal 7 and higher.
A better way to alter the weight of your module is to get the weight of the Taxonomy module, increase it of 5 (or 10), and then use that value as weight of your module. In this way, your module hooks would be called after the Taxonomy module is loaded, even in the case a third-party module would change the Taxonomy module weight to a value different from its default.

If the error is caused from the implementation of hook\_init(), then you can only use `drupal_load('module', 'taxonomy')`, as the Taxonomy module doesn't implement `hook_init()`.
> 1 votes

# Answer
Maybe the taxonomy module is just loaded after yours... Have you tried to load the taxonomy module before calling taxonomy\_get\_tree()? :

```
drupal_load('module', 'taxonomy');
$tree = taxonomy_get_tree(6, $parent = 0, $max_depth = NULL, $load_entities = FALSE);
print_r($tree);

```
> 1 votes

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


# Question
Title: Pre-populating a CCK field item with values from another field
I'm working on a project that has two compound field ("flexifield," or "multifield," if you use CCK3) sections that output content types "rooms" and "levels".

Level is defined first and has a title, a total area and an "above ground" binary value.

Room has a length, width and area, then a level defined by a select box — populated by the first set of fields via the following "allowed value" code:

```
$result = db_query('SELECT `vid`, `field_level_label_value` FROM `drupal_content_type_meas_areas`;');
while ($item = db_fetch_object($result)) {
$items[$item->vid] = $item->field_level_label_value;
}
return $items;

```

Alas, while the proper label is available when filling in the fields, when actually viewing the content type, the value of each "level" field is a numerical value, instead of the label defined by the level's "field\_level\_label" field.

**How do I make this field save the field's string value instead of its (I'm guessing) vid?**

Thanks!

# Answer
> 1 votes
```
$result = db_query('SELECT `vid`, `field_level_label_value` FROM `drupal_content_type_meas_areas`;');
while ($item = db_fetch_object($result)) {
$items[] = $item->field_level_label_value;
}
return $items;

```

I figured it out -- removing the $item-\>vid bit as $items' array key results in the proper values.

Oh Drupal, so subtle in its frustrations! :D

---
Tags: entities
---


title: Problem with Drupal 7 file permissions

text:
# Question
Title: Problem with Drupal 7 file permissions
I set up a working Drupal 7 installation on somebody else's server and the image generation *only* worked if all folders leading to the thumbnail folder were given 777 permission.

This must be a an Apache configuration issue - has anybody else come across this?

# Answer
> 6 votes
You need to go to your drupal installation root folder and type the following

```
chown -R user:www-data .
find . -type d -exec chmod u=rwx,g=rx,o= {} \;
find . -type f -exec chmod u=rw,g=r,o= {} \;

```

where www-data type the user under which apache/http process runs

Then go at sites/ directory and type the following

```
find . -type d -name files -exec chmod ug=rwx,o= '{}' \;
find . -name files -type d -exec find '{}' -type f \; | while read FILE; do chmod ug=rw,o= "$FILE"; done
find . -name files -type d -exec find '{}' -type d \; | while read DIR; do chmod ug=rwx,o= "$DIR"; done

```

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

# Answer
> 3 votes
As provided by John, Drupal.org has an entire page on permissions.

With `ls -alh` you will see the user and filepermissions that are used. If that gives access denied, or too little information, run ls -alh as root: `sudo ls -ahl`. You should see something like:

```
drwxrwx---  7 www-data greg      4096 2008-01-18 11:02 files/
drwxr-x--- 32 greg     www-data  4096 2008-01-18 11:48 modules/
-rw-r-----  1 greg     www-data   873 2007-11-13 15:35 index.php

```

The first column will, in your situation look like drwxrwxdrwx, a more readable version of 777.

The next two columns are more important: they should contain the user under which the apache server runs. On Ubuntu and Debian that is www-data, under CenOS/Redhat that is apache. Other unices may have other usernames.

Then simply change the ownership of the files directory and all files underneath it.

```
chown -R www-data:www-data files/

```

This will recursively (-R) change group and user ownership to apache of files/ and its content.

From there you can change the permissions to something safer:

```
sudo find . -type d -exec chmod u=rwx,g=rx,o= {} \; #change permissions on directories (-d)
sudo find . -type f -exec chmod u=rw,g=r,o= {} \; #change permissions on files (-f)

```

`x` for directories means accessing and scanning it. `x` for files meens executable. You don't want your images to be "executable" :)

---
Tags: 7, files
---


# Question
Title: How to sort/delete comments by a particular user?
I have a relentless human spammer that is extraordinarily difficult to keep away. Spam filters are unhelpful as he does not use a set of frequently used words. Rather, his insults are more "subtle" to be captured by any regext. Each time I block him, he comes back with a new username but soon the new user reveals his spammy nature. So I need to go through the list of comment to finds the one by him and delete them one by one. On the other hand, I don't want to disable comments auto-approval just because of one bad apple.

It is painful especially when you need to do it a couple of times a day! so I wish there was an easier way to sort and then delete comments of a particular user, and not involved direct querying the database?

# Answer
Using Views Bulk Operations, you can create a view for all the comments written by a user, which allows you to delete all the comments written by a user without the limitation of deleting them in groups of 50 at time. When you click on the button to select the comments shown in the pager's page, you are asked if you want to select all the comments; in that way you can delete all the comments with a single click. As the view can be set to use batch operations, it is able to delete a great number of comments without any timeout.

You can create a view that is shown in the user profile page (as done on Drupal.org), or you can create a view that replaces the page shown in admin/content/comment. Being a view, you can filter the comments listed using different criteria, such as the content type of the node for which the comments have been created, the author of the comment, the author of the node to which the comment is attached, etc.

Views Bulk Operation doesn't come with a custom view to show the comments made from a user; it comes with a view that can be used to replace the page shown at admin/content/node. Using that view as example, you can easily build the view you need for the comments.
> 4 votes

# Answer
You can quite easily delete comments with a bit of PHP, for Drupal 6 it would look like this:

```
$uid = xx // the spam users id;
$query = db_query("SELECT cid FROM {comments} WHERE uid = %d", $uid);
while($cid = db_result($query)) {
  comment_delete($cid);
}

```

For Drupal 6 there is also the alternative way of dealing with trouble users like this, by bringing misery upon them. Banning their IP address might be a bit more effective though.
> 2 votes

# Answer
A solution to attack the root of the problem:

Drupal offers the option of banning an IP in `Users -> Access Rules -> Add Rule -> Deny Host`

To know the IP of the user -\> In the report logs you will see *"Session open for user"* messages. Click it and you will see the IP of that user.
> 0 votes

---
Tags: comments
---


# Question
Title: Better Performance by putting image dimensions
YSlow advises that all images should have dimension attributes even if they are presented at 1:1 scale, so that the browser knows the dimensions before the images are loaded, to start rendering the page faster.

I have a view of 20 taxonomy titles and their image fields. How I can make Drupal put their dimensions attributes on each image html tag?

I have drupal 7.

# Answer
This is a known issue in Drupal 7. A conscious choice, as it were, from the issue Remove unnecessary I/O from theme\_image().

There is a patch to fix this here: Images are not printed with height and width.
> 2 votes

---
Tags: 7, performance, media
---


# Question
Title: Disabling auto-removal of 'rel' attributes in full HTML input format
My Drupal 7 site , which is using Wysiwyg with the TinyMCE library, keeps removing the 'rel' attributes. Do you have any idea on how I disable this?

# Answer
I fixed this by changing the formatting library from TinyMCE to Yui as it does not remove the 'rel' tag.
> 0 votes

---
Tags: wysiwyg
---


# Question
Title: Importing node_revisions records from version 5 to version 6
Probably a dumb question, but could I simply export an SQL file from the database of a Drupal 5 site and import it into a Drupal 6 database in the same table provided I used the same CCK fields for both? I've tried to migrate content in so many different ways and pretty much everything has failed so far... importing csv through the feeds module was my greatest hope and was made to look so easy but I keep getting an HTTP error.

Also is node\_revisions the table that contains all of the stories? I tried exporting nodes, but it didn't seem to contain the body field.

# Answer
> 1 votes
Instead of trying some convoluted way of exporting and then re-importing the data and maintaining all meta-data - have you tried simply upgrading the site to Drupal 6?

This has been heavily documented on drupal.org

When you do a major drupal upgrade, so long as there is a drupal 6 module for your functionality, there will be update hooks that alter the database to convert it to the new schema.

This includes CCK, revisions etc

---
Tags: nodes, 6, migrations
---


# Question
Title: How to override individual blogs/% page?
I've got a question about overriding the default blogs/username page with Views. I've created a new view with a page display with blogs/% as path, and set arguments to user:name. I'm typing blogs/rustam, the default page of individual blog is displayed. How do I correctly override the blog page with Views?

# Answer
> 4 votes
blogs/\[username\] is the path alias; the internal path is blog/\[uid\]. Change your view to use the internal path blog/%.

Where % represents the passed value that you are capturing like the userid. Then you will need to add an argument as well like User: User ID so that everything is consistent

---
Tags: views
---


# Question
Title: How do get a body.onload event executed?
Background:

(\*) I'm a JavaScript dilettante -- I just dabble when I need to.

(\*) I have a piece of javascript that I've tested with a dummy page that I loaded by just calling it from a `<body onload="..."/>`. It does what I want there. (See https://github.com/cwestin/bobt/blob/master/site/style/article.html , and the sibling file http://github.com/cwestin/bobt/blob/master/site/style/bobt.js).

(\*) I want to add this onload behavior to my Drupal site.

I followed the instructions on how to create a Drupal 7 module from here: http://drupal.org/node/361112.

However, this seems to be aimed at PHP development of block modules that generate content. All I have is the JS file, which will act on some div classes I put in my content's unfiltered HTML markup.

I also found instructions on managing JavaScript here: http://drupal.org/node/756722.

And, a search on this site found these instructions for including JS: Best way for including javascript/jQuery OnLoad in EVERY page on my site . However, that didn't really seem to answer the question it posed -- that I could tell.

However, having created a module by following these incomplete instructions as best I can, it doesn't look like my JS is getting triggered. A View Source shows that my .js file is being included in the pages, but the transformation it does isn't happening (it did work in my dummy test page). It's possible I'm not translating into jQuery correctly; I've never used that before, and the syntax is clearly not just plain old JS.

Here's the module: https://github.com/cwestin/bobt/tree/master/site/style/sectiontoc . As you can see, in the spooky `function($)` thingy, I add the required `attach()` to try to add my behavior to `$(document).ready` at the bottom. But as I said, it's not getting triggered.

Could anyone please tell me what I'm missing, or what I'm doing wrong here? Thanks in advance for any help.

# Answer
> 3 votes
I'm not sure if this is the most correct or most elegant solution, but it works for me. I use this to automatically face out messages on page load.

```
(function ($) {
        $(document).ready(function() {
        $("div.messages").delay(10000).fadeOut("slow");
    });})(jQuery)

```

I use this with a zen sub-theme, and include it in the .info file like this:

```
scripts[] = js/scripts.js

```

hope it helps.

-J

# Answer
> 3 votes
Putting $(document).ready inside of Drupal.behaviors attach is redundant.

The point of attach is that it will run when the document is ready.

---
Tags: 7, javascript
---


title: How to compare values from two views

text:
# Question
Title: How to compare values from two views
I have two views, "viewA" and "viewB;" "viewA" contains all the users that post within the day, and "viewB" contains all the users. I need to get the difference between the two so I can get the users that don't have any post. I could use `views_get_view_result()` and `views_get_current_view()`, but I don't know how to implement the code.

# Answer
Instead of trying to compare the result of two views and find the difference, which is highly inefficient and difficult, it will be a lot easier to create a new view that filters out the users that that has posted within a day.

You should be able to duplicate ViewA and reverse it's filter(s). It should at least provide a good starting point.
> 2 votes

# Answer
You could load the view-results and compare them with a helper like this:

```
function _get_view_result($view_name,$display,$argument) {
    $view = views_get_view($view_name);
    $view->set_arguments(array($argument));    // only if you have arguments
    $view->set_display($display);
    $view->pre_execute();
    $view->pager['items_per_page'] = 0; // get all items (only if you have a pager)
    $view->execute();
    return $view->result;
}

```

Afterwards you can compare them the way you like. But in many cases you are better off with a seperate view for such things.
> 0 votes

---
Tags: views
---