# Question
Title: Subtheming -  what happens with parent theme's style.css
Trying to pin down in better details the steps involved when sub-theming, I can manage to get a sub-theme up in D, but there is a question I still have, concerning the style.css that is unfortunately not clear in my head. Is the sub-theme's style.css supposed to come from the parent theme or from subtheme?

The example I have show the subtheme as having *no* style.css. I tried the advice and flushed style.css, created an empty simpleblueMaster.css, added it to file\[\] in the .info file.

Author stated that css styles from parent theme will be loaded to be overridden if needed by sub-theme, and this totally makes sense. Unfortunately this is not the case on my installation and I would of liked to confirm the expected behavior.

THe author erases all css and images in his sub-theme, except if I do that in mine, nothing works. Parent theme's style.css does not seem to load and I assumed it should be. Anyone know what happens to style.css in sub-themes?

Or what could be preventing parent theme's style.css from not loading, if it should be?

Any insight appreciated, Thanks all!

**Update:**

Basically, there are 2 main ways (ok, probabably more I don't know of!) for a sub-theme to override the parent theme's css.

One involves copying the whole style.css in sub-theme and hacking on that. This works but a much cleaner approach as also mentionned in the answer is to *not have a style.css in subtheme*, and override with css in a sub-theme specific file. If there is a better way, I'd be very happy to know!

Thanks all

# Answer
You can choose which files you want to override in the parent theme... its as simple as including a copy of the files using **the same name** ex *style.css* just drop that anywhere inside your sub theme and tweak away.

Any file with the same exact names as files in the parent-theme will now default to the file that is in your sub\_theme. So... if you still want the original *style.css* to load, do not add it to your sub-theme at all & instead create a custom.css and any similarly named style codes will default to the copy in your sub-themes css files first then if needed the original.

To add from your comment below, do not remove the style.css in the main theme unless you are going to bring in all of its code into your custom file. What would be easiest for light edits would be to create a custom.css file in your sub-theme and only copy over the codes you need to tweak, if your going hog-wild just copy over the whole contents style.css

Hope that helps :)
> 3 votes

---
Tags: 7, theming
---


title: Relation with one content type to other

text:
# Question
Title: Relation with one content type to other
How can I give relation once content type to other. Eg If I have a product and the product sub items. I need to make a product content and a product\_sub\_item content type. Also need to select the product while creating the sub item. How to achieve this relation

# Answer
> 0 votes
Using node\_references cck module we can achive this. In manage fields need to create a new field and select the type node reference and the parent type to be referenced

# Answer
> 2 votes
Check out the module "References". It allows you to create a field where you can reference on other content types and nodes.

# Answer
> 1 votes
In addition, you might also want to take a look at the module Relation which looks to have a brighter future in terms of active maintenance and integration with other Drupal contribs. Another module that will come handy is Rules.

For both modules there are good introductory screencasts available by Johan Falk on http://dev.nodeone.se/sv

# Answer
> 1 votes
I discuss some of the different options available here: http://drupal.org/node/1293792#comment-5275780

This discussion is particularly relevant if you care about back-references. For your use case, perhaps references & cnr would give the best user experience.

---
Tags: nodes
---


# Question
Title: Varnish causes page load time to increase
I am running Drupal 6 with pressflow on Ubuntu 11.04. I installed Varnish http accelerator and Varnish Drupal module. The Varnish is running and the Varnish page at admin/settings/varnish confirms this.

I measured the Time per request before and after installing Varnish with apache bench like this:

```
ab -n 10 http://my-site.local/

```

Installing varnish actually increases the Time per request from about 1 second to 1.3 seconds so there must be something wrong in my configuration of Varnish http accelerator.

In php.ini I have set a memory\_limit of 512M.

While configuring Varnish to talk with Drupal I followed these instructions given in http://groups.drupal.org/node/25425.

Here is the contents of my /etc/default/varnish

```
 # Configuration file for varnish
    #
    # /etc/init.d/varnish expects the variables $DAEMON_OPTS, $NFILES and $MEMLOCK
    # to be set from this shell script fragment.
    #

    # Should we start varnishd at boot?  Set to "yes" to enable.
    START=yes

# Maximum number of open files (for ulimit -n)
NFILES=131072

# Maximum locked memory size (for ulimit -l)
# Used for locking the shared memory log in memory.  If you increase log size,
# you need to increase this number as well
MEMLOCK=82000

# Default varnish instance name is the local nodename.  Can be overridden with
# the -n switch, to have more instances on a single server.
INSTANCE=pressflow

# This file contains 4 alternatives, please use only one.

## Alternative 2, Configuration with VCL
#
# Listen on port 6081, administration on localhost:6082, and forward to
# one content server selected by the vcl file, based on the request.  Use a 1GB
# fixed-size cache file.
#

DAEMON_OPTS="-a :80 \
             -T localhost:6082 \
             -f /etc/varnish/default.vcl \
             -u varnish -g varnish \
             -S /etc/varnish/secret \
             -s malloc,256M"

```

And here is the statistics Varnish module gives after running apache bench few times:

```
      41  Client connections accepted
      41  Client requests received
      29  Cache hits for pass
      12  Cache misses
      41  Backend conn. success
      12  Backend conn. was closed
      12  Backend conn. recycles
       1  Fetch with Length
      11  Fetch chunked
      29  Fetch wanted close
      11  N struct sess_mem
       2  N struct object
       4  N struct objectcore
       4  N struct objecthead
      10  N worker threads
      10  N worker threads created
       1  N backends
      10  N expired objects
      40  Objects sent with write
      41  Total Sessions
      41  Total Requests
      29  Total pass
      41  Total fetch
   16495  Total header bytes
  645600  Total body bytes
      41  Session Closed
       1  Session Linger
    3776  SHM records
     899  SHM writes
      53  SMA allocator requests
       4  SMA outstanding allocations
   19984  SMA outstanding bytes
 5254284  SMA bytes allocated
 5234300  SMA bytes free
      41  Backend requests made
       1  N vcl total
       1  N vcl available
       1  N total active purges
       1  N new purges added
      41  HCB Lookups without lock
       3  HCB Lookups with lock
       3  HCB Inserts
     922  Client uptime

```

# Answer
I cannot comment yet as a new user so here goes my response.

For starters 1 second to 1.3 seconds is not all that much of a difference, and you dont seem to have an overabundance of misses so its doing its thing. Run some tests that simulate a lot of page requests on the same content and watch the hits/misses. Also did you test again without Varnish on the same site?

One other thing is to be sure you've properly sized the Varnish storage to match your servers available resources. This being off too much can drag the system for obvious reasons.

Any reason your not using Drupal 7? Pressflow 7 is available now too.

There is also the option to use Boost + Varnish. http://www.trellon.com/content/blog/boosted-varnish-high-performance-caching-made-easy
> 1 votes

---
Tags: proxies
---


# Question
Title: Best approach to inject variable data into JavaScript files?
I'm looking for a good approach to manipulate some JS code from within a module call. (Using Drupal 6.)

I have a set of JavaScript functions I need to add to a page. (Regular JavaScript, no jQuery.) Unfortunately they rely on some variables from the page they are shown on. So my current approach is to generate all the JavaScript from within PHP code which results in a whole lot of escaped strings like `$output .= ' var url = "'. $url . '";' . "\n";`, which is not so nice after 20-30 lines of code.

So I would like to move all the JavaScript code into it's own `.js` file, and find a way to inject my variables. So far, the only solution I could come up with is putting it in a temporary file, read that, modify and save it to the `/files` directory. But is there another, more preferred way?

# Answer
> 6 votes
Drupal have a javascript array for save settings and variables, take a look here:

http://api.drupal.org/api/drupal/includes--common.inc/function/drupal\_add\_js/6

Check the "settings" option in that page.

A example could be:

```
$my_module_variables = array(
  "url"  => "http://google.com",
  "name" => "this is a variable"
);

drupal_add_js(array("my_module_vars" => $my_module_variables),'settings');

```

And for use it in your javascript files you can do:

```
console.log(drupal.settings.my_module_vars.url);
//will print http://google.com
console.log(drupal.settings.my_module_vars.name);
//will print "this is a variable"

```

In this way you can set javascript vars without need print javascript code, only using a php array.

---
Tags: 6, javascript
---


# Question
Title: How do I print a username of current profile?
I am making a profile page for users on my site, and would like to print out their username. If I do `print $user->name` it will just print out the username of the currently logged in user, I want the username of the profile I am looking at. Thanks.

# Answer
Modules can implement `hook_username_alter()` to alter the displayed username of any user, so you cannot simply load a user account object with `user_load()` and print its `name` property. Instead, the `format_username()` function should always be used.

In the `user-profile.tpl.php` template, you should be able to retrieve the viewed user account object in `$elements['#account']`. If the code is executed in the context of an user page (ie. path starting with `user/%nid`), you can always retrieve the currently viewed user with `menu_get_object()`.

```
$account = $elements['#account'];
// OR
$account = menu_get_object('user');
if ($account) {
  $username = format_username($account);
}

```
> 2 votes

# Answer
It depends on how you build the profile page (which modules you use), but usually you will get the user info on profile templates by accessing `$account`, while `$user` is the logged in user.

So, in short, `$account->name` should be what you are after. Again, this depends on how you create the profile page. For a profile page built with Views, this would not help, but you could add the name in the View itself.
> 2 votes

# Answer
The way I figured out is to use `print $elements['account']->name`. I found this out with the help of the Devel module, using `dsm($elements)` in the user-profile.tpl.
> 0 votes

# Answer
You write that your site "requires more complexity on the profile page than the default offers", but I still wouldn't consider that a reason to not use the user/\[uid\] page. Allow me to explain why.

A module like RealName gives you a lot of control over the displayed user name, not just on the profile page, but everywhere in your site. That means it's a more consistent solution than template-specific code.

The Field system in D7 provides a lot of options to further customize the default profile page, especially when combined with even more flexible and powerful modules such as Entity Views Attachment and Display Suite.

It's not my goal to convince you, I just want to make sure you have all information you need to choose your optimal solution. Hope that helps.
> 0 votes

# Answer
I guess it should be simple enough with the use of user\_load(), and using the loaded object to print the name.
> -1 votes

---
Tags: 7, users
---


# Question
Title: How to programmatically list users with a certain role?
What is the preferred way of programmatically generating a list of users with a certain role?

