# Question
Title: Sometimes CCK custom fields get lost although they appear normally in the database
I have pressflow 6.22.

When the editors try to create new node, they lose what they have inserted in CCK custom fields. I have checked `node_load` and the result is missing those values as well.

I checked the tables and the result is as below:

```
mysql> select * from content_field_headline_image where nid=380320\G
*************************** 1. row ***************************
                                  vid: 380322
                                  nid: 380320
  field_headline_image_imceimage_path: http://mywebsite.com/sites/default/files/im/Maven.jpg
 field_headline_image_imceimage_width: 0
field_headline_image_imceimage_height: 0
   field_headline_image_imceimage_alt: Maven
                                delta: 0

```

but this image doesn't appear in node\_load result as well as in the preview of the node itself.
**##EDIT##**

I fixed it when I flush\_all for memcache !!

Any idea of how to disable memcache for logged-in users only??

note:cache mode is disabled (cache mode in admin\>\>performance)

Thanks for your help

# Answer
> 3 votes
Even though some fields appear correct in the DB, they don't always load up into the edit view, I've noticed similar oddness long ago when trying to replace some `image assist` tags in the database directly with a php script.

In our case, the edit view *(node/edit)* begun showing correct data after we purged all caches.

To solve your problem, read and understand how `Memcached` works from http://en.wikipedia.org/wiki/Memcached -- When making manual DB edits, you must let Memcached know that you've made modifications to tables, this functionality is built into Drupal database handling, hence you'll never notice it when working directly from Drupal, but if you are making custom update queries into the tables, you must let Memcached know there was a change. Was a bit of a surprise to me since I thought it just automaticly *works* in the background. :)

See the example code part from the wikipedia page how to do it.

..and if you don't use custom update queries to modify those CCK fields, I suspect there must be some sort of a bug in Pressflow itself. Do the changes propagate into the edit view after few hours? Apart from this, there's not really enough info to dig in deeper :/

---
Tags: entities, 6, caching
---


# Question
Title: Manually Send Ajax request to a PHP file
It seems that the Drupal Ajax API are comming a little un handy for my current project so i was trying to do the ajax request the good old way with actual Javascript.

I have this code

```
valdBut.click(function(event){
    event.preventDefault();

            jQuery.ajax({
            type: "POST",
            dataType: 'json',
            data: grabValue(),
            url: urkl,
            success: function () {

                alert(back)

            }
        });
    alert(grabValue())

})

```

What i am wondering is how should i link that URL value to my module page, so that my user\_login hook receive the data sent via Ajax ?

Thanks for any help, Manu

# Answer
> 0 votes
This tutorial (tough Drupal 6) helped me a lot http://viziontech.co.il/tutorial1?1309179897 .

The big piece that i was missing is that i needed a Hook\_menu that countain my php script that will handle the ajax request, then in the ajax path i add the newly created link (from the Hook\_menu).

Also the JS needed to be added to that specific module with a drupal\_add\_js for the ajax call back to be received. It took me a while to figure out but if i add the script via Theme.info file it behaves very oddly..

# Answer
> 2 votes
For most functionality that you require with drupal, there is typically a module that already does what you are after or close to it.

I would recommend either:

Hope this helps

---
Tags: javascript, ajax
---


# Question
Title: If I using Ubercart and "PayPal Website Payments Pro", Can customer pay with credit card directly?
I'm not familiar with payment gateway. I'm building shopping cart selling physical product. Currently the website using: Drupal 6, Ubercart 6.x-2.4, with PayPal free account.

My client asked me to make credit card payment as simple as possible. Some customer don't know what is PayPal? When making ckeckout, they are redirected to PayPal account. After registration, they then asked to transfer from credit card to their PayPal account. They really confused and finally they refused to buy the product.

My question is: If I using Ubercart and "PayPal Website Payments Pro", Can customer pay with credit card directly without redirected to other website?

Read here why Authorize.net is not my choice

# Answer
yes. With Paypal Pro, users remain on your site and the transaction is completed underneath by Paypal. There is no visible relationship between the two for the end user.
> 2 votes

---
Tags: ubercart, payment-gateways
---


# Question
Title: What's the difference between access arguments and access callback?
What's the difference between access arguments and access callback?

Suppose I set the access callback to `'user_access'`, and `array('custom permission')` is the value for the access arguments.

What does that mean? How do they affect each other?

# Answer
"Access callback" is the function that is called to verify the user has access to the page. As special case, it could be the value `TRUE`, and in that case all users would have access to it; in other words, the access permission would be bypassed.

