# Question
Title: Newly (programmatically created) blocked user gets access denied when resetting
I'm trying to import some users into Drupal programmatically as **blocked**. I found two methods to do this: user\_save and drupal\_execute. However, the first one doesn't send notification email with the link to reset the password while the other method does send the mail, but when clicking the link I get a **denied access.**

I tried the code in 2 environments (Ubuntu and Windows) with one fresh installation. Here is the code I'm actually using:

```
// register a new user
$form_state['values']['name'] = 'username';
$form_state['values']['mail'] = 'mail@example.com';

// generate and assign password
$pass = user_password(8);
$form_state['values']['pass'] = array (
    'pass1' => $pass,
    'pass2' => $pass
);
$form_state['values']['status'] = 0; // add user as blocked
$form_state['values']['notify'] = 1; // send notification with reset link
$form_state['values']['op'] = t('Create new account');

// check if user it's not already imported
$sql = "SELECT uid FROM {users} WHERE name = '%s'";
$result = db_query($sql, $form_state['values']['name'] );
$data = db_result($result);
#print_r($data);
if (!$data) {  // if the user does not exist, add it
    drupal_execute('user_register', $form_state);
}

```

The user is added correctly in the database as blocked, I receive the notification email but when I click on the reset link I get **access denied** (which, by the way, it's appearing twice: all the elements of my theme twice with the error as content; really nasty bug... don't know why, anyone?)

Here goes the second code:

```
// user details
$users = array(
    'name' => 'username',
    'pass' => user_password(8),
    'mail' => 'mail@example.com',
    'access' => '0',
    'status' => 0,
    'notify' => 1,
    'timezone' => 7200,
    'init' => 'mail@example.com'
);

$sql = "SELECT uid FROM {users} WHERE name = '%s'";
$result = db_query( $sql, $users['name'] );
$data = db_result( $result );
#print_r($data);
if (!$data)
    user_save( NULL, $users, NULL );
}

```

With this method, everything works fine but I don't get the email, which is pointless because the users are blocked.

I don't know if this is a hard question (only for Drupal gurus), but I would appreciate any help.

Thank you!

# Answer
I'm assuming that you are wanting users to click on a link in the registration email to validate the address (this is configurable in your user settings)

You should set status=1 in the user as this is the default behavior and if it is 0 the login link will not work.

If you look at user\_register\_submit() there is code in it to send out emails.

I think you want

```
$account =  user_save( NULL, $users, NULL );
if($account) {
  _user_mail_notify('register_admin_created', $account);
}
else {
// Error code
}

```

at the end of your second method.
> 2 votes

# Answer
Here's the final code:

```
// setup the details
$password = user_password(8);

$user = array(
    'name' => 'username',
    'pass' => $password, // field to save in the database
    'password' => $password, // required to send in notification mail
    'mail' => 'mail@example.com',
    'access' => '0',
    'status' => 1,
    'timezone' => 0,
    'init' => 'mail@example.com'
);

$sql = "SELECT uid FROM {users} WHERE name = '%s'";
$result = db_query( $sql, $user['name'] );
$data = db_result( $result );
#print_r($data);
if (!$data) {  // if the user does not exist
    $account = user_save( NULL, $user, NULL );

    // send notification
    if ($account) {
        // add profile fields
        $profile = array('profile_field' => 'Value');
        profile_save_profile($profile, $account, 'Profile Category');

        _user_mail_notify('register_admin_created', $account);
    }
}

```
> 1 votes

# Answer
Only users who have the permission of administer users can access pages that are associated with blocked accounts.

If you want to allow to the user who gets the email to access the page the link takes to, you would need to give permission to administer users to the anonymous user, as before to log in, the user who follows the link is an anonymous user. As this is highly not recommended, if you want that who gets the link is able to access the linked page, then you have to create the user account in the enabled status.