(I know how to do it with a database query, but surely there's a higher-level method.)

# Answer
In Drupal 7, `user_load_multiple($uids = array(), $conditions = array(), $reset = FALSE)` will load the user details for the given user IDs. In Drupal 6, there isn't that function, but you can use `$user = user_load(array('uid' => $node->uid));`.
> 3 votes

# Answer
```
SELECT u.* FROM users u,role r, users_roles ur WHERE r.name="authenticated user" AND r.rid=ur.rid AND ur.uid=u.uid;

```

try this query.
> 3 votes

# Answer
Umm? Create a view of type USER, filter on USER ROLE, and have field USER NAME?
> 1 votes

---
Tags: 6, users
---


title: How do I use hook_views_query_alter()?

text:
# Question
Title: How do I use hook_views_query_alter()?
Following what reported in the documentation for hook\_views\_query\_alter(), I created a file named `alterform.views.inc` and put it into an enabled module called `alterform`. I added the following code in `alterform.views.inc`.but it doesn't work.

```
function alterform_views_query_alter(&$view, &$query) {
  switch($view->name) {
    case 'myViewName':
      echo 'test test'; // test
      $query->orderby[0] = "FIELD(node.type, 'story', 'page', 'productTypeC', 'productTypeD') ASC";
      $query->orderby[1] = "node_title ASC";
      break;
  }
}

```

why doesn't it output "test test"? What's wrong with my code?

there is still no output of test and views. what's wrong with my code? thank you

# Answer
Right. In order to "do" anything with views in a module, you have to implement hook\_views\_api. Without this, your module won't be recognised by Views, at all, ever (AFAIK).

Please add the following to your module code:

```
/**
 * Implementation of hook_views_api().
 */
function alterform_views_api() { // your module name into hook_views_api
  return array(
    'api' => 2,
    // might not need the line below, but in any case, the last arg is the name of your module
    'path' => drupal_get_path('module', 'alterform'),
  );
}

```

This should fix it so your module is at least recognised, then you can start debugging it :)

A good way to start debugging a view (i.e. a baby step) is to put `dpm($view);` right at the start of the views function you're implementing. In most cases, that will dump info onto the screen that will help you see where you're at. Would suggest doing this with devel.module installed/switched on.

Edit: This assumes Views 2 and Drupal 6. You'd best ask around if those aren't your weapons of choice.
> 22 votes

# Answer
you can test 3 things:

* clear your cache
* download and enable Devel,
* use `dpm()` instead of `echo()`
* test `$view->name` with `dpm()`
> 4 votes

# Answer
You need to put the yourmodule.views.inc file in the module directory, not within a subdirectory, or Views cannot automagically pick it up.
> 3 votes

# Answer
```
    $query->orderby[0] = "FIELD(node.type, 'story', 'page', 'productTypeC', 'productTypeD') ASC";

```

should be

```
    $query->orderby[0]['field'] = "field_name ASC";

```
> 2 votes

# Answer
if you are using a directory for yourmodule.views.inc, you need to mention its path in the module file, using code similar to the following one:

```
    'path' => drupal_get_path('module', 'mymodule') . '/subdirectory/';

```
> 1 votes

---
Tags: 7, views, hooks
---


title: CCK fields revisions (D6)

text:
# Question
Title: CCK fields revisions (D6)
I have a node type with its revisions set to ON I am not sure this is a bug on my copy or Drupal 6 doesn't save any revisions for CCK fields in the node and only does that for title and body?

