title: Where does theme($row) get evaluated?

text:
# Question
Title: Where does theme($row) get evaluated?
I am baffled by this line of code:

```
$work[$id] = $view->field[$id]->theme($row);

```

Does anyone know where `theme($row)` gets evaluated?

`$word[$id]` gets set to this emfield's url, "http://mysite.com/myvideo.flv", which is the value of both:

```
$view->field[$id]->last_render
$view->field[$id]->original_value

```

So I am guessing that `theme($row)` gets evaluated to either 'last\_render' or 'original\_value'. But when I add debug code to print `theme($row)`, nothing gets printed.

Any ideas?

Here is the context in which this line of code appears, from views-view-swftools.tpl.php:

```
   foreach ($rows as $key => $row) {

          // Reset the work array
          $work = array();

          // Render each field in this row using the assigned handler
          foreach ($keys as $id) {
            $work[$id] = $view->field[$id]->theme($row);
          }
          ...
    }

```

# Answer
> 2 votes
This is a method call, the `theme` method is invoked on the `$view->field[$id]` object. The method is likely `views_handler_field::theme` but it may have been overrided by the `views_handler_field` subclass used for a particular field handler. Usually, the method will eventually ends up calling the `theme()` function to use a defined theme function or template for the field (if this is a CCK field, a formatter will likely be used).

# Answer
> 0 votes
> But when I add debug code to print theme($row), nothing gets printed.

That's just because that function has no output.

---
Tags: views
---


# Question
Title: How to hook to content profile edit form validation
I try the following code, but it doesn't seem to work.

```
function mymod_profile_node_form_validate($node,&$form) {
  firep($form, 'form');
}

```

Could anybody help?

# Answer
If you would like to add a custom validation to a form 1st you're going to have to modified the form and inject your validation.

So 1st lets infect our validation into a form.

```
/**
 * Implements hook_form_alter()
 */
function hook_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'name_of_the_form_we_want_to_alter') {
    // Notice that we're appending to the array, we not replacing, this is to keep the regular validation function.
    $form['#validate'][] = 'name_of_our_custom_validation_function';
  }
}

```

Now we need to add out validation function:

```
function name_of_our_custom_validation_function($form, &$form_state) {
 //We do all our processing in here.
}

```

This should cover most use cases in Drupal 6 and 7.
> 2 votes

# Answer
It will not work as it is not a hook.

Try `hook_form_alter()` to edit form so that `$form['#validate']` can be defined.

```
$form['#validate'] = !empty($form['#validate']) ? $form['#validate'] + array('mycustom_validate_handler') : array('mycustom_validate_handler');

```

Then define your function

```
function mycustom_validate_handler($form, $form_state){
     // Do your validation.
}

```
> 2 votes

---
Tags: 6, forms
---


title: 404 errors with Nginx

text:
# Question
Title: 404 errors with Nginx
I'm trying to test nginx on Dreamhost following the instructions in the wiki, but going to any page except for the front page results in a 404 error: http://wiki.dreamhost.com/Nginx#Drupal.

Certain things are assumed, and from that assumption I cannot tell if they apply to what I'm trying to do or not. I'm guessing its some kind of clean URL based error.

For example, /home/YOURUSER/nginx/example.com/drupal.conf; my path is /home/YOURUSER/example.com/drupal.conf.

I'm assuming at this point that is not the issue. I've tried various things including just putting in what appears to be the bare minimum to no effect:

```
if (!-e $request_filename) {
rewrite ^/(.*)$ /index.php?q=$1 last;
}

```

Any pointers would be helpful. I'd like to get this working with Boost.

I also attempted to use this: http://wiki.nginx.org/Drupal#Not\_So\_Simple.

Disabling clean URLs allows me to log in, and Drupal states that clean URLs are not enabled.

# Answer
> 0 votes
Even though it seemed odd, I created a nginx/site.com and put the .conf there. I am accustomed to .htaccess, but apparently this file does not belong even in the same dir so in the end it was just a silly mistake with where I put the .conf.

# Answer
> 2 votes
This is what I use (with Drupal 6 and Boost), most is self explanatory but I added additional comments here and there:

```
server {
        listen          80;
        server_name     IP.NR example.com www.example.com;  # Multiple hostnames seperated by spaces
        root            /path/to/drupal; # Replace this
        charset         utf-8;
        access_log  /var/log/nginx/example.com.access.log  combined;
        error_log   /var/log/nginx/example.com.error.log;

        index  index.php;

        if ($host ~* (^example.com|www.example2.com)) { # Redirect to www.example.com
                rewrite ^(.*)   http://www.example.com$1 permanent;
        }

    ## 6.x starts
        location / {
                #rewrite ^/(.*)/$ /$1 permanent; # remove trailing slashes - disabled
                try_files $uri @cache;
        }

        location @cache {
                if ( $request_method !~ ^(GET|HEAD)$ ) {
                        return 405;
                }
                if ($http_cookie ~ "DRUPAL_UID") {
                        return 405;
                }
                error_page  405 = @drupal;
                add_header  Expires "Tue, 24 Jan 1984 08:00:00 GMT";
                add_header  Cache-Control "must-revalidate, post-check=0, pre-check=0";
                add_header  X-Header "Boost Citrus 1.9";
                charset         utf-8;
                try_files   /cache/normal/$host${uri}_$args.html /cache/$host${uri}_$args.html @drupal;
        }

        location @drupal {
                ###
                ### now simplified to reduce rewrites
                ###
                rewrite ^/(.*)$  /index.php?q=$1 last;
        }

        location ~*
        (/\..*|settings\.php$|\.(htaccess|engine|inc|info|install|module|profile|pl|po|sh|.*sql|theme|tpl(\.php)?|xtmpl)$|^(Entries.*|Repository|Root|Tag|Template))$
        {
                deny all;
        }

        location ~* /files/.*\.php$ {
                return 444;
        }
        location ~* /themes/.*\.php$ {
                return 444;
        }

        location ~ \.php$ {
                try_files $uri @drupal;           #check for existence of php file
                fastcgi_param  SCRIPT_FILENAME    $document_root$fastcgi_script_name;
                include /etc/nginx/conf.d/php_fpm; # Includes config for PHP-FPM (see below)
        }

        location ~ \.css$ {
                if ( $request_method !~ ^(GET|HEAD)$ ) {
                        return 405;
                }
                if ($http_cookie ~ "DRUPAL_UID") {
                        return 405;
            }
                error_page 405 = @uncached;
                #access_log     off;
                expires         max; #if using aggregator
                add_header      X-Header "Boost Citrus 2.1";
            try_files   /cache/perm/$host${uri}_.css /cache/$host${uri}_.css $uri =404;
        }

        location ~ \.js$ {

                if ( $request_method !~ ^(GET|HEAD)$ ) {
                        return 405;
                }
                if ($http_cookie ~ "DRUPAL_UID") {
                    return 405;
                }
                error_page 405 = @uncached;
                #access_log  off;
                expires  max; # if using aggregator
                add_header X-Header "Boost Citrus 2.2";
            try_files /cache/perm/$host${uri}_.js /cache/$host${uri}_.js $uri =404;
        }

        location @uncached {
                #access_log  off;
                expires  max; # max if using aggregator, otherwise sane expire time
        }

        location ~* /files/imagecache/ {
                #access_log         off;
                try_files $uri @drupal;  #imagecache support - now it works
        }

        location ~* /files/backup_migrate/ {
                deny all;
        }

        location ~* ^.+\.(jpg|jpeg|gif|png|ico)$ {
                #access_log  off;
            expires          14d;
            try_files $uri = 404;
        }

        location ~* \.xml$ {
                if ( $request_method !~ ^(GET|HEAD)$ ) {
                        return 405;
                }
                if ($http_cookie ~ "DRUPAL_UID") {
                        return 405;
                }
                error_page 405 = @drupal;
                add_header Expires "Tue, 24 Jan 1984 08:00:00 GMT";
                add_header Cache-Control "must-revalidate, post-check=0, pre-check=0";
                add_header X-Header "Boost Citrus 2.4";
                charset utf-8;
                types { }
                default_type application/rss+xml;
                try_files /cache/normal/$host${uri}_.xml /cache/normal/$host${uri}_.html /cache/$host${uri}_.xml $uri @drupal;
        }

        location ~* /feed$ {
                if ( $request_method !~ ^(GET|HEAD)$ ) {
                        return 405;
                }
                if ($http_cookie ~ "DRUPAL_UID") {
                        return 405;
                }
                error_page 405 = @drupal;
                add_header Expires "Tue, 24 Jan 1984 08:00:00 GMT";
                add_header Cache-Control "must-revalidate, post-check=0, pre-check=0";
                add_header X-Header "Boost Citrus 2.5";
                charset utf-8;
                types { }

                default_type application/rss+xml;
                try_files /cache/normal/$host${uri}_.xml /cache/normal/$host${uri}_.html /cache/$host${uri}_.xml $uri @drupal;
        }

#        error_page  404              /index.php;

        # redirect server error pages to the static page /50x.html
        #
#        error_page   500 502 503 504  /50x.html;
#        location = /50x.html {
#            root   html;
#        }

        # deny access to .htaccess files, if Apache's document root
        # concurs with nginx's one
        #
        #location ~ /\.ht {
        #    deny  all;
        #}

        location /server-status {
                stub_status on;
                access_log off;

        }

     }

```

I'm using PHP-FPM (which is included in PHP 5.3 but I'm using 5.2) so I also include this file (...conf.d/php\_fpm)

```
        fastcgi_pass   127.0.0.1:9000;    #php-fpm listening on port 9000
        fastcgi_index  index.php;
        fastcgi_param  QUERY_STRING   $query_string;
        fastcgi_param  REQUEST_METHOD     $request_method;
        fastcgi_param  CONTENT_TYPE   $content_type;
        fastcgi_param  CONTENT_LENGTH     $content_length;

        fastcgi_param  SCRIPT_NAME        $fastcgi_script_name;
        fastcgi_param  REQUEST_URI        $request_uri;
        fastcgi_param  DOCUMENT_URI   $document_uri;
        fastcgi_param  DOCUMENT_ROOT      $document_root;
        fastcgi_param  SERVER_PROTOCOL    $server_protocol;

        fastcgi_param  GATEWAY_INTERFACE  CGI/1.1;
        fastcgi_param  SERVER_SOFTWARE    nginx/$nginx_version;

        fastcgi_param  REMOTE_ADDR        $remote_addr;
        fastcgi_param  REMOTE_PORT        $remote_port;
        fastcgi_param  SERVER_ADDR        $server_addr;
        fastcgi_param  SERVER_PORT        $server_port;
        fastcgi_param  SERVER_NAME        $server_name;

        # PHP only, required if PHP was built with --enable-force-cgi-redirect
        fastcgi_param  REDIRECT_STATUS    200;

        fastcgi_connect_timeout         60;
        fastcgi_send_timeout            180;
        fastcgi_read_timeout            180;
        fastcgi_buffer_size             128k;
        fastcgi_buffers 4 256k;
        fastcgi_busy_buffers_size   256k;
        fastcgi_temp_file_write_size    256k;
#   fastcgi_intercept_errors        on;

```