In the case you are using a function name for the "access callback" value (by default, it's "user\_access"), then you can also use "access arguments", which is an array containing the arguments passed to the access callback function.
As with other menu callbacks, the arguments must be a string, or a number; in the case it's a number, the value will be replaced with a value taken from the menu path. If you want to avoid this replacement, instead of a number you need to use a string; for example, using `"1"` as one for the arguments passed to the access callback would avoid the automatic replacement.

These are some example of menu callback declarations used from Drupal core modules. (The examples are from Drupal 7 code, but for what I want to point out, that doesn't make any difference.)

This is an example where the access callback is user\_access().

```
  $items['file/progress'] = array(
    'page callback' => 'file_ajax_progress',
    'delivery callback' => 'ajax_deliver',
    'access arguments' => array('access content'),
    'theme callback' => 'ajax_base_page_theme',
    'type' => MENU_CALLBACK,
  );

```

This is an example where the access callback is not a function name.

```
  $items['user'] = array(
    'title' => 'User account',
    'title callback' => 'user_menu_title',
    'page callback' => 'user_page',
    'access callback' => TRUE,
    'file' => 'user.pages.inc',
    'weight' => -10,
    'menu_name' => 'user-menu',
  );

```

In this case, the access callback is user\_view\_access() to which is passed, not the number 1, but a value taken from the menu path (which in this case is "user/%user"); this is a particular case, as the function will get the value returned by `user_load()`.

```
  $items['user/%user'] = array(
    'title' => 'My account',
    'title callback' => 'user_page_title',
    'title arguments' => array(1),
    'page callback' => 'user_view_page',
    'page arguments' => array(1),
    'access callback' => 'user_view_access',
    'access arguments' => array(1),
    // By assigning a different menu name, this item (and all registered child
    // paths) are no longer considered as children of 'user'. When accessing the
    // user account pages, the preferred menu link that is used to build the
    // active trail (breadcrumb) will be found in this menu (unless there is
    // more specific link), so the link to 'user' will not be in the breadcrumb.
    'menu_name' => 'navigation',
  );

```

Suppose the previous menu were defined as follows, and invoked with a path like "user/hello."

```
  $items['user/%'] = array(
    'title' => 'My account',
    'title callback' => 'user_page_title',
    'title arguments' => array(1),
    'page callback' => 'user_view_page',
    'page arguments' => array(1),
    'access callback' => 'user_view_access',
    'access arguments' => array(1),
    // By assigning a different menu name, this item (and all registered child
    // paths) are no longer considered as children of 'user'. When accessing the
    // user account pages, the preferred menu link that is used to build the
    // active trail (breadcrumb) will be found in this menu (unless there is
    // more specific link), so the link to 'user' will not be in the breadcrumb.
    'menu_name' => 'navigation',
  );

```

In this case, the access callback would have received as argument the value taken from the path (0 means "user," and 1 means the part after "user" and the slash); in this case, that value is "hello."

To better understand these wildcard arguments, see Wildcard Loader Arguments. The documentation page is tagged Drupal 6, but what reported is still valid for Drupal 7.
> 29 votes

# Answer
Access callback is a function that examines if some user has some permissions. The default access callback is user\_access()

Access arguments lists permission those are examined by access callback. e.g. "access contents"
> 4 votes

---
Tags: routes, users
---


# Question
Title: Manage the stock of raw-materials when products are ordered
I have a scenario where I have an idea of how to solve it but I want to be sure that I am not making it more complicated than it has to be. I am new to Ubercart and Drupal in general (but experienced in software development / databases).

## Scenario

Generalization: need to manage stock levels of raw materials which a user can select among to build a product and order the product. The specific scenario follows below.

On the site the user can customize bags. Specifically each model of a bag is divided into four parts. The user may choose a specific fabric for each part - but which fabrics to choose from depends on the model.

An example. A user may select among fabric A,B,C,D for parts in bag1 and among fabric C,D,E,F for bag2.

It is required to manage stock at fabric level, but the cart should only show the final customized bag level.

So if enough orders are made of bag2 with fabric C so that it runs out, then the option fabric C should no longer be available for bag1.

## Question

It seems to me it is not possible to accomplish the above straight in Ubercart, so my idea is to use an auxiliary database. But perhaps it can be done with configuration and/or some additional module - my first question is whether it could somehow be possible to configure this without having to do code customization / additional database.

I am planning to create a specific module where the user can choose bag-model, and then proceed to choose fabric for the parts and have the bag displayed as it is currently customized.

My second question, assuming that an additional database is required, is the below solution a good solution or is there perhaps a way which would require less work?

## Possible solution (new)

EDIT: This is a way to not have to rely on an auxiliary database outside of Drupal.

* use a product class to represent Fabric-Products, each Fabric-Product is just a piece of fabric
* use a product-kit to represent a Customized-Bag
* use a product class to represent Bag-Model which represent a particular model. Note, it is not customized, fabrics has not been chosen.
* use a product class Bag-Model-Part which has one node reference to one Bag-Model, so these specifies which parts exists per bag. It also has a list (node reference) to Fabric products, these are the possible Fabrics among which one can be chosen for the part
* use a product class to represent Bag-Part-Fabric, which has a node reference to a Bag-Part and to one Fabric (so it is a particular configuration, there one specific fabric has been chosen for one specific part). It also has an image which shows how the part looks like with that fabric.
* the Customized-Bag product kit has a set of Bag-Part-Fabric which specifies exactly how that bag is to be customized, and it also has the set of Fabric used - so that the stock level of the Fabric goes down when it is ordered. It has one image which shows how the final bag looks like.

With this idea, the number of product kits will be PLENTY and so I would have to generate these by code. The manager of the site can easily manage using Drupal the Fabric, Bag-Model, Bag-Model-Part. A bit more tedious but possible for the site-manager is to also add the Bag-Part-Fabric. So the code to generate the product kits can find this data in Drupal, fetch the images from the Bag-Part-Fabric to generate the final image for each product kit.

I assume the code to generate the product kits would be a module which the site manager can trigger to run every now and then (after a batch of new bag-part-fabrics has been created).

The flow for a user visiting the site to customize a bag is: \# choose one of Bag-Model \# for each Bag-Model-Part with that Model, choose one Fabric among possibles and in stock \# once all parts have a chosen fabric, I have the set of Bag-Part-Fabric, use these to find the particular Customized-bag product kit \# when/if user adds to cart, then put the Customized-bag product kit in the cart

Is this an OK solution? Is there something easier or better?

## Possible solution (old)

Idea on how to solve the scenario using Ubertcart and an auxiliary database.

Create a Product Class for: fabric and bag-model

Create a Product Kit for: bag There bag is a final configuruation (e.g. 630 bags if 3 models, 10 fabrics, 4 parts)

Create a non-Drupal auxillary database:

* links SKU of a bag-model to allowed fabric SKU per part
* links SKU of a bag to the specific fabric SKU in that bag configuration

### Setup

By owner of site

* enters (some) unique id for each bag model and the parts of the bag
* enters (some) unique id for each fabric
* enters the allowed unique id of fabric per part per bag model
* Code:
    + generates SKU per bag model and per fabric
    + use Ubercart API to create all bag-model products
    + use Ubercart API to create all fabric products
    + use Ubercart API to create all bag product-kits (all possible combination of fabric)
    + write to auxillary db, for each bag-model, link fabric SKU to part in bag-model

### Running

The user selects among the bag models

* code
    + from Ubercart, get all bag models
    + display all bag models
    + (perhaps not display bag model if all fabric for all its parts is out)
* user
    + user selects bag model

The user selects part to customize

* code
    + use part-names in bag-module to get image, display the parts
* user
    + user selects part

The user selects fabric for part

* code
    + from auxillary db, get fabric SKU allowed for part-nr, using the choosen bag-model SKU
    + from Ubercart, for each fabric SKU check if is in stock
    + display fabric SKU allowed for the part and which is still in stock
* user
    + user selects fabric for part

Add to cart (Once user has customized each part)

* user
    + press Add to cart
* code
    + from auxillary db, get bag-product kit using the fabric SKU selected per part and the bag-model
    + using Ubercart API, add the bag-product kit to the cart

Checkout

* user
    + press Checkout and finish transaction
* code
+ Ubercart updates the stock of the fabric in the product-kit

# Answer
> 1 votes
Using existing modules and maybe a little custom code, you should be able to do something with a nicer workflow than your current proposed solution.

You've probably already looked at uc\_stock. It tracks stock for traditional physical products nicely. By using attributes and Ubercart Stock Manager With Attributes, you can keep track of the stock of products with different attributes. For example, to sell t-shirts in sizes small, medium, and large, you give your t-shirt product the attributes S, M, and L; let the attribute alter the SKU; and uc\_multi\_stock will be able to track the stock of small, medium, and large t-shirts independently.

Since you want to track the quantity of raw materials, you'll need to decrement the stock of other products with the same attribute whenever an item is purchased. From the S/M/L t-shirt example, imagine you sell multiple t-shirt designs, but they're printed on demand. You have a limited number of small, medium, and large t-shirts to print on. Each time a small t-shirt is purchased, decrement the stock of all the other small t-shirts (etc).

Similarly, you'll need to set it up so that you can set the stock of all the small t-shirts at the same time.

You can either implement this using Conditional Actions or by building a small custom module that implements hook\_order. I'd recommend the custom module, since that's more portable and easier to version control. If you do it in code, uc\_stock\_adjust($sku, $qty) adjusts the stock of $sku by $qty and uc\_stock\_set($sku, $qty) sets the quantity of $sku to $qty.

Happy coding!

---
Tags: ubercart
---


# Question
Title: Anyone any good reference about the variables available in the view template?
Tried to print variables in view template, but the print-out is huge,deep-nested and recursive... crazy thing... Just can't drill down to the rendered\_fields array, which seems to be just what I need. Is there any comprehendable reference anywhere?

# Answer
What I usually do when I need to inspect a views variable, that often can be as complex as you describe is to use dpm. Dpm can't always show all of the items since the information is repeated. But then you can dpm the specific parts you need.

So you often start doing `dpm($view);` but end up using `dpm($view->displays...);` to get what you need. Using a reference might be a bit overkill since the view varisble is dymanic, but after doing it a while you start figuring out where you can find stuff. The names is pretty selfexplanatory.
> 2 votes

# Answer
A little underground byt you have

```
<?php
dpm(get_defined_vars());
?>

```
> 2 votes

# Answer
There is a row template that can be found in the Views theme section. It iterates through each field and then wraps it in markup. Another way to do it is to test if a field is empty then print it. Here is an example from a template I just created.

```
  <?php if (!empty($fields['field_dicussion_category']->content)): ?>
    <div class="category"><span class="field-label">Category: </span><?php print $fields['field_dicussion_category']->content ?></div>
  <?php endif; ?>

```

What you can do is a dsm($fields) which will show you the available options.

I don't know too much about the Eclipse IDE or ClientXDebug but I use PhpED to work with code in Drupal. It only costs a couple hundred bucks and is completely worth it. I can put a breakpoint in any part of the code and the IDE will stop the page load and show all the variables. Better yet I can step through and see how the variables change.
> 1 votes

---
Tags: views, theming
---


title: Use entity_uri or drupal_path_alias()?

text:
# Question
Title: Use entity_uri or drupal_path_alias()?
What are the difference? And when should you use which one?

entity\_uri() is rather new to me (Drupal 7) and I see it little used. But it appears to be a lot cleaner and better performing then drupal\_get\_path\_alias().

FYI: I want to get some background information to deal with an issue on Tagadelic.

# Answer
These functions actually have not much in common. There is no question of using one or the other. You will in fact use both of them, although you will most likely not call `drupal_get_path_alias()` directly.

`entity_uri()` returns an array that contains the path and options to link to an entity. So for example for a node, you call it like this: `entity_uri('node', $node)` and it will return `node/$node->nid`. That's kinda trivial. It gets more interesting with other entity types, like private messages (where the path is `messages/view/$message->thread_id#privatemsg-mid-$message->mid`).

You use the returned array like this: `url($uri['path'], $uri['options'])` (or similarly with `l()`). Then, that function will call `drupal_get_path_alias()` internally to check if there is an alias for that internal path and will use that.

The idea is that you can generate the internal path for any entity, without any kind of special handling. A real life example is the Userpoints project. Userpoints transactions support to reference an entity by specifying type and id (Yes, Userpoints used the entity\_type terminology since Drupal 5...). Previously, there was a large bunch of code with support for nodes, comments and users and a custom hook to be able to support more things. When I ported the module to Drupal 7, I was able to replace all that with a simple call to entity\_uri() and it now supports all entities out of the box: userpoints\_create\_description().
> 8 votes

# Answer
The 'problem' with a lot of entity-centered functions is that the entity type is a required parameter. (I ran into that before...) Also, entity\_uri() requires a fully loaded entity, so I guess it may be bad for performance if you have to do a lot of entity\_uri calls.

On the other hand, drupal\_get\_path\_alias requires you to know (read: hard code) the url patterns (like node =\> node/\[nid\]) for every entity type. That might be OK for a a custom module, but it could break in a contrib module that is supposed to work with all kinds of entities.
> 1 votes

# Answer
`entity_uri()` returns the URI associated with the entity passed as argument, while `drupal_path_alias()` returns the alias of the path passed as argument, which could also be not associated with an entity (which is what happens with URLs to administrative pages).

For example, if you have an alias for example.com/node/1 (e.g. example.com/home), the following code would set `$alias` to "home."

```
$alias = drupal_get_alias('node/1');

```

The following code would set `$path` to "node/1."

```
$node = node_load(1);
$uri = entity_uri('node', $node);
$path = $uri['path'];

```

In the latter case, you could have used `"node/" . $node->nid`. Using `entity_uri()` allows you to get the correct URI, even in the case the URI associated with nodes are changed, and the same code works for different type of entities.
> 1 votes

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


# Question
Title: Can solr point into a certain point in a document?
I have very long documents (around 100 pages when printed) that I need to index with Apache Solr Search. Is it possible to index the pages with solr in such a way that clicking the result from the result page takes the user into the right document and **into the right place** in the document?

# Answer
> 1 votes
Not easily (unless there is a module I don't know of which does it).

Solr can return highlighted terms, you can use this highlighting, to preprocess the node when being displayed to insert an anchor tag (after removing the ems), you cold append this tag to the search results page.

Another way would be to index the pages separately. So you could at least link to the correct page (even if is a fragment id) when showing the results.

# Answer
> 0 votes
I think the best solution to this would be to either create book pages for the docs, or have some sort of parent/child relationships, so they all get index separately, and will return the correct pages and spots, but they will all be organized. That is the way I would do it hands-down.

Instead of finding a solution to link to a certain point in the docs, I would be more focused on how I could organize the actual documents in a better fashion.

---
Tags: 7, search
---


# Question
Title: Why drupal includes *.profile file on every page?
I developed an installation profile that contains many various hooks. After an installation process, it is still included on every page, and all my installation hooks are executed. Please explain me why it happens, and by which way I can avoid including \*.profile file after the installation.

# Answer
> 8 votes
This is a new feature of Drupal 7: install profiles behave like modules.

See #509398 : Install profiles should be modules with full access to the Drupal API and all it entails

Code that you don't want loaded during run-time should be moved to hook\_install().

Edit - Xio asked about uninstalling a profile. variable\_set('profile', 'standard'); might work.

# Answer
> 2 votes
Drupal will not include installation files after installation by default.

The best reason I can give to this problem, would be some custom code toy have made includes the files. With the limited information you have provided it's hard to answer with more detail.

**Update**
If you want to "uninstall" a drupal install profile, this can be done by deleting the `install_profile` variable:

```
variable_del('install_profile')

```

You should be aware that doing this will not allow you to use modules located in your install profile folder like you normally can when using install profiles.

---
Tags: 7, distributions
---


# Question
Title: Trying to get COUNT(*) from custom content type with EntityFieldQuery
How can I retrieve the 'count(\*)' from a query in drupal 7? The query needs to include a custom content type and a custom field.

Notes

* Custom Content Type: **employees**
* Custom Field Name: **field\_employees\_email**
* As a note, I'm looking to add

WHERE field\_employees\_email = 'example@example.com'

to the query...

So far, I have something like:

```
$query = new EntityFieldQuery;

$result = $query
     ->entityCondition('entity_type', 'node')
     ->propertyCondition('status', 1) // Getting published nodes only.
     ->propertyCondition('type', 'employees') //Getting 'employees' type only.
     // How do I include custom field as part of query?
     ->execute();

```

Also, is there an easier way than

```
$total = count($result);

```

to return the COUNT(\*) from the query?

# Answer
> 13 votes
You can use EntityFieldQuery::count(), as reported in the documentation for EntityFieldQuery::execute().

> \[The result is\] Either a number if `count()` was called or an array of associative arrays of stub entities.

The code you should use is similar to the following one:

```
$query = new EntityFieldQuery;

$count = $query->entityCondition('entity_type', 'node')
  ->entityCondition('bundle', 'employees')
  ->propertyCondition('status', 1) // Getting published nodes only.
  ->count()
  ->execute();

```

To filter the result by the content type, you need to use EntityFieldQuery::entityCondition('bundle', $content\_type).
For conditions on fields, you should use EntityFieldQuery::fieldCondition().

---
Tags: 7, database
---


# Question
Title: How do you force drupal 7 to make a new revision every time you edit a node?
I'd like to make drupal 7 create a new revision every time you edit a node? This was an option in Drupal 6 but not 7.

# Answer
Just like in Drupal 6, you enable this in the content type settings. At admin/structure/types, click edit for the content type you want to enable this and then check "\[\] Create new revision" under Publishing options.
> 21 votes

---
Tags: 7, nodes
---


# Question
Title: Found user with uid of 0 (zero) in users table... huh?
Is it normal to have a user with uid of 0 in users table?

# Answer
> 16 votes
It is normal, as Drupal creates that entry when it is installed, for the anonymous user. That is done from user\_install() (Drupal 7), or system\_install(), which contain the following code.

```
  // Drupal 7.
  // Insert a row for the anonymous user.
  db_insert('users')
    ->fields(array(
    'uid' => 0,
    'name' => '',
    'mail' => '',
  ))
    ->execute();

```

```
  // Drupal 6.
  // Inserting uid 0 here confuses MySQL -- the next user might be created as
  // uid 2 which is not what we want. So we insert the first user here, the
  // anonymous user. uid is 1 here for now, but very soon it will be changed
  // to 0.
  db_query("INSERT INTO {users} (name, mail) VALUES('%s', '%s')", '', '');
  // …
  // This sets the above two users uid 0 (anonymous). We avoid an explicit 0
  // otherwise MySQL might insert the next auto_increment value.
  db_query("UPDATE {users} SET uid = uid - uid WHERE name = '%s'", '');

```

That entry is normally used when joining the data contained in the "node" table with the data contained in the "users" table.

Not having that entry would cause Drupal not to work correctly in some circumstances.

If you need to restore the anonymous user data in the database, I would execute code similar to the one executed from Drupal. In particular, for Drupal 6, I would execute the following code.

* If the data for the anonymous users already exists in the database, but the user ID is not 0:

```
db_query("UPDATE {users} SET uid = uid - uid WHERE name = '%s'", '');

```
* If the data for the anonymous user don't exist, even with the wrong user ID:

```
db_query("INSERT INTO {users} (name, mail) VALUES('%s', '%s')", '', '');
db_query("UPDATE {users} SET uid = uid - uid WHERE name = '%s'", '');

```

If you want to automatically restore the anonymous user data, you could implement `hook_cron()` in a custom module, and execute code similar to the following one. (The code is for Drupal 6.)

```
function mymodule_cron() {
  $uid = db_result(db_query("SELECT uid FROM {users} WHERE name = '%s'", ''));

  if ($uid === FALSE) {
    // The data has not been found in the database; re-create the row.
    db_query("INSERT INTO {users} (name, mail) VALUES('%s', '%s')", '', '');
  }

  db_query("UPDATE {users} SET uid = uid - uid WHERE name = '%s'", '');
}

```

If you give to the module a lower weight, its implementation of `hook_cron()` will be executed before the other implementations, and this would avoid they will fail because the missing row in the database.

# Answer
> 2 votes
By default anonymous user is 0 and this is the first user present in the users table at the time of installing drupal and the admin id will be 1 and he will be the second user in the users table.

---
Tags: users
---


# Question
Title: Is it possible to export only specific content types?
While I was working on the theme update on my test server, original website got quite a lot of updates. But I can't just re-import the whole database, since I've got some new blocks and views here now. Can I somehow export only specific content types and import only them?

Any handy feature in Drupal itself, or maybe module? It should be a wide-spread requirement, since Drupal is such content oriented.

# Answer
Take a look at the Node export module. From the project page:

> This module allows users to export nodes and then import it into another Drupal installation, or on the same site. The idea is similar to the way you export/import Views or Content Types.
> 4 votes

---
Tags: importing-exporting, nodes
---


# Question
Title: Display User Relationship request dialog on content profile page
I need to create an 'add friend' link programatically.

```
       $content .= '<li>' . l('<span class="icon"></span>Add to your friends', 'relationship/' . $tid . '/request/1?destination=user/' . $tid, array('html' => true, 'attributes' => array('class' => 'add`-friend')));

```

It leads me to another page with confirmation form for the invitation.

Could anybody tell me how (if possible) I can display this confirmation form in dialog?

# Answer
It's all because laziness. It's so easy to do.

I need to add this link with dialog on content profile page.

All to do is:

* add js to content profile page:

```
    if ($variables['node']->type == 'profile') {
        drupal_add_js(drupal_get_path('module', 'user_relationships_ui') .'/user_relationships_ui.js');
    }

```
* add class to request relationship link:

> user\_relationships\_popup\_link
> 0 votes

# Answer
I've created Add as friend likes in a project once doing this:

```
l(t('Add as friend'), 'relationship/' . $account->uid . '/request');

```

It served me fine, but I'm not sure if you want something different.
> 1 votes

---
Tags: 6, users, forms
---


# Question
Title: having a backup of 'sites' folder and database backup is all I need?
I'd to be sure that having a backup of 'sites' folder and database backup is all I need to restore a site?

# Answer
So long as you know which version of core you have and it is un-patched then yes.

If you are backing up sites, make sure you back up any other databases. You may have multiple sites under there.

One good way to test is to do a restore on another server and check things work, after all unless you know your restore works a backup is worthless.

I have found Drush make scripts a handy way to make sure that the core and modules that you use are correct. That way you only need to back up the make script, the site directory itself sites/yoursite.com and the database.
> 4 votes

---
Tags: backups
---


# Question
Title: Reason for javascript disabled in drupal site?
I am using multisite module to maintain three sites. In that i have used "hierarchical\_select" module for a form.

In one of my multisite this form is working great, But in the same form for other site, I am getting following error.

I have attached a screen shot of the error.

As it is using the same files, i am thinking that it should be an configuration issues. But i have checked thrice for all the configuration and unsuccessful.

Please help.

Thanks in advance for any help

# Answer
Hierarchical select adds that info box but removes it with JavaScript. This means that this error can happen for three reasons:

* The `hierarchical_select.js` file is not loaded on the page.
* You have an js error on the page before the `hierarchical_select.js` file is executed.
* You have changed the markup for that info box, so that it is not removed by the JavaScript.

The most obvious reason is a that a JavaScript error breaks this page for you, but that is something you'll have to debug yourself...

To do so open firebug on Firefox or the preinstalled Developer Tools on Chrome (strg+shift+i). If you use firebug first enable the Console. Then reload the page and if there is a Javascript Error it will be indicated with a red warning.
> 2 votes

---
Tags: multi-sites
---


# Question
Title: Drupal 7 - access to page content in template.php
In Drupal 7 I'm trying to access the body field of a page from template.php. I want to find a keyword in the text and then send subsequent text to a separate variable so that I can format it in page.tpl.php

I can access the node using *$vars\['node'\]* but can't find a way of accessing the content part of the node.

I can access the content in page.tpl.php using: *$node-\>body\[$node-\>language\]\[0\]\['value'\]* but cant use the same or similar syntax in template.php

# Answer
In `page.tpl.php` the content of the ***page*** is available in `$page['content']`. It seems that your are mixing two different concepts here: *pages*, any page on the site (including administration page, taxonomy terms page, and other not directly editable pages) and *nodes*, editable content. This can be rather confusing as a default Drupal installation provides a *page* content type. So you end up with *page nodes*, which are nodes of a the page content type.

The layout of the content of a page displaying a node, is handled in the `node.tpl.php` template. In this template, the body of the displayed node is available in `$content['body']`.

If you really need to access a field (handled using the Field API) of the node object (`$node`) from the page preprocess function in your template.php, you can use:

```
function THEME_preprocess_page(&$variables) {
    $node =& $variables['node'];
    $value = field_get_items('node', $node, 'FIELDNAME);
}

```
> 1 votes

---
Tags: 7, theming
---


title: Link to latest poll?

text:
# Question
Title: Link to latest poll?
I set up my poll tpl file to include the poll fields (form, results, etc) along with a list at the bottom for the previous polls, ordered by date. What I am trying to do is, from the main menu, link to the latest poll. In other words, my current latest poll is node/123456/. I can link to that, obviously. But when we create a new one, that link needs to be updated. I'd love to have it so the menu item doesn't need to be edited each time a new poll is created.

Any ideas?

**UPDATE**

Just so you don't think I'm waiting expecting you to write it for me - this is where I am:

`$items['poll/latest'] = array(
 'title' => 'Latest Poll',
 'page callback' => 'latest_poll_find_poll',
 'access callback' => TRUE,
 'type' => MENU_NORMAL_ITEM,
 );`

`return $items;`

`/**
 * Find latest poll and redirect user
 */
function latest_poll_find_poll() {
 $nid = db_query('SELECT MAX(nid) AS nid FROM {node} WHERE type = "poll"')->fetchField();
 $latest = is_numeric($nid) ? 'node/' . $nid : '';
 drupal_goto($latest);
}`

# Answer
> 2 votes
Create a small custom module that implements `hook_menu()` and a custom callback that determines the latest poll and redirects the user. Something like this perhaps (for D6, D7 will be similar):

**Drupal 7**

---

MYMODULE.info

```
name = "MYMODULE"
description = "Adds a menu item for the most recent poll"
core = 7.x

```

MYMODULE.module

```
<?php
/**
 * Implementation of hook_menu()
 */
function MYMODULE_menu() {
  $items = array();

  $items['poll/latest'] = array(
    'title' => 'Latest Poll',
    'page callback' => 'MYMODULE_find_poll',
    'access callback' => TRUE,
    'type' => MENU_NORMAL_ITEM,
  );

  return $items;
}

/**
 * Find latest poll and redirect user
 */
function MYMODULE_find_poll() {
  $nid = db_query('SELECT MAX(nid) AS nid FROM {node} WHERE type = :type', array(':type' => 'poll'))->fetchField();
  $latest = is_numeric($nid) ? 'node/' . $nid : '<front>';
  drupal_goto($latest);
}

```

**Drupal 6**

---

MYMODULE.info

```
name = "MYMODULE"
description = "Adds a menu item for the most recent poll"
core = 6.x

```

MYMODULE.module

```
<?php
/**
 * Implementation of hook_menu()
 */
function MYMODULE_menu() {
  $items = array();

  $items['poll/latest'] = array(
    'title' => 'Latest Poll',
    'page callback' => 'MYMODULE_find_poll',
    'access callback' => TRUE,
    'type' => MENU_NORMAL_ITEM,
  );

  return $items;
}

/**
 * Find latest poll and redirect user
 */
function MYMODULE_find_poll() {
  $nid = db_result(db_query('SELECT MAX(nid) AS nid FROM {node} WHERE type = "poll"'));
  $latest = is_numeric($nid) ? 'node/' . $nid : '<front>';
  drupal_goto($latest);
}

```

Replacing "MYMODULE" with the name of your custom module and placing those files in your site's modules directory in a folder named MYMODULE (replace of course).

---
Tags: routes, polls
---


title: Default file on a cck field

text:
# Question
Title: Default file on a cck field
I want to have a .pdf application form attached by default as a cck field on a custom content type called vacancies, so that every new vacancy created has the pdf file attached without the user having to upload it manually. Is there any way to do this? Thanks in advance!

# Answer
> 1 votes
Probably you need to show a default PDF file attachment with custom type nodes. And need to upload some specific to replace the default one via CCK file field.

CCK file field cannot be associated with some default file easily.

The best approach can be...

* Place the default document in file system
* Edit `content-type.tpl.php` and check CCK field (e.g. `$node->field_name`) for file upload
* Print the link of uploaded file if exists Else print the link to default file

---
Tags: 6, entities, files
---


title: user_roles with features

text:
# Question
Title: user_roles with features
When I use `user_roles()` when there are roles added by features, the feature roles are not returned. How can I get a list of all roles on my site included those defined in features?

# Answer
> 1 votes
Is the Role listed on `admin/user/roles`? If not, your Feature might not be defining a Role, or the Feature might be overridden.

Roles defined by Features *do* actually show up in `user_roles()`. I created a simple Feature defining a single role, then enabled it:

```
% drush php-eval "print_r(user_roles())"
Array
(
    [1] => anonymous user
    [2] => authenticated user
)

% drush pm-enable yayfeature
The following extensions will be enabled: yayfeature
Do you really want to continue? (y/n): y
yayfeature was enabled successfully.                                                                                [ok]

% drush features-revert yayfeature
Do you really want to revert user_role? (y/n): y
Reverted user_role.                                                                                [ok]

% drush php-eval "print_r(user_roles())"
Array
(
    [1] => anonymous user
    [2] => authenticated user
    [5] => yay
)

```

---
Tags: 6, features, users
---


title: How do I show revision users in a view

text:
# Question
Title: How do I show revision users in a view
I would like to create a view that shows the title of all newly revised or updated content with the username of who modified it. The first part is easy, but for the life of me, I can't figure out how to show a the username of who updated it as everything shows the original author, not the user who updated the content.

Any ideas on how to accomplish this?

# Answer
> 4 votes
Have you tried creating a relationship?

Sounds like that might give you the data you need, but you'll need to test it out.

---
Tags: views, 6, users, nodes
---


# Question
Title: line break or second row for single record in view?
I'm using views2 in Drupal 6. I have a view for a custom table. One of the column is called 'notes', which is a textarea. Most of the time it's blank, but sometimes not.

I would like to have it so that if there is a value in the notes column, instead of displaying it in the column, it would add a line break or another row underneath the normal values, like this:

```
+-------+-------+-------+-------+
| col 1 | col 2 | col 3 | col 4 |
+-------+-------+-------+-------+
| val 1 | val 2 | val 3 | val 4 |
+-------+-------+-------+-------+
| val 1 | val 2 | val 3 | val 4 |
| this is a note.               |
+-------+-------+-------+-------+
| val 1 | val 2 | val 3 | val 4 |
+-------+-------+-------+-------+

```

Is this possible to do with built-in views functionality, or is there a module that can accomplish this?

# Answer
> 1 votes
Add your 'notes' field to your view, but exclude it from display (in views field settings), then output it in any way you want (as new table row for example) using views' Theming Information.

# Answer
> 2 votes
There is a module for Drupal 7 and Views 3.x called Views Secondary Row. Sadly, it's not available for Drupal 6 or Views 2.x.

---

A first-glance at the code of Views Secondary Row makes me think that a backport to Drupal 6 and Views 6.x-3.x might not be too difficult if you have some module-development experience (although I've never written modules to work with Views before, so I'm not sure how accurate that observation is). If you don't want to try your hand at it personally, you could put a feature request in the issue queue.

---
Tags: views, 6
---


title: Question related to page-user.tpl.php

text:
# Question
Title: Question related to page-user.tpl.php
Is there a way to tell when we are in the /user/1/edit page vs in the /user/1 page when inside the template file page-user.tpl.php?

Are there any of the $variables that I can check?

I think I would rather check this, than create a nearly identical template file called page-user-edit.tpl.php. Or is there a better way?

# Answer
Check for `arg(2)` to differentiate both paths. Arg() function docs.

In case `user/1` arg(2) will be Null

Incase `user/1/edit` arg(2) will be 'edit'
> 1 votes

---
Tags: theming
---


title: Global redirect edit link

text:
# Question
Title: Global redirect edit link
I am using the global redirect module. This makes `/node/1` goes to my path auto `/node/clean-title`. If I goto `/node/clean-title/edit` I get a 404 error. If I go to `/node/1/edit.` How can I get it so that `/node/clean-title/edit` works. I would like this to happen on all my nodes automatically.

# Answer
> 2 votes
You want the Subpath Alias module.

> For example, if node/1 is aliased to content/alias, this module rewrites the link to the node edit page node/1/edit to use the aliased URL content/alias/edit instead.

# Answer
> 1 votes
By default, path auto only supports node display urls. You could create a small custom module that integrates with path auto and creates the edit urls as as well.

The easiest thing to do, is probably to look at the path auto module and see how it does it. You should be able to copy/paste a lot of code and add `/edit` where needed to make it work for node edit urls as well.

---
Tags: 6, redirection
---


# Question
Title: Show highest and lowest price in a view from a node reference
I have a content type called **Cars**, and a content type called **Prices**. They are node referenced. The **Prices** content type has a decimal cck field for the price called **field\_price**. So you can create a new **Prices** node that will have the price for the car. There are multiple **Prices** nodes for each **Car** node. In views, how would I be able to show the lowest and highest prices for the car. For instance, it would say, **Prices for this car range from $10,568 to $18,259**.

# Answer
There may be a more fancy-pants way to do this, but I would take the view template, extract the car type, and do a manual MIN() MAX() query to fetch these values.
> 1 votes

---
Tags: views, 6, nodes
---


# Question
Title: Import won't import content in CCK image fields
I am using the Node Export module to migrate thousands of nodes from a Drupal 5 site to a Drupal 6 site, and it is working really nicely except for one thing: It systematically fails to import my CCK image field and I get the following error message.

> Unknown error occurred attempting to import file: ***\[path to file\]***

Does anyone know how to resolve this issue?

# Answer
Are the images already in the directory in the new site? For most import modules, the images *Have* to been in the directory before you start importing.
> 2 votes

---
Tags: entities, nodes, media, importing-exporting
---


title: How to override default favicon.ico?

text:
# Question
Title: How to override default favicon.ico?
I would like to load my own, but Drupal seems to forcefully load it's own by default behind the scenes.

# Answer
Turned out to be as simple as placing favicon.ico into the theme root folder (!)
> 8 votes

# Answer
http://YOURSITE/admin/build/themes/settings \- upload your favicon for all enabled themes, as for "Global settings".
> 6 votes

# Answer
In Drupal 7 there's a way that's easier than loading the image file to a particular directory and you get some error checking. There's a global admin page that allows you to upload in icon image. Log in as an administrator and visit

http://www.EXAMPLE.com/#overlay=admin/appearance/settings

Look near the bottom of the page for the "Shortcut Icon Settings". You can turn on/off the default, set a path to a file and upload images.

Each theme has a similar setting that overrides the global setting. Be aware that changing the global setting my not work as you expect for a changed theme.

-Bob
> 5 votes

---
Tags: files
---


# Question
Title: advise for managing and troubleshooting modules
I think anyone using Drupal runs into this sooner or later. You're trying to get to some solution and you start adding modules. Then somethings start breaking. The last time I had this problem, I uninstalled and then reinstalled the modules by enable/reenable the check boxes on the module page.

This time I have a lot of new content types and views and wot wot, and I'm scared. (\>\_\<) I don't know if I'll lose these bits. I've exported my views, I've dumped the database. But I'm still nervous. What advise would you give, or reassurance?

# Answer
Unchecking the module does not uninstall it, it is just disabled. The schema related to the module is only removed when it is first disabled and then uninstalled.

If disabling and then enabling can solved your issues then do it.

But disabling and then enabling a module would not do any thing harmful except to remove and then add its record in system table and would invoke few hooks like hook\_menu, hook\_theme etc.
> 1 votes

---
Tags: 7
---


# Question
Title: Why isn't the code in my implementation of hook_form_alter() being called?
When I test to see if my form is called by checking for its `$form_id`, there is no output. Why is it that under the comment form it can't invoke the `mymodule_ask_form`?

```
/**
 * @Implement of hook_form_alter()
 */
function mycaptcha_form_alter(&$form, &$form_state, $form_id) {
    if ($form_id == 'comment_form') {
      mycaptcha_ask_form($form);
      echo 'test';
    }
  }

function _mycaptcha_get_ask($key = NULL) {

  $ask = array(
    'test 1' => 'example 1',
    'test 2' => 'example 2',
  );

  return isset($key) ? $ask[$key] : $ask;
}

function mycaptcha_ask_form(&$form) {
  $ask = _mycaptcha_get_ask();
  if (isset($_SESSION['mycaptcha_ask_key']) && $ask[$_SESSION['mycaptcha_ask_key']]) {
    $ask_key = $_SESSION['mycaptcha_ask_key'];
  }

  if (!$ask_key) {
    $_SESSION['mycaptcha_ask_key'] = $ask_key = array_rand($ask);
  }

  $form['mycaptcha_ask'] = array(
    '#type' => 'textfield',
    '#required' => 1,
    '#title' => 'tetst'.$ask_key,
    '#weight' => -1
  );
}

```

# Answer
> 0 votes
First of all - have you checked that Drupal sees your function at all, and calls it?

Then, have you tried printing out $form\_id? As for default D7's content types (article and basic page) comment form ids are not "comment\_form", but:

* comment\_node\_article\_form - for article
* comment\_node\_page\_form - for basic page

---
Tags: forms
---


title: Variable theme name

text:
# Question
Title: Variable theme name
I want to use template, which name is determined in runtime (specialized template). If such template is not defined, use fallback template with fixed name (like node-sometype.tpl.php is used before node.tpl.php):

```
return theme(
    array('my_theme_'.$node->type, 'my_theme'),
    $some_arguments
);

```

If I do not declare specialized templates in my hook\_theme, and just make my\_theme\_page.tpl.php files in theme directory, they are not used.

If I declare them (here themes are specialized by node type, so it is possible), Drupal always uses them, producing include/call\_user\_func error, instead of using fallback one.

```
$themes = array(
    'my_theme' => array(
        'arguments' => array('some_arguments'=>NULL),
        'template' => 'my_theme',
        'path' => $path,
    ),
);
foreach (node_get_types() as $type => $_)
    $themes['my_theme_'.$type] = array(
        'arguments' => array('some_arguments'=>NULL),
        'template' => 'my_theme_'.$type,
        'path' => $path,
    );

```

So the question is:

How to declare theme in module, without providing implementation, so it can be used with theme() fallback mechanism.

# Answer
> 4 votes
When you want to allow users to have more templates to choose from that are more specific, fx one for all nodes vs one for each node type, you should use what Drupal call template suggestions. This will allow you to have a single theme function, and not have to clear cache to add the extra options.

You can read more about template suggestions.

What you want to is to create a single theme function with hook theme:

```
 function module_theme() {
   return array(
     'module_theme_function' => array(
       ..
     ),
   );
 }

```

Then create a preprocess function for that theme function:

```
function template_preprocess_module_theme_function(&$vars) {
  // Add template suggestions:
  $vars['template_files'][] = 'my-template-file-' . $some_var;
}

```

This would allow you to use the `my-template-file-X.tpl.php` file where X equals the variable you added. You can use this technique to add as many template suggestions you like. The last ones added will take precedence if several of the options is defined.

# Answer
> 1 votes
For actual templates, you simply want to define so called template suggestions, then you don't need to define them at all in hook\_theme(). See Working with template suggestions.

For theme functions, it is also possible to set the `pattern` property in hook\_theme(), see privatemsg\_theme() for an example.

---
Tags: 6, theming
---


title: Customize Drupal 6 Nice_Menus Output

text:
# Question
Title: Customize Drupal 6 Nice_Menus Output
I had asked this exact question on StackOverflow, until I cam across this StackExchange site...makes much more sense to post this here!

I'm using **nice\_menus-6.x-2.1** with Drupal 6.22 and would like to know if there is any way to rewrite the menu output so that the end-result resembles the following:

```
<ul>
    <li><a href="node/xx">Parent Link 1</a></li>
    <li>
        <a href="node/xx">Parent Link 2</a>
        <div>
            <ul>
                <li><a href="node/xx">Child Link 2<span>[Description]</span></a></li>
                <li><a href="node/xx">Child Link 2<span>[Description]</span></a></li>
            </ul>
        </div>
    </li>
    <li><a href="node/xx">Parent Link 3</a></li>
</ul>

```

Basically, I only want the customization on the second tier of sub-menus onwards. The `<div>` wrapper is there for styling purposes. The `<span>` within the link tag is supposed be the description that you usually get on mouse-over, but I want this to show a bit smaller below the link (but be part of the link itself, and therefore not outside the `<a>` tag). I'm sure this is possible? I just don't know where to start. I'm looking within **nice\_menus.module** but can't seem to find the function for the children rewrite. I currently have this working in a mock using plain HTML markup and CSS, but I just can't work out how to customize the PHP function in Drupal.

Has anyone been through this and would care to share?

Thanks a million everybody!

# Answer
Probably you would just want to implement your own version of theme\_nice\_menus\_build(), and add all your required divs/spans right there.
> 1 votes

---
Tags: routes
---


# Question
Title: Adding a class to select options from Views Exposed Filters
Currently I have a views exposed filter for a "City" field. Typical output looks like:

```
<option value="Liverpool">Liverpool</option>

```

I would love to be able to add a class to this such as:

```
<option value="Liverpool" class="north-west">Liverpool</option>

```

I currently have a CCK field "field\_region" which is set to "North West" for Liverpool - so it would be brilliant if anyone had any suggestions with how to achieve this on my exposed form input.

Cheers, Garry.

# Answer
Normally this would be accomplished with hook\_form\_alter, but sadly Drupal 6 doesn't support attributes in the options Form API element, which means you can't add any classes to it.

You're going to have to do this with Javascript. :-(

You can't start with something like this:

```
  $('.view-NAME_OF_YOUR_VIEW .views-exposed-widget option').each(function(index) {
    $(this).addClass($(this).val());
  });

```

This will get you

```
<option value="Liverpool" class="Liverpool">Liverpool</option>

```

I know it's not perfect, but sadly that's probably the simplest route.
> 5 votes

# Answer
Hm. You could always implement your own theme\_select(), and them from it call your implementation of form\_select\_options() - in which you can do whatever you want with your options...
> 3 votes

---
Tags: forms, views, theming
---


title: How to make archive of drupal database

text:
# Question
Title: How to make archive of drupal database
How to make archive of drupal database with a php code inside node? Without any scripts. This needs in case you forget your FTP access.

# Answer
> 3 votes
There is a module for this, use that instead of custom coding PHP in nodes. Generally you never want to put code in nodes for a lot of reasons:

* No version control.
* If you make a syntax error you're in big troubles.
* very hard to maintain when you need to upgrade a site (API changes).
* Greater possibility to open your site for security vulnerabilities.
* ...

Anyways the module backup and migrate will do what you need.

**Alternative solution**

If you don't have DB password or FTP password and want to create a dump, the simplest thing you can do it to:

1. get the DB password from Drupal

```
global $db_url;
drupal_set_message($db_url);

```
2. Use the password obtained from Drupal to login to PHPmyadmin or similar
3. Use the GUI to create the dump.

---
Tags: database
---


# Question
Title: What is the meaning of $form['cid']['#value']?
```
    /**
     * @Implement of hook_form_alter()
     */
    function mycaptcha_form_alter(&$form, &$form_state, $form_id) {
     if ($form_id == 'comment_form' && !$form['cid']['#value']) {
。。。。。

```

Someone has written the above code, but I don't know what `$form['cid']['#value']` is for, and what I should use in Drupal 7.

# Answer
> 4 votes
cid is the comment id. And this comment checks if it is empty or not. When it is not empty, it means that we are editing an existing comment as opposed to creating a new one and this code doesn't need to run.

---
Tags: 7
---


title: Need help with Block Caching

text:
# Question
Title: Need help with Block Caching
I run a flash card game embedded as a block in a Drupal 7 site.

Below that main block I display 3 further blocks for the winners of the previous and current week and top 7 best players:

And these 3 blocks are really dragging the performance of my web site (loading page is taking 5-10 seconds more than without them). I'd prefer them to be cached every 15-30 minutes because the weekly top 7 doesn't change often.

How could I do that - without jeopardizing my main block with the game? I.e. the main block contains flash vars specific to each user (his authentication hash) - **this one block may not cached and served to any other user**.

Below is my code:

**pref.info -**

```
name = Pref
description = Pref module
package = Pref
core = 7.x
files[] = pref.module

```

**pref.module -**

```
function pref_block_info() {
  return array(
    'pref_main' => array(
      'info' => t('Display flash game for auth. users'),
      'cache' => DRUPAL_NO_CACHE,
    ),
    'pref_winner' => array(
      'info' => t('Show the winner of the last week.'),
      'cache' => DRUPAL_NO_CACHE,
    ),
    'pref_leader' => array(
      'info' => t('Show the leader of the current week.'),
      'cache' => DRUPAL_NO_CACHE,
    ),
    'pref_top' => array(
      'info' => t('Show the top 10 of the current week.'),
      'cache' => DRUPAL_NO_CACHE,
    ),
  );
}

function pref_block_view($block_name = '') {
  global $user;
  $viewer_id = $user->uid;

  if ($block_name == 'pref_main') {
      .... # may not be cached
      return array(
        'subject' => '',
        'content' => '...here I return the .swf file + user-specific hash...');
  } else if ($block_name == 'pref_winner') {
      .... # should be cached
  } else if ($block_name == 'pref_leader') {
      .... # should be cached
  } else if ($block_name == 'pref_top') {
      .... # should be cached
    $result = db_query("
select u.id,
        u.first_name,
        u.female,
        u.city,
        m.money,
        u.login > u.logout as online
from pref_users u, pref_money m where
        m.yw=to_char(current_timestamp, 'IYYY-IW') and
        u.id=m.id
order by m.money desc
limit 7
");
    $i = 0;
    $list = array();
    foreach ($result as $record) {
      $list[] = user_link($record) . ($i++ > 0 ? '' : ' »');
    }
    $theme_args = array('items' => $list, 'type' => 'ol');
    $content = theme('item_list', $theme_args);
    return array(
      'subject' => 'Семерка лучших',
      'content' => $content,
    );
  }
}

```

For module caching I probably should enable it in the **/admin/config/development/performance** and then use some other constant instead of the **DRUPAL\_NO\_CACHE** (but which one to take from the **includes/common.inc**)?

# Answer
A simple solution would be to cache the output instead of caching the block. This would be done in your `hook_block_view` implementation.

It could look like this:

```
...
$cache = cache_get('pref_pref_leader', 'cache_block');
// Return cache if possible.
if (!empty($cache) && isset($cache->data) && !empty($cache->data)) {
  return $cache->data;
}

// no cache, generate the output.
...
$content = ...;
$block = array(
  'subject' => 'Семерка лучших',
  'content' => $content,
);
// Cache for 30 mins.
cache_set('pref_pref_leader', $block 'cache_block', time() + 1800);
return $block;
...

```

See documentation for
> 2 votes

---
Tags: 7, blocks, caching
---


# Question
Title: Can I pass variables from more specific template/preprocess function up to less specific?
I need to display a node as a block, so I went with the most obvious way and created a view with a display block and this very node in it. But now I need to style it and I can't pick up the proper template. **block-views.tpl.php** looked great, but being in this template I do not seem to have access to view's variables anymore, have I? Basically I need a place where I could have access to view's variables and control over the look of the block. If I could just pass variables up the chain, that would be great...

# Answer
> 2 votes
Nodes In Block or Node Block can help to place nodes in blocks.

The other part, to theme that particular node can achieved by different scope of templates from general to specific node templates. e.g.

* node.tpl.php
* node-\[type\].tpl.php
* node-\[nid\].tpl.php

---
Tags: views, theming
---


# Question
Title: Why does drush en give differerent results than enabling mymodule in the ui?
When I perform `drush en mymodule -y` my module enables no problems. When I do the same in the UI it seems to install great. No errors. However the roles defined in `hook_install()` are not created. In Drush they are. What is the difference between Drush and Enabling the module in the UI?

# Answer
One gotcha between the UI and Drush is the user. Drush commands are run as anonymous by default. Where as in the UI you are user with greater rights (normally the admin user).

Some parts of Drupal will check for rights before doing things, node\_save is one such place. Depending on how you are creating your roll you may find there is another.

A work around for this is to use the `-u` flag with Drush.

```
drush -u 1 en my_module

```

I can't say for certain that this will fix your issue, but there is a fair chance that it will help.
> 2 votes

---
Tags: 6, drush
---


title: Can't print $base_root in headers view

text:
# Question
Title: Can't print $base_root in headers view
I have a View and inside it I have and Attachment display. In this attachment I set a Header with the value you can see in the image below. I'm sure I have register\_globals = 1; But nothing is printed...

# Answer
Well, you need to say that what you want to display is global as well:

```
<?php
global $base_root;
print $base_root;
?>

```
> 3 votes

---
Tags: views
---


# Question
Title: Which file do I need to edit to implement a 'Back to top' link?
I am running a Drupal 6.22 site, with a custom template installed in /sites/all/themes/mytheme. Which template file should I edit to implement a back to top link?

# Answer
It depends where you want the link to be, but your best bets would probably be `page.tpl.php`, `node.tpl.php` or a variation of those templates (specific to content types, etc).

For more on templates see Drupal 6 template suggestions
> 2 votes

---
Tags: 6, theming
---


# Question
Title: How to print url arguments in headers view
I have a View and inside it I have and Attachment display. In this attachment I set a Header where I need to print the 2nd url argument. How can I do this? With globals?

Thanks

# Answer
```
<?php print arg(1); ?>

```

See: `arg`

Arg can be used to get the url arguments. It's 0 indexed, so 0 will give the first url argument.

Notice, when using url aliases that arg will bring the internal url arguments (the original path).
> 2 votes

---
Tags: views
---


# Question
Title: Initialize & override a Drupal7 jQuery module's (Superfish) provided .js, in code
I'm migrating a Drupal6 site to Drupal7.

The v6 site was subthemed in Fusion, and used its bundled Superfish menu js. The init I used that worked was:

```
$(document).ready(function(){
 $("ul.sf-menu").supersubs({
  minWidth:    12, // min sub-menu width, em
  maxWidth:    27, // max sub-menu width, em
  extraWidth:  1,
 }).superfish({
  hoverClass: 'sfHover',
  speed:       0,   // ms, cref jquery animate()
  delay:       0,   // mouseout delay, ms
  animation:   {opacity:'none',height:'none'},
  autoArrows:  true,
  dropShadows: false,
  disableHI:   true,
 }).supposition();
});

```

In moving to D7, Superfish has been UN-bundled from Fusion, in favor of using the Superfish *module* for system-wide support.

I'm using the module's js in some custom markup, and need to init the module & override the module's defaults.

I understand that in D7, we need to init jQuery a bit differently. My 'best shot' so far (which, unfortunately, is NOT working) at reproducting what I had in D6 is:

```
( function ($) {
        Drupal.behaviors.mySuperFish = {
            attach: function(context, settings) {
                $('.sitemenu-inner .sf-menu ul', context).supersubs({
                    minWidth:    12, // min sub-menu width, em
                    maxWidth:    27, // max sub-menu width, em
                    extraWidth:  1,
                }).superfish({
                    hoverClass: 'sfHover',
                    speed:       0,   // ms, cref jquery animate()
                    delay:       0,   // mouseout delay, ms
                    animation:   {opacity:'none',height:'none'},
                    autoArrows:  true,
                    dropShadows: false,
                    disableHI:   true,
                    dropShadows: false, /* Needed for IE */
                }).supposition();
            }
        };
    })(jQuery);

```

noting that the targeted div/tag *has* changed.

With this code in place, Firebug is showing me no errors; then again, I'm seeing no sfHover autoclassing, or any of my Superfish submenu functionality.

What am I still doing wrong here?

# Answer
> 0 votes
It turns out that your suspicion,

> You have a different superfish version

is likely correct(ish). Removing

```
animation:   {opacity:'none',height:'none'},

```

from the stanza above fixes the problem; autoclassing, submenu dropdown, etc are all working.

The use of property =\> 'none', which works just fine in D6, apparently causes an element parsing problem in D7.

Afaict, Superfish hasn't changed, or at least, I haven't found the docs that say it has.

'animation', iiuc, is effectively invoking jQUery's 'animate'. jQuery version has certainly changed from D6-\>D7. Checking the current api docs for animate(),

" ... In addition to numeric values, each property can take the strings 'show', 'hide', and 'toggle' ..."

And, changing it to either

```
animation:   {opacity:'show',height:'show'},
animation:   {opacity:'toggle',height:'toggle'},

```

also does the trick.

I can't find the jQUery version changelog that says the arg list changed; in any case, it DID work with 'none' in D6, it doesn't now with D7 -- until the property arg's corrected.

Thanks.

# Answer
> 0 votes
The JavaScript that you have written for Drupal 6 and 7 does the same thing, only the targets has changed a bit `ul.sf-menu` vs `.sitemenu-inner .sf-menu ul`.

This gives a few options as to what *could* be wrong.

* You have a different superfish version, that behaves a bit differently
* Your markup has changed and doesn't work like it did for your Drupal 6 site.

It's hard to debug why you're not getting the desired result, you could try to test out superfish on a static page and see if you can get it working. That will reduce some of the complexity and reduce your problem to a JavaScript/jQuery problem.

---
Tags: theming, javascript
---


title: Drupal 7: adding an image to 1 menu tab

text:
# Question
Title: Drupal 7: adding an image to 1 menu tab
The main menu at my Drupal 7.2 site is represented as tabs. I wonder please, how could I add an image to one of the tabs - for example a letter-icon for the last /contact tab?

When I look at the HTML code I see that tab as a **class="menu-276 last"** list item:

```
<div id="main-menu" class="navigation">
<h2 class="element-invisible">Основные ссылки</h2>
<ul id="main-menu-links" class="links clearfix">
<li class="menu-270 first active"><a href="/" class="active">Преферанс</a></li>
<li class="menu-300"><a href="/help">Как играть</a></li>
<li class="menu-278"><a href="/top20.php">Рейтинг</a></li>
<li class="menu-368"><a href="/forum/1">Форум</a></li>
<li class="menu-392"><a href="/etude">Этюды</a></li>
<li class="menu-276 last"><a href="/contact">Письмо админу</a></li>
</ul>
</div>

```

How would you be adding an image there, through editing the core Menu module or maybe there is a nicer way? (a CSS-solution would be ok too...)

Thank you! Alex

# Answer
You could use CSS:

```
#main-menu-links li.menu-276 a {
  background: url(path/to/img.png) no-repeat left;
  padding-left: 16px; /* Change depending on icon size */
}

```
> 0 votes

---
Tags: routes, media
---


# Question
Title: Display edit link for a node in a view when user has permission
I have a view displaying fields from one node.

Is it possible to display a link for a user to edit the node if they are logged in and have the appropriate permission to edit? Something similar to the tabs with edit displayed for a regular themed node would be nice.

# Answer
> 5 votes
In Views, there is a field you can add called `Node: Edit link` that will display a link to the edit page for the node, taking into account the user's permissions.

---
Tags: views, 6
---


# Question
Title: Is it possible to customize user profile URLs based on a custom profile field?
At the moment, my user profile URLs are changed in the standard way with pathauto, e.g.:

`/users/user.name`

However, I have different types of users (e.g. students, faculty, staff, etc.).

I would like the URL of each user's profile page to reflect that, e.g.:

* `example.org/students/user.name1`
* `example.org/faculty/user.name2`

The user type is set in a custom profile field: `profile_user_type`.

Is it possible to customize the URLs based on a profile field (in Drupal 6)?

# Answer
As Pathauto uses the tokens provided by the Token module, you could use the Token Profile module that implements tokens which return the value of user profile fields.
> 4 votes

---
Tags: 6, users, uri
---


title: Simulate remote drupal user

text:
# Question
Title: Simulate remote drupal user
I am looking for a way to use an authenticated user session to remotely create content on my Drupal site.

My challenge is a somewhat complex one so please bear with me.

Using the Poster Firefox addon I am able to simulate creating and logging a user onto a Drupal website. The issue now is how to enable a persistent connection. So, using Chrome I login and I detect the session cookie details. I then try to use those cookie details in the Firefox Poster addon interface to remotely create a new node(page) on my drupal site. The objective is for Drupal to report the new remotely created node(page) as authored by my logged-in user on the Chrome browser.

Ultimately, I am trying to figure out the recipe to translate to a program that will serve as the remote client while Drupal is used as a server.

I hope someone can shed some light on this issue for me. Thanks for your time.

PS: The following images show how I am setting the http post header containing the cookie information and the variables Drupal uses to create my remotely created node.

# Answer
> 1 votes
I suggest you look into the Services Module. The entire concept is based upon 'programmatic remote users' logging into a Drupal site and accessing whatever portion of the 'out of the box' site API you enabled for your remote users to access. Additionally, Services offers a well designed means of creating your own API routines that your selectively expose to different remote users.

The out of the box API calls enable you to create users, nodes, comments, and so on. Most of the basic operations a user can do are available.

Check out: http://drupal.org/node/1070066

---
Tags: users
---


# Question
Title: Can administration menu be configured with a stripped down menu that only gives the user access to post content?
How would I go about setting up stripped down administration menu so that non-privileged users can see a menu allowing them to post content that they have permissions for? Right now the user sees no menus in their admin menu.

# Answer
From the role permission settings you can do so allowing him for `access administration menu` and then checking required permission sets (e.g. `access administration pages`)
> 3 votes

---
Tags: 6, users
---


title: what kind of views should I use?

text:
# Question
Title: what kind of views should I use?
I am going to download the Views module for a Drupal 7 website I am creating, but there are 2 different versions: There is the alpha3, the development snapshot, and another one that doesn't have a name I can see (it is highlighted in green). Which these three versions should I use?

# Answer
> 1 votes
There are two main version of View,s 2.0 and 3.0.

Drupal 6 has support for both views

* 6.x-2.12 with Views 2
* 6.x-3.0-alpha3 with Views 3
* 6.x-3.x-dev with Views 3 and is under development

It is recommended to use 6.x-2.12

---

After clarifying about drupal7:

For Drupal 7 there is `Views 7.x-3.0-rc1` recommended.

# Answer
> 1 votes
It is really a personal decision on which one you should download. It is recommended to always download the one's in "Green". However views3 offers a significant improvement in the user interface and if you are just starting out in views, this might be a better choice.

A good article on choosing modules http://drupalwatchdog.com/1/1/module-selection-in-the-wild

# Answer
> 1 votes
For Drupal 7, there's now an RC (Release candidate). However, I still think that for D7 modules before the first release, the -dev version is usually your best bet. This is the case with Views as well.

---
Tags: 7, views
---


# Question
Title: Trigger whenever a user uploads an image
I would like to enable certain actions to occur whenever a user uploads an image, namely movement to s3 and adding an entry in the db for site and metadata purposes. What would be my first steps in accomplishing this?

# Answer
> 1 votes
If you're using a field field in Drupal 7, you could accomplish this with the use of stream wrappers, core-supplied file API hooks, and a file field.

See the file examples in the Examples for Developers module. Also read through the 'Stream Wrappers and You' post from Advomatic for some background.

For more advanced triggered actions, you could also consider using the Rules module to react to a file being uploaded to the site via a new node or other entity type.

---
Tags: media, rules
---


# Question
Title: Create different URL alias based on CCK field
So I have a typical blog entry content type and I've added a CCK checkbox for some extra functionality. I'm using the pathauto module to automatically set the URL alias for the blog entry content type.

What I would like to do is alter the URL alias created depending on the value of the CCK checkbox. If the box is checked, I'd like to change the URL alias. If not, let pathauto do it.

Possible? Can this be done in the template.php file of my theme?

# Answer
> 1 votes
I'm assuming you're well-versed in the settings that Pathauto gives you (like it's own "automated alias" checkbox, and the settings that change what happens when a node is updated). I'm assuming those settings don't meet your needs.

This should be possible, but not in the theme layer. You'll need to write a module, probably a relatively small one. You'll need to implement `hook_nodeapi` in D6 or one of the hook\_node\* family in D7, and maybe `hook_pathauto`, to make sure the right thing happens.

**Drupal 6**

**Drupal 7**

---
Tags: entities, path-aliases
---


# Question
Title: How can I detect when a node is changed from 'Published' to 'Unpublished'?
In hook\_node\_update(), I can easily tell the 'status' of a node (whether it's published or not) after it's been updated.

However, is there an easy way to check to see if the updated node *was* published, but now is not? (Or vice-versa)?

I think Rules might have some condition for 'node value has changed' or something along those lines, but I'd like to do this programmatically.

I found this issue by fago (developer of Rules) on drupal.org that seems to deal with this in Drupal 7, but a nice explanation would be appreciated.

# Answer
Nevermind. After reading through the issue linked above (especially comment #38), I found that the $node object (any entity, actually) stores the 'original' cached copy in $entity-\>original.

So, I wanted to detect whether a node changed from 'status = 1' to 'status = 0' (this happens when the node is unpublished), and the following code does this:

```
<?php
function custom_node_update($node) {
  if ($node->type == 'article') {
    // Act on the unpublishing of an article.
    if ($node->original->status == 1 && $node->status == 0) {
      // Do something here.
    }
    // Act on the publishing of an article.
    if ($node->original->status == 0 && $node->status == 1) {
      // Do something here.
    }
  }
}
?>

```
> 34 votes

# Answer
`node_save()` contains the following code.

```
  try {
    // Load the stored entity, if any.
    if (!empty($node->nid) && !isset($node->original)) {
      $node->original = entity_load_unchanged('node', $node->nid);
    }
  }

```

`entity_load_unchanged()` loads the entity (in this case the node) from the database; it returns the entity object before any changes made from the running modules.

The code is executed before any pre-save, and update hooks.

```
module_invoke_all('node_presave', $node);
module_invoke_all('entity_presave', $node, 'node');

//...

node_invoke($node, $op);

// Save fields.
$function = "field_attach_$op";
$function('node', $node);

module_invoke_all('node_' . $op, $node);
module_invoke_all('entity_' . $op, $node, 'node');

```

In those hooks, it is possible to see the node properties before any change in `$node->original`, for example with `$node->original->status`.
> 1 votes

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


title: Searching using Solr within Views

text:
# Question
Title: Searching using Solr within Views
I'm learning Drupal, and having a lot of fun. I am approaching the phase were I'd like to make my content more accessible to users.

I haven't implemented it yet, but I am really liking the ApacheSolr Search Integration module. I was wondering if there was any module to search within Views. My problem is that most of my site is based on Views; I have a lot of content on external databases, which I am maintaining, and Views queries that content for the users.

If Solr doesn't have anything I need, is there any other solution?

# Answer
You have external data which you are exposing with views.

So you have a couple of options, one would be to get something to index your whole site but as this question shows that is not straightforward.

The second option is to get solr to index your external data. The inbuilt solr module (and solr views) are very node centric. If you have your data in nodes this works fairly simply. If you are only showing external data with views then this solution won't work for you.

So what you can do is to use a solr data import handler to index your data (that is outside the scope of DA but have a look here for some info)

If you get this working you still then have a way to go. Firstly you need to get drupal to talk to solr for non node terms. The solr module will happily talk to any solr server if you are happy to code things yourself, but for views integration you have a bit more work. There are a couple of projects looking to do this, but they are not really mature projects just yet.

Once you have views pointing to solr and searching working you can then format your search results so that they link to your other views.

So for example if you have an external entity with an id XZY you may have a view which takes a url argument at '/myview/XZY' you can edit your search results view so that it points to that url. I have done this here, most of the site is generated using views and solr.

However I think for most of this to work you will have to use views3.
> 2 votes

# Answer
Please see the Apache Solr Views module for combining Solr and Views together.

If you are looking for a Views-only approach, you should watch this screencast on Exposed Filters.
> 3 votes

# Answer
If you are still having issues, you can check out the IndexTank module.
> 0 votes

---
Tags: 7, views, search
---


title: Help Understanding Aegir

text:
# Question
Title: Help Understanding Aegir
So I've been struggling with installing Aegir for about a week now, and trying to understand how it should work, and hopefully get it resolved. (BTW, here is a related issue if you're curious: http://drupal.org/node/1202568 )

First, lay of the land:

* RedHat 5.5
* MySQL 5.5.13
* Apache 2.x
* PHP: 5.3.2

I am installing using this command

```
drush hostmaster-install --aegir_host=hostname --aegir_db_user=myadmin --aegir_db_pass=adminpasswd --aegir_root=/pathto/aegir

```

So my guesses of what needs to happen to get Aegir up and running:

* Upon a successful install, there should be a sites/hostname directory where Aegir lives
* This directory should contain a settings.php files
* This settings.php file grabs the database credentials that are set in a file inside the vhost.d directory using SetEvn, right? The vhost.d directory is empty. But an entry is needed to get Aegir up and running, right?

Does this make sense? What am I missing?

KM

# Answer
> 2 votes
(2nd Attempt!) It almost looks like the symbolic link they have you create in step 3.1.1, is not working correctly and may be causing this issue.

I don't know anything about the differences between Debian and RH 5.5, but maybe RE doesn't have a /etc/apache2/conf.d directory, in which case you would have to manually add an include line into httpd.conf

Cheers.

---
Tags: multi-sites, aegir
---


# Question
Title: How to customize the input phase of a custom field
i'v created a custom field using this tutorial (http://www.slideshare.net/zugec/fields-in-core-how-to-create-a-custom-field). everything went ok and i successfully created a custom field which consists of three different text-inputs.

Now i'd like to customize the way the user inputs this field and can add another field: instead of the standard drupal visualization, i'd like to implement something like when you add your language proficency in the euroCV.eu, where each 'field' is a row and the custom inputs are cell, and when you add another field, you add another row.

i think i have to modify this hook

```
function instruction_field_widget_form(&$form, &$form_state, $field, $instance, $langcode, $items, $delta, $element) {
  $base = $element;
  if ($instance['widget']['type'] == 'instruction_instruction_form') {
    $widget = $instance['widget'];
    $settings = $widget['settings'];

    $element['titolo_studio'] = array(
      '#type' => 'textfield',
      '#title' => t('Titolo di studio'),
      '#default_value' => isset($items[$delta]['titolo_studio']) ? $items[$delta]['titolo_studio'] : NULL,
    );
    $element['descrizione'] = array(
      '#type' => 'textfield',
      '#title' => t('Descrizione'),
      '#default_value' => isset($items[$delta]['descrizione']) ? $items[$delta]['descrizione'] : NULL,
    );
    $element['votazione'] = array(
      '#type' => 'textfield',
      '#title' => t('Votazione'),
      '#default_value' => isset($items[$delta]['votazione']) ? $items[$delta]['votazione'] : NULL,

    );

  }
  return $element;
}

```

but i'm not sure. Is there any tutorial on this?

# Answer
If you are building a curriculum vitae type website you might want to see the eRecruiter distribution profile.

What is does is makes separate groups of fields as entities with the Field Collection module. Keep in mind that taxonomy vocabularies are fieldable in D7 so they can be attached to an entity such as a field collection. The made a module called Term Level that gives an option to add superlatives to the taxonomy terms that are just an entity in a field collection that are added to a node as a field.

It's just another way to look at the same problem.
> 1 votes

---
Tags: entities
---


# Question
Title: SWF Tools install/ setup of media players
I'm trying to get any of the mp3 players in the SWF tools to work they all say *(under /admin/settings/swftools/handling)*:

**JW player:** *Missing flash\_media\_player/player-viral.swf*
**1 pixel out:** *Missing 1pixelout/player.swf*
*etc. for the other players...*

I followed the download link and tried putting the downloads under */SwfTools/Shared* -- and in the players direct folder e.x. */sites/all/libraries/mediaplayer4/player.swf*. But, the missing file warning isn't going away which is preventing me from being able to activate any of the mp3 players. I just wanna get these media players working. Anyone come across this situation? Thank you.

# Answer
Figured it out. As you said chellman the version matter greatly. I had to go under: /admin/settings/swftools/flowplayer3 and under plugins I had to change the Player File from the default to flowplayer-3.0.7.swf. Than you have to manually create the directory /sites/all/modules/swftools/shared/"flowplayer3" where you add the plugin. So, there it is!
> 2 votes

# Answer
Assuming you're using Drupal 6, since there's no stable release of swftools for D7 yet. The version of swftools you're using matters greatly here. Here's the documentation. The summary is that swftools 2 used the swftools module folder (which is usually in sites/all/modules), while swftools 3 uses sites/all/libraries.
> 1 votes

---
Tags: 7
---


# Question
Title: Migrate site from dev environment to production server - 404 errors
We completed development on our dev environment and I copied the files over from the dev server to the production server through FTP.

Then through back up and migrade module, I made a back up of the SQL database. I created a new database through Plesk with the same name, username and password. I then imported the SQL database into the new server through phpmyadmin. I go to the URL and get the Site Maintenance message (which is correct, I placed the site in maintenance mode before copying the files over) but cannot navigate to any sub pages. Generally I can add /user or /admin to the end of the url and get the login screen. However all I get are 404 errors.

# Answer
> 7 votes
It sounds like your .htaccess file is missing, or AllowOverride is disabled. Clean URLs not working? Check your .htaccess file!

# Answer
> 1 votes
There could be an abundance of reasons as to why this is happening. The first thing that strikes me is that a backup created by the backup and migrate module is not compatible with phpmyadmin. Those files can only be restored through the backup module itself. My suggestion is to install Drupal as usual, then enable the Backup and migrate module, then restore through the Drupal UI using your backup and migrate dump.

# Answer
> 1 votes
You need to look at the server log to see what is happening. error\_log should give a clue.

Personally, I think @Dylan Tack's answer is spot on, but another possibility is that when you transferred the site to the production server, the file permissions got whacked.

The easiest way to do fix is via a shell

```
cd /the/drupal/install
find . -type d -exec chmod 755 {} \;
find . -type f -exec chmod 644 {} \;
```

You may also need to tweak your `sites/default/files` for how your Apache is running. Something like

```
cd /the/drupal/install/sites/default
chown -R apache.apache files/
```

Plain FTP is an all-around bad idea. Better ways are

* Use SFTP (eg, WinSCP under windows)
* Use rsync
* Use Subversion
* Use a VPS account so you can have a virtual hosts on the same server for development, staging, and live

---
Tags: migrations
---


# Question
Title: Which hooks should I implement in Drupal 7 that are the equivalent of hook_comment() and hook_nodeapi()?
This is the code I am using for Drupal 6:

```
/**
 * @Implement of hook_nodeapi()
 */
function mycaptcha_nodeapi(&$node, $op, $teaser, $page) {
  global $user;
  switch ($op) {
    case 'insert':
      if (isset($_SESSION['mycaptcha_ask_key'])) {
        unset($_SESSION['mycaptcha_ask_key']);
      }
    break;
    case 'validate':
      if ($node->mycaptcha_ask) {

        mycaptcha_ask_form_validate($node->mycaptcha_ask);
      }
    break;
  }
}

/**
 * @Implement of hook_comment()
 */
function mycaptcha_comment(&$comment, $op) {
  global $user;
  switch ($op) {
    case 'insert':
      if (isset($_SESSION['mycaptcha_ask_key'])) {
        unset($_SESSION['mycaptcha_ask_key']);
      }
    break;
    case 'validate':
      if ($comment['mycaptcha_ask']) {
        mycaptcha_ask_form_validate($comment['mycaptcha_ask']);
      }
    break;
  }
}

```

What are the equivalent hooks that I should implement for Drupal 7, to obtain code equivalent to the one I am actually using for Drupal 6?

**from kiamlaluno's help. i changed the code to the following. but the validation still doesn't work. but the above code(hook\_comment) works ok under drupal 6.**

what's wrong with my code in drupal 7.

```
function mycaptcha_comment_insert($comment) {
  global $user;
      if (isset($_SESSION['mycaptcha_ask_key'])) {
        unset($_SESSION['mycaptcha_ask_key']);
      }
   }

function mycaptcha_form_comment_form_alter(&$form, &$form_state, $form_id) {
    global $user;
  $form['#validate'][] = 'mycaptcha_comment_validate';
}

function mycaptcha_comment_validate($form, &$form_state) {
    global $user;
      if ($comment['mycaptcha_ask']) {
        mycaptcha_ask_form_validate($comment['mycaptcha_ask']);
      }

  }

```

# Answer
I will reply to your question basing on the value for `$op` shown in your code snippet.

### `hook_nodeapi()`, "insert"

The equivalent for Drupal 7 is hook\_node\_insert(), which receives just one parameter: `$node`.

### `hook_nodeapi()`, "validate"

The equivalent for Drupal 7 is hook\_node\_validate(), which receives three parameters: `$node`, `$form`, `&$form_state`.
The implementations of `hook_node_validate()` don't usually use the last parameter, but they check the values of the properties for the `$node` object.

### `hook_comment()`, "insert"

The equivalent of that hook, in Drupal 7, is hook\_comment\_insert(), which receives the comment object as unique parameter.

### `hook_comment()`, "validate"

Unfortunately, in Drupal 7 there isn't `hook_comment_validate()`; you need to add a validation handler for the comment form.

```
function mymodule_form_comment_form_alter(&$form, &$form_state, $form_id) {
  $form['#validate'][] = 'mymodule_comment_validate';
}

function mymodule_comment_validate($form, &$form_state) {
  /**
   * Validate the comment.
   * $form_state['values']['name'] is the name of the user who wrote the comment;
   * $form_state['values']['is_anonymous'] is TRUE if the user is anonymous (not logged in);
   * $form_state['values']['mail'] is the email address of who wrote the comment;
   * $form_state['values']['homepage'] is the URL of the website of who wrote the comment;
   * $form_state['values']['subject'] is the title of the comment;
   * $form_state['values']['comment'] is the text of the comment;
   * $form_state['values']['language'] is the language associated with the comment;
   * $form_state['values']['uid'] is the user ID of who wrote the comment.
   * $form_state['comment'] is the comment object.
   */
}

```

Notice that `mymodule_comment_validate()` doesn't get any `$comment` parameter, and `$form_state['comment']` is an object, not an array. You are using a `$comment` variable that is not defined, nor is one of the parameters.

The code I wrote works independently from the content type of the node where the comment appears. In Drupal 7, the hooks called to alter a form build from another module are `hook_form_alter()`, `hook_form_BASE_FORM_ID_alter()`, `hook_form_FORM_ID_alter()`. The base form ID for the comment form is "comment\_form."
If you just need to alter the comment form for a specific content type (e.g. the "Article" content type), then you replace `mymodule_form_comment_form_alter()` with `mymodule_form_comment_node_article_form_alter()`.
> 6 votes

# Answer
See the documentation for Converting 6.x modules to 7.x.

Specifically, `hook_node_insert()`, `hook_node_validate()`, `hook_comment_insert()`, and `comment_form_validate()` (see `commment_validate()` removed).
> 2 votes

---
Tags: 7, hooks
---


# Question
Title: Why is this code using the global $user variable?
This is the code used by someone:

```
/**
 * @Implement of hook_comment()
 */
function mycaptcha_comment(&$comment, $op) {
  global $user;
  switch ($op) {
    case 'insert':
      if (isset($_SESSION['mycaptcha_ask_key'])) {
        // unset the information
        unset($_SESSION['mycaptcha_ask_key']);
      }
    break;
    case 'validate':
      if ($comment['mycaptcha_ask']) {
        // validate the information
        mycaptcha_ask_form_validate($comment['mycaptcha_ask']);
      }
    break;
  }
}

```

On the above code, why is he using `global $user;`? I see he doesn't use `$user` in his code.

# Answer
The code is not really using the global `$user` variable. Probably, the code was first using it, and that line has been left; it could also be the code using it was moved in `mycaptcha_ask_form_validate()`.

As that line is just a variable declaration, there is no problem in leaving it, even if I generally remove it.
> 3 votes

---
Tags: 6
---


title: Views exposed filter block shows twice

text:
# Question
Title: Views exposed filter block shows twice
I have a view with two page displays both of which share (defaults) an exposed filter block. I've set the exposed filters to show as a block on both displays. I think used the standard block UI to display the proper filter block on the proper URL for each page display.

However, now just the **correct** filter block shows twice on each of these two pages.

*Cache extremely cleared.*

# Answer
> 0 votes
The problem (in Context 3.0) is that the page was built via Context Layouts (which makes use of an alternate page.tpl.php template within that context) was conflicting with blocks placed via the core block UI.

Looks like currently if you're going to have a page build via Context Layout, you need to use content to place any blocks within the pages effected by that Layout.

I'm sure this will get fixed. Issue queue note: http://drupal.org/node/1204826

# Answer
> 0 votes
Try to switch to Garland theme to see if the problem still occurs, if not, it maybe a theme problem.

---
Tags: blocks, views
---


title: Display a view in an overlay?

text:
# Question
Title: Display a view in an overlay?
I want to create a view of display type page with a path of '/%/bookmarks'. Whenever this view is linked on a page clicking on the link will open the view in an overlay instead of a new page. How can I do this?

# Answer
The best solution I can think of for Drupal 6, would be to add some custom JavaScript to that page that scans all the links and attach a click handler on the links that matches the desired URL. Something like this:

```
$("a").each(function(){
  if (this.match('/bookmarks$/')) {
    $(this).click(function(){
      $.get(this.href, function(result) {
        $(result).find('#some .element').dialog();
      });
      return false;
    });
  }
});

```

The above code is written from memory, so is untested and probably flawed, but is can give you an idea of how to do it. The code requires jQuery UI dialog plugin to be loaded.
> 3 votes

---
Tags: views, 6, modal-dialogs
---


title: An unrecoverable error occurred

text:
# Question
Title: An unrecoverable error occurred
My site has run fine for some time; recently, when I upload an image, it always shows the following error message.

The first time I upload the image is OK, but when I create the second article, and upload an image, it shows the above error; the upload button disappears. Does anyone know how to correct it, and what's the reason of this error?

If I disable the site cache, the error disappears, and uploading the image is fine.

What's wrong with my site? What should I do to fix it?

# Answer
The error is most likely that you in your browser have cached the form. So when you go to the form page, instead of getting a fresh form, the browser shows you the cached page.

Since each form has a unique id and can only be submitted once (security reason), you get that error instead. I've seen similar things happen with IE/varnish when varnish was incorrectly setup.

To test, try clearing your browser's cache where this happens and try to load the page again.
> 2 votes

---
Tags: 6
---


title: Custom OG Node Type

text:
# Question
Title: Custom OG Node Type
I am creating a module that creates a node type. How do I declare the node type as an OG group node and other OG settings on the module install?

# Answer
Just use the following code:

```
variable_set('og_content_type_usage_'. $type, 'group');

```
> 1 votes

# Answer
Just edit the content type and in 'Organic groups' section mark it as 'Group node'.
> 0 votes

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