# Answer
CCK stores values against the vid, so you should be able to see the history of your fields (you can look in tables like `content_%` to check that the raw data's there). Otherwise a revert would be fairly useless for most situations involving fields. Can you confirm the results of the following?

1. Create new content type with revisions turned on.
2. Add text field.
3. Create a node of this new type (add some text to the field).
4. Edit the node and update the title, body and field.
5. Revert the node to its first state.
> 1 votes

# Answer
Drupal 6 does not save CCK field data in node revision saves, just the Title and Body as far as I know.

edit: finally got to testing - CCK field data does indeed get saved in Drupal 6. Are you sure you're creating a new revision?
> 0 votes

---
Tags: entities, nodes
---


# Question
Title: How to connect to drupal 7 using web service?
can I connect to my Drupal website using web services and pass a variable (with post method) to it? I know that forms in Drupal actually have hidden elements so that it is not possible to submit the form from external sources.

There is also a service module but I don't think I can achieve what I am trying to do with it.

The following is what I am trying to do with Drupal:

When I connect to www.drupal-site.com/web-service (*web-service* is just an example), I would like to be able to post variables to it and perform complex database queries. I would also like to return the result of the queries in json (using echo maybe). I would also like to be able to remove the headers and footers of my drupal site.

I really need some direction on how this can be achieved.

# Answer
Your use case can be achieved using Services module easily.

All you need to do is write a hook\_service()

refer http://drupal.org/node/118126 Or just look into the services module's any child module, may be user\_services.

Do this,

1. Write a service that exposes all your query parameters as fields.
2. Accept these parameters into your web service callback and perform your business logic.
3. Return your results, this is just a return statement, no JSON conversion here. ex: return $output. //$output contains your array or data structure that you have as a result of your queries.

Now, how to convert the data to JSON. ?

Services module will provide you intermediate servers, XML-RPC, JSON. (these are by default, there are more avaialable on drupal.org). These servers function as end points to whom you can connect using external applications or entities. ex: http://www.domain.com/services/json.

Thats it, the flow will be,

1. You connect to the endpoint, URL http://www.domain.com/services/json. Pass the data in JSON.
2. the JSONserver will convert that into PHP and will pass it to your web service callback.
3. You do the processing and return the data to the web service in PHP.
4. The server converts the data into JSON again.
5. This is handed over to the HTTP request that requested the processing in the first place.
> 2 votes

# Answer
It is possible to submit a form from another site out of the Drupal, this is the code I use on an external site to display a Drupal login form and it works fine, after submitting the form, the user will be logged-in on the remote site.

```
<form id="loginForm" action="http://mydrupalsite.com/node/60?" method="post" name="login">
  <div class="login-datas">
    <div class="login-field">
      <label for="name">Login: </label>
      <input type="text" name="name" id="name" class="txt">
    </div>
    <div class="login-field">
      <label for="pass">Password: </label>
      <input type="password" name="pass" class="txt" id="pass">
    </div>
  </div>
  <div class="login-send">
    <input name="Submit" type="submit" id="submit" value="Enter">
    <input name="form_id" id="edit-user-login-block" value="user_login_block" type="hidden">
  </div>
</form>

```
> 0 votes

---
Tags: services
---


title: Inverse of Drupal contextual filters?

text:
# Question
Title: Inverse of Drupal contextual filters?
Does anyone know how to / know if Drupal 7 Views 3 is capable of using the inverse of a contextual filter to display results?

Basically I want to display a result not involving the logged in user ID. I can get the view to display only the data associated with the user ID using the contextual filter. I just want the opposite of it. I have tried using the current user filter and checking no for the particular relationship but was unsuccessful. If anyone can point me in the right direction that would be greatly appreciated.

Unfortunately no.. This helped but this does not establish the relationship I need. The data is in two tables. I basically need query like this:

(the first select grabbing all the nid's available)

```
SELECT DISTINCT n.nid
 FROM node n
  WHERE n.status = '1'
    AND n.type = 'job'
    AND n.nid not in

```

(the second select grabbing all the nid's that are associated to a specific uid)

```
(SELECT DISTINCT n2.nid
  FROM node n2
  LEFT JOIN applicationsTable ON n2.nid = applicationsTable.nid
   WHERE n2.status = '1'
    AND n2.type = 'job'
    AND n.nid= n2.nid
    AND applicationsTable.uid ='999');

```

Oddly enough my query doesn't work as a straight db call so feel free to correct me on that too :P

# Answer
In settings of the User ID contextual filter, you can exclude this argument/contextual-filter. Expand the last field-set and you'll see it. isn't it what you need to do ?
> 1 votes

---
Tags: views
---


title: Can I disable input filters in a view?

text:
# Question
Title: Can I disable input filters in a view?
I have created an admin-only view on a certain content type where we want to review the body content all in one place. The problem is that the input format for these nodes does some additional glossary markup etc. and we want to see the raw body content.

Is there a way to disable or change the input format for this view without changing it for each node?

# Answer
I hope i understand the question correctly:

In views you can check the option "**Strip html tags**" in options.
> 1 votes

# Answer
I dont' think this is possible via the UI. You could use tokens and a PHP field or some custom theming to do it.

I would probably do custom theming or a preprocess function although I understand those are somewhat advanced topics.

This might be a helpful resource for you: http://evolvingweb.ca/story/theming-views-drupal-templates-and-preprocess-functions
> 1 votes

---
Tags: views
---


# Question
Title: Drupal isn't picking up my custom action
I wrote a couple of actions for my Drupal page, but for some reason, Drupal isn't picking them up... Nevertheless, it's a copy/paste of the Drupal.org website...

```
   function publicatie_omgeving_action_info() {
      return array(
        'publicatie_omgeving_publish_action' => array(
          'type' => 'node',
          'label' => t('A'),
          'configurable' => FALSE,
          'behavior' => array('changes_property'),
          'triggers' => array('comment_presave', 'comment_insert', 'comment_update'),
        ),
        '_mijn_organisatie' => array(
          'type' => 'user',
          'label' => t('AA'),
          'configurable' => TRUE,
          'behavior' => array('changes_property'),
          'triggers' => array('comment_presave', 'comment_insert', 'comment_update'),
        ),
        'publicatie_omgeving_menu' => array(
          'type' => 'comment',
          'label' => t('AAA'),
          'configurable' => FALSE,
          'triggers' => array('comment_insert', 'comment_update'),
        ),
      );
    }

```

I only get the first one, `A`. Is there something wrong with this code?

# Answer
> 1 votes
It's my understanding that, by convention, an action function should start with modulename\_ (to prevent namespace collisions) followed by a short description of what it does, eg publish, but in order to be found at all, it needs to end in \_action.

So try naming all of your functions:

```
publicatie_omgeving _ SOMETHING _ action

```

and see what happens.

---
Tags: actions
---


# Question
Title: jquery in select (views module) -- change submit click to link
This is regular Views selector exposed to user:

---

---

This is a part of block, attached to Panel on main page. I want to create links "show expiring" and "show latest" but I need to learn what function is fired while clicking Apply. Anyone knows where can I find it? Debugging it with Chrome is tricky, a lot of JS files…

Is there a way of previewing all javascript acitvity?

# Answer
> 1 votes
The image above shows an exposed form generated by Views in the file `views_plugin_exposed_form.inc.` Line 242 in the function `exposed_form_alter` reads `$form['#attached']['js'][] = drupal_get_path('module', 'ctools') . '/js/auto-submit.js';` so the js looks to be in ctools however, I believe that script is being called whenever a change is made on the form. If you want to modify the form note that views is managing the form in this file. Selecting the 'Apply' button calls `exposed_form_validate` and `exposed_form_submit` which are tapping into the Drupal form API (php not JS). Go to api.drupal.org to find out more about the various hooks available to modify the forms

---
Tags: views, javascript
---


# Question
Title: How do I go about telling Captcha that my form exists?
I've got a drupal situation where I want to add reCaptcha to a custom form (built in an add-on module). You can see from the captcha admin page that there is a list of forms that I can dynamically add captcha to... but my problem is that the form I created in the add-on does not appear in this list.

I'm sure I'm missing something (perhaps in the `myform_block_info` function?)

Does anyone know what hook I'm looking for? Have a working example?

# Answer
> 1 votes
This was embarrassingly easy. See that box at the bottom of the table? Put your form ID in there. "myform\_form"

---
Tags: forms, captcha
---


# Question
Title: What to do when a theme doesn't show up in the enabled or disabled themes?
I am moving from one server to another a Drupal 7 site. I have Drupal set up on the new server and modules installed. However, I would like to enable a theme (shoppica, in particular). I have followed the instructions in placing the files in ./sites/all/themese/shoppica, however it does not show up in the list of themes. What other steps am I missing in order to get this theme to show up?

# Answer
I would double check that all the theme files crossed over. As long as there is a .info file in the theme folder, it should show up in your drupal site.
> 1 votes

---
Tags: theming
---


# Question
Title: How to format 'node reference' field values from the Views module
How can I format the output of a 'node reference' field that is generated using a View?

Currently it's formatted as (See 2nd graphic): **"FirstName - Lastname Pagetitle"**

I'm trying to change that to: **"Firstname Lastname"**

Where do I modify this fields format?

Here is my current view:

Here is the 'node reference' output:

# Answer
Interesting. Initially it would appear that the "Pagetitle" is being stored in the Last Name field. However assuming that it's not, you can use the devel\_themer module to find out what and where is theming that field's output. The culpript could very likely be inside one of your own custom Views templates or theme function override. If not, devel\_themer should point you in the right direction.
> 2 votes

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


title: HIPAA compliance

text:
# Question
Title: HIPAA compliance
I'm building an application that needs to be HIPAA compliant. I've already gotten a HIPAA compliant server through Rackspace. I'm wondering whether I still need to use encryption/decryption modules such as these: http://drupal.org/project/aes and http://drupal.org/project/encrypt. How safe are these? I've looked into this company that encrypts your entire database: http://www.gazzang.com, but I don't see why I'd need to do that if I can just encrypt the necessary columns of my database. Can you guys shed some light on this

Thank you

# Answer
As of this writing the AES module has a security flaw that exposes the password on the 'My Account' page when JavaScript is disabled (read: not so HIPAA compliant). For that reason I would either not use it, or seriously consider fixing that issue and contributing a patch to the D.O. community ;)

Both modules encrypt a string of text that you pass to their functions, however, they do not handle the storage of the ciphertext. You would still be required to write a custom Drupal module that stores let's say the contents of a Drupal field into the database using the functions provided by these modules.

I would be seriously concerned about the performance characteristics of encrypting the entire database. e.g., I wouldn't use it without doing some performance benchmarks first.
> 2 votes

---
Tags: 7
---


title: Drupal 7.10 upgrade theme problems

text:
# Question
Title: Drupal 7.10 upgrade theme problems
I was running with Drupal 6.22 and tried doing an upgrade to drupal 7.10. The upgrade reported everything was successful.

My problem is that I was previously using a theme called 'contrast'. I thought that I had disabled it, but it now has references to that theme.

How can I get around these errors?

I tried moving garland into the all/themes folder and renaming it to contrast, but that only created another set of errors.

```
Notice: Undefined variable: site_name_and_slogan in include() (line 14 of   /mysite/sites/all/themes/contrast/page.tpl.php).
Notice: Undefined variable: site_name_and_slogan in include() (line 14 of /mysite/sites/all/themes/contrast/page.tpl.php).

```

# Answer
Chose another default theme, disabled & deleted the 'contrast' directory. Clear your cache to make sure, but there should be nothing trying to reference a theme that isn't there.
> 1 votes

# Answer
Configuration -\> Development -\> Logging & ERrors

Set error messages to display: Errors & warnings

The, notices will not appear.

Notices are a good thing, the best option is to fix them in the theme, or have them fixed, but if that's not an option, my instructions above will hide them. As a developer, notices will catch little mistakes right away, which otherwise may have caused a lot more debugging time later.

Notices in PHP environments are often hidden, and it's not that big of a deal to hide them. Drupal 7 shipped with them forced on by default though because it looked bad when users would enable notice reporting on D6 and earlier because lots of modules weren't tuned up to handle notices.

Without seeing your theme, most likely the change is something like changing: `if ($site_name_and_slogan)` to `if (isset($site_name_and_slogan)`

Basically variables need to be defined before you can do anything with them.

Examples:

```
<?php

// throws a notice if $foo was never defined above it
if ($foo) {
}

// will not throw a notice, even if we did not define it above
if (isset($foo)) {
}

// will throw a notice if we never defined what $output is
print $output;

// will not throw a notice
$output = 'hi';
print $output;

```
> 0 votes

---
Tags: upgrading
---


# Question
Title: How do I save the user submitted values of a multi-step node editing form in the database after last step submission?
In Drupal 7, I am trying to programmatically create a custom content type. I have defined my custom content type implementing `hook_node_info()`.

For my node editing form, I am using `hook_form()` and defined my custom node's title here. I used `hook_form_alter()` to convert my node editing form into a multi-step form, where I used the following code.

```
if ($step == 4) {
  $form['actions']['finish'] = array(
    '#type'   => 'submit',
    #value'  => t('Submit'),
  );
}
// Add validation handler.
$form['#validate'][] = 'mymodule_form_validate';
// Add submission handler.
$form['#submit'][] = 'mymodule_form_submit';

function mymodule_form_validate($form, &$form_state) {
  drupal_set_message(t('validating multistep form'));
}

function mymodule_form_submit($form, &$form_state) {
  switch($form_state['triggering_element']['#value']) {
    case $form['actions']['next']['#value']: // if 'Continue >>' is clicked.
      $step++;
      $form_state['rebuild'] = TRUE;
      break;
    case $form['actions']['finish']['#value']: // if 'Submit' is clicked.
      $form_state['rebuild'] = FALSE;
      // To Do.
      // Store the values from the form in the database here.
      drupal_set_message(t('Your form has been submitted'));
      break;
  }
}

```

My multi-step form is working great, but I am stuck on my last step of the form, where I save the user submitted values in the database. I am not getting any reference on this topic. I am looking for information on how to save my this node in the database, what hooks to use, and some more details. Please guide me in the right direction.

# Answer
> 1 votes
After you have constructed your custom node object by stepping through your multi-form, use the node\_save() function. That will write your node to the database.

To see how Drupal creates and saves it nodes you can take a look at node\_add(). Hope that helps a little.

---
Tags: 7, forms
---


title: What does URI mean in drush site alias?

text:
# Question
Title: What does URI mean in drush site alias?
I want to create drush site aliases for my sites in order to use rsync. However, I'm not sure what URI means. Is it the (sub)domain I have assigned to my site, or the sites/ folder it is in? If it's the sites/ folder and I am using sites/default , does that make the URI "default"?

```
$aliases['demosite.drupal7.local'] = array (
  'uri' => 'demosite.drupal7.local',
  'root' => '/var/www/drupal7',
);

```

### Update

I found my answer in drush/examples/example.aliases.drushrc.php.

> 'uri': This should always be the same as the site's folder name in the 'sites' folder.

# Answer
> 6 votes
Okay, I wrote that line you're quoting above ("uri': This should always be the same as the site's folder name in the 'sites' folder."), but unfortunately that is an oversimplification that is not always correct, especially when using a Drupal 7 site.

This is what I say about "uri" in the Definitive Guide to Drupal 7:

> The URI used on the command line should be the same as when the site is being accessed from a web browser. It is also possible to use the name of the folder that contains the settings.php file for that URI (e.g. --uri=default). This works, and is, in fact, equivalent to \[back reference to an example that runs core-status using the cwd to select the Drupal site\] in terms of the site URI that Drush will use when calling in to Drupal; you can confirm this by comparing the output of the "Site URI" line in \[back reference to same listing\] with this output. Having a correct site URI is not always required, but some modules might need it if, for example, they are generating absolute URLs or making HTTP requests back to the same host; it's therefore advisable to set a correct URI whenever possible.

This quote is 100% correct for Drupal 7, but the situation is slightly more complicated with Drupal 6. In D6, the value of the --uri option (and correspondingly, the URI used to access the site from a browser), will sometimes be written into the database. For example, if your settings.php file is stored at sites/mysite.org/settings.php, and your URI (from the browser) is http://mysite.org, then you might in some circumstances find paths "sites/mysite.org/files/myuploadfile.png" in the database. The URI from the browser is converted to the name of the folder containing settings.php before being used by Drupal (for some uses), whereas the --uri option passed to Drush is always used as-is. Because of the fact that your site folders are written to the database, it's often handy to continue to use the sites folder "mysite.org" for your dev site "http://dev.mysite.org", and of course there's always the possibility that your sites folder is called 'default' (often a good idea on D6). So, while --uri=dev.mysite.org and --uri=mysite.org and --uri=default may will all work (presuming a site http://dev.mysite.org which is a dev copy of http://mysite.org with its settings.php file in the default folder) to select the site for Drush, there are some edge cases where --uri=default is better in that the other options will not match what your modules are seeing when the same code. On the flip side, there are also other edge cases where --uri=mysite.org is what you need to align your runtime variables with what your module will see with the browser (c.f. above dgd7 quote). So the truth of the matter is that there is no value that is absolutely best for D6. The simplified advice you quoted above was used in the example file because things can really go wrong if you use --uri=mysite.org instead of --uri=default, AND a path is generated and written to the database, AND you migrate your database to another instance of the site, breaking the path.

For D6, the most pragmatic thing to do would be to name your sites folder 'sites/mysite.org' instead of 'sites/default' (and make sure that it is also 'sites/mysite.org' for http://dev.mysite.org).

I changed the advice in examples/example.aliases.drushrc.php as follows:

> * 'uri': In Drupal 7, the value of --uri should always be the same as when the site is being accessed from a web browser (e.g. http://mysite.org, although the http:// is optional). In Drupal 6, the value of --uri should always be the same as the site's folder name in the 'sites' folder (e.g. default); it is best if the site folder name matches the URI from the browser, and is consistent on every instance of the same site (e.g. also use sites/mysite.org for http://dev.mysite.org).

# Answer
> -1 votes
Found my answer in drush/examples/example.aliases.drushrc.php : "uri': This should always be the same as the site's folder name in the 'sites' folder."

---
Tags: drush
---


# Question
Title: Programmatically adding and removing users to a user reference field?
I would love to see some code samples for this task. I have found this example already http://www.midwesternmac.com/blogs/jeff-geerling/programmatically-adding-or, but it is unclear why that example uses node language for array key, and based on the comment the user removal could be better as well.

# Answer
> 3 votes
It should be pretty simple:

1. Load the node you are trying to modify using node\_load().
2. Look for the user referencing field.
3. Modify the user referencing field.
4. Save the node using node\_save().

I wrote those steps before looking at the example you linked, but after looking at it, it pretty much follows those steps. To answer your question regarding the language: The reason for that is that you are not supposed to hardcode the language key directly. If I am not mistaken, in Drupal 7 this key is something like 'und', but when you use a language on a node this key changes dynamically to something like 'es' or 'en'. If you hardcode the language key, then your code will be translation incompatible. Even if you don't use translation, it is still consider a good Drupal programming practice not to hardcode that language key ;)

If you follow the code that it is given in your link you will be fine.

---
Tags: 7, users
---


title: Cron fails when calling hook_node_view

text:
# Question
Title: Cron fails when calling hook_node_view
When running cron manually via GUI the cron starts to run but I have traced down the failure to hook\_node\_view in one of my modules.

The code is:

```
if ($node->nid == 47)
{
     //THIS CODE IS HAPPENING, but HOW in hook_node_view when running cron?
     drupal_goto('node/48');
}

```

# Answer
When you implement `hook_node_view()`, don't forget to check if you're really displaying the node using this code:

```
function MYMODULE_node_view($node, $view_mode, $langcode) {
  if ($view_mode == 'full' && node_is_page($node)) {
    //Do something...
  }
}

```

This should correct your errors.
> 2 votes

# Answer
I am not positive about Drupal 7, but I think I had a similar problem with Drupal 6.

My recollection is that the node is "viewed" when it is being indexed by the search module.

You can try disabling the search module, and then run cron.
> 0 votes

---
Tags: 7, cron
---


# Question
Title: How to create a view that searches nodes and users at the same time?
I'm creating a custom search to my site using Views.

I want to search both nodes and users at the same time, with exposed filters like this:

```
[ ] events
[ ] bands
[ ] products
[x] users

```

But when creating views I have to specify if I want to list nodes, or users, or files etc.

How can I search through two tables at same time?

# Answer
You can't really do what you ask the way views is built, not without overriding a lot of classes etc which probably would be more complex than building it all by hand.

A simple workaround would be to create two views and thus have two forms. Then you can show the form for user search when user is selected and node search when one of the node types is selected. That would also allow you to create custom filters for the user/node search, like date posted or last login.

You can use some simple JS to control hide/display of the forms.
> 3 votes

# Answer
If this is really your requirement you could do something with solr potentially. This can search different types at once as they are stored in one data source.

However this is non trivial to set up in the first instance and you would need to do a fair amount of custom coding to get it to work how you like.
> 0 votes

# Answer
There's a Drupal 5.x / Views 1.x module called "Views Union", which can combine the results of multiple Views queries. But it hasn't been touched in 3 years (and with Views 1.x, you could only query nodes, not users).

There are currently two sandbox projects for providing Views Union-like functionality:

Consider giving these a try, and providing feedback on http://drupal.org/node/1101938 and http://drupal.org/node/275162 so that one can be appointed as the successor to `views_union`.
> 0 votes

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


# Question
Title: How can I keep the current language prefix for internal link?
If the links are menu items the destinations of the links are always with the language inherited from the previous pages. But how can I do the same thing for the internal links using ordinal `<a href="">` tags? I have some internal links in some blocks but those links can't keep the language prefix the use is currently viewing of. For example:

`<a href="/about-us">` takes the user to `my-site.com/about-us` though the user is currently viewing the page with the language prefix "jp" which is Japanese. But I would like to make the destination of the link to `my-site.com/jp/about-us`.

I've been searching for the solution for days but no luck so far. I have tried pathfilter and pathologic but they don't seem to work for this purpose.

# Answer
> 2 votes
Generally you want to use Drupal core functions as much as possible. Both the l() and url() functions fit perfectly your need. The difference between them is that l() returns an anchor tag, and url() returns a URL without HTML.

As a perk, the l() function allows you to specify the language for the link. Example:

```
<?php
$options = array('language' => 'jp');
$link = l('About Us', 'about-us', $options);

```

---
Tags: uri, navigation
---


# Question
Title: How to access Drupal variables in a PHP included file?
I have a snippet of HTML that I've saved in my theme as mysnippet.inc. I'm using this code in template files (eg. node.tpl.php) to include it:

```
<?php include($directory."/includes/mysnippet.inc"); ?>

```

This is working fine, but the snippet also needs to access Drupal variable $node\_url. So I tried to global it into my snippet:

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

```

This doesn't work.

What would be the best way to achieve this? Should I be using template.php to create a variable containing my code snippet instead?

# Answer
> 0 votes
The best way to achieve this is to:

**1.** Create a custom theme function using hook\_theme().

**2.** Implement a preprocessor in your template.php (you can also do it in a custom module). Here's a D.O. document describing how to do it. Assuming you want to preprocess the node.tpl.php template, a preprocessor that would be run regardless of what theme you are using would be called `phptemplate_preprocess_node`.

**3.** Inside your preprocessor, call the custom `theme()` function you created in step #1. Add the results of your theme function to the $variables array that are passed to your preprocessor. For example:

```
<?php
// In your template.php...
function phptemplate_preprocess_node($variables) {
  $variables['foo_bar'] = theme('my_theming_func', $params);
}

```

**4.** Now on node.tpl.php all you have to do is:

```
<?php
if(isset($foo_bar)):
  print $foo_bar;
endif;

```

I know that this sounds more difficult than what you where trying to do, however using PHP globals in Drupal and `include_once` in templates is highly discouraged.

# Answer
> 0 votes
You can access the `$variables` array in your included file like this:

```
 // assuming you are viewing a node
 $node = $variables['node'];
 // the node is an object, so to display the url do
 echo drupal_get_path_alias('node/'.$node->nid);

```

To see what kind of data the `$variables` array contains do something like:

```
 echo '<pre>';
 print_r($variables);
 echo '</pre>';

```

---
Tags: 7
---


# Question
Title: Rules module: How do I execute code just before content is deleted?
I'm trying to execute some code right before content is deleted. The Rules module has events for

* After updating existing content
* Before saving content
* After saving new content
* After deleting content

However, none of these execute my code at the right time. Is there a way to easily add new events? If so, where should I hook? My knowledge of the Drupal core is very small.

*Background:*

What I'm doing is updating a menu link that links to the content in the database, but as the update code only runs *after* having deleted the content, there isn't any row to be updated because Drupal apparently deletes menu items that link to non-existent content.

# Answer
> 1 votes
You might be looking to implement hook\_delete().

You can also check node\_delete\_multiple() in node.module, if you want to have an idea of what Drupal core does when it delete nodes...there's other hooks that get called as well.

---
Tags: database, rules
---


title: How to add cck custom date field?

text:
# Question
Title: How to add cck custom date field?
I am trying to create **custom compound** field with a text field and a date popup.

I've tried the following code:

```
 $element['year'] = array(
    '#title' => t('date'),
    '#type' => 'select',
    '#default_value' => $options['year'],
    '#options' => $options,
    '#weight' => 2,
  );

```

...

```
function _universitydegrees_values_year() {
    $options = array(
        'year',
        1970,
        1971,
        1972,);
    return $options;
}

```

# Answer
> 1 votes
In Drupal 6 we had the Multigroup module, which was bundled as part of the CCK 3.x branch. As of comment #353 on the *State of the multigroup module* thread, you should be able to just swap your CCK 2.x code for the 3.x branch and run the updates without no problem. I used this module a few years ago and it worked fine.

Be advised however that apparently the CCK Multigroup module migration path to D7 is undefined. i.e., if you develop your site in D6 with CCK 3.x there's no guarantee that you will be able to automatically convert your CCK data to D7.

There are other Drupal 6.x field-grouping modules metioned here that you might find worth researching. This post also talks about different grouping modules and it might interest you.

---
Tags: 6, entities, datetime
---


# Question
Title: Independent arguments for View Page and Attachment
Setup:

A Views page with an Attachment

Is it possible to have the first argument in the url affect the main page only, and the second argument affect the attachment only?

e.g. http://url.com/%1/%2

%1 is a cck field in a node. If %1 == 'acme' the main page displays a list of all nodes where a certain cck field equals 'acme'. It then ignores the second argument (e.g. %2 can equal anything or nothing without affecting the page list).

%2 is an nid. The Views page's attachment displays a single node where the nid the value of the second argument. (Argument 1 will always be true for this node, so it can be inherited, but it doesn't have to be).

Is this possible?

I also tried by using a combination of an argument for the page and exposed filter for the attachment I could create a url like:

http://url.com/cck\_field\_value\_to\_match?nid=123

…but that still produced no results for the attachment.

…but that still prod

# Answer
Personally, if you just want some content from the node at the top of a view, I'd override the Views template.

Then, in that template just use the following code to get the content:

```
<?php if (is_numeric(arg(2)) : ?>
  <?php $node = node_load(arg(2)); ?>
  <?php print $node->content; ?>
<?php endif; ?>

```

I'm pretty sure you can get attachments to inherit arguments, but they can't be used independently; all arguments will always affect the parent view.

If you have to use a view, you can always do as above, create a template, then create a 'new' view; then, embed that view inside the other using:

```
<?php print views_embed_view('viewname', 'displayname', arg(2); ?>

```

This will manually pass the third argument into the embedded view.
> 1 votes

# Answer
I could be wrong about this, but I believe that the first term in a view path cannot be a % (neither should the last term). The path you are defining is the identity for the view, not an intercept for the URL. In other words, The view is called when its path is called and there should not be another content item with the same URL path. You can use & as middle terms in the path and use contextual filters to read them and further filter the view. A view page can have a contextual filter and so can the attachment.

Remember that if you have two path segments with % that it takes two contextual filters to read the second one. Before expanding into all of that, could you provide some additional information about what you want to achieve?
> 0 votes

---
Tags: views
---


# Question
Title: In Views admin, is there a section to insert CSS to style the view? i.e. how to style view without editing theme code or other drupal PHP?
In the Views admin (i.e. admin/structure/views ), is there a section in the settings to insert CSS to style the view? i.e. how do I style a view without editing theme code or other drupal PHP?

I am able to find out which class identifiers that I need to style - see question/answer at: Which html div classes are relevant when styling Views in Drupal 7 (for CSS)?

But I don't know where to put the CSS code to actually style the view.

I assume that it is possible to style a view within the drupal views admin pages, without having to resort to editing/creating themes, PHP and HTML code via FTP (?). Obviously one can do those things too but I'd rather try to find a (non-theme specific) solution within the views admin first.

# Answer
Actually, the latest views does allow all kinds of CSSing, both from the easiest, such as adding CSS classes to the view Style Settings section, to embedding custom css and fields wrappers in the fields output when you click on their configuration and edit Style Settings there.

But I think the question here is, after you do all that, where do you put the CSS itself.

And that would be in one of your theme's css files, which are defined in your themename.info file (which is located in your theme's toplevel directory) like:

```
stylesheets[all][] = myfilename.css

```

So, you could ADD a css file to your theme with your customized CSS without touching anything else in there.
> 2 votes

# Answer
While I agree that style rules belong in a CSS file (compare with PHP that gets Eval'd) I can see the requirement, especially if it was a multi domain site that ran different themes. You could write a custom module (basically what CSS Injector does as mentioned in a previous answer) but for a complete code free way you could use Panels which is much more aware of CSS, in that you can add some style rules to specific containers within the interface itself.
> 2 votes

# Answer
Views does not have anything like that because it belongs in a theme. It's considered good practice for module maintainers to keep themeing small and out of the module itself.

The closest you can get to not editing theme CSS or template pages is using the CSS Injector module.
> 0 votes

---
Tags: 7, views, theming, location
---


# Question
Title: How to fill checkout form fields with values from a previous custom form?
Basically I have a few landing pages with forms with fields that are a subset of the checkout page form fields. I'd like for the user to submit the form and be redirected to the checkout page with the form values already filled.

I'm using Übercart and I think it's this function here that controls it:

`function uc_checkout_pane_delivery($op, &$arg1, $arg2)` and the values of $arg1 needs the be set by the previous form. My question is how? What would be an appropriate method for populating the checkout form fields? Thanks.

# Answer
I think you could get away with this by using hook\_form\_alter (checkout is still a form) and just setting `#default_value` on the required field. The previous form could save it in `$_SESSION` somewhere.
> 2 votes

---
Tags: ubercart, forms
---


# Question
Title: Creating a relationship between taxonomy lists
I'm working on a website about cars, the question is quite simple, but probably, will need as much information as possible.

So here's the situation, I need to create several vocabularies that define a car, starting from a car maker, car model, year, engine, etc... what I need to do is put it in a form of sorts, that filters every section, so say I want Skoda, then in the model, it gives me Fabia/Octavia/Superb/etc... because definitely, A corvette has nothing to do with skoda!!!! then I choose Octavia, and the next list gives me years which it was in production, so it doesn't matter which year I choose the next one is Engine, which engines did it have at that year?

Lets put it in a Graph:

Skoda \<- Octavia \<- 2000 \<- 1.6 8v \<- etc...

How do I create the relationship? Do I really need to structure the taxonomy in a very complicated way or what do I do?! Help me, I'm clueless :'( Many websites do it, why is it so complicated on drupal?

Any help will be greatly appreciated!

# Answer
There are other ways to do this, in Drupal there are always other ways. But before you try to implement a solution, ask the question 'what will I want to do with the information besides a direct look up' of say Corvette, year, motor size. As soon as you find something else you want to include, say various models in a year - coupe, convertible, etc.- or information on colors, performance, displacement, maximum this and that, you will find yourself redesigning that taxonomy again. Drupal is a Content Management System and is entirely contained in the database. Instead of laying out a taxonomy, work on the design of your database. When you have a good structure for that, start creating fields and use the Views module to generate the content in whatever form you desire. Views is basically a UI for database queries with some great Drupal flexibility for assembling and displaying the content.

I hope this is helpful. By the way, Drupal **is** complicated. It is very powerful and has a bit of a learning curve. That's why this site has been successful. Three months ago, I couldn't even spell Drupal, now I can :)

As you get going, come back to this site for more help.
> 3 votes

---
Tags: taxonomy-terms
---


title: Attach a view to a specific node

text:
# Question
Title: Attach a view to a specific node
I'm looking for a module that makes it possible to attach an existing view to a specific node. I've looked at eva, but it seems only to allow connecting a view to all entities of a specific content-type. I wrote my own module, that can do this, and it works, but I would like to use a module that is well tested and maintained. Does anyone have any suggestions?

*** EDIT ***

I have installed the `views reference` module and this seems to be what I want, but when I do `print_r($content)` in my `node--type.tpl.php` file, the only thing related to this field is the following:

```
[field_attached_view] => Array (
                        [und] => Array (
                            [0] => Array (
                               [view_id] => products_view:first_display
                               [arguments] => sample/all/jeans
                             )
                         )
                     )

```

I have managed to load and display the view by something like this:

```
  $view_id = $node->field_attached_view[$node->language][0]['view_id'];
  $parts = explode(':',$view_id);

  $args = explode('/',$node->field_attached_view[$node->language][0]['arguments']);
  $view = views_get_view($parts[0]);
  $view->set_display($parts[1]);
  $view->set_arguments($args);
  $view->execute();
  echo $view->render();

```

But, there must be a cleaner way of doing this?

Thanks in advance.

# Answer
You can use the View reference module.

> Defines a field type *View reference* which creates a relationship to a Views display and allows the view to be displayed as the content of the field.
> 3 votes

# Answer
Just create a view as a block. In the block settings you can configure it to display it on "Only the listed pages" and display in the region you want.
> 2 votes

# Answer
You can use Context:

1. Create a Block Display in your View.
2. Create a new context.
3. Use the specific node path as a Rule for that Context. Example: node/123
4. "Drag & Drop" the Block Display you created in step #1 to one of the regions available in your node page.

You could also do more complex things with Views, such as attaching a View to all the nodes of a particular content type when a user with a certain role is active, just to name an example. As a plus, Contexts are exportable, and you can package and deploy them to your production sites using Features. If you decide to use Context you will be using a method widely used by the larger Drupal community.
> 1 votes

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


# Question
Title: How can I lock a user profile field after registration?
I have a custom field on my user's profiles; I would like it is filled out at registration, but then not changed on post-registration.

How can I achieve this?

# Answer
> 3 votes
Could you use the Field Permissions module? You could set permissions on the field so that authenticated users (or any other user role if you're using any) cannot edit this specific field, but anonymous (registering) users can.

---
Tags: 7, users
---


# Question
Title: Autocomplete results showing behind the form
How can I make the autocomplete search results appear above all elements on the page?

I have 2 forms on one page, the top form has the autocomplete text field. Immediately below that is another form. When the autocomplete results show, they are behind the second form.

# Answer
> 0 votes
I can only speculate as to how you've styled up the second form, but it might be its z-index is higher than that of the autocomplete dropdown.

Trying setting a higher `z-index` for the autocomplete div in your stylesheet:

```
#autocomplete {
  z-index: 1000;
}

```

---
Tags: ajax
---


# Question
Title: How do I display some no results text in a view if the views results are aggregated?
I have created a view block that displays the number of users a separate user has flagged. I did this by using the "Use aggregation" option in the advanced drop down. I have a UID field that I have grouped by count, and in the no results configuration I have written "0". For some reason when I go and print out my view, if there are no results, it won't display anything and I am wondering why.

# Answer
> 1 votes
I figured it out. Instead of configuring the no results display on the UID field, I had to configure it in the no results display of the view itself.

---
Tags: 7, views
---


# Question
Title: Select a taxonomy parent ID based on the current node type for shared field declarations in cck
I have a taxonomy vocabulary with the below heirarchy:

```
*Property Type

 -Commercial
    -Office
    -Building
    -Warehouse
 -Residential
    -Villa
    -Apartment
    -Penthouse

```

I have two content types for the property information that has a common field called: 'Property Type' relating to that vocab above, again, for the two content types: "Commercial Property" & "Residential Property" they are using the same field declaration that relates to the same vocab group.

I want to use the php advance code to filter 'commercial' and 'residential' whichever content type is concerned. E.g. Villa, Apartment and Penthouse should only show under the "Residential Property" content type.

My Current code is this but it does not work:

```
if (arg(0) == 'node' && is_numeric(arg(1))) $nodeid = arg(1);
if($nodeid) $type = noad_load($nodeid);
if($type->type=='commercial_for_rent' || $type->type=='commercial_for_sale') return 798;
else if($type->type=='residential_for_rent' || $type->type=='residential_for_sale') return 799;

```

In other words: Show only the sub category items of 'Property Type' vocab (e.g. "Residential terms") if content type being edited is this (e.g. "Residential Property" content type)...

Can someone help me point to the right direction please.

Thank you!

# Answer
> 2 votes
Apparently, I am answering my own question. This may not be the best solution (the drupal way) but it works and at least for the meantime I can continue the project. Here is how I solved it:

arg(0), arg(1).. will always refer to the current url arguments. so arg(0) will be the first arg after the siteroot, arg(1) is next.. etc..

With my problem, when you are editing a content type here is my current url path for example: http://localhost/mysite/node/add/commercial-for-rent, where arg(0) = node, arg(1)=add etc..

simply posting this to php snippet worked:

if(arg(2)=='commercial-for-rent' || arg(2)=='commercial-for-sale') return 798; else return 799;

That's at least as far as the url pattern goes. ../node/98/edit is when editing the content which is again this solution will no longer work...

As I said this is not the best solution if there is anyone out there who has better ideas please do tell me so I can edit the snippet and solve this the drupal way.

# Answer
> 1 votes
You also want to select the right parent node when editing a node. The problem is the $node object is not available to determine `$node->type`. But you can use other variables.

I use the following code to select the parent node. It works for node creation and editing an existing node.

Thanks to ablommers.

```
<?php
// Get available variables and load into object
$vars = get_defined_vars();
//$vars is now an array object; get contenttype
$type = $vars['field']['type_name'];
//derive termid for termname = contenttype
$tids = taxonomy_get_term_by_name($type);
// returnvalue is an array containing all matching terms, that needs to be filtered on vocabulary
foreach($tids as $tid) {
   if ($tid->vid == $vars['field']['vid'])
     return ($tid->tid);
}
// if no matching taxonomy term is found return null
return null;
?>

```

---
Tags: nodes, taxonomy-terms, 6, entities
---


title: image_scale_and_crop

text:
# Question
Title: image_scale_and_crop
In Drupal 6 there is a parameter $destination for the function 'image\_scale\_and\_crop()' . The parameter is not available in D7. I have the following code block.

```
image_scale_and_crop($image, 100, 70);

```

This code is executed an the thumbnail is created in a path if I examine the file directory.

My question is, how I can determine the path where the cropped file is created in order to save it to db.

# Answer
> 0 votes
Thanksfully I could find the answer. After using this function,, I have to say drupal..

```
image_save($image);

```

It was due to insufficient information in the documentation.

# Answer
> 2 votes
Maybe it's better to use an image style and use theme\_image\_style($variables)

# Answer
> 0 votes
not sure if this is the link to answer your question http://api.drupal.org/api/drupal/includes--image.inc/function/image\_save/7

---
Tags: 7, media
---


title: Set Permissions in Custom Module

text:
# Question
Title: Set Permissions in Custom Module
I am writing a custom module for my Drupal 7 site. I have added the code to enable a configure form.

I want to restrict the config to admin users only, and some of the functions to another group of users. How do I go about doing this?

Any and all help greatly appreciated.

# Answer
You can use hook\_permission() in your module. This allows you to add a custom permission. For example:

```
return array(
  'your permission name' => array(
    'title' => t('your permission title'),
    'description' => t('Description.'),
  ),
);

```

Afterwards, go to the permission page and set the ticks where you need them.
> 2 votes

---
Tags: 7, users
---


title: Set a views path to base URL

text:
# Question
Title: Set a views path to base URL
I am using view.

Every view needs path and i want to set that path to my base url.

For example i want to make a view which will take a Car as a argument and show result at

```
www.example.com/Car

```

Any help will be appreciated.

# Answer
I think what you are looking for is `contextual filters`.

You should add a `contextual filter` to your view and set the path to `%`. What kind of filter you should use depends on if `Car` a taxonomy term or a node and so on.

In the following example I have set my path to `stores/%` and a `store` is a node with a associated taxonomy term. I can display stores marked with a specific term by going to `http://example.com/stores/england` or `http://example.com/stores/sweden`.

* You find the `contextual filters` under the `advanced tab`.

* Here are the settings for the filter. Arguments from the url will be transformed into `Term ID`.

*** EDIT *** Perhaps this link will help you Views contextual filters taxonomy name
> 4 votes

# Answer
To expand upon Krister Andersson's answer...

When creating a view, and defining its path keep in mind that the path you are defining is basically the name of the path. IF you have a % in the path then th view has multiple names. If you define its path as cars/%, for instance, the view is called for any combination of path components in the % segment. If you had a view with the path /% it would basically be called for all URLS. This does not work for Drupal so wildcards are not used in the first position.
> 2 votes

---
Tags: 7, views, uri
---


# Question
Title: Why should you use theme(), rather than calling the theme functions directly?
Why should you use `theme()`, rather than calling the theme functions directly?

```
theme('box', $title, drupal_get_form('comment_form', $edit, $title));

```

Why doesn't the code call the theme function directly, as in the following code?

```
theme_box($title, drupal_get_form('comment_form', $edit, $title));

```

# Answer
> 13 votes
You have to use the theme() function for the override system to work. For example, your theme may override the theme function for a module, or a template (.tpl.php) file might be used instead.

# Answer
> 1 votes
In the example you made, when you call `theme_box()` you are calling a specific function; when you are calling `theme('box')`, the function is calling a function that normally is`theme_box()`, but if a module implements hook\_theme\_registry\_alter() using the following code, the function being called is `theme_mymodule_box()`.

```
function mymodule_theme_registry_alter(&$theme_registry) {
  // Kill the next/previous forum topic navigation links.
  if (!empty($theme_registry['box'])) {
      $theme_registry['box']['function'] = 'theme_mymodule_box';
    }
  }
}

```

Notice that in Drupal 7 every theme function has a preprocess function, not just the theme functions using a template file. This means that, in few cases, it is not necessary to override a theme function. If the code just need to change the content of a variable passed to the theme function, using a preprocess function is what should be done in Drupal 7.

---
Tags: theming
---


# Question
Title: The calendar_style style requires a Date argument error when Using CCK as a date argument
Can´t use a date CCK field when setting up a calendar as a view When I want to save the view I´m getting this error message:

```
The calendar_style style requires a Date argument.

```

I´ve added the same CCK field to the fields so views would stop complaining about another error message that in the new versions of views was added..that the same argument has to be present on the fields

Still ..the date type of the CCK isn´t recognized as a valid date argument... Works with node updated date though...

I have Drupal

```
Date 6.x-2.7
Calendar 6.x-2.4
Views   6.x-2.12
and Drupal 6.22

```

# Answer
> 2 votes
When building a calendar in Drupal 6, you should clone the default calendar views in order to create a new on instead of trying to make it from scratch (Error when changin Date argument).

Have a look at these tutorials if you need some extra help:
\- Drupal Calendar Setup
\- How To: Create a Drupal Calendar

---
Tags: entities, datetime, views
---


title: How to make a 2-line menu link title?

text:
# Question
Title: How to make a 2-line menu link title?
I have set up a menu with a list of menu titles which is working fine. But as I want to style the link `li` with a `background-color` and rounded corners, I need to be able to manually insert a break in longer length menu titles, rather than rely on the width controlling the line break automatically.

From what I've been able to glean from searching online, there is some way to do this by modifying a copy of a template file from core into my theme, but I'm not sure how to do this or if there is a simpler way.

Using Drupal 7.

# Answer
> 4 votes
You need to override `theme_menu_link()`, so in your `template.php` file from your theme put this code:

```
function MYTHEME_menu_link(array $variables) {
  $element = $variables['element'];
  $sub_menu = '';

  if ($element['#below']) {
    $sub_menu = drupal_render($element['#below']);
  }

  //Split titles using a <br /> when longer than 20 characters
  $element['#title'] = wordwrap($element['#title'], 20, "<br />");
  //Set HTML to TRUE to display properly the HTML
  $element['#localized_options']['html'] = TRUE;

  $output = l($element['#title'], $element['#href'], $element['#localized_options']);
  return '<li' . drupal_attributes($element['#attributes']) . '>' . $output . $sub_menu . "</li>\n";
}

```

Change MYTHEME by your theme name.
I used `wordwrap()` to split long menu title in small chunks but you can implement your own logic there.

---
Tags: 7, routes
---


# Question
Title: Drupal substracts 2 hours from the CCK date field when saving. Why?
I have defined a CCK field of the date type with an Hour granularity it looks like this:

When I save it, it subtracts 2 hours from each one.

I think it is caused from the set timezone.

My current timezone is "Europe/Madrid."

> Mac-Pro:~ usuario1$ date
> martes, 13 de diciembre de 2011, 17:33:23 CET

The server's timezone is the same.

> Server:~ root$ date
> mar dic 13 17:32:43 CET 2011

Why is Drupal doing this?

The dates have to be the same just as I type them.

# Answer
> 3 votes
In Drupal 6 at least, you would go to admin/settings/date-time to check the default timezone of Drupal. I'd check to see if that's set correctly. If it is, then you have to check if user configurable timezones are enabled, and if so, check what you or the logged in user has set in his/her account against all of the above.

---
Tags: entities, datetime
---


# Question
Title: Is this the right way to do this? Inserting a block into the content body field of a node
I'm very new to using Drupal 7 and trying to understand the correct way to insert a book navigation menu block into the content field of a node, or any field/block of content into anything for that manner.

Anyways, one solution I have come up with is this: **In field--body.tpl.php**

```
<?php
$block = module_invoke('book', 'block_view');
//render book menu
if($block){
echo'<div class="book-menu-navigation">';
print render($block);
echo'</div>';
}
?>

```

I have no idea if this is the proper/orthodox way to do this; I'm pretty sure a better way would be with a pre-process in template.php. Could someone explain/demonstrate how would this get implemented in that way?

# Answer
> 2 votes
I am not one to say what is a/the best way, but if template\_preprocess\_WHATEVER() is, you set it up something like this:

```
function template_preprocess_WHATEVER(&$vars) {
  if ( CONDITIONS YOU NEED IF ANY ) {
    $block = module_invoke('book', 'block_view');
    if ($block) {
      $book_block_view='<div class="block-menu-navigation">';
      $book_block_view.=render($block);
      $book_block_view.='</div>';
    }
    $vars['book_block_view']=$book_block_view;
  }
}

```

and now you would have $book\_block\_view available in WHATEVER to print or use.

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


# Question
Title: Unable to debug $items variable in hook_menu_alter(&$items)
I want to print out $items variable (the argument of hook\_menu\_alter) for debugging the menu properties in various pages.

I tried:

```
/**
 * Implement hook_menu_alter()
 */
function mymodule_menu_alter(&$items) {
  debug($items);
  kpr($items);
}

```

cache cleared.

but $items are not printed out on the page. Any ideas?

# Answer
> 7 votes
It is not working because `hook_menu()` and `hook_menu_alter()` are invoked when the menu list is rebuild. This generally happens when a module is installed, or uninstalled, but modules can force the menu to be rebuild setting a Drupal variable, as with the following code:

```
variable_set('menu_rebuild_needed', TRUE);

```

When `hook_menu_alter()` is invoked, Drupal could also not serving a page that is visible on the browser. The function that rebuilds the menu, menu\_get\_tem(), is called by menu\_execute\_active\_handler(), which is called every time Drupal bootstrap, even when an AJAX callback is invoked. In that case, the output of the debug function is not visible (nor would JavaScript get it).

In such cases, I think it is preferable to write the output to the database using `watchdog()`. The output is not immediately visible, but will be logged even when an AJAX callback is invoked.

# Answer
> 1 votes
You should use my\_module\_menu\_local\_tasks\_alter(&$data, $router\_item, $root\_path) for menu tabs

# Answer
> 0 votes
I don't know why it's not working for you (it has for me in the past). Have you double checked that the function's being run? As a last resort you can use `dd()` and then `tail -f /tmp/drupal_debug.txt` (or wherever the file is with your configuration).

---
Tags: routes, hooks
---


title: Display bare HTML from hook_menu()

text:
# Question
Title: Display bare HTML from hook_menu()
What would be the cleanest way to route URLs to functions and return **only** the HTML output from those functions (a.k.a. the menu callback)?

If I use `hook_menu()` the string that's returned will be the HTML within the rest of the site. I want the page to display **only** the string returned from the menu callback.

Should I use `drupal_set_header()` in the same way `drupal_json()` does? Is this not inefficient having fully bootstrapped Drupal, and then changing the header at the last minute?

I want the fastest code path possible since this is going to be for widgets on external sites. I could start with a standalone .php file and bootstrap what I need but the hook\_menu routing is nice.

How should you do this?

# Answer
> 4 votes
To show only the output of the callback, and not the complete page Drupal would render, output the HTML using `print` or `echo`; if you return the HTML output as string, Drupal will render the normal Drupal page, which includes the HTML your callback returns.

The code contained in index.php that causes this behavior is the following one:

```
// Menu status constants are integers; page content is a string.
if (is_int($return)) {
  switch ($return) {
    case MENU_NOT_FOUND:
      drupal_not_found();
      break;
    case MENU_ACCESS_DENIED:
      drupal_access_denied();
      break;
    case MENU_SITE_OFFLINE:
      drupal_site_offline();
      break;
  }
}
elseif (isset($return)) {
  // Print any value (including an empty string) except NULL or undefined:
  print theme('page', $return);
}

```

`drupal_set_header()` is used from `drupal_json()` to change the content type of the output (the "Content-Type" metadata); normally Drupal will set it to "text/html" which is not appropriate for what returned from a callback returning JSON; in that case, the content type that allows the requester to handle the output correctly is "text/javascript."

---
Tags: 6, hooks, routes
---


# Question
Title: Can we change the schema in services module?
I am new to Drupal services; I have the below XML format, in which I need to expose nodes as services.

Can I do this using the Services module?

```
    <?xml version="1.0" encoding="UTF-8"?>
<ngd:mediafile xmlns:ngd="http://www.xyzy.com/ngdine"
               xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
               xsi:schemaLocation="http://www.xyzy.com/ngdine mediafile.xsd">
  <ngd:description>
    <![CDATA[This is the description]]>
  </ngd:description>
  <ngd:mediatype id="1"/>
  <ngd:internal>Aalborg city.JPG</ngd:internal>
</ngd:mediafile>

```

Can I change the schema?

# Answer
> 2 votes
If you need to expose the output that way, THeres 2 ways you can do it. You can alter the response before it gets sent as a payload, or you can write your own Response Format.

Both should do what you need, but its merely a preference.

```
/**
 * Triggered when the REST server request a list of supported response formats.
 *
 * @param array $formatters
 *  An associative array of formatter info arrays keyed by type extension. The
 *  formatter info specifies an array of 'mime types' that corresponds to the
 *  output format; a 'view' class that is a subclass of RESTServerView; and
 *  'view arguments' that should be passed to the view when it is created;
 *  a 'model' can also be specified which the controller then must declare
 *  support for to be able to serve data in that format.
 * @return void
 */
 function hook_rest_server_response_formatters_alter(&$formatters) {
   /*
    * Sample modifications of the formatters array. Both yaml and
    * rss are formats that already are supported, so the changes are
    * nonsensical but illustrates the proper use of this hook.
    */

    // Add a Yaml response format.
    $formatters['yaml'] = array(
      'mime types' => array('text/plain', 'application/x-yaml', 'text/yaml'),
      'view' => 'RESTServerViewBuiltIn',
      'view arguments' => array('format' => 'yaml'),
    );

    // Add a Rss response format.
    $formatters['rss'] = array(
     'model' => 'ResourceFeedModel',
     'mime types' => array('text/xml'),
     'view' => 'RssFormatView',
    );
 }

```

The altering of the response is, function HOOK\_services\_request\_postprocess\_alter

# Answer
> 1 votes
Besides retrieving content as XML, do you need any other functionality provided by the Services module? If not, it might be overkill.

One simple alternative might be to write a module that implements hook\_menu() to define a menu item for a wildcard path such as `node/%/xml`, which then, in its page callback, outputs the XML in your specified format.

In Drupal 7, you might do this as follows:

```
<?php

function mymodule_menu() {
  $items['node/%nid/xml'] = array(
    'page callback' => 'mymodule_xml_view',
    'page arguments' => array(1),
  );
  return $items;
}

function mymodule_xml_view($nid) {
  drupal_set_header('Content-Type: text/xml');

  echo '<?xml version="1.0" encoding="UTF-8"?>';
  echo '<ngd:mediafile ...>';
  echo '<nid>' . $nid . '</nid>';
  // ...
  echo '</ngd:mediafile>';

  drupal_exit();
}

```

Then, after enabling the new module, you can retrieve XML content by simply fetching, for example, URL http://example.com/node/42/xml .

---
Tags: services
---


# Question
Title: Help understanding Drupal form creation/content creation
I am fairly new to Drupal 7.9 and still trying to get a hang of it. Understandably it has a learning curve which I am trying to scale at the moment.

My challenge here is to basically create a page that has some backend processing to it. The front page consists of form elements (mostly textboxes) arranged in a tabular format.

A little bit of exploring and I reckoned I might need to create a kind of content type and then add content. But I got nowhere with this.

Then I discovered the webform module that lets me create form elements and provides a bunch of operations. But it doesn't necessarily allow me to display my form elements in tabular format.

So before exploring on my own again, I felt it would be right to ask questions from you guys.

Anybody with any leads on this ?

Thanks much !!!

Parijat

# Answer
> 1 votes
You probably need to explain what you mean by "background processing", i.e. are you looking to save content or do something else?

At any rate, if you really need to template your form to be table based, this is possible by implementing `hook_theme`. An example entry for a form with an id of `example_search_form` (this is the argument passed to drupal\_get\_form() or can be found by looking at the id of the generated form by viewing source) and a template file called `example-search.tpl.php` looks like:

```
  $hooks['example_search_form'] = array(
    'arguments' => array('form' => NULL),
    'template' => 'example-search',
  );

  return $hooks;

```

Then in your `example-search.tpl.php` you can render individual form items however you would like.

---
Tags: forms, nodes, webforms
---


# Question
Title: How can I echo a views object ($data->nid) into javascript?
I need to echo out a few different variables in an onclick event for Google analytics.

I figured this would work but the specific $data objects aren't echoing out. The variable\_get does, however.

```
<?php
  echo "<script>jQuery(document).ready(function($) {
 _gaq.push([ '_trackEvent', 'my_category', 'my_action', '". variable_get('4_measly_letters', 'AAAA') ."|".$data->nid ."|".$data->node_data_field_i."']);
  });
 </script>";
?>

```

# Answer
If I understand well your case, you can test if `$data` indeed is loading your desired data. you can do this with `<?php print_r($data); ?>` (or if you use Devel module, is best use `<?php dsm($data); ?>`). if you see the list of values, you also will see the respective keys's names of each value.

If you do not see values, you can load the respective node informatation with `$data = <?php node_load($IdNode) ?>` where `$IdNode` is the ID of your node. Remember `<?php dsm($data); ?>` to see the data of your node.
> 2 votes

# Answer
If you view your source do you see your script tags at all? You should be using drupal\_add\_js or it may get stripped out.
> 0 votes

---
Tags: javascript
---


# Question
Title: What is the difference betweeen hook_validate and case 'validate' in hook_nodeapi
I am bit confused about `hook_validate()` and case 'validate' in `hook_nodeapi()`. Both do validate a node.

Could anyone clear me the difference with a simple example that even a beginner can understand?

# Answer
`hook_validate` is used inside a module that creates a node type of its own, and is used along with the form used to create the node to validate that all the information required has been entered.

For example, let's say you created a node type with a specific field in it of "area" and you wanted to make sure it was of the format city-state. You would do it in here.

`hook_nodeapi` with `op=validate` is used to validate any nodes that are being edited but not created by the module in question.

For example, let's say you wanted to make sure a description field in a node with that field had more than 1000 characters. You would do it with `nodeapi`/`validate`.

Carefully read `hook_validate` and hook\_nodeapi for more information or clarification.
> 5 votes

# Answer
The main difference is the following:

**hook\_validate:** when you create a new content-type programmatically you can use a certain number of hooks for define a how will be behave your new content-type, you can see these hooks in the developer hooks section of Drupal site, between that hooks exists hook\_validate for apply a validation for your new content-type.

**validate in hook\_nodeapi:** with this, you can add any validation for a node for any content type .
> 2 votes

---
Tags: 6, hooks
---


# Question
Title: how can we display the field in image or pdf format
I have a `Content Type` as `Article` with fields `Title`, `Article Content` and `Tags`.

When a user sees a `Article`, then how can we display `Article Content` in Image or pdf format. And `Title` and `Tags` will be in default state.

How can we convert Text into image or pdf. Is there any module or any hook to implement this.

# Answer
Below are the some instructions to be manualled

1) First need to install Cufon module

2) Enable it and set permission as mention on above link

3) Download cufon-yui.js and place it in any subfolder under:

```
* current theme folder
* sites/all/modules/cufon/
* sites/all/libraries/cufon/

```

below link to download cufon-yui.js

http://cufon.shoqolate.com/js/cufon-yui.js?v=1.09i

4\] Generate a font definition and upload it in any of these folders:

```
* current theme folder
* sites/<your site>/libraries/cufon-fonts/
* sites/all/libraries/cufon-fonts/

```

below link to generate the custom font you want to display

http://cufon.shoqolate.com/generate/

Once you generate and save it to above directories as mention

5\] Now goto admin/config/media/cufon

and some css selectors as

```
  `.cufon_selector` and select any font type from the dropdown and enable it

```

Note: you can give .(dot) and # (hash) with name is must

And if you want to other one you can more number of fonts

6) Now Save configuration

7) Now goto you site directory choose you theme directory