Just ask if you have any questions about specificities.

---
Tags: caching
---


# Question
Title: How to programmatically print node from a specific author
I am trying to print all nodes published by a specific author on my page. Anyway knows a way to do so ?

Thanks

# Answer
```
// returns an array of all nodes from the current user.
// From this array, create whatever page display you want:
function all_nodes_from_logged_in_user( ) {
  global $user;

  $finalAnswer = array();

  // note: it's "Safe" to build a query like this when the
  // data being embedded in the query does not come from a user:
  $query = "SELECT nid FROM {node} WHERE (node.uid = ".$user->uid.")".'ORDER BY node.changed DESC';

  $ret = db_query($query);
  while ($nid = db_fetch_object($ret)) {

    $node = node_load( $nid->nid ); // load entire node so all data is available to the caller
    $finalAnswer[] = $node; // put in return array
  }

  return $finalAnswer;
}

```
> 1 votes

# Answer
With the Views module I think you can add a filter on the user name. I don't know if you are aware of this module, but for short you have to create a view with some settings like :

* Row Style : Node (or fields but then you have to add some fields)
* Filters : User-\> Name (or ID)

To finish you have to add a display, for example "Page" and then edit the path. With this you can create a menu with the View Page.

See the documentation for more.

If it's not a good answer, can you explain more your problem ? (D6 or D7, how do you want to display the nodes...)

(Hope my english is not too bad)
> 4 votes

# Answer
If you want this programmatically, then instead of using **User-\>name** as filter, you can have it as "argument" in the view and expose it. Now you can load the view programmatically and set the value for the exposed field(i.e username).
> 0 votes

---
Tags: users
---


title: Nginx + Wysiwyg + CKeditor

text:
# Question
Title: Nginx + Wysiwyg + CKeditor
I've got several sites up and running on Nginx, but no editor loads. Wysiwyg is configured properly with CKeditor downloaded and in the libraries directory.

At this point I'm unsure if its something I'm missing, or something in my config that is blocking it.

The current configuration is the following.

```
#######################################################
### nginx.conf catch-all
#######################################################

client_max_body_size 75M;

gzip_static on;
gzip on;
gzip_comp_level 9;
gzip_types application/x-javascript text/css text/plain text/xml application/xml application/xml+rss text/javascript;

location = /favicon.ico {
    log_not_found off;
    access_log off;
}

location = /robots.txt {
    allow all;
    log_not_found off;
    access_log off;
}

# This is mostly based on Drupal's stock .htaccess
location ~* ^.+(\.(txt|engine|inc|info|install|module|profile|po|sh|.*sql|theme|tpl(\.php)?|xtmpl)|code-style\.pl|/Entries.*|/Repository|/Root|/Tag|/Template)$ {
    return 404;
}

# serve static files directly
location ~* ^.+\.(jpg|jpeg|gif|png|ico|swf|flv)$ {
    access_log off;
    expires 30d;
}

# Very rarely should these ever be accessed outside of your lan
location ~* \.(txt|log)$ {
    allow 192.168.0.0/16;
    deny all;
}

location ~ \..*/.*\.php$ {
    return 403;
}

## Deny some crawlers
if ($http_user_agent ~* (HTTrack|HTMLParser|libwww) ) {
    return 444;
}

## Deny certain Referers (case insensitive)
if ($http_referer ~* (poker|sex|girl) ) {
    return 444;
}

## 6.x starts
location / {
    rewrite ^/(.*)/$ /$1 permanent; # remove trailing slashes - disabled
    try_files $uri @cache;
}

location @cache {
    if ( $request_method !~ ^(GET|HEAD)$ ) {
        return 405;
    }

    if ($http_cookie ~ "DRUPAL_UID") {
        return 405;
    }

    error_page 405 = @drupal;
    add_header Expires "Tue, 24 Jan 1984 08:00:00 GMT";
    add_header Cache-Control "must-revalidate, post-check=0, pre-check=0";
    add_header X-Header "Boost Citrus 1.9";
    charset utf-8;
    try_files /cache/normal/$host${uri}_$args.html /cache/$host${uri}_$args.html @drupal;
}

location @drupal {
    rewrite ^/(.*)$ /index.php?q=$1 last;
}

location ~* (/\..*|settings\.php$|\.(htaccess|engine|inc|info|install|module|profile|pl|po|sh|.*sql|theme|tpl(\.php)?|xtmpl)$|^(Entries.*|Repository|Root|Tag|Template))$ {
    deny all;
}

location ~* /files/.*\.php$ {
    return 444;
}

location ~* /themes/.*\.php$ {
    return 444;
}

location ~ \.css$ {
    if ( $request_method !~ ^(GET|HEAD)$ ) {
        return 405;
    }

    if ($http_cookie ~ "DRUPAL_UID") {
        return 405;
    }

    error_page 405 = @uncached;
    access_log off;
    expires max; #if using aggregator
    add_header X-Header "Boost Citrus 2.1";
    try_files /cache/perm/$host${uri}_.css /cache/$host${uri}_.css $uri =404;
}

location ~ \.js$ {
    if ( $request_method !~ ^(GET|HEAD)$ ) {
        return 405;
    }

    if ($http_cookie ~ "DRUPAL_UID") {
        return 405;
    }

    error_page 405 = @uncached;
    access_log off;
    expires max; # if using aggregator
    add_header X-Header "Boost Citrus 2.2";
    try_files /cache/perm/$host${uri}_.js /cache/$host${uri}_.js $uri =404;
}

location ~ \.json$ {
    if ( $request_method !~ ^(GET|HEAD)$ ) {
    return 405;
    }

    if ($http_cookie ~ "DRUPAL_UID") {
    return 405;
    }

    error_page 405 = @uncached;
    access_log off;
    expires max; # if using aggregator
    add_header X-Header "Boost Citrus 2.3";
    try_files /cache/normal/$host${uri}_.json /cache/$host${uri}_.json $uri =404;
}

location @uncached {
    access_log off;
    expires max; # max if using aggregator, otherwise sane expire time
}

location ^~ /sites/default/files/imagecache/ {
    index index.php index.html;

    # assume a clean URL is requested, and rewrite to index.php
    if (!-e $request_filename) {
        rewrite ^/(.*)$ /index.php?q=$1 last;
        break;
    }
}

location ~* ^.+\.(jpg|jpeg|gif|png|ico)$ {
    access_log off;
    expires max;
    try_files $uri =404;
}

location ~* \.xml$ {
    if ( $request_method !~ ^(GET|HEAD)$ ) {
        return 405;
    }
    if ($http_cookie ~ "DRUPAL_UID") {
        return 405;
    }
    error_page 405 = @drupal;
    add_header Expires "Tue, 24 Jan 1984 08:00:00 GMT";
    add_header Cache-Control "must-revalidate, post-check=0, pre-check=0";
    add_header X-Header "Boost Citrus 2.4";
    charset utf-8;
    types { }
    default_type application/rss+xml;
    try_files /cache/normal/$host${uri}_.xml /cache/normal/$host${uri}_.html /cache/$host${uri}_.xml $uri @drupal;
}

location ~* /feed$ {
    if ( $request_method !~ ^(GET|HEAD)$ ) {
        return 405;
    }
    if ($http_cookie ~ "DRUPAL_UID") {
        return 405;
    }
    error_page 405 = @drupal;
    add_header Expires "Tue, 24 Jan 1984 08:00:00 GMT";
    add_header Cache-Control "must-revalidate, post-check=0, pre-check=0";
    add_header X-Header "Boost Citrus 2.5";
    charset utf-8;
    types { }
    default_type application/rss+xml;
    try_files /cache/normal/$host${uri}_.xml /cache/normal/$host${uri}_.html /cache/$host${uri}_.xml $uri @drupal;
}

#######################################################
### nginx.conf catch-all
#######################################################

```

I've uninstalled the WYSIWYG module, reinstalled it, and it cannot see CKeditor. If I paste the URL into the address bar, I can access the CKeditor.js file directly.

# Answer
> 3 votes
Make sure you do not have CKeditor installed twice. Its easy to do this with the CKeditor module (which I used on older sites) and the WYSIWYG module which requires CKeditor in a different directory.
WYSIWYG has issues detecting newer versions of CKeditor. The issue queue has several related issues. Downgrading was the simplest way to resolve it.
Cutting edge features on a CDN can behave poorly or interact in unexpected ways.

---
Tags: wysiwyg
---


title: Why isn't Drupal object oriented?

text:
# Question
Title: Why isn't Drupal object oriented?
I just started to peek into the docs and source (Drupal 6 at the moment) and noticed that there are no classes to be seen, only vast number of prefixed functions. Is this handy? Does such decision have a background? Why?

# Answer
This is pretty well explained on Drupal programming from an object-oriented perspective.

In short, Drupal has existed for much longer than you could properly use OOP in PHP. Which means, PHP5.

Drupal 7 already uses classes internally in a lot of places and it will probably continue so with Drupal 8.

But this is a step by step process and not everything needs to be a class. For example, it does not make any sense to make modules into a single class.
> 14 votes

# Answer
Drupal was created before oo became better in php5. Objects are being used more in drupal in each release but you need to balance a complete rewrite and adding new features.
> 5 votes

---
Tags: 6
---


title: Panels vs template performance

text:
# Question
Title: Panels vs template performance
Sorry for rather newbie question. I am reading an Panel CookBook and how to create different layouts for homepage and other landpages. Apparently it is possible to achieve the same result with Panels models and template sub-theming and overriding. So my questions are: 1. When to use one of the above methods? 2. Performance issues Panels vs Theme overriding? Thanks.

# Answer
I think the thing to keep in mind here is how the site is going to be used. If users are not going to log into it, it *almost* doesn't matter in terms of performance because you use Boost.

http://drupal.org/project/boost

You can also use caching features in panels. I've never really noted a large hit for using panels on a website, as long as the layout is reasonable and the site does not have an excessive amount of modules on it. Panels exposes *a lot* of functionality, and you can pry it out of my cold dead hands.

If you've not used Boost before, do yourself a favor and commit to doing so!

NOTE: In your other question you referenced D7. Boost may not be ready for D7 just yet but you should keep it in mind.
> 4 votes

---
Tags: theming, panels
---