After all, as the user password has been set from the code, nobody knows the password (if you don't set a too easy one); it is perfectly useless to create a blocked account, considering that the user who needs to use it would not be able to use it, when it's blocked.
> 0 votes

---
Tags: 7, users
---


title: Add a block to a region

text:
# Question
Title: Add a block to a region
How can I add a block to a region using Drush?

I'm using Drupal 7.0 and Drush 4.3.

# Answer
The Drush extras project has commands for administering blocks.

Short instructions (following their README.txt):

1. Install this Drush add-on:

```
drush dl drush_extras

```
2. Determine desired module name and delta of block, and the desired region name and weight for adding the block:

```
drush block-show

```
3. Add the block to the region:

```
drush block-configure --module=block_module --delta=block_delta \
  --region=region_name --weight=-12

```

More instructions via:

```
drush help block-show
drush help block-configure
drush help block-disable

```
> 13 votes

# Answer
I think you maybe asking the wrong question here. I think your question might be - "how do I automate deployments to include blocks being placed in regions"?

In this case you have a few options, I would recommend:

* Use panels and the page manager (currently on alpha 3)
* Add blocks to a page layout and get this exactly how you what it. Views etc can also be added to the layout
* Export the pages to features (current just hit beta 2 for drupal 7)
* The feature can optionally have dependencies on other modules that may provide blocks for you module
* On deploy, revert the feature to enable the dependent modules and place the blocks in the right spot on the panel layout

I prefer this approach as it keeps your entire site layout in code, thus making it able to be stored in version control, and of course deployable to your production web servers with little hassle. Roll back is also made easy.
> -1 votes

---
Tags: 7, drush
---


# Question
Title: Set dropdown list programmatically in exposed view filters
I have programmatically set a text CCK to a `select` and given a few choices:

```
function mymodule_form_alter(&$form, $form_state, $form_id) {
  if ($form_id == 'views_exposed_form' && $form_state['view']->name == 'myview') {
    // Add our custom All buttons.
    $form['field_1hour_currency']['#type'] = 'select';
    $form['field_1hour_currency']['#options'] = array(
      '' => t('<Any>'),
      'USD' => 'USD',
      'EUR' => 'Euro'
    );
  }
}

```

But this display defaults to a Multiple Choice box, and I want it to be a dropdown list. **How can I set programmatically a `select` to *force single* so it displays a dropdown list?**

Thank you

# Answer
> 0 votes
Add the following to your form\_alter implementation:

```
$form['field_1hour_currency']['#multiple'] = FALSE;
$form['field_1hour_currency']['#size'] = 0;

```

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


# Question
Title: Best way to update/upgrade things in the drupal database
I know this is a broad topic, but maybe there is a good way/module doing this. I want to make "automated" updates to a drupal installation. This includes updates of nearly everthing (contenttypes, user-permissions, content itself, views, module-settings).

I would love to have the "update-information" outside the db (e.g. php-code). I could imagine doing that via an own update\_module that implements `MYUPDATEMODULE_update_xxx()` functions for every update. But I fear coding complicated updates (views, large contentypes) "by hand".

I've never used the Features module and don't know if this really fits my needs. Are there any other modules or workflows for something like that? Perfect would be something that lets me trigger the update via the console (e.g. using drush).

# Answer
> 4 votes
Features seems to be what the community is clustering around, and is well worth a look. You can use update hooks, but it can be complicated for large updates, as you fear. It also dosn't make it easy to reset values to a default.

Features seems to be much simpler to use. It can't do everything but most core content can be exposed and managed via features.

Features also has drush hooks.

```
drush features-revert myfeature

```

Will set the system to reflect the content of myfeature. The down side of features is that it is still fairly immature, or more to the point many of the add on modules are immature, so sometimes code is a little buggy.

---
Tags: 7, updating
---


# Question
Title: 301 redirect one site in multi-site installation
I have a drupal 6 installation that is hosting numerous sites. They're all located in the sites/ folder. Like: sites/site-1 sites/site-2, etc.

One of these sites has been discontinued, and we need to redirect from it to a new domain name.

Placing a .htaccess file in the sites/site-1 folder does not work.

How can I redirect ONLY THIS ONE SITE out of a multisite installation to a new domain name?

# Answer
In the root .htaccess file is a set of rewrite rules. You can add a rule to that to redirect to the new site.

```
RewriteCond %{HTTP_HOST} ^www\.olddomain\.com
RewriteRule ^(.*)$ http://www.newdomain.com/$1 [R=301,L]

```

untested, but should be about right.
> 2 votes

# Answer
I am guessing that you have a *"mysite-1.com"* folder in the /etc/apache2/sites-available directory. Basically, this is not exactly a drupal question, since the redirections can (and should -if you ask me-) be handled by the server.

Assuming that you have a specific dedicated for the site that you want to redirect, you should change it to something like this:

```
<VirtualHost *:80>
ServerAlias example.com
redirect permanent / http://www.sometothersite.com/
</VirtualHost>

```

The change should be made to the conf file where the VirtualHost directive resides (the one that is used to describe the site that you want to discontinue). Most commonly the specific directive can be found in the apache2.conf, the httpd.conf or the .htaccess file in the root of your drupal installation.

Notice, that the sample above is not the only way to do it: you can use mod\_rewrite too, but keep in mind that you should do it inside the VirtualHost directive.
> 1 votes

---
Tags: 6, redirection, multi-sites
---


# Question
Title: Joining Taxonomies in an Ubercart Views into a single Field Group (D6)
I have a view for a taxonomy term filtered by the argument.

A particular product has more than one taxonomy term related to the individual node.

This works for only all nodes that have just one taxonomy term. Unfortunately i have a product that has more than one taxonomy term.

Thus on the page with that particular product I have them grouped by fields. When i do this they're displayed as two different fields. All the products with a singular term and another taxonomy term with two terms.

Is there a way for me to group the node into one field ?

# Answer
> 0 votes
The solution was adding "Term" as a field.

Then grouping terms by the field "Term" and not "All Taxonomy Terms"

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


# Question
Title: Manual Ubercart Views Taxonomy Order (D6)
Client wants the parent taxonomy view page to be ordered in a manual arrangement just based on his belief of which products are most popular (this isn't a field in the database; nor do we have this information in the database).

Is there anyway to order the view page based on a weight?

# Answer
Ended up using taxonomy manager: http://drupal.org/project/taxonomy\_manager

Allows you to setup weights for Taxonomy Terms easily and quickly.

I then had to adjust the view to sort terms by Taxonomy weights in order to order the terms accordingly in my views.
> 1 votes

# Answer
You could use draggable views. Create a view of the taxonomy terms you're interested in sorted by the draggable field, and the clients can reorder on a display which also shows that field (they also need the permission IIRC).
> 0 votes

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


# Question
Title: How To Set Node Path/Alias Programatically
I am creating some nodes in Drupal 6 programatically by creating an empty object, setting some properties and calling node\_save() on the object.

When I print out the object again, I see new properties, since node\_save() alters the node object by reference, but I don't see a path property, but from Drupal I can always view the node at 'node/NID'.

Is 'node/NID' the path?

Should I not set a 'user friendly' path property on the node itself, and just use path\_set\_alias() after node\_save instead of mucking with the path property on the node itself?

# Answer
`node/[nid]` is indeed the path to any node. That is how it is defined in the node module, you can see for yourself in the `node_menu` function.

With pathauto module, you can set up rules for automatic aliases so you don't have to figure out yourself what the alias of the node should be. This is the preferred way of creating and automatic "user friendly" or "SEO optimized" URLs, instead of hardcoding the logic in your custom module.
> 4 votes

# Answer
The canonical URL for a node is http://example.com/node/`<nid>`; if you want to set a path alias, you need to set it with `path_set_alias('node/' . $node->nid, $alias)`.
> 5 votes

---
Tags: 6, nodes
---


title: Custom view filter

text:
# Question
Title: Custom view filter
I need to add a custom (exposed?) filter to a view - it would query a large 'postcodes' table to find out coordidnates of postcodes accross the UK, and then perform a comparison of 2 postcodes (belonging to users) to find out the distance, and filter out users that are over a certain distance.

I've got the scripts to do this already, its just I'm really new to Drupal so the whole blocks/views/nodes/content types/filters thing is still confusing me a little.

Perhaps what I'm asking is beyond the scope of a filter.

# Answer
Another option is the Location module, which integrates with Views and lets you do proximity searches. While not exactly what you want, this handbook page should help you get started.
> 4 votes

# Answer
From what I understand that may be possible with the Views PHP Filter Module. There you can create a list of nid's that you want to intersect or remove from the views result. Take a look at the example here.
> 1 votes

---
Tags: views
---


title: Hierarchical select breaks custom js

text:
# Question
Title: Hierarchical select breaks custom js
I am building a case tracker on top of Open Atrium. My case node has some custom fields, and the "Case" category is a hierarchical select taxonomy field. I have another field called level which is dynamic and expected to change when the value of hierarchical select field input changes with custom JavaScript.
It works fine, but when the hierarchical select makes an AJAX update of the node form, the custom Javascript code stops working. I checked the Firefox JS error console, and Drupal recent log, but I could not find any error. For some reasons the hierarchical select doesn't work well with my custom JavaScript code.

Do you have any suggestion on how to fix this problem?

# Answer
> 1 votes
Are you using the live() function in jQuery to bind your behaviors? Drupal behaviors are triggered on page load and after every ajax request. If your behavior only needs to be called once then you can use the add class processed trick. It is explained here.

---
Tags: javascript
---


title: hook_help() argument

text:
# Question
Title: hook_help() argument
I don't see the second parameter `$arg` being use in the function.

```
function hook_help($path, $arg) {
  // ....
}

```

Why should I declare it? What is its use?

# Answer
> 1 votes
Take a look at the api. It states:

> $arg An array that corresponds to the return value of the arg() function, for modules that want to provide help that is specific to certain values of wildcards in $path. For example, you could provide help for the path 'user/1' by looking for the path 'user/%' and $arg == '1'. This given array should always be used rather than directly invoking arg(), because your hook implementation may be called for other purposes besides building the current page's help. Note that depending on which module is invoking hook\_help, $arg may contain only empty strings. Regardless, $arg\[0\] to $arg\[11\] will always be set.

Example:

```
function hook_help($path, $arg) {
    if($path == 'user/%'){
        if($arg[1] < 10) {
            return 'one of the early users';
        }
        else {
            return 'foo';
        }
    }
}

```

Doing this without the `$args` would be ugly.

# Answer
> 1 votes
> Why should I declare it? What is its use?

@nonsenz already answered about the use of that argument. I will reply to the first question.

You should declared it if you need it. Hook implementations don't need to declare the same arguments declared in the hook definition.

I could define the function using the following code, and it would work the same.

```
function mymodule_help($secret_key) {
}

```

Using the same parameter names you see in the hook definition helps who reads your code, and avoids to document the parameters used by the function, as they match the parameters described in the hook definition.
Parameters that are not necessary can be omitted. I normally add them, in the case I rewrite the hook code, and I need them; if I write the parameters I find in the hook documentation, I don't need to change them later.

---
Tags: 7, hooks
---


# Question
Title: How do I give the permission to add points, but not to moderate them?
When I give users the permission to administer user points, they can both add and moderate points. How do I give them only the permissions to add points, but give other users the permission to moderate points?

Can someone tell me how to use the `hook_menu` stuff, to set permissions? My email is lucas.famelli@gmail.com

# Answer
In Drupal 6, there is no easy way to do that. It might work if you implement `hook_menu_alter()` in a custom module and add a different permission in access arguments that the default.

It might not help you at this point, but I have taken over that module for Drupal 7 and we have improved it *a lot*. Among many other things, it now has separate add/edit and moderate permissions which allow for fine-grained access control. So if you are just starting your site, you might want to consider using Drupal 7 instead.
> 1 votes

---
Tags: 6, users, userpoints
---


# Question
Title: Which backup system is good for my local project?
I'm using ubuntu, and I accidentally deleted my project last weak. I tried to recover it but no luck.

Which is the best way to backup my project automatically including my Database (my database is Mysql)? What do you recommend?

# Answer
First of all, let me just state the obvious: the solution that I'm about to propose is not going to bring your files back; it is a measure that you'll have to take from now on in order to prevent similar disasters in the future.

Basically, since you are working in your local machine (if you were working in the cloud you could automate a snapshot-taking process) you will have to keep a backup of 2 different things: the files and the database. Assuming that you are following the "drupal best practices code" and you are keeping every new file in the sites folder of your drupal installation, all you have to do is keep a regular backup of this folder and the database. So:

**1) Regarding the "sites" folder**: you can create a simple cron job that will compress and archive the folder regularly (even though it is out of the scope of this answer, you can find more information on crontab here)

**2) Regarding the database**: the solution here is actually pretty simple: "Backup and Migrate" module. It gives you the option to schedule your database backup and save the file through FTP in a remote server, send it through email or save it in your local machine. It's basically more than you'll ever need for this purpose.

P.S: I'm pretty sure that you will get some answers that you should be running a version control system to avoid things like that in the future. It's true that a version control system would be the ideal way to make sure that your files will not be lost in the future (the database is another story). However, the solution that I mentioned above is considerably faster and can get you up and running in no time. If you have time though, I would strongly suggest that you take a look at SVN or GIT (or any subversion control system that you like for that matter).

P.P.S: If the data that you lost is important, you can do a google search for data recovery software. A very quick search that I did gave me this.
> 4 votes

# Answer
Another option is to use "rsync" in Ubuntu, you can set it to perform regular cron jobs. I use this with the "luckybackup" graphical front-end and it is fast. Both are available from the ubuntu repositories and are quite easy to set up. I find it very effective, and I suppose its one of the many options available, but I find it very fast at backing up remote VPS installations, including the MSQL databases folder found on Ubuntu at /var/lib/mysql.
> 3 votes

# Answer
You should use a source control system for your code, github offers free hosting for public projects, or you can create a sandbox project on drupal.org.

Your database is a little more tricky, use mysqldump to export the database, and back it up via something like drop box. You can put the database into source control as well if you like, but it isn't ideally suited to that.
> 2 votes

# Answer
Take a look at the drush commands. drush helps you dumping your database with extra features (e.g. gzipping, import/export via rsync, filtering tables and more...). Take a look at the following commands:

It also makes syncing the filesystem easy. For this check out the core-rsync command. In combination these features can be very handy. Make sure to check out the other drush commands as well.
> 2 votes

---
Tags: 7, backups
---


# Question
Title: How do I replace the SQL query of a view?
I need to override an SQL query of a view. I'm using Drupal 7 and Views 3.x-7.x-alpha1.

I understood I can write my own query with views\_pre\_execute. I followed the instructions mentioned here: http://blog.raisedeyebrow.com/2010/04/rewrite-a-views-query/.

I added this piece of code to my custom module.