```
 `theme->themename->templates`

```

In this select and copy `node.tpl.php` and paste it and rename with your **content type** you want to display

for example : I have content type : `articles`

so `node--articles.tpl.php`

8) Now open `node--articles.tpl.php` or your `node--yourcontentype.tpl.php`

9) Find the

```
<div class="content clearfix"<?php print $content_attributes; ?>>
<?php
// We hide the comments and links now so that we can render them later.
hide($content['comments']);
hide($content['links']);
print render($content);
?>
</div>

```

And make some edit

```
<div class="content clearfix"<?php print $content_attributes; ?>>
<?php
// We hide the comments and links now so that we can render them later.
hide($content['comments']);
hide($content['links']);

echo "<div class='vegur_one'>";
print render($content);
echo "</div>";
?>
</div>

```

As i have created `.vegur_one` just add

```
echo "<div class='vegur_one'>";
print render($content);
echo "</div>";

```

10) Now flush the cache and refresh and enjoy it..
> 1 votes

---
Tags: 7, nodes, files, media
---


# Question
Title: Display views result from a certain entry on
I have a ranking list on my Drupal site (Database output sorted by points, and I assign a rank via the field "Global: View result counter"). Now, displaying the entire ranking list is no problem. But I would also like to add a view where a user can find himself in this ranking list and see the list from his position on (i.e. himself and then all users with lower points). Any idea how I could do this? Filters are not suitable, as they retrieve only a selection of the original ranking list from the database, hence the rank does not match anymore...