# Question
Title: How do I test for node type to print a variable from template.php?
In Drupal 7, you can use the following in template.php to test for the presence of a node type:

```
function MYTHEME_preprocess_node(&$variables) {
if ($variables['type'] == 'NODETYPE') {
***CUSTOM CODE****
}

```

In Drupal 7, you can use the following in template to create a variable which can be printed out in your page.tpl.php file:

```
function MYTHEME_preprocess_page(&$variables) {
      $variables['greeting'] = 'Custom Greeting';
}

```

But how do you combine the two, to create a variable inside of template.php (that can be printed in page.tpl.php) which changes according to the node type?

I would have thought the following would work:

```
    function MYTHEME_preprocess_page(&$variables) {
              if ($variables['type'] == 'NODETYPE') {
  $variables['greeting'] = 'Custom Greeting';
    }
    }

```

But it doesn't work. Why is this? (Using the same code on MYTHEME\_preprocess\_node also does not work).

Thanks for any help!

# Answer
Each template has a different set of variables available. The variables available in a given theme is generally documented in the comment section at the top of the file. You can consult this documentation on http://api.drupal.org.

The node type is not directly available as a variable in the `page.tpl.php`. However, you have the `$node` object which has a `type` property:

```
function MYTHEME_preprocess_page(&$variables) {
  if (!empty($variables['node']) && $variables['node']->type == 'NODETYPE') {
    $variables['greeting'] = 'Custom Greeting';
  }
}

```
> 6 votes

---
Tags: theming
---


# Question
Title: Displaying fields in multiple rows for one node with Views format
In a view I need to display a node's fields in multiple rows, how can I achieve that?

The node contains:
Port1Name
Port1Arrival
Port1Departure
Port2
Port2Arrival
Port2Departure
Port3Name
Port3Arrival
Port3Departure

I need the display to be in a table as (for example)

Port Arrival Departure
Istanbul 1/1/11 2/1/11
Mersin 2/1/11 4/1/11
Mykanos 5/1/11 6/1/11

When I used table, it puts all fields on the same row, as it detects the view contains only one node. I tried with grid..played with settings, no luck. I tried Views Secondary Row and it only works when I need to have two rows, not more...

How can I achieve this with views formats?

# Answer
Drupal 7 Field API handles this case very well. I rewrote the Office Hours module using the Field API. Each row has day of week and time open and time close. This would be exactly the same for you except instead of day or week it would be port, time open would be time of arrival and time close would be time of departure.

The solution is to build a custom module with Field API in Drupal 7. Are you using Drupal 7?
> 1 votes

# Answer
Can't you just try to use unformatted rows? They will stack one after the other if you do that. Do you need the display to do anything else?
> 0 votes

# Answer
Because this type of information is tabular you can use CCK Tables or the Table Field module.
> 0 votes

---
Tags: views, nodes, theming
---


# Question
Title: Change Sent By in Drupal 6 Webform Module?
Is there a way to make it appear the email is coming from the person who submitted it, instead of the site it resides on? The webform has an email field, and I'd like to use that as the source of the email.

# Answer
Depending on the Webform version, you can accomplish this in one of two ways:

### Webform 2

When you edit the webform, look under *Webform mail settings* for *E-mail from address*. As long as you have an email field attached to the webform, you can select that field under the *Component* option.

### Webform 3

Click on the *E-mails* task underneath the *Webform* tab when viewing a webform node. Within the E-mail header details fieldset, you'll see an option to change the *E-mail from address*.

---

The one caveat: Drupal sets the `Sender:`, `Errors-To:`, and `Return-Path:` headers to the site's email address. You can, however, change these headers using `hook_mail_alter()`.

If you wanted to make sure the email field is set to user's email address (for a logged in user), you should've noticed the *User email as default* checkbox in the email field's settings, which will accomplish this and will work with the setting I mentioned above.
> 2 votes

# Answer
According to this code: http://api.lullabot.com/webform\_submission\_send\_mail

There is no way.

But you can send an e-mail in a hook: http://api.freestylesystems.co.uk/api/drupal/contributions--webform--webform\_hooks.php/function/hook\_webform\_submission\_insert/6

In this hook you just load e-mails you want to send this webform. You can gather sender e-mail from $node argument of this hook.
> 0 votes

---
Tags: webforms
---


# Question
Title: How do I display bare, stripped content with no menus, footers, etc?
Here's what I am trying to do:

I need to have a way to display only the content in a node without any of the Drupal adornment. All I want is the styles to be inserted, and the content itself.

The reason I am doing this is I am setting up a portfolio web site that contains examples of work. Each clip will be displayed in a lightbox2 popup. A lot of the clips were authored in Drupal.

I don't want the site title, menus, and all of that garbage to show inside the lightbox. Just the content.

I did the following, which seems to be a non core files hacking way of doing things:

I created a new content type, called "barepage". I copied some content into barepage.

I created a new content specific template file for barepage: node-barepage.tpl.php.

Just for testing, here is what is inside this file (I commented out the actual content):

```
<div id="node-<?php print $node->nid; ?>" class="<?php print $classes; ?> clearfix">

   <?php if (!$page): ?><div class="list-node"><?php endif; ?>

  <div class="content">
   <?php /* print $content; */ ?>
  </div>

  <?php   if (!$page): ?></div><?php endif; ?>

</div> <!-- /.node -->

```

All of the standard Drupal stuff displays: the page header, the primary navigation links, the node title inside the page, and the page footer. But as expected, the content is empty.

of course, if I uncomment $content, the page displays like a standard "Page" content type.

What in the heck do I override to eliminate all of this stuff and just display the content? I'm trying to avoid hacking the template's core files or the Drupal core.

This is with Drupal 6.2, and the Zen theme with the CTI\_Flex subtheme.

# Answer
> 5 votes
Main layout of a page is done in the `page.tpl.php` file. You have to override that templates for your *bare* pages in order to not output anything you don't want to see on the page. The correct way to override the used templates for a particular situation is to use suggestions.

From the Drupal 6 Template Suggestions, you can see that the suggestions to override this templates are summarized as `page-[front|internal/path].tpl.php`. So, out of the box, you only have to option to provide a *bare* template for either the front page of the site or all pages starting with a given path. There is no suggestion that allow you to override the `page.tpl.php` template for node pages of a specific content type.

But if you look at the `page.tpl.php` documentation, you see that the template has access to a `$node` object: *The node object, if there is an automatically-loaded node associated with the page, and the node ID is the second argument in the page's path (e.g. node/12345 and node/12345/revisions, but not comment/reply/12345)*. Using this information, you can use the template preprocessing in your theme to add an additional `page.tpl.php` suggestion.

```
function THEME_preprocess_page(&$variables) {
  if (!empty($variables['node']) {
    $node =& $variables['node'];
    $op = arg(2);
    if (empty($op) || $op == 'view') {
      $variables['template_files'][] =  'page-'. str_replace('_', '-', $node->type);;
    }
  }
}

```

This should add the `page-<content type>.tpl.php` template suggestion for node pages. You can then create the `page-barepage.tpl.php` file with your simplified markup.

Keep in mind that this will not prevent Drupal from processing and rendering any blocks for the page, it will only prevent them from being outputted in the page.

# Answer
> 0 votes
The header, menu, footer etc are not in node.tpl.php but in page.tpl.php

To stop all those from displaying in the barepage content type, I believe you copy page.tpl.php and rename page-barepage.tpl.php.

Once that is done, you should be able to comment out all the php code for outputting those "undesireables"

# Answer
> 0 votes
You should not have to hack core. See Drupal Template Suggestions for alternate naming conventions of `page.tpl.php` to override the default.

---
Tags: theming
---


title: Fields from custom nodes into Webform

text:
# Question
Title: Fields from custom nodes into Webform
I have some nodes like this http://sprachzentrum.com.ar/cursos/curso-intensivo-de-alem%C3%A1n-nivel-a21-agosto-2011 and webforms and want to insert titel and day field as an option in the webform.

So that the user can choose from different levels

---

thanks of course! My question was: I have a node with an titel and some customer fields like level an time an I ask myself if its possible tu render the listbox automaticaly so that i will a options like:

1| \[custom-field-level-1\] \[node-title-1\] \[custom-field-time-1\]
2| \[custom-field-level-2\] \[node-title-2\] \[custom-field-time-2\]
3| \[custom-field-level-3\] \[node-title-3\] \[custom-field-time-3\]

So for each node from a certain type I will get an option on my webform

# Answer
> 2 votes
For both level and date (I understand these are session, so a range of date), you can add some "select list" in order to let the user select between the available options. Do you have troubles adding this ? Can you make your question a little clearer regarding what you want and what causes you difficulties ?

Select the "listbox" option and it will produce:

**Edit June, 23:**

* so you have a Content Type named "webform\_info" with some fields "field\_level" and "field\_time".
* the idea is to implement a hook\_form\_alter (in a custom module) to retrieve these fields and put them in the webform

```
    <?php
    function custom_form_alter(&$form, &$form_state, $form_id) {
      //you need to set up a custom module to store this.
      //use devel with dsm($form); to figure the name of each field
      if ($form['#id'] == 'webform-client-form-123') {
        //delete the array of options from the webform field, they start by "con_"
        $form['submitted']['con_level']['#options'] = Array();
        $form['submitted']['con_level']['#options'][''] = '- Select one level/time -';
        $i = 1;

        //retrieve the nodes of the type webform_info
        $result = db_query("SELECT nid FROM {node} n WHERE type = 'webform_info' AND status = 1");
        while ($row = db_fetch_array($result)) {
          $node_level = node_load($row['nid']);
          $form['submitted']['con_level']['#options'][$i] = $node_level->field_level[0]['value'] . $node->title . $node_level->field_time[0]['value'];
          $i++;
        }
      }
    }
    ?>

```

Doing `node_load` can be pretty heavy if you have a great number of nodes, so you might want to use the CCK table structure, have a look at another answer to adapt the code.
Code is for D6 but should give you some insights to apply this to D7 if needed.

---
Tags: nodes, entities, webforms
---


title: Depended CCK Fields

text:
# Question
Title: Depended CCK Fields
There are two Fields, Image and Video Users have to use only one field, image or video. The problem is how do I remove video field if user upload a image ? is there any custom validation for this ?

Thanks

# Answer
> 2 votes
The Conditional fields module can do this. It allows to set up conditions and dependencies between multiple files (for example, only show field X if field Y is filled/checked).

# Answer
> 0 votes
You have to use `hook_form_alter` to add your own validate handler to your content type form. For example code View this question.

---
Tags: entities
---


title: Add new images to existing nodes

text:
# Question
Title: Add new images to existing nodes
I am using imagefield to make photo albums. Now I want to allow all registered users to upload new images to any photo albums and it should get added to the exisiting album. I do not want to give them permission to edit the node. How can I do this?