```
function alterquery_views_pre_execute(&$view) {
  dsm($view);
}

```

Following the instructions, when I look for the value of `$view->build_info['query']`, I see that the type is object of a class SelectQuery.

How am I able to get total control of the query and use my own select statement?
I know that with `hook_views_query_alter()` I can modify a keyed array, but I would rather write the select statement from scratch.

# Answer
> 4 votes
Well, nothing is stoping you from building your own SelectQuery object and replacing the existing one. Overriding the query plugin is also an option. In this case it would be best to know WHY you're trying to replace the whole query. It makes very little sense to me.

Also, you're using alpha1? Why? That code is four and a half months old. Before attempting anything else, please update to -dev.

# Answer
> 3 votes
If you create your own views class you can overide the execute() method to do whatever you like. If you look at the apachesolr\_views or sparql\_views modules you can see how they do just that. The views don't even use SQL.

# Answer
> 1 votes
Any reason you couldn't implement hook\_views\_query\_alter to change the query itself?

http://drupalcontrib.org/api/drupal/contributions--views--docs--views.api.php/function/hook\_views\_query\_alter/7

---
Tags: 7, views
---


# Question
Title: Show a dynamic text depending on the day
I'd like my Drupal website to show at the right top something like:

> **\____** day (eg. **Medicine** day)

and fill `__________` dynamically depending on the current day.

I will create a new content type `DayType` or something like that, with two fields:

* `Title`
* `Date`

My question is:

How can I show in `__________` the title depending on the current day?

I could do that with a *View*, but what I don't know is how to show it on the right-top, and not apparently in a block or just in a new page.

# Answer
> 1 votes
You can use views\_embed\_view() to get the output of a view manually. Supposing your view is called 'days' and you want to display the output of this view:

```
print t('Today is @dayname day.', array('@dayname', views_embed_view('days')));

```

(This assumes the output of your view is just some text, and contains no HTML.)

By 'on the right-top', do you mean the page title? In any case, you could set a variable in your theme's preprocess function (which goes in the theme's template.php), like this:

```
function mytheme_preprocess_page(&$vars) {
  $vars['daystring'] = t('Today is @dayname day.', array('@dayname', views_embed_view('days')));
}

```

Now, in your page.tpl.php, you can write something like this:

```
print $daystring;

```

---
Tags: 7, views
---


# Question
Title: Checking two databases when logging in a user with a custom module
I am trying to create a module that will check for two databases when logging in a user to Drupal. If drupal's native login is a success but the external application does not have that account, then the module will create an account on the external application. If the account is not on drupal but is on the external application then drupal will create a local account. If the user does not exist on either database then the login will fail. Which hook(s) would I need to implement this in a module?

# Answer
> 4 votes
Never tried, but you can basicaly:

* try hook\_user() but you may not catch the case where the user doesn't exists in drupal but your other site.
* create your own login form & callback and:

You may find some interesting code in the openid\_authentication().

---
Tags: 7, users
---


# Question
Title: Programmatically execute an action set (Rules module)
I want to use Rules UI to define some action sets, but want to execute those actions programmatically from a custom module.

How to I execute the action by code and pass the needed arguments (just a node in this case).

Thanks!

# Answer
> 25 votes
If you have set it up as a rules component, you can use `rules_invoke_component`, alternative you can invoke an event, which could trigger mutiple rules by using `rules_invoke_event`.

Both is similar in that you pass first a name/id and the rest of the args is passed along, so something like

```
 rules_invoke_component('name', $node);

```

if your custom component rule has several parameters pass them one by one and separate them with comma as example

```
rules_invoke_component('rules_save_search_send_activation_sms',  'paramval1', 'paramval2', ....);

```

is properly how you need to do it. This again depends on how the rule/component is defined and configured.

---
Tags: rules
---


# Question
Title: Web service with application-level and user-level authentiation
I need to create a Drupal site (D6 or D7 are both OK) with an API. The Services module is the obvious choice, but I couldn't yet figure out if it is possible to do what I want.

My site will contain users and a list of mobile apps that are known to the site. Every user has an 'activity log' on the site (probably a view of nodes where type = activity and user = current user). The users can use one or more of those apps on their mobile devices. When a user does something with an app, the app should connect with the site through the API and write a message (ie. create an 'activity' node) in the user's activity log.

As far as I can see, I will need two levels of authentication. On the application level, the mobile app should identify itself as one of the known apps. On the user level, the user must log in with his username and password, to make sure that his actions will end up in the correct activity log.

I have not yet figured out the best way to do this with Services and related modules. I hope someone can tell me:

* if it can be done;
* which version of Services I need;
* which related modules could be used for authentication;
* how to configure them.

Thanks!

# Answer
Under D6, using Services 3.x

It may be more easy to consider that:

* User authentication should be handled directly by Services (OAuth/API/Session)
* Using an specific mobile app is a Permission:
    + in your module, in the resources definition, add a access\_callback & access arguments:

Code:

```
/**
* Implementation of hook_services_resources().
*/
function mymodule_api_services_resources() {
  return array(
   'myresource' => array(
     'retrieve' => array(
       'callback' => '_mymodule_resource_retrieve',
       'access callback' => '_mymodule_api_access',
       'access arguments' => array('Use registered mobile app'),
       'access arguments append' => TRUE,
       ...

```
* add corresponding permissions in a my\_module\_permission() hook: Code:

```
/**
* Access callback for the resource.
*
* @param string $op
*  The operation that's going to be performed.
* @param array $args
*  The arguments that will be passed to the callback.
* @return bool
*  Whether access is given or not.
*/
function _mymodule_api_access($op, $args) { ... }

```
* And then return false if the mobile app is not registered...
> 6 votes

---
Tags: services
---


# Question
Title: How to display picture from field near every blog entry
When I go into mywebsite/blog I have blog entries displayed. What I want to do, is display a picture uploaded to every blog entry left to the entries displayed on this page. How can I achieve this? Is there some code to display uploaded picture in page--blog.tpl.php? I also would like to NOT display picture when someone actually click and goes to some single blog entry.

# Answer
> 1 votes
You should be able to do this with standard field visibility.

Add an image field to your blog type.

Then click on display fields, you can have it displaying for teaser view, and hidden in the full view.

---
Tags: 7
---


# Question
Title: Using a node editing form on a page that not a node edit page
I have created a menu item, as reported below. I have taken the form ID from the page source (form id=listorious-list-power-100-node-form) but when I go to the specified URL, I get the following error:

> call\_user\_func\_array() expects parameter 1 to be a valid callback, function 'node\_form' not found or invalid function name in drupal\_retrieve\_form() (line 771 of /var/www/drm6/drm001/site/includes/form.inc).

The form is the standard node form found on node/add/listorious-list-power-100.

```
$items['admin/config/listorious/settings/add'] = array(
  'title' => 'add Listorious List item',
  'description' => 'Add list item information.',
  'page callback' => 'drupal_get_form',
  'page arguments' => array('listorious_list_power_100_node_form'),
  'access arguments' => array('administer site configuration'),
  'access callback' => TRUE,
  'type' => MENU_NORMAL_ITEM,
);

```

# Answer
> 6 votes
```
      'file path' => drupal_get_path('module','node'),
      'file' => 'node.pages.inc',

```

needs to be added to the array.

---
Tags: 7, routes
---


title: Insert images with Media

text:
# Question
Title: Insert images with Media
I am using Media and Wysiwyg with CKEditor to insert images in the post editing field, and for some reasons I keep getting this code instead of my images.

Does anyone know how to fix it?

```
[[
  {
   "type" : "media",
    "view_mode" : "media_large",
    "fid" : "412",
    "attributes" : {
      "alt" : "",
      "class" : "media-image",
      "typeof" : "foaf:Image"
    }
  }
]]

[[
  {
    "type" : "media",
    "view_mode" : "media_large",
    "fid" : "395",
    "attributes" : {
      "alt" : "",
      "class" : "media-image",
      "typeof" : "foaf:Image"
    }
  }
]]

```

I fixed it; you have to go into Administration » Configuration » Content authoring » Text formats and check the box Converts Media tags to Markup.

# Answer
I fixed it; you have to go into Administration » Configuration » Content authoring » Text formats and check the box Converts Media tags to Markup.
> 9 votes

---
Tags: 7, nodes, media, wysiwyg
---


# Question
Title: administer MSSQL databases from Drupal 6
Can you advise on a way to manage my SQL Server databases from Drupal 6x. I am using SQL Server for PHP driver (i.e. `sqlsrv_connect()`) to connect to my databases. Is there any module I could use to administer my databases?

If any more information about my query is needed, please let me know.

# Answer
There is no support for MSSQL Server in Drupal 6, so it is higly unlikely that a module that can help you to administer your MSSQL databases exists.

You could maybe write your own, see MSSql or SQL Server Wrapper for custom module? for a possible way to connect to your database while still being able to rely on some API's provided by Drupal.
> 1 votes

# Answer
I am also connecting to sql server from drupal, and here is what I've learned on my blog http://www.barnettech.com/taxonomy/term/28 It describes what to install on the linux box to run queries and stored procs. You need to create custom modules to make calls to sql server from within Drupal. In my case I made my own services to add on to the services module.
> 1 votes

---
Tags: 6, database
---


# Question
Title: Overriding the output for the primary navigation links
Is there another way the primary navigation is supposed to printed out besides how it is done in the core system template?