Thanks for your help!

Tobias

# Answer
As far as I can tell, you have no choice right now but to write a simple custom module which would use the current user name and output themed results of a corresponding query.

Though of course it would be nice to be able to use the Views UI in this, so I understand that perhaps this is not the best solution for you.
> 0 votes

---
Tags: views
---


# Question
Title: Webforms with subheadings that have their own fields
I realise what field sets are as they can group parts of your webform together. What I am looking for though is to have subheadings within those fieldsets.

I've been trying to find tutorials about this but all I can find is tutorials on how to build a simple webform with just a title, description and then label-field pairs.

**Edit:** Say I want a form that calculates taxes for someone and I want to start off with a fieldset that has a couple of radiobuttons like male/female, I live rural/I live in the city and whatnot. Then I want some label/textfield pairs like name address phone, etc... Then within the same fieldset I would have a title that says 'do you have a secondary address?' and have that be the title for a subset of fields with again address and zipcode, etc..

# Answer
> 0 votes
Basically I got away with just putting up a markup title. I thought it was really necessary to have field groups in order to make a valid web form since it was suggested to me. I guess like Andy said, nested fieldsets might have worked as well.

---
Tags: 7, webforms
---


# Question
Title: In sent message, the user name is not displaying
I am using the Privatemsg module, version 6.x-1.x.