# Answer
> 1 votes
You'll likely have to change what you mean by "edit the node". You could use Field Permissions to restrict what they're able to change when editing the node.

But to truly accomplish this without letting them "edit the node", you'll need a very complex custom solution that would be unreasonably complicated for an answer on this site.

---
Tags: 7
---


# Question
Title: Creating a Testimonials Content Type and making it work as it should
I have a **Testimonials content type** which asks for a visitor's name and testimonial. Is it possible to make this form available to *Anonymous users* so anyone can post a testimonial without having to register?

I don't want people going through the Admin theme so I'm guessing I'll have to create my own form in the standard theme but how do I connect that to the actual Content Type? Posts must also *not* be published immediately but are set for moderation so I myself can say who gets in and who doesn't. Is this possible?

# Answer
You can give anonymous users the permission to create content of that type. And you can set the default publishing setting to unpublished (They can't change that unless they have the required permission).

For the theming part, if you are using the admin theme for the node add/edit forms, then you'll have to disable it for that content type. You can do so with a bit of custom code and implement hook\_admin\_paths() and return `'node/add/content-type' => FALSE` path. This will override the definition in node\_admin\_paths(). Because for a path to be considered as an admin path, there needs to be an entry that returns TRUE and no entry that returns FALSE.
> 2 votes

# Answer
Get into user permission (example.com/admin/people/permissions)

Under the node module settings there would be all the content type and their access actions against anonymous users and authenticated.

This Role-Action permission grid will help you to fine tune on privileges to users.
> 0 votes

---
Tags: 7, nodes
---


# Question
Title: Change authoring information on multiple nodes
How can I change the publication date for multiple nodes at the same time without to individually edit each node?

# Answer
> 4 votes
You may be able to use Views Bulk Operations (VBO).

> This module augments Views by allowing bulk operations to be executed on the displayed rows. It does so by showing a checkbox in front of each node, and adding a select box containing operations that can be applied. Drupal Core or Rules actions can be used.

---
Tags: datetime, nodes
---


title: Bulk language assignment

text:
# Question
Title: Bulk language assignment
In the past I created hundreds of nodes in a specific language.
Finally, the website will have only one language and I think it is best to set them all to unassigned language for development reasons.

How I can change the language in bulk?
Is there any module for that, or some SQL queries to run directly at the database?

# Answer
You can use Language Assign module
> 1 votes

---
Tags: i18n-l10n
---


title: Get the date only

text:
# Question
Title: Get the date only
I found out that `print render($content['created']);` displays the date the node was created. But it shows other info as well such as the author's name. Is there a way so only the date comes out? And can that date be given a different format?

# Answer
Another solution is to use `<?php print $date?>` in the node.tpl.php file. In Drupal 7 the markup is wrapped in lovely RDF for future SEO happiness.
> 2 votes

---
Tags: 7, datetime
---


# Question
Title: How to print id of user whose profile I visit rather than id of  logged in user?
I would like to print the id of the user on his profile page? How can I do it in Drupal 7. So far I could only print logged in user id..Any advice appreciated.

# Answer
> 2 votes
The function menu\_get\_object() allows you to get a user/node/.. object based of the current request URL.

To get the account object, you can do this:

```
if ($account = menu_get_object('user')) {
  print $account->uid;
}

```

# Answer
> 0 votes
You can use the arg() function. You can add a condition to test if the page is the user page. It would be appropriate to place this in the template.php file using HOOK\_preprocess function.

```
if (arg(0) == 'user' && is_numeric(arg(1)) {
  $MY_USER_PAGE_ID = arg(1);
}

```

---
Tags: users
---


# Question
Title: When theming a view there are two approaches, in a template file or rewriting field output, what are the advantages and disadvantages of each?
When configuring a field in a view such as the node title, there are options to add or remove formatting to the view by either excluding the field from view, wrapping the field in a certain type of tag such as div, span or h3 or rewriting the output of the field which in conjunction with replacement tokens can yield quite complex structures.

The default views row template, for example, just loops through each field and prints it to the template. However, it is possible to print each field's variable in a particular place by rewriting the template. The templates are good because logic can be added to the template, for example, testing for number of comments to determine the plurality of the word comment that is prefixing the number of comments. The template is also useful for using the drupal\_add\_js() function to add javascript files that are only loaded even when the Drupal javascript caching is enabled during that particular page load.

There is third place to add logic to theming a view which is in the hook\_views\_pre\_render() function.

With the several different ways to control the markup and output logic of a view are there best practice? Are there different techniques that are appropriate for different situations?

# Answer
You would want to use a template suggestion as they are called for small modifications to the design or DOM output adjustments. You will use this %90 of the time.

rewriting field output should be handled by hooks EXAMPLE: if you are taking a value and turning it into an image for rating display....

Use pre-processing hooks when you are applying logic to output values. Use theme suggestions when making adjustments to layout structure.
> 2 votes

---
Tags: views, theming
---


# Question
Title: Move views pager to top of node instead of bottom
Is there a simple way to move views' pager to a different place than the default bottom?

# Answer
Go to the View UI. Click Theme: information. The top list item will say Display output. There are several file names to go from the least specific to the most specific. These are the choices to override the default View template for Display output. If you want every view pager to be at the top choose views-view.tpl.php otherwise choose something more specific.

Create a file in your theme folder titled with one of these title options. Click the blue Display output link and copy the code into the file you just created. Save. Clear cache. Congratulations you have now overridden the View theme template.

Find the code

```
  <?php if ($pager): ?>
    <?php print $pager; ?>
  <?php endif; ?>

```

and move it to the top of the code where you want the pager to be. Save.
> 8 votes

---
Tags: views, 6, paging
---


# Question
Title: How to make a module prerequisite in drupal
How should i make a module that is prerequisite for an existing module.

For example:

Step 1 : There is comment module in core itself.

Step 2 : In my module i am doing some **form alter which affects comment module**. Consider my module name as comment\_test.

Step 3 : **While enabling comment module my custom module that is comment\_test should be as required module.**

Step 4 : How can this be done?

Thanks in advance...

# Answer
using below format in .info file of the module.

```
dependencies[] = D1
dependencies[] = D2

```

I the above lines, D1 & D2 represent the names of the modules you module depend on.
> 8 votes

# Answer
Have you looked into how Drupal manages module files? You define a module's dependencies in the .info file. Here is the documentation on drupal.org.
> 4 votes

# Answer
When you are enabling a module in Drupal, the module dependencies are checked from the module .info file, and you will have to enable all dependencies to enable you module.

Lets say you have two modules : foo & bar, and that foo requires bar. If you add: dependencies\[\] = "bar" in the foo's .info file, you will need to enable bar in order to enable foo.

In your case if you are working with the core comment module, you could edit the comment module .info file. But usually when you set a dependency, it means that the module needs the dependency to run properly. So unless you have modified the core comment module, it should not need another module to run properly. If you have modified the core module, you should know that for many reasons its is not advised to do so. The first reason is that you will not be able to update the core modules. The good way to do it is to create another module alter the comment module behavior.

The logic should be :

If i only need the comment module, i can enable it without having to enable other modules.

If i need the comment\_test module, i can enable it, but it will require the comment module as it is a dependency.

This is why you cannot set your module as a prerequisite to a core module without creating another module that would extend Drupal with such behavior or by modifying the .info file in the core module.
> 1 votes

---
Tags: 7
---


# Question
Title: How to allow users upload images to existing nodes?
Let’s say I have created a content type called movies and I want all nodes in movies to have a gallery tab. Inside the gallery tab it should allow users to upload images. How can I do this?

# Answer
The best / simpler way would be to create a second content type called 'image', and give user the permission to create nodes of type 'image'. You can add a CCK imagefield to provide an image upload field.

Then you will want to be able to store relationships between your movie node and the related images nodes. You can add a node reference field on the image content type. You can populate this field by default with the movie reference. So any image added in the website will be related to a movie.

You can then create a view that will list the images related to your movie ID.
> 2 votes

---
Tags: 7
---


title: Overriding views-view-fields.tpl.php

text:
# Question
Title: Overriding views-view-fields.tpl.php
Is it possible to override `views-view-fields.tpl.php` file for a specific view? I've tried creating a `views-view-fields--view-name.tpl.php` file and have re-scanned template files and cleared the cache with no effect. Similar issue as reported here: http://drupal.org/node/1137942

Though if I name the file `views-view-fields.tpl.php` in my theme folder, the new file is applied when template files are re-scanned. But this would mean that it applies to all views.

I noticed that views-view-fields.tpl.php is NOT one of the files listed in the Theme Information screen which Views presents.

Can someone definitively tell me that overriding of this file by creating a `views-view-fields--view-name.tpl.php` (or following similar naming conventions) is **not** possible/is not supported?

# Answer
> 4 votes
The order of precedence for the naming convention of the tpl files is from broadest to narrowest in it's scope. Thus the field override for all views is one combination, but you can't change the order, as you have tried, only go more specific. To achieve what you want, the view object is available in the tpl you have created so it is possible to have an if(){} else{} statement in there to filter the views that need the override by inspecting the name/display of the view.

# Answer
> 7 votes
For views 3 - make sure that under "Format-\>show" field is selected "Fields" (NOT content)

Than go to views and find "Theme: Information" there you can see list of all template currently used (BOLD) and candidate template files. Find witch tpl.php file you want to use.

Go to views module directory and under "theme" folder you should be able to find base tpl.php for your chosen file. Copy that file in your theme folder. Rename it on naming convention given in Theme:Information.

Rescan template files. If everything is OK views-view-fields.tpl.php should not be bolded anymore. Bolded should be your newly created tpl.php then you can style new tpl.php file as you like.

---
Tags: views, theming
---


# Question
Title: How to correctly configure Fivestar module with a node reference?
I have a content type "review" with a node reference to "product". I want to be able to have users rate the product while writing a detailed review. I added a Fivestar "rating" field in "review" and selected as "voting targed" the "node reference field". Users can enter the review and rate it at the same time. I created a view to show all the reviews for a product and it pulls the ratings nicely from the "rating" field.

However I can't get a view configured correctly to show an average rating for a product. I setup a relation with "Content: Vote results", left the "required" box unchecked, "value type" = percent, "vote tag" = "vote", "aggregation function" = "average vote". All the vote results fields come up empty.

What am I doing wrong?

thank you

# Answer
> 6 votes
You first need to go to path admin/structure/types/manage/product/fivestar and click the Enable Fivestar rating for the "vote" tag. For Full node display I choose Static display above node body because the voting widget will be on the Review form.

At admin/structure/types/manage/review/fields create a Node reference called Reference with a machine name field\_review\_reference. Add a field for Fivestar voting. Set the Voting target to Node Reference: field\_review\_reference. Under Reference Field Settings check the Product content type. At admin/structure/types/manage/review/fivestar the widget should NOT be enabled.

(edit: paragraph removed per suggestion of ericduran)

Now you can create another View with field to make a list of products that show fields from the product such as title, price, and image. Add the relationship Content: Vote results. Set Value type as percent, Vote tag as vote and Aggregations function as Average vote. Add the field Vote results: Value, set Relationship to Vote results, set Appearance to Fivestar Stars (display only).

That should be it.

# Answer
> 3 votes
In Drupal 7, there really is no reason to use a different content type for reviews. Unless you really want too.

In drupal 7 comments are now field-able which will allow your comments to use the fivestar rating field. Also when you use the fivestar field in a comment, there is now an option to use the "Parent Node" as the target which is exactly what you want.

After you have your comment set up to use the Parent Node as the target you still need to enable rating on the Product. The reason for this is that the vote will not be cast is the Tag being voted on isn't enabled.

Also makes sure you're using the latest -dev version. Fivestar doesn't currently have any release out yet. But it will really soon and the latest -dev version is pretty stable.

---
Tags: 7, rating
---


# Question
Title: D6: Create block view which returns all nodes with related terms
I have a vocabulary which contains a large number of terms, most of which have been given relationships to other terms.

I want to create a block display of a view which takes the term from the current node and displays all the other content which has a related term from the same vocabulary.

So far, I have been able to return all nodes with the same term using this as a views argument:

```
node = node_load(arg(1));
if($node) {
foreach($node->taxonomy as $term) { $terms[] = $term->tid; }
return implode('+',$terms);
} else { return; }

```

However, I haven't been able to combine this with taxonomy\_get\_related to return nodes related by term. Any suggestions?

# Answer
> 1 votes
You probably have to do the follwing:

* create a view
* add a block to that view
* add a contextual filter (in Drupal 6 it is an Argument)
* configure it with:
    + Action to take if argument is not present: Provide default argument
    + Default argument type: Node ID from URL
    + Validator: taxonomy term
    + You can use Term ID from the URL, or try to use the term name.

Then you have to save and configure the block to show on the desired page...

These settings in Drupal 7 (more or less, there are some slight differences in interface) work for me...

---
Tags: views, blocks
---


# Question
Title: Where do i start when trying to get webservice API's integrated?
I am building a travel website for a client, and we need search form tied to different API's and in some cases combined API's returning results.

I am a seasoned PHP developer, but fairly new to Drupal.

Where should I start? what modules should i be looking at?

Any help would be great.

# Answer
There is a very active group of developers working with the Services module. I am sure that another seasoned PHP developer would be welcomed by them.
> 1 votes

# Answer
If you want to use external web services and not create WebAPIs of your own, check out: http://drupal.org/node/1070066.

In that Drupal.org docs page, I overview two methods for someone to communicate with a Services.module created WebAPI. If your situation is communicating with 3rd party web services, you need to do something similar. Logic like the section labled "Using the Drupal API to communicate with a RESTful API" is what you'll need.
> 0 votes

---
Tags: 7, services
---


title: Using node variables in another block?

text:
# Question
Title: Using node variables in another block?
I'm trying to create a block which would include informations on the displayed node like author picture, name, and points (using Userpoints module), the creation date, and some other infos contained in created fields for certain types of nodes.

The thing is that I want to display this block in my sidebar-second (my theme is based on bartik, except that sidebar-second is included in the `<div id="content"></div>`).

But I don't manage to use variables available in files like node.tpl.php. For instance, when I try to display the author picture in the block, I write `<?php print $user_picture; ?>` but nothing appears...

Here's what I created on photoshop and I'd like to translate into Drupal (if it can help, and yes it's in French ^^) :

Thks !

EDIT : I'm using D7.

**EDIT by nyoz :** Ok, so it seems like Multiblock is a good beginning. README.txt says the following :

> DEVELOPING MULTIBLOCK-ENABLED BLOCKS: Multiblock should successfully clone any regular block created with the block API. However, if you clone a regular block that implements a hook\_block\_save or hook\_block\_configure hook, the custom block settings of one block instance will overwrite the settings of another. To get around this, you can make a block "multiblock enabled." To do this, you should add a 'mb\_enabled' key with a value of true in hook\_block\_info to each multiblock enabled block you are creating. Next, add an optional $edit argument to your hook\_block\_view and hook\_block\_configure functions. Once you do this, the instances you create will get the block instance ID passed in the $edit variable for the view, configure, and save $ops. This will let you save and load different data to different instances based on this instance ID. It is passed in with the 'multiblock\_delta' key with the following format: $edit\['multiblock\_delta'\] = array( '#type' =\> 'value', '#value' =\> $block\_id );
>
> Example implementation of hook\_block\_info: function hook\_block\_info() {
> $blocks\['powered-by'\] = array( 'info' =\> t('Powered by Drupal'), 'weight' =\> '10', 'cache' =\> DRUPAL\_NO\_CACHE, 'mb\_enabled' =\> TRUE, ); return $blocks; }

... So, I created a custom module containing :

```
function hook_block_info() {
  $blocks['content'] = array(
    'cache' => DRUPAL_NO_CACHE,
    'mb_enabled' => TRUE,
  );
  return $blocks;
}

```

I've also tried `$blocks['main'] $page['main'] $page['content'] -with return $page-`. BUT NONE OF IT WORKED (the block is still not multiblock enabled when I look in the instances list).

DO YOU HAVE ANY CLUE PLEASE ? Thks!

# Answer
> 1 votes
Try MultiBlock module.

> MultiBlock module solves this problem by allowing you to create multiple Block Instances of already existing blocks. Please read the README for more information.

---
Tags: 7, nodes, blocks
---


title: Taxonomy and URL aliases

text:
# Question
Title: Taxonomy and URL aliases
I am developing a product catalog by means of taxonomy, and want to use URL aliases to better reflect the hierarchy. For example, I have a taxonomy product in the following branch:

```
category/subcategory/product

```

The thing I'm sort of surprised is that I have to paste the complete URL path instead of having it automatically glued up out of the aliases of the parent branches, ie. category + subcategory + product

Is there anything I'm doing/understanding wrong? Is that what you guys been through and accepted "as is"?

Artur

# Answer
You will want to use the pathauto module. This will also required for you to install the token module.

Once you have those two modules install you will want to head over to the pathauto settings path at admin/build/path/pathauto. You will see there's a field-set for Taxonomy. There is also replacements patterns which contains various different tokens you can use to generate your path.

In your case the pattern you want to use looks like this:

```
category/[catpath-raw]

```

This will automatically generate the path for those taxonomy terms based of these categories.

I assume most of this is for 6.x but the same concept applies for 7.x
> 3 votes

---
Tags: taxonomy-terms
---


# Question
Title: Token replacement pattern for triggered rules on node creation
I am currently using triggered rules to send notifications whenever a certain node type is created (by anonymous, unauthenticated users). In the email notification sent I would like to include some of the content submitted in the form but I cannot find any of the replacements tokens when editing the ruleset for the event.

Right now, the token replacement patters for Form and for Form State are listed as empty.

How can I get hold of the relevant replacement tokens for the Form content?

Is there any modules that are capable of sending similar notifications (with node/Form content) upon node creation?

I am using Drupal 6.20, Rules 6.x-1.4, Token 6.x-1.15, CCK 6x.2.9

# Answer
This should be possible with the the above modules.

You do not need to get data from the form/form\_state.

I'm assuming the data you want is from a cck field because you're sending the email when a new node is created.

Rules has the "Replacement patterns for saved content" field set for pattens.

In there there's going to be cck specific token replacements. You can use those cck tokens to get the data you want.

These replacement tokens will look like \[node:field\_name\_of\_your\_field-formatted\]

Also make sure you're using the "After saving new content" event.
> 2 votes

---
Tags: 6, rules, tokens
---


title: Custom "account" pages

text:
# Question
Title: Custom "account" pages
I am creating custom account management pages in drupal with quite a few criteria. The first being that there is a page at `/account` which contains two separate forms: 1) To enter a new email address and a confirm new email address 2) To enter a new password and confirm new password