```
print theme('links__system_main_menu', array('links' => $main_menu));`

```

None of the changes I made via the `theme_menu_link()` function are recognized when the links are printed this way. Are they only seen if I manually put the primary links *block* into a region?

Which is the function that I could use to override the primary links when printed out this way? Everything I have with `theme_menu_link()` does nothing.

# Answer
> 3 votes
That syntax (two underscores) means that it first looks for a `theme_links__system_main_menu()`theme function and then falls back to `theme_links()` if that doesn't exist.

So to override only the main menu, create the following theme function for your theme: `yourtheme_links__system_main_menu()`.

---
Tags: 7, theming
---


# Question
Title: Are CCK shared fields loaded on node_load()?
`field_metatitle` is a CCK field that is used amongst 5 different content types, meaning that it is a "shared field". When I do `$node = node_load('123');`, I see that $node-\>field\_metatitle is not present.

# Answer
> 6 votes
They definitely should be attached to the node object via `content_nodeapi()` and `content_load()`.

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


title: Why no pid in node object?

text:
# Question
Title: Why no pid in node object?
I am setting an alias programatically, using path\_set\_alias() in Drupal6.

Looking at the code of path\_set\_alias in path.module, I see that if I pass the pid (path id), the old alias(s) for that node will get deleted, which is what I want.

When I load the node, though, I see no pid property set on the node, but the record for the node's alias exists in url\_alias table.

Why doesn't pid exist on the node object? Must I retrieve the pid from the url\_alias table and then pass that in to path\_set\_alias to remove the old alias?

# Answer
> 1 votes
It looks like a bug, see http://drupal.org/node/633916

It's optional to path the pid to path\_set\_alias() so it should work without passing it.

# Answer
> 0 votes
As you can see in path\_nodeapi(), path.module only loads the alias and adds it to the node object, not the pid.

In fact, it is doing it wrong anyway (it is supposed to return new data, not add it to $node) since that won't work in PHP 4. Not that anyone on this world should still use that, but Drupal 6 still officially supports it.

Also, there is no `page_node_load()` function in Drupal 7, so this part has been removed completely there, possibily for performance reasons (No need to load the alias if no link for this node is displayed anywhere and since it's not used anyway when a link *is* generated, it is mostly useless).

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


# Question
Title: Can I create surveys with unique URLs for each recipient?
Does anybody know if there's a module that can support unique URLs for survey participants?

To clarify, what I mean is, I'd like to send out letters/ documentation to people in a particular geographic area. I'd like to encourage them to complete a survey, but for each recipient of the letter I'd like to assign a unique URL for their survey, which can then be used by me to marry them up to the data I already hold about them.

So, for example:

Person A receives a letter and is given a survey URL of www.mysite.com/ab123 Person B receives a letter and is given a survey URL of www.mysite.com/eg462 Person C receives a letter and is given a survey URL of www.mysite.com/qt368

and so on.

For a number of reasons, this method is better for my data collection purposes, rather than asking participants to include an assigned ID number or their own details.

# Answer
> 2 votes
You can use the webform API in a tiny module to access the form to add a hidden element to it. Then use the handy Drupal arg() function to determine the value of your unique URL argument. After, use the webform API function to change values before saving to the hidden field for administration usage later.

I can't guarantee this will work so hopefully some of the other Drupal Stack Exchange folks can verify this.

---
Tags: 7
---


# Question
Title: How to make each header in a table clickable and add a chart to it?
I have used the Views module to display an external database (which is working fine), but I want to make each header clickable and add a chart.

Is there a module to do this, or is there a way I can do this?

I found a few charting modules; some are good but they require me to create each chart manually, using the style and the data gets feed to it dynamically. The problem is that my tables have many headers; I flip the rows and columns but there are over 100 headers in it.

# Answer
> 3 votes
There's no drag-and-drop solution. You would either have to create a custom module yourself that would do what you want, modify a module that gets close to what you want or use one of the solutions out there that makes you enter things in manually.

---
Tags: 7, views, charts
---


# Question
Title: How do I use CCK fields with the form API?
Does anyone know how to use OpenLayers CCK fields with the form API? I want to get a coordinate and some other data from users in my custom form.

# Answer
> 1 votes
I believe in this case you want to create a new content type with the appropriate cck fields to collect the location data. This will be much, much easier than trying to recreate the same experience with the forms api, custom tables and some custom module to integrate CCK fields.

---
Tags: 7, entities
---


title: Show empty fields

text:
# Question
Title: Show empty fields
I've created a custom node (node--CONTENT\_TYPE.tpl.php) where I print the fields my way. For example,

```
<div class="test">
   <?PHP echo $content['field_tipsol']['#title'].":".$content['field_tipsol']['#items'][0]['value'] ?>
</div>

```

My problem is I can't see titles for the empty fields. How could I retrieve this information? It doesn't appear in $content array :(

# Answer
Try doing a var\_dump of $content and see what shows up. Var\_dump specifies what it's being returned even if it's boolean, empty, null, etc.
> 1 votes

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


title: Know a term to get the parent in Views

text:
# Question
Title: Know a term to get the parent in Views
Is there a way to use a taxonomy term name to get all the parent terms in Views?

If the taxonomy terms are the following, is there a way to get "one" and "two," given "three"?

* one
    + two
    + - three

# Answer
taxonomy\_get\_parents\_all will do what you're looking for, but I don't believe it's possible in views. http://api.drupal.org/api/drupal/modules--taxonomy--taxonomy.module/function/taxonomy\_get\_parents\_all/6

That being said, there's a module that might help you with that. It's called Taxonomy Views Integrator http://drupal.org/project/tvi
> 2 votes

---
Tags: 7, views
---


# Question
Title: Convert a node from one content type to another, using a rule set
I want to convert a node from one content type ("Project") to another one ("Project follow up"), basing on the comparison between the current date (using PHP) and the value of a field date ("Project signup date," which is a CCK date field). Currently, I am using a rule set that will be scheduled based on a check that a rule does when the project is created. The rule set than checks (upon a successful cron run) if the date is higher than the field date (using the date timestamp); the rule set will then convert the node from "Project" to "Project followup."

As I keep getting errors when testing the rule/rule set, I must ask if I'm doing it right. What are the proper PHP evaluation and token replacement pattern? The following are the replacement tokens, and my default PHP code.

### Replacement tokens

```
[node:field_pdate-value]     The raw date value.
[node:field_pdate-view]      The formatted date.
[node:field_pdate-timestamp] The raw date timestamp.
[node:field_pdate-yyyy]      Date year (four digit)
[node:field_pdate-yy]        Date year (two digit)
[node:field_pdate-month]     Date month (full word)
[node:field_pdate-mon]       Date month (abbreviated)
[node:field_pdate-mm]        Date month (two digit, zero padded)
[node:field_pdate-m]         Date month (one or two digit)
[node:field_pdate-ww]        Date week (two digit)
[node:field_pdate-date]      Date date (YYYY-MM-DD)
[node:field_pdate-datetime]  Date datetime (YYYY-MM-DDTHH:MM:SS)
[node:field_pdate-day]       Date day (full word)
[node:field_pdate-ddd]       Date day (abbreviation)
[node:field_pdate-dd]        Date day (two digit, zero-padded)
[node:field_pdate-d]         Date day (one or two digit)
[node:field_pdate-dS]        Date day (one or two digit) with ordinal suffix (st, nd, rd or th)
[node:field_pdate-time]      Time H:i

```

### PHP code

```
php echo time();