If my username is "TEST" and I am sending the email to myself, the sent messages doesn't show "TEST." The "From" field is empty.

If I send the email to other users their names is displaying fine.

What is the reason of this, and what should I do to display my name there?

# Answer
> 0 votes
Here's the answer:

```
/**
 * Theme the participants field.
 *
 * @see theme_privatemsg_list_field_participants()
 */
function YOUR_THEME_NAME_privatemsg_list_field__participants($thread) {
  global $user;
  if ((arg(1) == 'inbox' && arg(0) == 'messages') || (!arg(1) && arg(0) == 'messages') || ($_SESSION['parti'] == 'From') || (arg(1) == 'list' && arg(0) == 'messages')) {
    $msg = privatemsg_message_load($thread['thread_id'], $account = NULL);
    $participants[$msg[$msg['author']->uid]] = $msg['author'];
  }
  elseif ((arg(1) == 'sent' && arg(0) == 'messages') || ($_SESSION['parti'] == 'To')) {
    global $user;
    $participants = _privatemsg_generate_user_array($thread['participants'], -4);
    unset($participants[$user->uid]);
  }

  $field = $to = array();
  $limited = FALSE;

  if ($participants) {
    foreach ($participants as $account) {

      if (count($to) >= 1) {
        $limited = TRUE;
      }
      $to = get_profile_name(array('uid' => $account->uid));
      if($to->field_profile_first_name_value && $to->field_profile_last_name_value) {
        $dis_name = drupal_ucfirst($to->field_profile_first_name_value) .' '. drupal_ucfirst($to->field_profile_last_name_value);
      }
      else {
        $dis_name = drupal_ucfirst($account->name);
      }
      $pname[] = $dis_name;
      $plink[] = 'user/'. $account->uid;
    }
  }
  // This else do the magic of the displaying the user name.
  else {
    $to = get_profile_name(array('uid' => $user->uid));
    if($to->field_profile_first_name_value && $to->field_profile_last_name_value) {
      $dis_name = drupal_ucfirst($to->field_profile_first_name_value) .' '. drupal_ucfirst($to->field_profile_last_name_value);
    }
    else {
      $dis_name = drupal_ucfirst($account->name);
    }
    $pname[] = $dis_name;
    $plink[] = 'user/'. $account->uid;
  }

  $limit_string = '';
  if ($limited) {
    $limit_string = t(' and others');
  }
  if(count($pname)>0){
  $implodeVal = implode(', ', $pname);

    if(strlen($dis_name) > 10 && $_SESSION['parti']) {
      $textName = truncate_utf8($implodeVal, 10, FALSE, TRUE);
    } else {
      $textName = truncate_utf8($implodeVal, 35, FALSE, TRUE);
    }
    $explodeNameArray = explode(',',$textName);
    foreach($explodeNameArray as $key => $value){
      $splitedText[] = l($value,$plink[$key], 'title' => $value)));
    }

    $finalParticipants = implode(', ',$splitedText);
    $field['data'] = $finalParticipants;
  }
  $field['class'] = 'privatemsg-list-participants';
  return $field;
}

```