I'd like other pages for example `/account/orders` to view past orders and `/account/billing` to edit credit card data and billing address (I'm using ubercart and authorize.net for e-commerce and credit card processing, respectively) How can I access the billing data (address and last 4 digits of credit card number) from ubercart?

What are some general tips for this? Should I create a custom "account" module? Should I just try to edit some existing templates somehow? I know I'm asking a lot of big questions, and I'm not asking for a complete answer. Just some general advice and ideas.

Also, I hate the user account pages with numbers in them identifying the user. It seems simple enough just to have it know depending on who is logged in (i.e. `/user/5/edit` vs. `/user` or `/user/edit`

# Answer
> 1 votes
You will have to work on custom module implementation.

Custom solution would not effect content on `account` page.

`hook_menu` will define the menu items like `account/orders` and `account/billing`

If you are using Ubercart then you will have to carefully investigate if your required information are being stored and in which table. I am not sure if Ubercart stores Credit Cards data. I think Ubercart uses DPM (Direct payment method) to process cards which totally happens on Authorize.net pages.

`Pathauto` normally defines url alias also for user profile pages. But I think there is no way to skip user id from url while editing a user.

---
Tags: ubercart, users, path-aliases
---


title: Make uploaded image thumbnail bigger

text:
# Question
Title: Make uploaded image thumbnail bigger
I have file upload field in node edit form. After succesfull upload process (ahah by clicking Upload form button) I am getting thumbnail instead of file upload field. It's standard Drupal behaviour. I would like to know how to change size of image thumbnail generating by Drupal after ajax upload.

Could somebody give me any advice?

# Answer
Here's want you need to do to modified the image field thumbnail thats display after you upload an image.

You will need to overwrite the imagefield\_widget\_preview theme function. You can drop this theme overwrite in the template.php file of your theme.

```
function THEMENANE_imagefield_widget_preview($item = NULL) {
  //By default this returns  theme('imagefield_admin_thumbnail', $item);
  //But If you're going to change it I would recommend replacing it with image-cache.
  //Also you should keep the imagefield-preview div.
  return '<div class="imagefield-preview">' . theme('imagecache', 'your_custom_preset', $item['filepath'], $item['alt'], $item['title']) . '</div>';
}

```

This will replace the thumbnail images uploaded using image field.

Hope this helps.

Also remember, to use the name of the theme thats being used when editing. In-case you're using different themes.
> 2 votes

# Answer
If you are thinking to scale up some image so there is no solutions.

Using Imagecache in different ways:

If you are working on template then you can use this code to get a thumbnail of your image.

```
<?php
    pring theme('imagecache', 'preset-name', 'path-to-raw-image', 'alt', 'title', array('class'=> 'thumb'));
?>

```

In Views, under cck image field configuration, there are different formats that target to Imagecache presets processed images.

If you want to mange the preset output in node preview, then Edit your content type and check Display fields settings.
> 0 votes

# Answer
I use ImageCache in D6 to control thumbnail and other preview sizes. It's a simple and robust image module.

Drupal 7 has these controls in the core.
> -1 votes

---
Tags: entities, 6, media
---


# Question
Title: Calling a PHP script from Drupal retrieves different result than calling it outside Drupal
I'm trying to create a module that creates a Shortlink using Google Apps Shortlink Api (undocumented since its still in labs).

Here's the script (also at http://drupalbin.com/18667):

```
function drapps_shortlinks_createlink($url, $verbose = FALSE, $bypass_validattion = FALSE) {
  //loads ShortLink Class
  include_once('ShortLink.php');

  // URL validation with 2 clauses:
  // 1 - FILTER_VALIDATE_URL -> tests if the url is well constructed
  // 2 - @fopen -> tests if the URL actually exist
  if (!filter_var($url, FILTER_VALIDATE_URL) OR !@fopen($url,"r")) {
    // URL not valid or inexistant, so bail
    if ($verbose) {
      $msg = 'Invalid URL';
      return $msg;
    }
    else {
      return;
    }
  }

  // Get configuration values
  $domain = 'mydomain.com';
  $key = 'someHMACKEY';
  $user = 'username@mydomain.com';

  // Check if user admin has configured DRAPPS and DRAPPS ShortLinks
  if (!$domain OR !$key OR !$user) {
    //Something is missing so bail
    if ($verbose) {
      $msg = 'DRAPPS Shortlinks is not configured. Please go to <a href="' . base_path() . 'admin/settings/drapps">admin/settings/drapps</a>';
      return $msg;
    }
    else {
      return;
    }
  }

  //PHP Google Apps ShortLinks Implementation
  $slink = new ShortLink($domain, $key, $user);
  $r = clone $slink->pub($url);
  $status = $r->status;

  if ($status == 'ok') {
    return $r;
  }
  elseif ($verbose) {
    return $status;
  }
  else {
    return;
  }
}

```

This script uses a custom created class called SHortLink.php.

EDIT: This function is called in Drupal's node-news.tpl.php like this:

```
...
<div class="test"><?php print drapps_shortlinks_createlink($url, TRUE, FALSE); ?></div>
...

```

test.php

```
<?php

$path = "path/to/drupal"; //changed for security reasons

include_once($path . 'sites/all/modules/drapps_shortlinks/drapps_shortlinks.inc');

$url = 'http://www.google.com/';

print drapps_shortlinks_createlink($url, TRUE, FALSE);

?>

```

When I go to http://www.mydomain.com/test/test.php, the script works fine and I get an 'ok' response from google; a short link is created and it works fine. When I navigate to a news node, the script runs OK, but Google responds with a 403 (forbidden) error.

EDIT\_1: THIS SCRIPT WORKS. So i think I can safely assume that the reson behind this has something to do with drupal rather than the script itself.

EDIT\_2: I think the real question behind this is: What reasons could make a script behave differently when called from drupal? Any input will be appreciated: brainstorming, ideas, tips, troubleshooting methods, anything you think that might help, I will really appreciate it.

# Answer
You really shouldn't use include\_once, Instead you should use module\_load\_include.

After you've done this start putting in Debug code in your include file to make sure it's being loaded.

Also makes your your include file contains namespaces functions and no variable being used outside a function scope. To avoid any naming collisions that could happend.

Besides that, there really is not much help anyone can provide. A script will work the same way in Drupal as it would when being include in a regular php file.
> 3 votes

---
Tags: 7
---


title: How to auto reference?

text:
# Question
Title: How to auto reference?
I have created 2 content types one is called Album and the other is Image. I gave Image a reference field so it's linking to Album. Now when a user goes to upload a image how can I make it auto reference to the album? cause the user will have no knowledge in using drupal

# Answer
Check out the nodereference url module. It's designed exactly for this use case.
> 2 votes

# Answer
You should take a look at the module Node Reference URL Widget. With this module you can create a link in your content type Album, so when the user clicks on it, takes him to the content type image to upload the picture and your reference field will take from the url the id of that Album.

Easy to configure.
> 2 votes

---
Tags: 7
---


# Question
Title: Multiple currency  displayed in ubercart product page
I have a website where I need to display the product in 2 different currencies. Once the user selects one price, adds the product to cart, and tries to checkout, the currency can be posted to the payment gateway in USD. For example, if the user selects the price in Indian Rupees as 450 INR and tries to checkout, the value is converted into USD if the user pays through Paypal, but if the user selects the Indian Payment gateway, the same will be posted as 450 INR. How can we do this?

# Answer
Take a look at Ubercart Currency Conversion. From the project page:

> This module converts prices of ubercart products from one currency to another currency. The target currency will be selected as follows
>
> 1. Administrators can select the currency and force all prices to be automatically converted
> 2. If the above is not set, then the currency is determined based on user's address
> 3. If the above is not possible, then the site's default currency is used.
>
> The module depends on Currency module.
> 2 votes

---
Tags: 6, ubercart
---


# Question
Title: How to display content of a link in a tooltip on hover
I need to display the content returned from a link in a tooltip on hovering over that link.

I know about the some jquery plugins, which displays inline content, But didn't come across any plugin which satisfy my requirement.

If any one know any tooltip plugin, which loads the content from a link and displays it on hover, please help me.

Thanks in advance for any help,

# Answer
Beauty Tips is a drupal module and a jQuery plugin that will allow you to display content tooltip style via hover, click or a range of other events.

There is to my knowledge not built in support for loading content from different placed, but this is near trivial with the power of jQuery AJAX APIs.
> 1 votes

---
Tags: javascript
---


title: My pager code doesn't work

text:
# Question
Title: My pager code doesn't work
I'm using the following code just to see if the paging works in Drupal 7, but I'm having trouble to set it to work.

```
$query = db_select('node', 'n')
  ->fields('n', array('nid', 'title'))
  ->extend('PagerDefault')
  ->limit(5);

$headers = array(t('node'), t('Title'));
$rows = array();
$result = $query->execute();

foreach ($result as $record) {
  $rows[] .= array($record->nid, $record->title);
}

$output = theme('table', $headers, $rows);
return $output . theme('pager');

```

I'm not so good with PHP, so can someone please tell me what am I doing wrong?

# Answer
> 1 votes
Your code is using the string concatenation operator with an array; you need the assignment operator.

```
$rows[] = array($record->nid, $record->title);

```

```
$headers = array(t('node'), t('Title'));
$rows = array();

$nodes = db_select('node', 'n')
  ->fields('n', array('nid', 'title'))
  ->extend('PagerDefault')
  ->limit(5)
  ->execute();

foreach ($nodes as $node) {
  $rows[] = array($node->nid, $node->title);
}

return theme('table', $headers, $rows) . theme('pager');

```

Depending from which function contains that code, it could also be re-written as follows:

```
$page = array();
$rows = array();

$nodes = db_select('node', 'n')
  ->fields('n', array('nid', 'title'))
  ->extend('PagerDefault')
  ->limit(5)
  ->execute();

foreach ($nodes as $node) {
  $rows[] = array($node->nid, $node->title);
}

$page['table'] = array(
  '#rows' => $rows,
  '#header' => array(t('Node'), t('Title')),
  '#theme' => 'table',
  '#empty' => t('No content available.'),
);

$page['pager'] = array(
  '#theme' => 'pager',
);

return $page;

```

---
Tags: 7, paging
---


# Question
Title: When I add the comments to each node in a Views content list am I creating a n+1 database query problem?
I have a node type product and a node type review. The review has a node reference field pointing to the node type product. Using the Node Reference URL module a user can click a link on the product page and create a review of that product. The View that renders a list of the reviews is show below the product node on the node type product view page.

I tried to add comments to the View by configuring in Views UI Format -\> show -\> content -\> full content -\> show comments. However, this did not render any of the comments. Instead I created another View of type comments using the Entity Views Attach module. So each content type review now has a field that loads a View of comments using its nid.

This works great. Still there is a now few extra queries run for each review of each product which I think is a case of the n+1 select problem.

I enabled the Devel performance logger to look at how much of a hit this causes to performance. Without rendering the extra comments and attaching them to each rendered node of type review the number of queries is 165 and the query time is 95MS (my computer is super old) with the comments rendered for each node of type review the number of queries is 189 and the query time is 111MS.

(edit) I had to hack Views to test if using the content with comments was faster than adding a different View as a field to the Review content type. Oddly the number of queries was 188 with a query time of 138MS so the slightly more convoluted method was faster.

Will I be shooting my self in the foot with a bad performance bottleneck with this configuration?

If you are having a difficult time visualizing this, it is just like Stack Exchange. With a node type question that has comments. There is node type answer that is rendered in View attached to the node type question view page. Each answer can have comments too. Same thing.

# Answer
> 1 votes
You are creating a n+1 select problem, but you would do that if you created a list of full nodes since extra queries will happen on every full node display.

This isn't necessarily problem though, as you probably don't want to display 100 or 1000 nodes this way, but instead use a pager. When using a pager, n will never be more than your pager count which could be something like 10 or 20. 10 or 20 queries is not ideal but hardly a problem either unless you need to run a very high performance site, but if that were the case, you probably wouldn't use views anyways.

Views has some cache options which could be used to optimize, and reduce all of the queries to a single query on the cache instead. That is an easy of increasing performance.

---
Tags: 7, views, performance, nodes
---


# Question
Title: Search page is not shown properly with D7 custom theme
I am currently building a D7 theme for a website. I experiment some problems with the search page. After entering a search term the page "domain.com/search/node/\[searched term\]" is opened. But it just show the base page with nothing in the main-content block.

With another theme it works : results are shown properly on the search page and I can see both node tab and user tab. I assume something is wrong in my theme. I try to override "search-results.tpl.php" because I read that this template is used to build the search page, but in my case it seems that the template is not used because if I put this code on it :

```
<?php print "foo"; ?>

```

there is no changes on the search page.

Any ideas ?

# Answer
> 1 votes
I finally solve the problem. The problem was my implementation of the template page "page.tpl.php" because inside this I never call :

```
<?php print render($page['content']); ?>

```

As a consequence the results of the search were never shown, so I can't saw changes made in "search-results.tpl.php" ...

---
Tags: theming, search
---


# Question
Title: Why do I get a notice after migrating the site to a new server?
I am getting this error after migrating the site to a new server:

> Notice: unserialize() \[function.unserialize\]: Error at offset 2 of 23 bytes in includes/bootstrap.inc on line 478

I'm sure somewhere a setting has been corrupted; however, the site does appear to be functioning correctly. This error does return inconsistently, for anonymous users, so I do need to take care of it.
The error does not occur on the old server.

I have full control of the server, both the new and the old are Amazon EC2 VMs. The only major difference in the infrastructure is that the old server used a MySQL DB in the same VM, while the new server is using a MySQL Server in RBS.

I've read somewhere that this issue could be caused by the SQL export/import process, and something regarding UTF8. I wasn't able to garner anything I could mold into instructions to follow, but I have a feeling that's a path I need to take; I'm not really sure where to start.

# Answer
> 5 votes
The problem might be the error handling settings have changed on the new server. You probably have a corrupt variable in the variable table that can't be unsterilized. Try using the variable check module.

# Answer
> 3 votes
This is rather difficult to debug, but you might edit `includes/bootstrap.inc` where the unserialising happens – this is from the `variable_init()` function, where I assume the error occurs.

The original code looks like this.

```
while ($variable = db_fetch_object($result)) {
  $variables[$variable->name] = unserialize($variable->value);
}

```

Try altering it to something like this:

```
while ($variable = db_fetch_object($result)) {
  $variables[$variable->name] = unserialize($variable->value);

  if (!$variables[$variable->name]) {
    drupal_set_message('Possible error while decoding ' . $variable->name);
  }
}

```

There will be some false positives here, given that some values are actually FALSE or 0, but it should narrow the field, helping you to identify the broken variable. Then you can inspect the variables table in the database to find and fix it :)