```

# Answer
> 2 votes
Node Convert might help you with the node conversion from one type to another. http://drupal.org/project/node\_convert

I'm not sure if you can use this module to do it programmatically, but it might help to look at this structure and run something similar on a cron job.

---
Tags: 7, rules, tokens
---


# Question
Title: For an event node type, should I use Datetime or Datestamp?
I'm about to create a node type event and have to choose between three different date formats, Date, Datestamp and Datetime. I've read how they are stored differently in the database, but that doesn't explain to me which is best for an event node type. Well, not exactly, from what I understand the Date format doesn't store time so that can't be used. I'll be using views to sort events if the make a difference. Which format would you use and why?

# Answer
> 2 votes
Especially in Drupal 7, you should use the Date field. Datestamp is almost useless, and there is no real need for Datetime.

# Answer
> 1 votes
http://drupal.org/node/262066 has the answer. It discusses the differences between the different formats and which is best to use in which case. Scroll down to "Date Fields."

---
Tags: 7, datetime
---


# Question
Title: Run update.php after updating several modules?
In Drupal, if several modules need updating, is it OK to copy all the files across and run update.php once, or do I need to copy each module individually and run the update each time?

# Answer
From drupal.org: "The update script should only be run once. It will complete all the updates at once. If prompted for which version, choose the closest starting version that makes sense for you."

Reference: http://drupal.org/upgrade/running-update-php
> 3 votes

# Answer
You can copy all the files at once and run update.php just once.
> 4 votes

# Answer
In general, you should be able to perform all of your updates at once. That said, if you have modules that have interdependencies and which don't take programmatic steps to ensure their dependencies are installed and up-to-date in your system, you could ostensibly experience an error in the update process by running them all at once.

So if you have "mainstream" modules, I wouldn't worry about anything; just upgrade all at once. If you have modules with several interdependencies that don't receive as much development attention, it would be a good idea to make sure you upgrade modules in a specific order to satisfy dependencies.
> 3 votes

---
Tags: 7
---


title: Secure Pages module is not redirecting

text:
# Question
Title: Secure Pages module is not redirecting
I installed Secure Pages on a site, where I need to secure admin and user login pages. In general, it does its job, but when the user first tries to log in, and goes to the /user page, that page is not redirected to the secure page. The form action attribute is rewritten to the corresponding https link though.

Do you have any ideas why this could be happening?

In Secure Pages config, I use 'Make secure only the listed pages' option, and tried 'user', 'user\*', and 'user/\*'. Base urls are blank, but I tried filling them in. There are entries in 'ignore pages', but I tried removing them.

Another thing I noticed is that it works when the user is logged in. Could be a permission issue, but I did not see any relevant permission.

# Answer
We had a similar issue as well on some of our drupal 6 sites and IE8 not redirecting to HTTPS, our solution was to use a custom URL alter to physically rewrite the URL's on the page to the HTTPS

@see the issue http://drupal.org/node/893840 and here is a link to the patch that we used - http://drupal.org/files/issues/893840-6-securepages.urlalter.patch. The patch adds a dependency on the https://drupal.org/project/url\_alter module

A nice side effect is that a bootstrap is no longer required to do a silly redirect ;)
> 2 votes

# Answer
I just did a fresh Drupal 6 install with the latest Secure Pages module. Only modules enabled are default core + Secure pages. I did not modify permissions in any way.

Using the default Secure Pages settings, including

```
user
user/*

```

in the "Pages:" textarea, navigating to /user while logged out presents me with the user login form on a secure page, and logging in sends me back to the home page (where I started).

How are you redirecting your users to their /user profile upon login? Logintoboggan or some such? Let me know and I'll dig further.
> 2 votes

---
Tags: 7, security
---


# Question
Title: The $directory variable doesn't contain the correct value
When I print the content of `$directory` in my theme's page--front.tpl.php, it outputs "modules/system."

This is not I want; I want to output "sites/all/mytheme/images/…." How can I do it?

# Answer
if you want to find the folder of your theme you have to use something like this:

```
<?php echo drupal_get_path('theme','your_theme').'/images/whateverfile.ext'; ?>

```
> 4 votes

---
Tags: 7, theming
---


# Question
Title: Why is the backup of the site not behaving the same as the original?
I've cloned my site onto a testing server prior to making changes (database and all files), but it's not behaving like the original, and I'm unable to login.

The site was at www.original.com/drupal/ and www.original.com/node/3 works. The test site is at www.test.com (note no /drupal) and www.test.com/node/3 gives me an Apache 404 error page.

Why are the two sites not behaving the same? No Drupal specific content resides above www.original.com/drupal.

# Answer
The problem was caused by .htaccess not being processed due to the "AllowOverride None" directive in my "httpd.conf" file.

Changing to "AllowOverride All" and restarting Apache cured it.
> 3 votes

---
Tags: 7
---


# Question
Title: Using hook_form_alter to set default values for multiple-value CCK fields
I was previously using the Default Value PHP field in the CCK Field Properties page to define multi-value default which was working fine. However the code is now getting so complex and I need to pass arguments to it that developing it within the CMS is becoming unfeasible, so I'd like to move the functionality out to a custom module.

I'm successfully using hook\_form\_alter to set defaults for single value CCK fields, so this isn't a problem. What I'm curious about is that when $form is passed to hook\_form\_alter, only the first element (0 or $form\['field\_myfield'\]\[0\]) exists, whilst I need to have from 0 to x default values.

Is the best practice simply to clone element 0 for as many default values as I need? Or is there another hook I should be using to set the initial number of empty fields before setting the defaults or something else I'm not thinking of?

Thanks :D

# Answer
> 4 votes
I think you may need to use #after\_build, to ensure that your alter code runs after CCK has completely built the form element. Try something like this

```
function mymodule_form_alter(&$form, &$form_state, $form_id) {
  $form['field_myfield']['#after_build'][] = 'mymodule_after_build';
}

function mymodule_after_build(&$form_element, &$form_state) {
  // Have a look at the element with devel's dsm
  dsm($form_element);

  // Code to adjust your form element here...

  return $form_element;
}

```

I'm not 100% on the above syntax. I'd sugest you have a look at this article entitled hook\_form\_alter() and CCK fields

---
Tags: 7, entities
---


# Question
Title: Why does Drupal 7 prefer CSS @import rules to <link> tags?
"Don’t use `@import`," lots of guys say.

There are lots of shortcomings of using `@import`.

* Using `@import` within a stylesheet adds one more roundtrip to the overall download time of the page.
* Using `@import` in IE causes the download order to be altered. This may cause stylesheets to take longer to download, which hinders progress rendering making the page feel slower.

Why does Drupal 7 use it?

I want to change the `@import` rules to `<link>` tags. How can I do this?

# Answer
> 21 votes
Don't use @import to import css files:

> @import is used only in non-CSS aggregation mode. This is done to workaround IE limitation with the number of tags.

This should explain the reason and how to get rid of it. Any production site should use CSS aggregation, and not have @import.

---
Tags: 7, theming
---


title: Views pagers for anonymous users

text:
# Question
Title: Views pagers for anonymous users
I've been trying to figure out why the pager element for views won't show up for anon users in Drupal 7. The following are the things I've tried to get them to show, cache clear, mess with the access param in the actual view, create a function that calls

```
drupal_static_reset('user_access');
drupal_static_reset('user_role_permissions');

```

Has anyone been able to solve this? I've searched Google for over an hour for a fix/explanation.

# Answer
If after running the permission checks drupal doesn't find enough items to fill your view it will not show the pager (for any user role). You should check why there aren't enough items for the view. Did you check for the number of items on a page (in the view). Is the pager set to be on (in the view). There are chances that you forgot to check some of these settings. It happens.
> 1 votes

---
Tags: 7, views
---


title: Secure Login not Working

text:
# Question
Title: Secure Login not Working
I'm running drupal 7 with the secure login module and login toboggan. After installing it, going to http://site.com I see the usual site, with the login button.

The login form `action` has not changed, it remains a POST to `/node?destination=node`. Sure enough, if I login there my password is sent in the clear with a POST to `http://site.com/node?destination=node`

Any ideas on how I might start debugging this? The securelogin.module seems really straightforward, just some hooks. Is there a logging statement I can add there to see if these hooks are being called?

**update** I also noticed this other problem (probably the same cause).

Sometimes when I start a fresh browser and go to http://site.com I get 302's to https://site.com automatically. If I then log in the POST goes over https (good!) but I then get 302'd back to http://site.com, where I appear NOT logged in. If I just change the URL to https://site.com I can see that I am indeed logged in.

I am very confused.

# Answer
Ok, the problem seems to have been that I had `$base_url = 'http://site.com'` set in my settings.php.

This resulted in that, after a successful login on https, the user got 302'd back to an http: page which showed him as not logged in. By commenting out the `base_url` the re-direct now sends the user back to an https and shows him logged in. So, it all seems to work.
> 0 votes

# Answer
To force SSL for login, admin, node editing etc, I use http://drupal.org/project/securepages \- also has has configuration options to force plain HTTP when browsing the site as well (which can save you load).
> 2 votes

---
Tags: 7, security
---


# Question
Title: Drush Make for a custom module hosted at github
I am trying to fetch a custom module versioned at github.com via drush make, but I get

```
Could not retrieve version information for custom_migration
Non-existent project type  on project techarena_migration

```

My drush make file section for the custom module is the following:

```
projects[custom_migration][subdir] = "custom"
projects[custom_migration][type] = "module"
projects[custom_migration][download][type] = "git"
projects[custom_migration][download][url]="git@github.com:qed42/custom_migration.git"

```

I also tried giving the branch parameter, but no change

```
projects[custom_migration][download][branch] = "master"

```

This is a private repository, could it be that?

**Update:** I am so sorry, I was using the wrong makefile. Sorry to have wasted your time. I am not sure if I should close the question?

P.S git:// doesn't work with private repo on github, git@github.com does!!

# Answer
According to the documentation, you have to write the download url line this way:

```
projects[mytheme][download][url] = "git://github.com/jane_doe/mytheme.git"

```
> 6 votes

# Answer
> This is a private repository, could it be that?

Can you do `git clone git@github.com:qed42/custom_migration.git` from the same shell that you are running drush make from?

You may need to add a new public key to be able to access the repo.
> 2 votes

# Answer
In order for drush to be able to checkout the code, it must be available for the terminal running the make file. So if you have an SSH key to the repo, that will work, but you can't checkout if you need to login to perform the checkout.

Also the link should like Drupol describes be formatted like the doc:

```
projects[mytheme][download][url] = "git://github.com/jane_doe/mytheme.git"

```
> 1 votes

---
Tags: version-control, drush
---


# Question
Title: How do I get the name and URL alias of a vocabulary using only  the vid?
I need the URL alias of the vocabulary, not the term and not the machine name; I need the name that appears to the user.

# Answer
> 3 votes
You can use taxonomy\_vocabulary\_load() to obtain the machine name of a specific vid.

Example usage:

```
$vocabulary = taxonomy_vocabulary_load($vid);
$machine_name = $vocabulary->machine_name;
$name = $vocabulary->name;

```

Vocabularies aren't exposed to the user like terms are, so they don't really have an url-alias. The name which is presented in the vocabulary list is `$name` in the above code.

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


# Question
Title: Sort criteria in views: how to add custom one
I have added a "node title" field. I want to add this sort criteria to the node: the number of times the node has been viewed by visitors in a week, descending.
If I want to add a sort criteria with PHP code and a SQL query to insert in Views module, how should I do?

**ps:i have overwritten a field. i want to query the database and using the query to Sort Criteria\**how to add the custom one**

# Answer
> 3 votes
First, make sure you have Drupal's **Statistics** module enabled and collecting page view statistics.

In Drupal 6, you need to enable **Count content views** under `admin/reports/settings`. This will count total node views and give you total day count. Unfortunately, it does not give you a weekly view count by default.

This will give you a sort criteria for `Node statistics: Total views` and `Node statistics: Views today`.

Upon closer inspection of the day count for node views, this value is reset to 0 every 24 hours by `statistics_cron`. This value would prove more useful as a sort criteria if it was the *most recent 24 hour's* node views. So, the `Node statistics: Total views` would be your best bet.

**NOTE:** See Statistics Granularity module for week, month and year.

---
Tags: 7, views
---


title: Display Wordpress posts

text:
# Question
Title: Display Wordpress posts
I currently have both a Drupal and a WordPress site. Is there a module that can display the latest posts from my WordPress site, or will I need to write my own?

# Answer
The Aggregator module that ships with Drupal core can pull in posts from the WordPress site's RSS feed. For more functionality and overall flexibility, you could use the Feeds module.
> 6 votes

# Answer
Yes, there is.

Assuming Wordpress makes your posts available using RSS, the module built-in within Drupal's core may be an answer: Aggregator Drupal module
> 1 votes

---
Tags: 7
---


title: Module to search node titles only

text:
# Question
Title: Module to search node titles only
Is there a module that allows me to restrict searches to node titles, rather than any node content? Preferably the user would choose between titles only or everything.

# Answer
> 2 votes
You could use Views Search and build a views with only the title of nodes as an exposed filter, then this module convert your exposed filter in a search option.

---
Tags: 7, search
---


title: Views calculations

text:
# Question
Title: Views calculations
I'm playing around with views, and I am sure on how to calculate fields based on Views data.

I thought Views Calc would do this, but it seems to only give me sums and averages of the fields. For example, suppose I'm making a financial site, and I want to do a price to earnings ratio; I would take price and divide it by earnings. Is it possible to do this in Drupal?

I know I can do this creating a PHP file for page, but to complicate things more, I ultimately want to give users the ability to do this as well; so, if possible, I want to stick with doing this with Views.

I see the view queries in generating; is there a way to modify the queries myself?

# Answer
> 7 votes
There is two ways to do this:

1. If your column information resides in a node, you can use Computed Fields in your node to create some new CCK fields with all sort of operations inside (you code directly in php there with access to all others fields of the node. If you're adventurous enough you can also make queries and everything you can imagine.
2. There's a similar funcionality directly for Views, it's called Views Custom Field and it's basically a Computed Field for Views.

So to summarize, if you need to have this information appearing in a node then Computed Field, if not just use Views Custom Field.

---
Tags: 7, views
---


# Question
Title: Save FileField file to an external server
When using FileField or ImageField, files are saved to a local folder in the Drupal install. This works great and all, but up till now the media files on my website are served from a discrete server (a CDN), and I'd really like to keep them separate.

Is there a module that extends File/ImageField to allow you to specify an external server (FTP and credentials) to use as a file server?

Any advice or pointers with this is appreciated.

(Ps I've seen the CDN module, but that requires the use of a server daemon or modifying the CDN's origin... and I'm not particularly fond of either implementation.)

\<3

# Answer
As far as I know, there is no other way to do this in Drupal 6 than what CDN does.

In Drupal 7, this is a completely different story, however. Drupal 7 uses stream wrappers when dealing with files and it is a) possible to implement custom stream wrappers with PHP code and b) the stream wrapper can be chosen per file/imagefield.

So if it is possible to access X with PHP (FTP, Flickr, Amazon S3, ..) then it should be possible to write a stream wrapper for it and therefore allowing Drupal to write the files to that place.

This probably doesn't help you in your situation, but maybe it will help someone else, when deciding to use Drupal 6 or 7 for a new project for example :)
> 5 votes

# Answer
It may be too powerfull and quite complex to set up but have you tested Media Mover ?

If you have shell access on your server, you may be interested in File Conveyor, a Python Daemon written by Wim Leers, a well know Drupal contributor. Of course after setting this up you'll have to rewrite your files URL to point to your CDN.
> 2 votes

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


title: Enable Paging on my theme

text:
# Question
Title: Enable Paging on my theme
I want to know how to enable paging on my theme. The theme 'Garlik' works fine but my theme does not work why?

---

This is my page.tpl.php :

```
<?php drupal_add_css('http://fonts.googleapis.com/css?family=Josefin+Sans:regular,bold', array('type' => 'file')) ?>
<?php drupal_add_css('http://fonts.googleapis.com/css?family=Droid+Sans:regular,bold', array('type' => 'file')) ?>
<?php drupal_add_css('http://fonts.googleapis.com/css?family=Goudy+Bookletter+1911', array('type' => 'file')) ?>
<?php drupal_add_js('jQuery(document).ready(function () { document.documentElement.className = "js"; });',
    array('type' => 'inline')
  );?>
<body class="home blog chrome">
    <div class="right-shadow">
        <div class="left-shadow">
            <div class="container clearfix">
                <div id="header" class="clearfix">
                                    <a href="<?php echo $base_path ?>">
                                        <img src="<?php echo $base_path ?><?php global $theme_path; echo  $theme_path ?>/logo.png" alt="Modest Theme" id="logo"/>
                                    </a>
                                    <ul id="top-menu" class="nav">
                                            <li id="menu-item-322" class="menu-item menu-item-type-custom menu-item-object-custom current-menu-item current_page_item menu-item-home menu-item-322">
                                                <a href="<?php echo $base_path ?>">Accueil</a>
                                            </li>
                                            <li id="menu-item-323" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-323">
                                                <a href="#" onclick="return false">Categories</a>
                                                <ul class="sub-menu">
                                                    <?php
                                                        foreach(taxonomy_get_tree(2) as $categoryObject) :
                                                            $path = taxonomy_term_uri($categoryObject);
                                                            echo '<li id="menu-item-'.$categoryObject->tid.'" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-'.$categoryObject->tid.'"><a href="'.url($path['path']).'">'.$categoryObject->name.'</a></li>';
                                                        endforeach;
                                                    ?>
                                                 </ul>
                                            </li>
                                            <li id="menu-item-372" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-372">
                                                <a href="/contact">Contact</a>
                                            </li>
                                    </ul>
                                    <div id="icons">
                                            <span>Drupal : Apprenons ensemble</span>
                                            <div id="et-social-icons">
                                                <a href='https://twitter.com/#!/drupal_addict' target='_blank'>
                                                    <img alt='Twitter' src='<?php echo $base_path.$theme_path ?>/images/twitter.png' />
                                                </a>
                                                <a href='/rss.xml' target='_blank'>
                                                        <img alt='Rss' src='<?php echo $base_path.$theme_path ?>/images/rss.png' />
                                                </a>
                                                <a href='https://www.facebook.com/pages/Drupal-Addict/222067957809636' target='_blank'>
                                                    <img alt='Facebook' src='<?php echo $base_path.$theme_path ?>/images/facebook.png' />
                                                </a>
                                            </div>
                                    </div>
                                </div> <!-- end #header -->

                <div id="content-area" class="clearfix">
                                    <div id="quote">
                                        <p id="quote-1">
                                            <span class="tagline-quote">“</span>Drupal Addict vous permet de découvrir et <a href="#" >proposer</a> des informations sur Drupal 7<span class="tagline-quote">”</span>
                                        </p>
                                        <p id="quote-2">En savoir plus sur Drupal 7 devient plus facile grâce à Drupal Addict</p>
                                    </div> <!-- end #quote -->
                                    <div id="blurbs" class="clearfix">

                                        <div class="blurb">
                                            <?php print render($page['content']); ?>
                                            <?php
                                                $nodes = db_query('SELECT count(nid) as total FROM {node}');
                                                foreach($nodes as $el)
                                                {
                                                    $total = round($el->total / 10);
                                                }

                                                echo '<div id="nav">';
                                                //Si c'est la première page
                                                if(!isset($_GET['page']) && $total > 0) :
                                                    echo '<div class="left"><a href="?page=2">Articles Précédents</a></div>';
                                                endif;
                                                if(isset($_GET['page']) && $_GET['page'] == 1 && $total > 0) :
                                                    echo '<div class="left"><a href="?page=2">Articles Précédents</a></div>';
                                                endif;

                                                //Si c'est la première page
                                                if(isset($_GET['page']) && $_GET['page'] < $total + 1 && $_GET['page'] != 1) :
                                                    echo '<div class="left"><a href="'.$_GET['page']--.'">Articles Précédents</a></div>';
                                                    echo '<div class="right"><a href="?page='.$_GET['page']++.'">Articles Suivants</a></div>';
                                                endif;

                                                //Si c'est la dernière page
                                                if(isset($_GET['page']) && $_GET['page'] == $total + 1) :
                                                    $page = $_GET['page'] - 1 ;
                                                    echo '<div class="right"><a href="?page='.$page.'">Articles Suivants</a></div>';
                                                endif;
                                                echo '</div>';

                                            ?>
                                        </div>

                            <div class="blurb last">
                                                            <!--
                    <h3 class="title">Examples of Our Work</h3>
                                                                        <div class="thumb">
                                <a rel="prettyPhoto[gallery]" title="Nam libero tempore soluta" href="http://www.elegantthemes.com/preview/Magnificent/wp-content/uploads/2009/08/thumb-1.png" class="prettyphoto">
                                    <img src="http://www.elegantthemes.com/preview/Modest/wp-content/themes/Modest/timthumb.php?src=http://www.elegantthemes.com/preview/Magnificent/wp-content/uploads/2009/08/thumb-1.png&h=56&w=56&zc=1&q=90" class='item-image'  alt='Nam libero tempore soluta' width='56' height='56' />                                  <span class="overlay"></span>
                                    <span class="zoom-icon"></span>
                                </a>
                            </div>
                                                                                <div class="thumb">
                                <a rel="prettyPhoto[gallery]" title="Sed neque ipsum pulvinar eu trist" href="http://www.elegantthemes.com/preview/Magnificent/wp-content/uploads/2009/08/thumb-2.png" class="prettyphoto">
                                    <img src="http://www.elegantthemes.com/preview/Modest/wp-content/themes/Modest/timthumb.php?src=http://www.elegantthemes.com/preview/Magnificent/wp-content/uploads/2009/08/thumb-2.png&h=56&w=56&zc=1&q=90" class='item-image'  alt='Sed neque ipsum pulvinar eu trist' width='56' height='56' />                                  <span class="overlay"></span>
                                    <span class="zoom-icon"></span>
                                </a>
                            </div>
                                                                                <div class="thumb">
                                <a rel="prettyPhoto[gallery]" title="Cras eu eros id dui porttitor luctus" href="http://www.elegantthemes.com/preview/Magnificent/wp-content/uploads/2009/08/thumb-3.png" class="prettyphoto">
                                    <img src="http://www.elegantthemes.com/preview/Modest/wp-content/themes/Modest/timthumb.php?src=http://www.elegantthemes.com/preview/Magnificent/wp-content/uploads/2009/08/thumb-3.png&h=56&w=56&zc=1&q=90" class='item-image'  alt='Cras eu eros id dui porttitor luctus' width='56' height='56' />                                   <span class="overlay"></span>
                                    <span class="zoom-icon"></span>
                                </a>
                            </div>
                                                                                <div class="thumb">
                                <a rel="prettyPhoto[gallery]" title="Vivamus vitae nibh id quam" href="http://www.elegantthemes.com/preview/Magnificent/wp-content/uploads/2009/08/thumb-4.png" class="prettyphoto">
                                    <img src="http://www.elegantthemes.com/preview/Modest/wp-content/themes/Modest/timthumb.php?src=http://www.elegantthemes.com/preview/Magnificent/wp-content/uploads/2009/08/thumb-4.png&h=56&w=56&zc=1&q=90" class='item-image'  alt='Vivamus vitae nibh id quam' width='56' height='56' />                                 <span class="overlay"></span>
                                    <span class="zoom-icon"></span>
                                </a>
                            </div>
                                                                                <div class="thumb">
                                <a rel="prettyPhoto[gallery]" title="Aenean vulputate fermentum ante" href="http://www.elegantthemes.com/preview/Magnificent/wp-content/uploads/2009/08/thumb-5.png" class="prettyphoto">
                                    <img src="http://www.elegantthemes.com/preview/Modest/wp-content/themes/Modest/timthumb.php?src=http://www.elegantthemes.com/preview/Magnificent/wp-content/uploads/2009/08/thumb-5.png&h=56&w=56&zc=1&q=90" class='item-image'  alt='Aenean vulputate fermentum ante' width='56' height='56' />                                    <span class="overlay"></span>
                                    <span class="zoom-icon"></span>
                                </a>
                            </div>
                                                                                <div class="thumb">
                                <a rel="prettyPhoto[gallery]" title="Ut sagittis ultrices urna eget erat non purus" href="http://www.elegantthemes.com/preview/Magnificent/wp-content/uploads/2009/08/thumb-6.png" class="prettyphoto">
                                    <img src="http://www.elegantthemes.com/preview/Modest/wp-content/themes/Modest/timthumb.php?src=http://www.elegantthemes.com/preview/Magnificent/wp-content/uploads/2009/08/thumb-6.png&h=56&w=56&zc=1&q=90" class='item-image'  alt='Ut sagittis ultrices urna eget erat non purus' width='56' height='56' />                                  <span class="overlay"></span>
                                    <span class="zoom-icon"></span>
                                </a>
                            </div>
                                                        -->
                                                        <?php print render($page['sidebar_first']); ?>
                                        </div> <!-- end .blurb -->
                    </div> <!-- end #blurbs -->

            </div> <!-- end #content-area -->
        </div> <!-- end .container -->

            </div> <!-- end .left-shadow -->
</div> <!-- end .right-shadow -->

<div id="footer">
    <div class="right-shadow">
        <div class="left-shadow">
            <div id="footer-top">
                <div class="container">
                    <div id="footer-widgets" class="clearfix">
                        <div id="customlogowidget-4" class="footer-widget widget_customlogowidget">
<p id="footer-logo"><img alt="" style="width:90px" src="<?php echo $base_path.$theme_path ?>/logo.png" /><span>©  2011 Drupal Addict</span></p>
<div class="thumb">
    <img class="item-image"  alt="" src="http://www.elegantthemes.com/preview/Modest/wp-content/themes/Modest/timthumb.php?src=http://www.elegantthemes.com/preview/DelicateNews/wp-content/uploads/2010/07/thumb-4.png&w=56&h=56&zc=1" />
    <span class="overlay"></span>
</div>
<p>Internautes et rédacteurs, bienvenue ! Ce site a pour objectif de rassembler nos connaissances et de les partager. Pour cela, j'ai mis en place la possibilité de créer de nouveau article. Bonne visite et participation</p>

</div> <!-- end .footer-widget -->
<div id="recent-posts-3" class="footer-widget widget_recent_entries">
    <h4 class="widgettitle">Articles Récents</h4>
    <ul>
        <?php
            $nodes = node_get_recent(5);
            foreach ( $nodes as $node) :
                if(isset ($node->uri['path']))
                    echo '<li><a href="'.drupal_get_path_alias($node->uri['path']).'">'.$node->title.'</a></li>';
            endforeach;

         ?>
    </ul>
        </div> <!-- end .footer-widget --><div id="text-3" class="footer-widget widget_text"><h4 class="widgettitle">Mentions Légales</h4>
                <div class="textwidget">
                    <h5 style="font-size: 13px">Site Internet : Drupal Addict</h5>
                    <div>
                        Créateur / Développeur : Francis NIKOU<br/>
                        1 rue de la saussaie fleurie<br/>
                        77230 Saint Mard
                        France
                        Tel. : 06 11 75 68 70
                        mail : webmaster@drupal-addict.fr
                    </div>
                    <h5 style="font-size: 13px; margin-top: 15px">Hebergement : OVH</h5>
                    <div>
                        2 rue Kellermann<br/>
                        59100 Roubaix
                        France
                        Tel. : 06 11 75 68 70
                        web : http://www.ovh.fr
                    </div>

                </div>
        </div> <!-- end .footer-widget -->                  </div> <!-- end #footer-widgets -->

                </div> <!-- end .container -->
            </div> <!-- end #footer-top -->
        </div> <!-- end .left-shadow -->
    </div> <!-- end .right-shadow -->
</div> <!-- end #footer -->
<script type="text/javascript">

  var _gaq = _gaq || [];
  _gaq.push(['_setAccount', 'UA-10074252-5']);
  _gaq.push(['_trackPageview']);

  (function() {
    var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
    ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
  })();

</script>
<?php drupal_add_js($theme_path.'/js/jquery.easing.1.3.js', array('type' => 'file', 'scope' => 'footer')); ?>
<?php drupal_add_js($theme_path.'/js/superfish.js', array('type' => 'file', 'scope' => 'footer')); ?>
<?php drupal_add_js($theme_path.'/js/custom.js', array('type' => 'file', 'scope' => 'footer')); ?>
<?php drupal_add_js($theme_path.'/js/jquery.prettyPhoto.js', array('type' => 'file', 'scope' => 'footer')); ?>
<?php drupal_add_js($theme_path.'/js/et-ptemplates-frontend.js', array('type' => 'file', 'scope' => 'footer')); ?>

```

I don't override theme\_pager. My cache is clear. This is my website : http://www.drupal-addict.fr/

# Answer
OK, if I understand correctly what you're trying to do...

You are not satisfied with the default Drupal pager and you're trying to build a different pager, more like the default Wordpress pager. Right?

I tried putting the large block of PHP from your code (the chunk after `<?php print render($page['content']); ?>`) in the original page.tpl.php of the Bartik theme and it seems to work: The output is printed right below the default pager. That said, your approach is not the right way to do it.

First of all, large blocks of php logic and database queries do not belong in template files. If you want to change what Drupal theme (like Bartik) does, you should override the appropriate theme function, in this case theme\_pager. You can learn how to do that in the documentation at drupal.org. By overriding the theme function, you have all variables available (no need to run extra queries). It's the most effective way of changing the output of any element on your page.

Second, if you're running `db_query('SELECT count(nid) as total FROM {node}')`, that is not the same as counting all nodes on the front page. The nodes that appear on the front page are the nodes where `status = 1` (it must be published) and `promote = 1` (it must be promoted to the front page).
> 1 votes

---
Tags: 7, paging
---


title: Add node week count?

text:
# Question
Title: Add node week count?
Drupal just stores the day count and the total count. Is there a way to give a week count to the node?

**ps**: i want to show a node title list.the sort creteria is decending the most viewsd in a week. by defaule Drupal just stores the day count and the total count. there is no week count.

**could i use this**: i add a node created time in a sql query which `where` clause is less than `time()-24*7` like this `where node time created < time()-24*7`)then i use the total node count. then descending the result. the node title show will be the same as the week count. am i right? if right, how to put the sql query to views sort creteria .

# Answer
> 4 votes
You can use this *not so well maintained* module Statistics Granularity or learn how to do it yourself with this blog post: Advanced statistics for Drupal: most viewed nodes in a week, month, ...

# Answer
> 0 votes
In case you are using views3, you can use the `GROUP BY` functions and do it via SQL. Alternatively there is a seperate module for views2.

---
Tags: 7, nodes
---


# Question
Title: Custom teasers and show summary checkbox
The function generating teasers in D6 does not make nice teasers. At the same time I do not want to bother my users to set teasers themselves, I would rather get rid of the whole system.

Anyway, I tried writing a little helper module which went through the published nodes and tried to correct teasers that were too short or too long.

My problem:

1. Between the `node_load()` and a `node_save()`, what parts should I care about, just place a `<!--break-->` in `$node->body` or adjust `$node->teaser`?
2. I had the problem after adjusting `$node->teaser` and deleting the break; the "Show summary in full view" checkbox was unchecked when manually editing this node. Which variable is controlling this checkbox and how do I set it?
3. If I wanted to implement some teaser-corrections via `hook_nodeapi()`, which event should I hook to, when I do not want to patch the node core module and interfere with its `node_teaser()` function?

I know there are a couple of modules around, that store teaser data in separate CCK fields. I would like to avoid this if possible. (and yes, I want to have a proper value for the teaser variable and not just manipulate the output via views etc.)

# Answer
> 1 votes
* Set `$node->teaser` to the value you want to use as teaser. That is what node\_submit(), the function indirectly called from node\_form\_submit(), does.
* node\_body\_field(), the function that add the form fields for the node body, contains the following code:

```
// Check if we need to restore the teaser at the beginning of the body.
  $include = !isset($node->teaser) || ($node->teaser == substr($node->body, 0, strlen($node->teaser)));

// …

$form['teaser_include'] = array(
  '#type' => 'checkbox',
  '#title' => t('Show summary in full view'),
  '#default_value' => $include,
  '#prefix' => '<div class="teaser-checkbox">',
  '#suffix' => '</div>',
);

```

The checkbox is not selected if

1. the teaser is set, or
2. the teaser is not the initial part of the body

* I would use `hook_nodeapi('presave')`, which is invoked before the node is saved, but before `hook_nodeapi('insert')` or `hook_nodeapi('update')`.

To notice that, if the problem is the length of the teaser, node\_teaser(), uses the value of the "teaser\_length" Drupal variable as length if the teaser. I am not using Drupal 6, but if I remember well, there should be a setting page that allow to change the value of that variable. If the value of the variable is not modified from a setting page, then you can set it in settings.php, or from a custom module.

---
Tags: 7, nodes
---


# Question
Title: Author information lost after saving node
I am developing a site using Drupal 6. Sometimes, when I edit and save a node, the author information is lost and the node is unpublished.

Some observations:

* When I edit the node again, even with the user 1 account, I no longer get the node publication controls on the edit form.
* In the content overview admin page, the column for author is empty, not 'anonymous'.
* I can force-publish the node again using bulk operations, but not via the edit node page. I cannot seem to restore the/a author for the node.

I have not yet been able to reproduce this problem consistently: it happens on various node types, only sometimes, regardless of using tinyMCE or filtered HTML for content.

It does seem to happen only on edit, not create. I have not recently enabled or disabled any modules.

Has anyone else experienced something similar? Any idea as to what might be causing this?

# Answer
I seem to have found the cause of this problem in this Drupal issue. Apparently, there's a bug that causes the combination of the vertical tabs module, translations and uploaded files to mess up the node edit form — causing information to be lost.

If you follow the trail on the above link, you'll find there's no real solution yet (although there are core patches).

The best workaround I have found is **disabling the vertical tabs module**.
> 0 votes

# Answer
That sounds strange and like a sideeffect. I would try do debug this using the devel-module. Write a Module and print (with dsm) the $node inside hook\_nodeapi. Inspect the content in subject to the operation ($op). Maybe do this two times with diffrent module weights (-1000, 2000) to see if any hook\_nodeapi implementation of another module fails.
> 0 votes

---
Tags: 6
---


# Question
Title: Allot space to individual registered user
I have a drupal site with many users.

How to add space to individual registered users in drupal site? Each user can be alloted a maximum space of 500MB for all his events, messages, videos and hotlist. How could this be done?

# Answer
> 2 votes
A disc quota is one thing but also checking user-content in the db could be tricky :-). Never done something like this but here's what I would try:

But as I said that checks only stuff inside the `files` table. No other content (text inside fields, cached content, thumbnails...) will be handled.

---
Tags: users, 7
---


title: Huge CCK field export/import

text:
# Question
Title: Huge CCK field export/import
I am having troubles exporting and importing a large numbers of CCK fields using Content copy (I need to have a file download/upload option).

Is there a SQL (or drush) command that can export and import CCK fields? I am interested in anything that bypasses the PHP memory limitations, 504 gateway time-outs, and what not.

Maybe I could still use HTTP from the webserver's CLI, something like `wget <export from content copy> >data.txt` and `wget --post-data data.txt <import via content copy>`.

# Answer
There's two ways to solve this...

1. Easy/tedious way, export only a few fields at a time using content copy and try to find out what's the max number of field you can select before running into php errors. This could be pretty cumbersome as you have a lot of field but this is the recommended/safe way.
2. Hard/dangerous way is messing up directly with MySQL. You need to be a little SQL savy to do this and rigorous to not forget anything.

So a little explanation for the n°2, the information your looking for is in these tables:

* `content_type_CONTENT_TYPE_NAME`, this table store all non multi-valued fields of your CT (CT = Content Type).
* `content_field_FIELD_NAME`, there's one of these tables for each of your field that is set to be multi-valued.

Internals CCK tables:

* `content_node_field_instance`, stores definitions of each of your fields (label, weight, widget, name of CT...)
* `content_node_field` additionals settings (required, multivalue, db storage...)
* `content_group_fields` and `content_group` informations regarding the grouping feature.

So now you have the table, now comes the tricky part.

If your CT and fields doesn't exists on the destination, it's quite easy, just export the tables of your CT and fields in SQL, export the content of the internal CCK tables using your CT and fields names.

If your CT or any of your fields (remember that fields can be shared between CT) exists on the destination you have to evaluate the changes and update the table structure to apply these changes, I think this easy pretty difficult to deal with so I wouldn't recommend you to do so.

Good Luck.
> 0 votes

---
Tags: 6, entities
---


title: Making a view block display link

text:
# Question
Title: Making a view block display link
I'm currently migrating a website from Drupal 5 to Drupal 6. I've migrated most of the modules but something keeps nagging me: on Drupal 5 I had a block that displayed a snippet of text with a "More" link in a separate line. This snippet of text sent the user to a page with the full text.

After the Drupal 6 migration that snippet of text no longer links to anything. How can I make it lu

# Answer
> 1 votes
Fixed it by going to Views, selecting this particular view, selecting Block display and in the Field section editing the Node: title checking the box labelled "Link this field to its node".

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


title: Update Drupal Modules - skip a version?

text:
# Question
Title: Update Drupal Modules - skip a version?
I've neglected a site for a while, and now I need to update some modules that are several versions out of date. Can I just jump to the newest version of the module or do I need to copy each version in order and run update.php each time?

Also, if several modules need updating, is it OK to copy all the files across and run update.php once, or do I need to copy each module individually and run the update each time?

# Answer
> 1 votes
Yes, you can skip steps when updating. The best method I've found is to use drush. "drush up" will make backups; update all modules, themes, and Drupal core; and then run update.php.

I do this on my development site, test, then commit to SubVersion and check it out on production. In fact, I'm just about to update our production site.

# Answer
> 6 votes
As long as you're not skipping major Drupal versions (i.e. going from Drupal 5.x to Drupal 7.x), just jump to the new version(s).

# Answer
> 2 votes
Generally speaking, you can update from (for example) version 6.1 to 6.20; Drupal saves the last update function executed for each module, and will execute the functions that have never been run, one by one.

I would check if the project page contains particular instructions for updating a module; the module could be incompatible with some versions of other modules, or require a particular updating procedure.

---
Tags: updating
---


# Question
Title: How do you wrap a link around the block header text with Drupal?
(sorry if i'm redundant) What's the easiest way to wrap a link to the header of any block title text?

I know a workaround would be to just not include a title and add it in the content; but that's not the most convenient at times.

# Answer
I f I understand that your question is *How to make block title a link?* You can use this module http://drupal.org/project/block\_titlelink
> 2 votes

---
Tags: 7, blocks, theming
---