# Answer
> 1 votes
This is currently working as designed. The message *listings* do not show your own username as you obviously are a recipient as it is displayed for you. It is however a limitation of the current system that when you send a message to yourself, no recipient is shown.

You can alter the sql query and remove the exclusion of the current user for the sent list, but then it will always show the current user there.

There are some ideas on how to make the whole listings more flexible but that's quite a bit of work and needs time that I currently don't have.

---
Tags: 6, privatemsg
---


# Question
Title: Adding hundreds of fields to a content type in Drupal 6
I have over a hundred fields to be added.

How can I use CSV or SQL statement to add these fields in Drupal? Is there any module to do this?

# Answer
The one time I had to do something like that (it was a Drupal 6 site) I exported the content type, edited the export manually (lots of copy-paste and search-replace) and imported it back into my site.

That said, a content type with hundreds of fields is going to be huge. I'm afraid that it's going to be a nightmare for your editors, terrible to maintain, and it might hurt performance as well. If I ever needed a content type with hundreds of fields, I would stop right there and start re-thinking my site architecture.
> 2 votes

# Answer
You could try the Features module, or maybe Drush.
> 0 votes

---
Tags: entities
---


# Question
Title: After enabling Calendar the Next/Prev buttons are off to the side
How can I get these two buttons in a better place to make them useful? Currently they reside overlapping the sidebar and calendar almost right in the middle of it. I've looked at documentation and I can't figure it out. I'm using drupal 7. Thanks