# Answer
> 2 votes
I have had this happen when I migrate a database from staging to live and have to hand edit the database for paths, domain name, etc.

What is happens in the case is that the search-replace matches a string in the variables table, and alters the row. The problem is that length (the number after the `s:` doesn't get changes, so the unserialize fails.

If you go into the variable editor via the admin menu, you will likely see a blank entry where there was a real variable. Either update it here and save, or use a MySQL tool and fix the length in that row.

---
Tags: 6, migrations
---


# Question
Title: Privatemsg with user_relationships - views link → send a private message to use
Trying to output Views link - send a private message to a user. But its displaying nothing. Using privatemsg 6.x - 2.x Dev version and user\_relationships 6.x - 1.x

# Answer
solved problem with the code below:

```
<?php
$profile = content_profile_load('profile', $data->users_user_relationships_uid);
$url = privatemsg_get_link(array(user_load($profile->uid)));
print '<div class="pm">'. l(t('Send a private message to the author'), $url, array('attributes' => array('class' => 'lichnoe'))) .'</div>';
?>

```
> 1 votes

---
Tags: users, privatemsg
---


title: Most viewed count always zero

text:
# Question
Title: Most viewed count always zero
I try to adapt my Views block, I add Node Statistics: total views but it always show Zero, what am I doing wrong? sth is missing

# Answer
Verify if you have enabled “Count content views” within Statistics module configuration. (`admin/config/system/statistics` for D7)
> 4 votes

---
Tags: views, nodes
---


# Question
Title: How do I add an additional sidebar to a Zen sub-theme?
I want to add an additional sidebar to my zen based theme with fixed columns.
I added it to the theme info, and printed it in the page.tpl.php file, but I don't know how to configure its CSS files to make it look correct; I don't know how to make the content region expand to fill the available space when there is an empty region with no blocks in it like with Zen.

My theme contains 4 columns:

* left sidebar 1 (130 pixels)
* left sidebar 2 (255 pixels)
* content (509 pixels)
* right sidebar (130 pixels)

The total width would be 1024 pixels.

How can I do that?

# Answer
You can do it with preprocess function at template.php template. I will write you just one example, and you can adapt it for your needs.

1.At Your **template.php** template.

```
function yourthemename_preprocess_page(&$vars, $hook) {
  $page = $vars['page'];
// if only left sidebar is present
  if ($page['left_sidebar'] && !$page['left_sidebar2'] && !$page['right_sidebar']) {
    $vars['class_content'] = t('yourclassforcontentwithsidebar');
    $vars['class_left_sidebar'] = t('yourclassforleftsidebar');
 }
// if no sidebar is present
  if (!$page['sidebar_left'] && !$page['left_sidebar2'] && !$page['right_sidebar']) {
    $vars['class_content'] = t('yourclassforfullwidhtcontent');
 }
}

```

You can find more variations here: php logical operators.

2.At your **page.tpl.php**, at all regions where you want flexible width, put extra class, for example for left sidebar:

```
   <?php if ($page['left_sidebar']): ?>
      <div id="left_sidebar" class="sidebar <?php print ($class_left_sidebar);?>" >
        <?php print render($page['left_sidebar']); ?>
      </div>
    <?php endif; ?>

```
> 1 votes

---
Tags: 7, theming
---


title: Programmatically create taxonomy term

text:
# Question
Title: Programmatically create taxonomy term
How would you programmatically create taxonomy term? I wish to bulk create some in a custom module.

# Answer
> 12 votes
You'll want to use taxonomy\_save\_term. The array you pass in to taxonomy\_save\_term should look like this.

```
$term = array(
 'name' => 'Taxonomy Term 1',
 'vid' => 1, // The VID of the vocabulary this term should be saved under
 'description' => 'A description of this term', // Not required
 'weight' => 5, // Not required
);
taxonomy_save_term($term);

```

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


# Question
Title: Why does core use print rather than echo?
I've read somewhere, and I don't remember where, that `echo` is a more efficient way of outputting data then `print`.

Why does Drupal core use `print` so much? Is there any special reason behind that?

# Answer
> 25 votes
`echo` is only faster in academic environments. The difference is very marginal. A quick benchmark I just did: The time fetching one row from a table with more than 2000 nodes is 1 unit.

In order to get an improvement of 1 unit, I would need to replace about 3.700.000 (over 3 milion) `print` statements with `echo`. In other words, if you want performance improvements, this is hardly the place to start.

Seen that `print` can be used in a much wider range of cases then `echo`, the first has some advantages. It leaves you three options:

* Always use `print`
* Use `echo` where possible and fallback on `print`
* Use `echo` always and refactor your code if `echo` cannot be used, to use it

Drupal has defaulted on the first.

To answer your actual question as to why this was chosen: It was not. It simply grew this way.

---
Tags: theming
---


# Question
Title: Product catalog site (+ Store) - what strategy?
I'm creating a site in Drupal 7 with a 200-item product catalog. Currently the products have only informative pages for which I created a custom content type and taxonomy, but at some point, when the site owner gets ready, I may have to launch a store.

Taking into account that the only store available for D7 is Drupal Commerce in its beta (is my research correct?), I was wondering what strategy you would choose:

a) install beta of DrupalCommerce only for product information pages, turn off the shopping cart, just to save yourselves work later (migrating the product pages content)

b) go on populating the custom content type pages and wait for the DrupalCommerce to go into stable release?

c) split the site into two domains - informative (www.example.com) and store (store.example.com). This solution scares me off a bit in that it'd require maintaining about twice as much content in parallel - this always smells of errors and problems... OTOH, I could employ a Drupal-independent solution, such as PrestaShop.

Has anyone used the DrupalCommerce beta? Does it cause much trouble at this point?

Looking forward to hearing your insights.

Artur

# Answer
> 1 votes
Drupal commerce is not your only bet for a shopping site for Drupal 7, but it is the best one.

At this time of writing commerce is on beta-4 but it wont be long before rc-1 will be released. It's very stable considering that it's a beta release, so I wouldn't worry too much about that.

Talking about personal experience I have launched one site on commerce, which was launched when commerce was still in alpha, most likely the first production on commerce. So I have a good firsthand experience with running commerce in a production environment. Other than the pain of having to do my own upgradings from alpha to beta, commerce has been running very stable without any major problems so far.

Taking into account the above. I would personally go with option a):

* Install commerce
* Create products
* Create nodes with products reference to display the data
* Don't display add to cart form anywhere.

You might need to use a bit of time to setup commerce and products types, but it would allow you to quickly and easily convert the catalog to an actual shop and that save you a lot of headaches later on.

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


# Question
Title: How can I look up the number of items in a Drupal View?
I have several views on my Drupal site. I also have a page that links to those views. I would like to see the number of items (e.g. the number of pages) that are listed in each view:

* link to foobar view \[5 items\]
* link to other view \[0 items\]

Is there an easy way to do this. I suppose I will need embedded PHP for this, but I would like to avoid huge SQL statements embedded in my linking page.

# Answer
You can get the amount of results in a view using their API calls.

```
<?php
$views = view::load("viewname");
$view->set_display('default'); //optional, could be default, OR the name of a specific display
$views->execute();
echo count($views->result);
?>

```

I tested this on views 3 (the current version). For further reading, check out http://groups.drupal.org/node/10129. It's written for views 2, but still relevant.
> 3 votes

---
Tags: views
---


# Question
Title: How to toggle views filter when user click on tab?
i got 2 tabs and i want to achive this goal: once user click on tab 1 for example, its shows him a filters for tab1, if he clicks on other tab, its toggles the form to other "sory by" forms elements related to tab2, im using drupal 6 and jquery attached image for demo: http://www.media396.com/tmp/tabsexampleugly.png

# Answer
> 2 votes
You can define two displays in the View which both pull from the "Default" view and use the Tab option for the menu type. Then, override the exposed filters in each of the two displays. So on the display for Tab 1 have the Tab 1 related exposed filters, then on the Tab 2 display you can use your Tab 2 related exposed filters.

---
Tags: views, 6, ajax, javascript, nodes
---


# Question
Title: When using hook_form_alter() and additional submit functions, can one reference a php file for the submit callback?
The following code works.

```
function bleh_form_alter(&$form, &$form_state, $form_id) {

  switch ($form_id) {
    case "webform_client_form_13":
      $form['#submit'][] = 'bleh_community_submit';
      break;
  }
}

function bleh_community_submit($form, &$form_state) {
  // Do some stuff here.
}

```

However, is it possible to use code similar to the following one, where the form submit function calls a PHP script (e.g. bleh\_community\_submit.php) containing the form submission handler?

```
function bleh_form_alter(&$form, &$form_state, $form_id) {
  switch ($form_id) {
    case "webform_client_form_13":
      $form['#submit'][] = 'bleh_community_submit.php';
      break;
  }
}

// Separate .php file in the module directory with the
   additional bleh_community_submit function

function bleh_community_submit($form, &$form_state) {
  // Do some stuff here.
}

```

# Answer
> 1 votes
Why not do something like

```
require_once('bleh_community_submit.php');

```

then call the callback function as per normal?

# Answer
> 1 votes
No, there is AFAIK no way to do so. You pretty much have to leave these functions in the .module file (You could place them in a second file which you include always, but that makes no sense performance wise).