# Answer
> 0 votes
CSS is your friend. Find the id and/or class of these offending buttons and override their positioning in your theme.

---
Tags: views, 7, datetime
---


title: Trouble theming poll block in Drupal 6

text:
# Question
Title: Trouble theming poll block in Drupal 6
I wanted to be able to control the layout and containers for all elements (choice,title,vote etc) inside my poll block and decided to add my own template for the same.

Like any noob, I checked the block with devel and got the block template file,preprocess methods used (in my case poll-vote.tpl inside drupal core poll module and the template\_preprocess\_poll\_vote inside poll.module) and the candidate file name for the template as poll-vote-block.tpl.php inside my themes directory (sites/all/themes/my\_theme) and in the theme's corresponding template.php used the preprocess function as follows:

```
function my_theme_preprocess_poll_vote(&$variables) {
  echo 'Im in';
  $form = $variables['form'];
  $variables['choice'] = drupal_render($form['choice']);
  $variables['title'] = check_plain($form['#node']->title);
  $variables['vote'] = drupal_render($form['vote']);
  $variables['rest'] = drupal_render($form);
  $variables['block'] = $form['#block'];
  // If this is a block, allow a different tpl.php to be used.
  if ($variables['block']) {
    $variables['template_files'][] = 'poll-vote-block-custom';
  }
  print_r($variables['template_files']);
}

```

Initially I set the template\_files value as 'poll-vote-block' and it didn't seem to be affecting the block, which i confirmed with devel again.

I printed the echo message to ensure the preprocess was called and it did print it. I renamed the template\_files (and the template file) and printed it to get the following:

**Array ( \[0\] =\> poll-vote-block \[1\] =\> poll-vote-block-custom )**

I once came across theme templating in drupal docs that preprocess methods are not necessarily overridden but placed in a queue... to me it appears that my preprocess method's tpl file is set with lower priority and hence unable to override. Hence I'm unable to fulfil my requirement of theming the poll block

It'd be nice know if I'm mistaken with this conception and hope someone would provide me some insight on this to get my problem solved.

Thanks in advance!!

**Edit**

The problem was finally solved. I created a **block-poll.tpl.php** file and was then able to override the default poll-vote.tpl.php with my preprocess method and poll-vote-block-custom.tpl.php.

Apparently just like the case where one needs block.tpl.php for his block-module-delta.tpl.php to override a default functionality this might've been my case.

Marking jimajamma's answer as solution as it proves to be a good documentation and reference material worth being a wiki for Drupal theming for novice developers.

Cheers!!

# Answer
If all you are just trying to change is the layout of the form, and not the data contained in it, all you should need to do is change the CSS for the various wrappers.

In this example, that would be looking at

```
<div class="poll">
  <div class="vote-form">
    <div class="choices">
      <?php if ($block): ?>
        <div class="title"><?php print $title; ?>:</div>
      <?php endif; ?>
      <?php print $choice; ?>
    </div>
    <?php print $vote; ?>
  </div>
  <?php // This is the 'rest' of the form, in case items have been added. ?>
  <?php print $rest ?>
</div>

```

so, if in your theme CSS you added

```
.poll {
  color: red;
  background-color: blue;
}

```

this block would now be in red and blue.

and if you added

```
.vote-form {
  border: 2px solid green;
}

```

then the form would have a border of green. etc etc etc.

Now, if you need to change things up more, add some more divs or change their order, etc, you can just copy the standard poll template to your theme directory, refresh your caches and drupal will pick it up and override the one from poll itself, no need to name it anything different.
> 1 votes

---
Tags: 6, theming, polls
---