Drupal 7 initially had a class *and* function registry, and it automatically scanned all your files for classes and functions and included them automatically (given that you used drupal\_function\_exists() for all functions that might be in an include file. But that turned out to be too fragile, too hard to maintain and actually made the site slower when using a opcode cache like APC. So the function part was removed again.

---
Tags: hooks, forms
---


title: How do I find out a blocks ID?

text:
# Question
Title: How do I find out a blocks ID?
```
$block = module_invoke('menu_block', 'block', 'view', 26);
print $block['content'];

```

I am trying to use this code to print out a block, but I do not know how to get the ID for the last parameter.

# Answer
> 2 votes
You just need to look for the hook\_block() implementation done from the module for which you are invoking `module_invoke()`. The last argument in the function call you reported is the `$delta` parameter that is used from Drupal to identify the block within the module.

For example, looking at the code of forum\_block(), the part of the code that implement the "list" operation, 0 is the delta parameter for the "Active forum topics" block, and 1 is the delta parameter for "New forum topics" block.

The code you wrote in your question is invoking the implementation of `hook_block` made from a module whose short name is menu\_block (which means the function implementing the hook is `menu_block_block()`). If you meant to invoke the implementation of `hook_block()` made from menu.module, then the code should be the following one:

```
$block = module_invoke('menu', 'block', 'view', 26);
print $block['content'];

```

The function implementing `hook_block()` is menu\_block(). The values used as `$delta` from that function are the values of the "menu\_name" field used in the "menu\_custom" table.

# Answer
> 1 votes
How to insert a block into a tpl or into content programmatically with Drupal

See part "Where do I get that information for the block I am trying to call?" at bottom...

Since it was removed from site, I am putting text from cached history of site:

---

Where do I get that information for the block I am trying to call?

The easiest way is to go to the blocks page and to hover over the “configure” link. Without clicking on the link look in the bottom left hand corner of your browser (at least with Firefox) there you should see the URL that you would be taken to upon clicking. The important information that you need is in the last two elements of the URL. So if the URL of the link is admin/build/block/configure/jquerymenu/0 then the module that created that block is the jquerymenu block and the $delta (or block number) is 0.

So to review, the example code calls module\_invoke with the following arguments: 'jquerymenu', 'block', 'view', 0 . What this does is call the jquermenu module, it calls its hook\_block, tells it that it wants the information that is returned under $op = ‘view’ and that it wants only the information from the block with the $delta of 0.

Now that you have the $block (which is an array) you need to get the ‘content’ element from it by calling $block\[‘content’\]. You could also call the title by using $block\[‘title’\].

I hope that makes this code snippet make sense for you. You can find more information regarding module\_invoke at http://api.drupal.org/api/function/module\_invoke.

---
Tags: blocks
---


title: setting user edit permissions

text:
# Question
Title: setting user edit permissions
In each user's profile there's a user reference field called "other editors." For all the users selected in that field, they should be allowed to edit that user's profile.

My first thought was that there'd be some kind of user access hook which would let me allow/deny users based on some criteria, but the only thing I can find is `hook_node_access()`, which doesn't get called when viewing a user profile. Is there a hook I'm missing, or do I need to look elsewhere?

# Answer
As far as I can see, there isn't a module that allows to the users listed in a user reference field to edit the user account where the field is contained. You should write your own module.

The easier step is to alter the access callback for the user edit form, and use a function that checks the value of that field, comparing it with the value of the user currently logged in.

```
function mymodule_menu_alter(&$items) {
  if (isset($items['user/%user/edit'])) {
      $items['user/%user/edit']['access callback'] = 'mymodule_user_edit_access';
  }
}

function mymodule_user_edit_access($account) {
  // The argument is the user object for the user profile being edited.
}

```

The default access callback is `user_edit_access()` which should be always called to verify that the currently logged in user has still the permission to edit the user profile, even if the user is not listed in the user reference field; users with the permission to administer users should always be allowed to edit a user account.
> 3 votes

---
Tags: users
---


# Question
Title: Change language programmatically after login
I have a multilingual site and I want to change the language programmatically after user login to his own language to see all the content in his language.

How can I do this?

# Answer
It should not be necessary to do it from code, as one of the settings present in admin/config/regional/language/configure allows to set the language to the one selected from the users in their user profile settings.
> 5 votes

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


# Question
Title: How do I set allowed extensions for a managed_file form field?
Not having any luck find this in Drupal documentation or developer examples. I need to set a managed\_file form field to only allow zip files in a Drupal 7 custom module.

# Answer
> 48 votes
```
$form['picture']['file'] = array(
  '#type' => 'managed_file',
  '#title' => t('picture'),
  '#description' => t('Allowed extensions: gif png jpg jpeg'),
  '#default_value' => (isset($foo->picture->fid) ? $foo->picture->fid : ''),
  '#upload_location' => variable_get('picture_upload_location'),
  '#upload_validators' => array(
    'file_validate_extensions' => array('gif png jpg jpeg'),
    // Pass the maximum file size in bytes
    'file_validate_size' => array(MAX_FILE_SIZE*1024*1024),
  ),
);

```

# Answer
> 1 votes
I am not sure if you are using Drupal 6 or Drupal 7, but in Drupal 6 you would choose:

* **Admin** \> **Content** \> **Content Types** \> \[Your Content Type\] \> **Manage Fields** \> \[Edit your file field\] and look for the field setting of *"Permitted upload file extensions"*
* In that field, enter *zip*

Drupal 7 is probably similar. Look for *Content Types* under **Admin** \> **Structure**.

---
Tags: 7, forms
---


# Question
Title: How do I remove the tab provided by a third-party module?
I'm using the Guestbook module version 6x-2.0. How do I remove the "My Guestbook" tab on user profile pages?

# Answer
I solved this with the Tab Tamer module.

> Tab Tamer is an administration utility that provides easy re-ordering, hiding, and deactivation of tabs and subtabs.
>
> Tab Tamer makes use of Drupal's drag ordering, but degrades gracefully when javascript is disabled.
> 3 votes

---
Tags: routes
---


# Question
Title: microblog module - problem with max characters
On the left column on http://ruh.kz, you can the output of the Microblog module. This module uses the node title as a microblog entry; the maximum length of the title is by default 255 characters. In a microblog.module I've made the following changes:

```
function microblog_form(&$node) {
  $type = node_get_types('type', $node);

  $form['title'] = array(
    '#type' => 'textarea',
    '#title' => check_plain($type->title_label),
    '#rows' => 4,
    '#cols' => 30,
    '#required' => TRUE,
    '#maxlength' => 500,
  );

  return $form;
}

```

Now, when I'm typing, it shows only 450 characters or less. Why it happens?

# Answer
The title column of the {node} table is limited to 255 characters. Just because you change it in the UI doesn't mean that it can be saved like that in the database, unless you mess around with the database schema manually (and you should **not** do that).

I am not sure why that module is exposing itself as a node type, sounds rather strange to me. The only reason I can imagine is being able to rely on the node access system. But nodes are a rather heavy thing, there is a lot of overhead that seems unecessary to me for this use case.
> 2 votes

# Answer
Textareas do not support the #maxlength attribute see here, and also here.

As for why it's only showing 450 characters I'm not sure. Is there any JavaScript running from that module that restricts the amount of characters?
> 1 votes

---
Tags: nodes
---


# Question
Title: Custom install profile calls another install profile
I want to create a custom install profile that will switch on some modules. I want it to be based on the open atrium profile. Ie Run the OA install profile and then switch on some additional modules. Is this possible?

# Answer
The way install profiles work on Drupal 6, I don't think this will be possible. The modules that are installed are based of the dependency list in the .info file, and since you can't depend on an install profile you can't create that full attachment.

You could come far, by doing includes and callling the fuctions that would otherwise be called by Drupal though, but you would probably have to maintain your own .info file.
> 1 votes

---
Tags: 6, distributions
---


# Question
Title: How to prevent access to Views-only content?
When I'm developing sites in Drupal, I create various content types and taxonomy vocabularies that I use with Views to build displays. I might not ever want the nodes to be viewable in their own right or listed by taxonomy. Visitors may never figure out the URLs to do this, but I'd still like to lock this down.

I'm aware of various content access modules, and have considered theming taxonomy displays to simply say 'page not found'. But I've yet to find a simple solution, so wondered what other people use to prevent content from being viewed outside of a View?

# Answer
> 3 votes
In D6, I set the path alias for these content types to be

`no-view/[nid]`

and then use

```
function MYMODULE_init ()
{
    $path = drupal_get_path_alias(request_uri());

    if (strpos($path, "no-view/") !== FALSE) {
        drupal_not_found();
        exit;
    }
}
```

I think this will work as-is in D7, but I haven't tried it.

# Answer
> 1 votes
I'd just leave that content unpublished. You can surface it through the view, but no one else can access it.

# Answer
> 0 votes
Instead of denying access to the page it would be much simpler to let the view page use the actual path you don't want found. Then you could use path\_auto to make pretty urls.

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


# Question
Title: How do I create a dynamic link for a block?
I have two dynamic links that I want to put in a block, e.g. http://domain.com/series/naruto/addreview ("series" is the content type, and "naruto" is the node title), http://domain.com/node/add/album/1 ("1" is the node ID).

I want to change the URL depending on what node is being viewed. How can I do it?

# Answer
Since Drupal 6, you can use menu\_get\_object() that, with the default arguments, will return you the node object associated with the URL being visualized. This means that if the URL of the page being show is example.com/user/1, then the function will return `FALSE`; if the URL is example.com/node/1, example.com/node/1/edit, then it will return the node object from which you can get the information you need.

```
$links = array();

if ($node = menu_get_object()) {
  $links[] = url($node->type . '/' . $node->title . '/addreview');
  $links[] = url('add/album/' . $node->nid);
}

```

I took the assumption that the URLs you reported were URLs for the site where Drupal is running; in this case, url() is the function that generated URL for the Drupal site for which the code is running.

If you want to generate the `<a>` tags, then you should use l(). In this case, the code changes as follow:

```
$links = array();

if ($node = menu_get_object()) {
  $links[] = l(t('Add review'), $node->type . '/' . $node->title . '/addreview');
  $links[] = l(t('Add album'), 'add/album/' . $node->nid);
}

```

The code I reported is just an example; your code should do what you need to do with the value returned from the function.
> 2 votes

# Answer
You can get the node id from the url, since all nodes are displayed at node/\[nid\]. So if you in your block do

```
$nid = arg(1);
$node = node_load($nid);

```

You will get the node which has the title and the nid that you can use in your links. You would need to check that the block is on a node page as well by doing:

```
if (arg(0) == 'node')

```
> 2 votes

---
Tags: blocks, uri
---