# Question
Title: how to print login_days with user_stats module?
```
<?php print format_date(user_stats_get_stats('login_days', $node->uid), 'custom', 'j'); ?>

```

Returns "1" always, how to use user\_stats - login\_days correctly?

# Answer
> 2 votes
As Berdir stated in the comment, `user_stats_get_stats('login_days'...)` returns a number of days so you can't use this with `format_date`, also I tried this on my site and if you're the author of the node this function will return nothing, but if you try with other users that have logged in, this should display the number of days since their last access.

In fact if you're only using this module for this function, it may be a little overkill and you should better do this manually:

```
$u = user_load(31);
print floor((time() - $u->access) / 86400);

```

Edit: 12/06 11:57 If you want to format the last access date then do:

```
$u = user_load(31);
print format_date($u->access, 'custom', 'j M H:i');
//will display 12 Jun 12:03 with hour formated in 24H.

```

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


# Question
Title: Difficulties with the #ajax form item attribute
My form item is the following one:

```
$form['foo'] = array(
  '#title' => t('Foo'),
  '#type' => 'radios',
  '#options' => $options,
  '#description' => t('Lorem ipsum.'),
  '#required' => true,
  '#ajax' => array(
    'callback' => 'foo_get_js',
    'wrapper' => 'foo-wrapper',
    'event' => 'click',
    'method' => 'replace',
  ),
);

```

My AJAX function is the following one:

```
function foo_get_js($form, $form_state) {
  return mktime().'<xmp>'.print_r($form_state['values'], true).'</xmp>';
}

```

My wrapper will get updated the first time the ajax call is made, but after that it will stay the same: the time and `$form_state` don't get updated. If I use the 'append' method instead of the 'replace' method then everything works as intended.

Is it the supposed behavior?

# Answer
Since 'foo-wrapper' is replaced at the first call, it doesn't exist in the second call, and therefore, the callback doesn't know where to put the return value.

A simple solution would be to include a wrapper in the return value, with the same id as 'foo-wrapper'.

```
function foo_get_js($form, $form_state) {
  return '<div id="foo-wrapper">' . mktime() . '<xmp>' . print_r($form_state['values'], true) . '</xmp></div>';
}

```

Please note that this is untested.
> 10 votes

# Answer
If you use replace, you also need to return the original wrapping tag which has the 'foo-wrapper' id.
> 1 votes

---
Tags: forms, ajax
---


# Question
Title: Theming html output of privatemsg 6.x-2.x module
How can I theme the output of Privatemsg? I took look at http://api.worldempire.ch/api/privatemsg/privatemsg.theme.inc/group/theming/1, but I didn't understood how to use that. I want to totally change the HTML output for the message list.

How do I use my custom date format in the messages? I guess the `format_date()` function would help me, but how do I use it correctly?

`print format_date($messages_timestamp, 'custom', 'd=m=Y')` returns "01.01.1970." What is that?

# Answer
Ok, here is some information.

* That list shows *threads*, not single messages. You can't change that, at least not with theming. The only thing you easily can do is enable the privatemsg\_limits module and set the number of messages per thread to 1. That basically disables threading and each message will be sent as a new thread. Then they will be shown separetly on the list, but they will also be shown separately on the thread view page. Privatemsg views is currently only compatible with 6.x-1.x and looks rather unmaintained at this point.
* You can configure the displayed columns and their order in the Privatemsg settings.
* The theming functions are used to customize the content of single columns. For example, to show a different date format, you can override phptemplate\_privatemsg\_list\_field\__last\_updated():

```
function phptemplate_privatemsg_list_field__thread_started($thread) {
  $field = array();
  $field['data'] = format_date($thread['thread_started'], 'custom', 'd.m.Y H:i');
  $field['class'] = 'privatemsg-list-date-started';
  return $field;
}

```

In 7.x, Privatemsg shows a different date format depending on the age of the message, that is done in privatemsg\_format\_date() if you want to backport that.
* To change how the table *looks*, you should be able to that with just CSS. Privatemsg adds tons of classes to that table, including a seperate class for every column and classes for rows with new messages and soon for unreplied messages too.
> 2 votes

# Answer
format\_date() requires a UNIX timestamp, which is an integer containing the number of seconds passed from January 1, 1970; when you pass a value that is 0, `NULL`, or a string that doesn't start with a number, then the result of the function is January 1, 1970.

In your case, it could also be that `$messages_timestamp` is not a defined variable, a variable that has been unset, or a variable that has been set to `NULL`.
> 0 votes

---
Tags: theming, privatemsg
---


# Question
Title: Hook into node operation from theme template.php?
I have made a new content type in Drupal 7 in Drupal Admin (not via module). What I want to do is to add a Hook on the insert and update operation. How can this be done when my node type is not created by a module?

Can this be done at all?

# Answer
> 4 votes
You want to create a custom module. Note that nothing stops you from creating content types through the user interface, it is in fact the suggested way to do so nowadays with fields and stuff (instead of using `hook_node_info()`)

Node API Hooks contains an overview of all hooks that can be used to interact with nodes at different events like create, view, delete..

# Answer
> 1 votes
Just wanted to add a comment on how I solved it in case anyone else needs it. This function ads a taxonomy term equal to the node title into a vocabulary defined in the function when a new node of your chosen type is inserted:

```
function node_title_taxonomy_node_insert ($node) {
if ($node->type == '<your node type>'):
    // Get vocabulary ID for vocabulary name
    $vocabulary_name = "<Vocabulary name>";

    // Prepare taxonomy term
    $taxonomy_term_name = $node->title;

    // Add vocabulary and term
    _node_title_taxonomy_add_vocabulary_term($vocabulary_name,$taxonomy_term_name);
endif;
}

```

Thanks for the help Berdir :)

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


# Question
Title: Comments - Allow deletion of comments on your content without Administer Comments permission?
Is there a way to allow users to delete comments that are on their own content without giving access to Administer Comments?

Example:

Authenticated user makes a blog post (or some node content) Another Authenticated user comments on it

Author does not like comment- wishes to delete.

The only option I have is edit/reply.

# Answer
> 3 votes
Should be doable with the User Comment module in Drupal 6, or the Comment Access module in Drupal 7. They both add permissions so that authors can approve, delete or administer comments on their own content.

# Answer
> 0 votes
Another way would be the use of the nodecomment module with Drupal 6. This way you have permission by contenttype like `delete own MYCOMMENT content`

---
Tags: users, comments
---


# Question
Title: Transition plan for PHP5 abomination to Drupal
# Background

A year from now my clients are going to port a relatively complex intranet portal service (scheduling, actual tracking and reporting, and more) to Drupal because the head office says so. Very little effort has been made to determine if this is the right technical choice and it is beyond the control of my client's or even their bosses.

The current portal is an abomination that is in the process of being re-factored and I believe the most cost effective plan will be to bring in a domain model layer via Doctrine 2 and put 99.9% of all business & input validation logic into the models, gutting out the abomination until it is a skeletal view & authentication logic layer.

# Question

For any Drupal specialist out there, does this seem like a viable approach? Could Doctrine2 play nice with Drupal or does Drupal higher level logic need a much tighter integration to the data?

# Answer
> 9 votes
We have done a few sites where we have connected outside systems to Drupal where the data **had** to be kept in the outside system. This is what I spend most of my time working with.

When we do this, we typically create a content type to "stub out" the content in the other system. The content type only contains the node title and a CCK field for the unique identifier in the other system. Along with this are a lot of hook\_nodeapi functions. For example, the `load` hook will call out to the remote system and add the data to the node. You also need to devise a method for getting the outside data into search results. There are a few methods for this, but those are too lengthy to get into here.

While there are some downsides, we find this works well and allows normal Drupal stuff like comments, tags, etc.

# Answer
> 4 votes
The only sensible thing to do, given the time line, is to build this in Drupal 7. One of the most prominent features of Drupal 7, is entities, DBNTG and fields.

**A quick overview**

* Entities is a way of defining a data structure. Examples of entities that is built in with Drupal is, nodes (main content), users, taxonomy terms.
* Fields is something that can be attached to an entity, which also holds data. Using fields has the advantage of only having one place to handle the data and they can be extending in various ways. An example of a field could be a file attachment, or a reference to another entity.
* DBTNG (Database the next generation) is what the Drupal community had codenamed the new database abstraction layer. Before this, we used to do queries with placeholders (which is still supported), but now most queries are built with class. A reason for this is also that fields get their database table(s) created based on settings. This helps creating code that will work, even if the field(s) are created with different settings.

This is just some of the features, but this means that unless you want to create a Drupal abomination, you should start thinking about how Drupal works and use that instead of trying to make Drupal work a way it wasn't designed for.

Since Drupal is PHP you could create custom modules and use Doctrine2 to do what you want. But my guess is that you will end up with a site that has very little in common with most Drupal sites.

# Answer
> 4 votes
This is quite a broad question so I'll give a high level answer, if you have more specific questions please ask them as separate questions.

I would suggest that you map out as much as possible the structure of the current site. What types of things does it do, what workflows are there. What is the content what are the users.

Content types are a handy way of dividing up content. Even the abomination would have had types I thing ( I would have hoped) that map to URLs.

Once you have determined the content types then you can look at migrating the content, to your new site. Then you can look at things like workflows, schedules, users, etc.

I would favor moving wholesale. Having content being managed by more than one system is a huge technical headache. And doubles your maintenance effort.

One thing I would say, is that it may be worth hiring someone in to do it. There have been some very successful Drupal migrations with huge data sets. But if you are not experienced in Drupal you may make several mis steps and cost yourself a lot of time. (I can personally recommend cyrve, I have no current affiliation with them)

---
Tags: database, migrations
---


# Question
Title: Update multisite modules and core in one click
I have a Drupal multisite install with 7 different sites, all sharing the same modules, themes and users but everything else is unique to the individual site. At the moment, I only have to upload one version of Drupal core or any contributed modules when I want to update them but I have to run `update.php` on each website separately. Is there an easy, quick way of making all of these updates run simultaneously?

# Answer
> 2 votes
I think the simple answer is no. And generally you would want it to be so.

Running update.php can cause sites to fail, so you should back up each sites database run update.php and then check it works. Each of your sites will work slightly differently, depending on the combination of modules. So a broken update hook, or a conflict would be something that you would want to check carefully for.

Having said all of that there are tools such as aegir which may make this possible to do safely.

---
Tags: 6, updating, multi-sites
---


title: Content Profile fields in rules

text:
# Question
Title: Content Profile fields in rules
I am using rules and want to access a field in a users content profile. how can I do this?

# Answer
> 2 votes
In Rules, there is a simple action that will allow you access to a user's content profile information. In your rule, select "Add an action" and choose `Load Content Profile`:

On the next page, first choose which user to load (ex. logged in user, acting user, content author, etc). This depends on what Event you chose for the rule. Next choose which profile content type you want to load and click "Save".

Now, other actions you add after the first step (loading the content profile) will have access to the fields of the user's content profile. If you have the Token module installed, settings for new actions should have a fieldset titled `Token replacement patterns`. Expand that fieldset and you should see another fieldset titled `Replacement patterns for Content Profile`. Expand that one to see all content profile tokens that can be used however you like. Ex:

---
Tags: 6, rules, users
---


title: need a help with if:else conditions cck

text:
# Question
Title: need a help with if:else conditions cck
```
function ruh_microblog_item($node) {
  $profile = content_profile_load('profile', $node->uid);
  $ava = theme_imagecache('microblog', $profile->field_photo[0]['filepath']);
  $noava = theme_imagecache('microblog', 'sites/default/files/imagecache/user_block_small/imagefield_default_images/no_photo.png');
  $content .= '<div id="mwrapper">';
  $content .= l($ava, 'user/' . $node->uid, array('attributes' => array('title' => $profile->title, 'class' => 'micro'), 'html' => 'true'));
  $content .= l($profile->title, 'microblog/'. $node->uid, array('attributes' => array('class' => 'microname', 'title' => 'Микроблог - '. $profile->title)));
  $content .= check_markup($node->title, $format = 'Full HTML', $check = TRUE);
  $content .= '<div class="clearfix"></div>';
  $content .= '<p align="right">' . l(format_interval((time() - $node->created), 1, NULL), 'node/'. $node->nid) . ' назад</p>';
  $content .= '</div>';
  $content .= '<br />';
  return $content;
}

```

The code above displays a CCK field (field\_photo), but what happens if the user has an empty "field\_photo"?
Would the following code work?

```
if ($profile->field_photo == TRUE) {
  $content .= l($ava, 'user/' . $node->uid, array('attributes' => array('title' => $profile->title, 'class' => 'micro'), 'html' => 'true'));
}
else {
  $noava = theme_imagecache('microblog', 'sites/default/files/imagecache/user_block_small/imagefield_default_images/no_photo.png');
}

```

# Answer
> 2 votes
```
if(!empty($profile->field_photo)) {...}

```

Should be able to work for you.

---
Tags: entities
---


# Question
Title: Is there a D7 module that allows you to create a content type to be displayed as a system message?
Is there a D7 module that allows you to create a content type to displayed as a system message?

Something like http://drupal.org/project/user\_alert but gets displayed in the system messages.

# Answer
It would be a lot of overhead for this one function but Rules can trigger arbitrary system messages with Token support. Here is a screencast by Node One which can give you an overview and he does the system message example in a couple of the videos. I think that if you need extended interaction with users Rules can be very helpful.
> 2 votes

---
Tags: 7
---


# Question
Title: Adding a new taxonomy term from a custom content type field
Is it possible to automatically add a new taxonomy term (related to certain vocabulary) from a field in a custom content type; so when submitting a new content entry (related to that custom content type) I add a new taxonomy term related to that entry to create a richer tagging functionality by time for future entries?

# Answer
> 1 votes
Check out taxonomy\_save\_term(). Here's an example from the comments:

```
$term = array(
'vid' => 5, // Voacabulary ID
'name' => 'Drupal', // Term Name
'synonyms' => 'Druplet', // (Optional) Synonym of this term
'parent' => 11, // (Optional) Term ID of a parent term
'relations' => array(15), // (Optional) Related Term IDs
);

taxonomy_save_term($term);

```

You could use this inside hook\_nodeapi() on the operations `insert` or `presave` (and `update`). See the comments at the first link for more info.

EDIT: For drupal 7 you have to check out the node api instead of of hook\_nodeapi().

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


# Question
Title: How to do taxonomy based css styling using template.php?
I'm looking forward to implement taxonomy terms based CSS styling; especially for the body tag which I want to add the current terms.

Here is what I have so far:

```
function _phptemplate_variables($hook, $vars = array()) {
  global $node;

  switch ($hook) {
    case 'page':
      // die ('test');
      $vars['body_class'] = '';
      if (arg(0) == 'taxonomy' && arg(1) == 'term' && is_numeric(arg(2))) {
        $vars['body_class'] = 'theme' . arg(2);
      }
      if (arg(0) == 'node' && is_numeric(arg(1))) {
        $node = node_load(arg(1));

        if (is_array($node->taxonomy)) {
          foreach ($node->taxonomy as $term) {
            $vars['body_class'] .= 'theme'.$term->tid;
          }
        }
      }

      if (drupal_is_front_page()) {
        $vars['body_class'] .= ' front';
      }
      break;
  }

  return $vars;
}

```

I think the code is OK, but it never get called (see my 'die' function); using simple phptemplate engine and minimal Drupal 6 install.

What obviousness am I missing here?

# Answer
> 1 votes
The reason it is not called is because `hook_preprocess_variables` is for Drupal 5: you should use hook template\_preprocess\_page in Drupal 6.

So if your theme is called "`mytheme`", the function would be best named "`mytheme_preprocess_page`" in your template.php.

---

Also, Drupal and the Taxonomy modules already generate many body classes, so you should check out what classes already exist because it may be that you don't need to preprocess the page at all (if all you want is to add a body class depending on taxonomy).

# Answer
> 0 votes
Well, years ago we wrote this up http://openconcept.ca/blog/jmlane/taxonomy\_specific\_css

It would need to be updated I expect for Drupal 6 or 7 but the principals still apply.

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


title: Customize a "Feature"

text:
# Question
Title: Customize a "Feature"
I'm trying to create a feature that includes an Automatic Nodetitle.

I want to change two things related to Automatic Nodetitle: Hide Title in content creation and populate the field with tokens.

How would I go about this?

# Answer
Use the strongarm module. When creating the feature select "Strongarm" from the component section then look for the variables that start with ant\_{content type name}

Automatic Nodetitle can have up to 3 different variables for every content type.

ant\_'{content type name} ant\_pattern\_'{content type name} ant\_php\_'{content type name}

Export those variables out with your content type and you should be ok.

This works in Drupal 6 & 7.
> 5 votes

# Answer
Apply the patch I wrote, #881170: Add Features support to Automatic Nodetitles, and it will work fine. When it works, comment on the issue and maybe the maintainer will eventually commit it.
> 3 votes

---
Tags: 7, features, nodes
---


# Question
Title: Migration has spun ubercart into checkout redirects
I just migrated Drupal from my development site to my production site. This included a full database migration as well as a file migration.

Now, after adding products to my shopping cart and then clicking the checkout button all that happens is that the shopping cart refreshes. This happens whether or not I'm logged in.

# Answer
> 1 votes
I had a very similar problem with Ubercart in my site as well. The difference is that I would end up getting told that there was an infinite redirect and that seem to be quite what you're hitting. However, the root cause *might* be the same. I had an error in an email template that was supposed to get sent after completing checkout. I would suggest checking your server logs and possibly even setting `display_errors = On` in your PHP config. Also check your Watchdog logs for any errors.

---
Tags: ubercart, migrations, 6
---


# Question
Title: Uncooperative Access Control settings for View in a Panel
I have a "Project" custom content type, and a View displaying existing Projects. The site has two types of users, with most users permissions set to only view Projects they created. The other user type is an 'admin' type who can view anything.

The site has half dozen custom modules I wrote. Among that custom logic are three new permission types: "View CEX Projects", "Access CEX Services" and "Admin CEX Services". Plus the associated hook\_access() implementation handling the access situations for the Projects.

The issue that I'm having is the Access settings for the View. I can't seem to find the right combination of settings so a regular user only sees Projects they created. Maybe it's right in front of me and I'm missing it...

The Projects View has three displays. There is a "Page" that displays all Projects with an 'active' field set to true; There is a "Page" displaying all "inactive" Projects. And there is a Block-View of the first Active Projects View, displaying fewer Projects before paging than the "full page" version.

Other than the "active" field's use in the Filters, the two Page versions are identical. Other than the number of Projects displayed, the Page and Block versions are identical.

In Basic Settings-\>Access they are configured for "Multiple roles", with the roles selected being the roles with permission to view/access/admin the webapp's projects/services.

There is a Relationship (and a related hook\_views\_data() implementation) connecting the author of a Project to the Views data of that Project. This is used in the Filters area for a Node Access filter. The Node Access Filter is supposed to use each Project's UserID for determining access to that Project.

Problem is the View (all three versions) display all the Projects. What's displayed is summary data, and links to the Projects. Clicking a link to a Project one does not own goes to an Access Denied page...

It's as if the Node Access Filter using the UserID relationship is not working at all... There's not much of an interface to the Access Control filter... it just asks if it should use the UserID relationship or not... selecting either one makes no difference.... maybe the Access Control Filter does not control display of the output??

Added: Here's the query generated by Views (interesting that I don't see any access logic):

```
SELECT DISTINCT(node.nid) AS nid,
   node.title AS node_title,
   node_node__users.name AS node_node__users_name,
   node_node__users.uid AS node_node__users_uid,
   node_revisions.teaser AS node_revisions_teaser,
   node_revisions.format AS node_revisions_format,
   node.vid AS node_vid,
   node.type AS node_type,
   DATE_FORMAT((FROM_UNIXTIME(node.changed) + INTERVAL -25200 SECOND), '%Y%m%d%H%i') AS node_changed_minute
 FROM node node
 LEFT JOIN node node_node ON node.uid = node_node.uid
 LEFT JOIN cex_project cex_project ON node.nid = cex_project.nid
 INNER JOIN users node_node__users ON node_node.uid = node_node__users.uid
 LEFT JOIN node_revisions node_revisions ON node.vid = node_revisions.vid
 WHERE (node.status <> 0) AND (node.type in ('cex_proj')) AND (cex_project.active <> 0)
 GROUP BY nid
  ORDER BY node_changed_minute DESC

```

Added again: I just noticed this series of Views generated PHP error messages in my dlog:

```
Warning: Parameter 3 to views_ui_build_form_state() expected to be a reference, value given in views_ui_ajax_form() (line 1606 of C:\wamp\www\sites\all\modules\views\includes\admin.inc).

Warning: call_user_func_array() expects parameter 1 to be a valid callback, no array or string given in drupal_retrieve_form() (line 378 of C:\wamp\www\includes\form.inc).

Warning: Invalid argument supplied for foreach() in views_ui_build_form_url() (line 1542 of C:\wamp\www\sites\all\modules\views\includes\admin.inc).

Warning: Attempt to assign property of non-object in views_ui_ajax_form() (line 1613 of C:\wamp\www\sites\all\modules\views\includes\admin.inc).

```

turning off the "Use ajax" setting seems to have stopped those error messages, but the Access issue still exists: anyone gets all Project nodes in their View even if they do not have access to them. Clicking a Project node a user does not own triggers the Access Denied page.

# Answer
> 1 votes
What I would do in this situation is create a view with two page display that have the same menu path. Set up the master permission of the 1st view to what ever the admin role is. Set up the master permissions of the 2nd view to be what ever permissions that is. Also modified the 2nd view (the one with the least protective permission) to filter based on nodes created by the current user.

Views it self will know that one view should be display to one user over the other. So your users with the admin permission will see the view with out the filter then other users will see the 2nd view which is filter by project they've created.

I'm not sure what your access function are doing, but this is one solution. Also I'm not sure how you're using the panel, so can't really comment on it.

# Answer
> 0 votes
Have you considered passing in the user as an argument to the view? If you use a views content pane, the argument can come from a panel context. Or maybe I misread your question?

---
Tags: views, 7
---


# Question
Title: how to compare two content type fields and filter the output by drupal views?
I have two content types.

```
*content_type1
*content_type2 [set as content profile]

```

In `content_type1`, I have a taxonomy term \[user has to choose any one of term\] and `content_type2` has cck select list field with same terms as `content_type2`.

I created two roles:

```
*role1 users can create content_type1
*role2 users can create content_type2

```

Now I want to display list of `content_type1`s in user `role2` profile page whose "select field Value" is as same as the "taxonomy term " of `content_type1`.

How can I implement this using drupal views?

# Answer
> 1 votes
Seems to me that you're going to need this:

views\_embed\_view() inside of the **user\_profile.tpl.php**

more specifically:

First set up a view to return content type 1 nodes, that takes an argument of taxonomy term id.

Then, assuming you can get the content type 2 node into user\_profile.tpl.php, grab the select list value like so:

```
<?php
    $selected_value = $content_type2_node->field_selectlistname[0]['value'];
    $term_id = taxonomy_get_term_by_name($selected_value);

?>

```

note use of taxonomy\_get\_term\_by\_name()

and use of a cck select list field named is field\_selectlistname, update that to your field name.

then you can use this:

```
<?php
   print views_embed_view("view_name","block_1",$term_id);
?>

```

to print out your view.

Note that the first two arguments are the view name of your view, and the display id, which is going to be something like 'block\_1', 'default' or 'page\_1'

I'm assuming here you know how to set up the view, and know how to get that user\_profile.tpl.php to work for your role.. (if isset($account-\>roles\[ role id \])... )

good luck!

---
Tags: views
---


# Question
Title: How do I filter the user who have logged in once in a view?
I need to create a view that shows the users who have logged in once to my site. How can I implement this with Views?

# Answer
> 4 votes
Take a look at the User Stats module. This will provide a count of how many times users log in and it integrates with Views 2

---
Tags: views, users
---


# Question
Title: How to set the permission for particular role user to access the user profiles of users with a particular role?
I have two user roles:

* business\_users
* company\_users

I want to set the permission for all users to see the user profile of users in "business\_users" role only.

* User with the "company\_user" role should not to see user profile of user in their role but they can see user profile of user in "business\_users" role.
* User with the "business\_users" role can see user profile of users with their role but they should not see the user profile of users with the "company\_user" role.
* Anonymous users should see user profile of user in "business\_users" role only.

Can you tell how can I implement it?

# Answer
You can make a template file for your profile content type, probably called something like node\_profile.tpl.

At the top of this file, write some code that will get the user object of the node owner, and check this against user's roles in `$user->roles`.

It's easier if you do this with the roleID numbers (you can see these by going to user\>role and hovering your mouse over the various links for the roles - the roleID appears as a number somewhere in the link).

Your code in the template then may look something like this. You'll need to know php to understand how it executes.

```
$userRoles = $GLOBALS['user']->roles;
$account = user_load($node->nid);
if(!empty($userRoles[2])) {
  // user is a company user
  if(!empty($account->roles[2])) {
    // profile belongs to a company user
    print 'Company users are only allowed to see business user profiles';
    return; // this will stop execution of the template file, and return to the page template
  } elseif(!empty($account->roles[1])) {
    // profile belongs to a business user
    // do nothing - just continue code execution of this template
  }
}

```

For your listings of users, you'll want to make three different views, with views filters in each to determine which users you want displayed. For this, you can create a page which chooses the name of the view based on the user's role(s) - either a "page" with the php code in the body (if you have php code as one of your input types), or else a page you create with a small custom module using `hook_menu()`.
> 1 votes

# Answer
Hello Dakshina Murthy I think you can refer this link and most probably It would help you out http://drupalmodules.com/category/User+management?page=6
> 0 votes

---
Tags: users
---


# Question
Title: how to give edit permission content to new user in drupal?
I have a content type called "company." I have uploaded a lot of company details to the site by myself.

Now I want that people employed by these companies create new accounts in my site, and they should be allowed to edit the details for the company where they work.
I need to give the permission for editing the "company" nodes in my site to new users.

Can you tell me how to implement this?

# Answer
> 3 votes
If there is only a single user that will have permission for a given company node, you can assign them as the author of the company node and give them the "edit own company nodes" (or similar) permission.

If there are multiple, it's going to be trickier, you could for example add a hidden user reference field to the company node (which only you can edit, with a field permission module) and use http://drupal.org/project/nodeaccess\_userreference. Or use http://drupal.org/project/content\_access, which allows to configure permissions for single users directly.

---
Tags: nodes, users
---


# Question
Title: How to distribute a Drupal website on a flash card?
I would like to take a Drupal website and distribute the information on it on a flash card or DVD -- even if it is a read only version. The people who will be using the website will not always have internet access. Plus, it's the type of information that somebody would like to sponsor. So at intervals the website will be published onto a flash card or DVD with a company logo on it and the website will be branded to the company. Any ideas?

# Answer
You can run a dynamic, database-driven Drupal site from a DVD or Flash memory stick using a system like portable XAMPP, which is designed to run on removable drives, and includes Apache, PHP and MySQL.

If you only need static pages, you can use the HTML Export module, which will export all your image, JavaScript and CSS, and export your nodes as HTML pages. I've tried it and it works as advertised.
> 7 votes

---
Tags: 7, theming
---


# Question
Title: How do I associate multiple nodes to a user?
I have some users, and I have a "product" content type, which has the following fields: "name," "type," and "description."

I want to associate specific nodes of this content type to a user. How do you suggest I should do this?

Shall I create a new table and store the user and the product ID?

# Answer
> 3 votes
There is a module for handling relationships between entities for Drupal 7 which shows great promise called relation. At the current time it's still in alpha and I haven't tested it out for a while, so I am not sure where it is at. When I last tried it out, it wasn't quite suitable.

A more stable version which could be made obsolete by the relation module is the references module, which is a port of the Drupal 6 CCK node reference field. I've used that with great success.

# Answer
> 0 votes
Possibly look into using a 'user reference', part of CCK in Drupal 6 to link products to users.

---
Tags: 7, nodes, users
---


# Question
Title: How to add a new tab to user profile in administration?
How can I add a new tab to user profile beside `View`(active tab) and `Edit`. I want to add for instance `New User Tab` which will be visible only by administrator (not by the user itself).

I want to add in this tab some informations related to the user and to make some associations with specific nodes related to the user.

# Answer
If this is for Drupal 7, you should take a look at the profile2 module. It allows you to create a profile entity where you can add any fields. It also creates tabs on the user page via permissions.

In general to create tabs, you need to create menu local items. Views 3 support this, and it is also possible to create such a tab with `hook_menu` by setting the `type` to `MENU_LOCAL_TASK`. There are some requirements to the path of the url to make this work, but this is all well documented at the drupal API reference, linked to above.
> 6 votes

---
Tags: 7, users
---


# Question
Title: How to embed Twitter  and E-mail links inside a webform?
I want to embed inside a webform a Twitter and E-mail button,so as the user to post/share the page to his Twitter account or e-mail it. How to do that? Thanks

# Answer
> 2 votes
There is a module for that, in fact there are many. Since a webform is a node, it makes the possibilities much greater. An example of a module that allows users to share your content in various ways is the Service links module.

---
Tags: nodes, webforms, social-network
---


# Question
Title: How to move custom code into template.php
In my node.tpl.php file I have this custom code:

```
<?php if($node->field_division['und'][0]['value'] = 1):
    $cta = $GLOBALS['base_url'].'/node/6';
elseif($node->field_division['und'][0]['value'] = 2):
    $cta = $GLOBALS['base_url'].'/node/7';
endif;
?>

```

I want to move it to my template.php file, so I can access it both from node.tpl.php and page.tpl.php.

How can I do this?

I tried following the examples in this thread and this article but I can't get it to work. Any help would be greatly appreciated.

# Answer
> 6 votes
First off, don't use `'und'`. You should use `field_get_items()`. This is a change from D6, which is likely why you can't use those articles as a reference.

Secondly, you are using `=` and not `==`, so you're assigning the value instead of comparing it.

So, you can probably just do the following:

```
function THEMENAME_preprocess_node(&$variables) {
  THEMENAME_field_division_helper($variables);
}

function THEMENAME_preprocess_page(&$variables) {
  THEMENAME_field_division_helper($variables);
}

function THEMENAME_field_division_helper(&$variables) {
  if ($node = $variables['node']) {
    $field_division = field_get_items('node', $node, 'field_division');
    if ($field_division[0]['tid'] == 1) {
      $variables['cta'] = $GLOBALS['base_url'].'/node/6';
    }
    else if ($field_division[0]['tid'] == 2) {
      $variables['cta'] = $GLOBALS['base_url'].'/node/6';
    }
  }
}

```

And then in your node.tpl.php and page.tpl.php file,

```
<?php if (isset($cta)): ?>
  <div class="some-wrapper">
    <?php print $cta; ?>
  </div>
<?php endif; ?>

```

---
Tags: theming
---


# Question
Title: How to get only the first value of a field in a Views template
I'm using Views 3.0 and I'm trying to access a field which allows users to upload 3 photos. When I type `print $fields['field_productshots']->content;` it displays all 3 product photos. Is there a way to limit it to just the first image?

# Answer
When editing the view, there's an option for Multiple field settings. By default view is going to set it up to Display All starting at zero.

You can easily change it to display 1 starting at zero. This will only show the 1st image now.

Hope this helps.
> 5 votes

---
Tags: 7, views
---


title: View query result

text:
# Question
Title: View query result
when i created view it shows the result and and the query in a preview and here is the query

```
SELECT node.title AS node_title, node.nid AS nid, node.language AS node_language,
node.created AS node_created, 'node' AS field_data_field_image_node_entity_type, 'node' AS field_data_body_node_entity_type
FROM
{node} node
WHERE (( (node.language IN  ('en')) AND (node.type IN  ('news')) ))
ORDER BY node_created DESC
LIMIT 2 OFFSET 0

```

there is a field that hold the image value i think (field\_data\_field\_image\_node\_entity\_type) but when i loop the result it does not display image value inspite it displayed in view result preview how am i get this value of image to display it rather than using views

# Answer
Views doesn't directly query every piece of that it needs to render data.

Some of the data is build on the pre\_render hook.

The pre\_render hook runs after the initial view query and is used to generate some of the missing data.

In drupal 7 views uses a pre\_render hook for loading the fields via a entity\_load and then field\_get\_items.

This is also common in the drupal 6 version of view. One good example is the Taxonomy get All terms. This is also build on the pre\_render hook.

If you want to get this field without using view you can do this

```
$entity = entity_load('node', $nid);
$image_field = field_get_items('node', $entity, 'name_of_the_field');

```

The field you want is now in the $image\_field variable.
> 2 votes

# Answer
Most likely views is doing an entity load, to get the node and all of it's fields. You could do the same, for nodes you can do node\_load($nid).
> 1 votes

---
Tags: views
---


# Question
Title: How to show only an image of the YouTube video while using Media: YouTube module?
Is there a way to show an image of a youtube video instead of the actual player ? This would be done only for the teaser view of the node.

I know that I can show a video thumbnail, but I need an image that looks like the actual player.

Thanks.

# Answer
If you can grab the id of youtube video then you can use following pattern of url to get a bigger youtube thumbnail.

`http://img.youtube.com/vi/[your video id]/0.jpg`
> 3 votes

# Answer
This would require a little work on your behalf to write a small module to get the youtube thumbnail and then process it.

For example if you use Embedded Media Field with Media: Youtube then you can get the URL with `$node->field_emvideo[0]['data']['thumbnail']['url']` (\*field\_emvideo\* is the name of your field) and use it with ImageCache Actions to add a background image which would be the Youtube player.

I don't have a full code to offer but using ImageCache API (see the code snippet at the bottom) is quite simple, ex:

```
<?php
 print theme('imagecache', $preset, $image['filepath'], $alt, $title,  $attributes);
?>

```

Good luck ;)
> 2 votes

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


# Question
Title: Drupal 7, Custom Content Type... Does an addon that does this exist?
I rebuilding my companies intranet... we have what's called a portal. Within the portal is pages. Each portal page is either HTML, a PDF or a Video.

Right now... I'm planning on creating 3 seperate content types. One with Text, one with a custom PDF Object for loading in browser and one for a video. So content types like:

```
PAGE content Type
* Title
* Image (Icon for content flagged News)
* Text with Teaser

PDF content Type
* Title
* Image (Icon for content flagged News)
* PDF Object (loads PDF in browser)

VIDEO content Type
* Title
* Image (Icon for content flagged News)
* Video Field

FILEVIEWER content Type
* Title
* Image (Icon for content flagged News)
* FileViewer Viewer

```

Notice... a lot of duplication.

What I'd like to do, and tell me if I'm stupid... is I'd like to have a drop down selector that shows the content type selected, while hiding the rest.

```
COMBINED CONTENT TYPE
* Title
* Image
* Select List (Three, or more, choices: Text, PDF, Document, Video)
* Text w Teaser
* Video Field
* PDF Field
* Fileviewer Field

```

It will display the selected content type and hide the others when displayed on the actual node/block. This particular case is simply "Select One type", so I'm not worried about selecting combinations (ie: Text + Video)

I'd just much rather baby one content type... than 3+ content types with near identical layouts.

Question updated. Basically... it's my desire to have one content type instead of 4 (and possibly more). I'm not afraid to make my own custom module, although it would be a learning curve.

# Answer
The obvious choice for that functionality would be the conditional fields module. It's still under development for D7, but you can check if it already supports your use case, or maybe you could even help the maintainer get the D7 version to a stable state.
> 4 votes

# Answer
I'm not very sure I understand your question, let me rephrase it: you have a content type with fields and a select list. Regarding of the value of this select list, you want to display some fields and hide the others. Correct ?

If so, I would build my fields in a preprocess function and define some variables to display only the fields depending on the value of your select.

Can you clarify a little your question so I can update my answer ?
> 1 votes

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


title: Adding content to Drupal database

text:
# Question
Title: Adding content to Drupal database
I'm running a rather large Drupal 6 site and I need to include additional information in the database, things that run independently of Drupal. Is it best to create a separate database and connect to it from the files I need to access the info from, or is it just safe to add a custom table to the Drupal database and add whatever I want in there?

Thanks!

# Answer
In theory, it's no problem to add tables to the database. It won't hurt Drupal. That said, I wouldn't recommend it. If things already *are* separated and there is no important reason to use a single db, just keep them separated for flexibility and performance in the future.
> 1 votes

---
Tags: 6, database, theming
---


# Question
Title: user relationships - add friend link in a content-profile node
I have installed the User Relationships module, and I have questions about how it works.

When you install the module, a "relationships" link should be added in a user profile page (users/myname), but in my case it doesn't; I've modified user-profile.tpl.php, and cleared the cache, but still the link doesn't appear. What's wrong?

How can I add a link to "add/remove friend" on a content-profile node of user? And also how to output list of user's friends? I guess a view block would help me in this situation.

# Answer
I followed the instructions that I found in the documentation of the module, and everything worked absolutely perfect. The steps for your reference were:

1. Enabled the modules: UR-API, UR-Mailer, UR-UI, UR-Views
2. Created a new relationship (e.g. friend)
3. In Permissions make sure that you have enabled the **can have relationships** permission in the **user\_relationships\_api module** (this is what I forgot the first time)

The rest of the permissions are pretty straight-forward. If you follow the instructions to the letter, you will get the link in the user profile page.

P.S: The guide in the above-mentioned link has a screenshot for the required permissions: **make sure that your permissions match this screenshot's EXACTLY**.

As for the block that you want to create:

Enable the UR-blocks module. It creates sample useful blocks (including a block for each relationship that you created). You can insert this block directly in the profile node using the corresponding tpl.php file and a code like the one that you can find in this article:

Drupal - How To Display Block In Node?
> 8 votes

---
Tags: users
---


# Question
Title: how to force  image file and music file  to download with zip format in drupal 6?
i have content type to upload music and image files.i want to provide a link to the users to download those music and image files.By using force download module , i can provide the download link for the file ,but now i want to zip the file when user click the download link and so user can download the image or music file in zip format.

i have installed the pclzip module and custom formatter module and i think we can achieve this by creating custom formatter for those cck field,but i dont know how to implement it? or any other module suggestion? thanks in advance.

# Answer
I'll answer with a question, do you want to make a zip file because it's an easy way to force browser to download the image or the mp3 instead of showing it ?

If so I'll recommend you the File Force Download module to achieve this. Also you have DownloadFile module and a .htaccess way to do this: Force Files to Download Instead of Showing Up in the Browser but I don't find this one to be very flexible.
> 1 votes

---
Tags: entities, files
---


title: Views RSS post date removal

text:
# Question
Title: Views RSS post date removal
What is the best way to remove the post date from a views created RSS feed? I have a calendar that I have created a feed for, but it is being sorted by a cck date value, making the post date not necessarily accurate.

Is there an easy way to remove this from within views (D6), or would this need to be a template change?

# Answer
This approach should work. I've tried it in the past and it did exactly what I needed.

Quoted from the above-linked comment:

Put `views-view-row-rss.tpl.php` in your theme directory

and replace `print $item_elements`;

with

```
$item_elements = preg_replace('<pubDate>.*</pubDate>', '', $item_elements);  // removes pubdate
$item_elements = preg_replace('<dc:creator>.*</dc:creator>', '', $item_elements);  // removes author
$item_elements = preg_replace('<category .*</category>', '', $item_elements);  // removes terms

$item_elements = preg_replace("!^\s+(\D)!m", "\\1", $item_elements);  // removes some blank lines

print $item_elements;

```
> 3 votes

# Answer
I did something like this about two years ago, so it is possible that things have improved since.

From memory I think you need to do a template change for this kind of thing in views rss feeds. It was not as flexible as it could be.
> 0 votes

---
Tags: views, 6, feeds, datetime
---


# Question
Title: Add a class to a div depending on which term was clicked
Since clicking on a taxonomy term opens a page showing all pages using that term, how do I **identify which term was clicked** so I can add a unique icon to each one? What do I type in *template.php* so I can add it to my *page.tpl.php* like so: `class="<?php if(this-term-was-clicked) : ?> add-this-class <?php endif; ?>"`

I have 3 terms right now and would like to customize the display of each one by adding a unique icon before the title.

# Answer
> 1 votes
The taxonomy term that is click will already have the class "active" applied to it.

The selector `.field-type-taxonomy-term-reference a.active` is the one you are probably looking for.

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


title: Creating special RSS channels

text:
# Question
Title: Creating special RSS channels
How can I create RSS channels for certain content type or it's subtype (certain taxonomy terms from that content type, so that users can effectively filter the information they need).

thank you

# Answer
You can build RSS feeds easily with views, after creating your first display (generally a page), you can click "+Add" and add a feed display, then you configure your fields and you're almost done.

In the "Filter Criteria" section you select your Content Types and or the taxonomy you want to target.
> 3 votes

---
Tags: 7, feeds
---


title: How to create "Add to my List"?

text:
# Question
Title: How to create "Add to my List"?
I have a movie site and I want users to be able to add movies (node) to their list by visiting the movie and it should have a link saying "Add to my list". When they are about to add to their list it should have a selection box with options like watching, completed, on-hold etc...

An example site http://myanimelist.net/anime.php?id=269 you can see when you click their "Add to my List" it gives some more options like status, eps seen, score

So how can I do this?

# Answer
> 2 votes
I would recommend using the Flag module, as it provides this functionality for users upon install. The Nodequeue module is intended for admin-configured lists.

# Answer
> 0 votes
Use the nodequeue module http://drupal.org/project/nodequeue: The Nodequeue module allows users to collect nodes in an arbitrarily ordered list. The order in the list can be used for a any purpose, such as...A user’s favorite music albums or the flag list module http://drupal.org/project/flag\_lists

---
Tags: 7
---


# Question
Title: Get the titles of the nodes whose node IDs are contained in a field
```
$attr = explode(",", $node->field_xlnum[0]['value']);

```

`$node->field_xlnum[0]['value']` contains `20,4,56,987,68,96`, where each value is a node ID. I want to get all the titles, and output them in an HTML list. How do I do it?

I tried the following code, but it doesn't work.

```
$attr = explode(",", $node->field_xlnum[0]['value']);
$result = db_query("SELECT nid, title FROM {node} WHERE nid IN ($attr) AND type = %s order by created DESC", test);
while(($items = db_fetch_object($result)) {
  $output = theme_item_list($items, array('class'=>'tabs primary'));
}

echo $output;

```

# Answer
> 0 votes
Following up on what tostinni posted, this is what worked for me. I also added the `$title` parameter. It's supposed to be the second parameter, and if you leave it out, the `array('class'=>'tabs primary')` would be used as the second parameter instead, which wouldn't work quite right. I simplified the query a little since I don't have a content type called 'test,' but you can put that in easily:

```
// the $attr should be a string
$attr = $node->field_xlnum[0]['value'];
// $attr put into a placeholder
$result = db_query("SELECT title FROM {node} WHERE nid in (%s) order by created DESC", $attr);

/***
  * if you put theme_item_list into the while loop,
  *  it will create separate lists for each item,
  * instead of adding 'li's to one ul, as I'm assuming you want?
  */
while($items=db_fetch_object($result)){
// put the title strings into an array
    $list[] = $items->title;
}
// including the $title parameter - if not needed, you can change to $title = NULL
$output = theme_item_list($list, $title = 'A list', 'ul class="tabs primary"');
echo $output;

```

# Answer
> 3 votes
A few remarks:

1. You said that `$node->field_xlnum[0]['value']` contains a list of nid separated by comas so you don't need to explode it in order to use them in a IN clause. If you do so, $attr will be an Array().
2. You put `test` as an argument in your query, isn't this a variable `$test` or a string `'test'`
3. You should better use db\_placeholders for putting multiples values inside a IN.

```
$attr = explode(",", $node->field_xlnum[0]['value']);
db_query("SELECT n.nid, n.title
  FROM {node} n
  WHERE n.nid IN (" . db_placeholders($attr, 'int') . ")
  AND type = %s
  ORDER BY n.created DESC", $data, 'test'
);

```

---
Tags: 6, entities
---


# Question
Title: Filtering the terms of a specific vocabulary
How do I get all the taxonomy terms of a specific vocabulary? If a page has terms coming from 2 vocabularies (e.g. "Software" and "Hardware"), how do I display the terms coming only from the vocabulary "Software," and not from "Hardware"?

# Answer
In a view, to filter terms from a page tagged with more than one vocabulary, so that only the terms from, say, `Hardware` show, you would:

* under **Format**, change the default 'Content' format to 'Fields'
* under **Fields**, add a 'Taxonomy: All Terms' field
* scroll down to the 'More' section and click
* you should see a screen like below, which allows you to filter terms to a single vocabulary (or more, if needed) http://img850.imageshack.us/img850/9266/filtertoonevocabulary.png
> 1 votes

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


# Question
Title: Where can I find an exhaustive reference of the Views module
I am new to the views module and am trying to get my head around how it works and what the possibilities are with it. Is there a resource, book, video tutorial, or site somewhere that does a good job of explaining the whole module from beginning to end?

# Answer
Here some things to start with:

And some nonfree stuff:
> 4 votes

# Answer
This is an excellent tutorial: http://nodeone.se/blogg/taming-the-beast-learn-views-with-nodeone-0
> 5 votes

---
Tags: views
---


# Question
Title: CCK E-mail field, display e-mail form in js dialog
I set display cck field to 'e-mail contact form'. It lead to page like email/15/field\_email.

Is this possible to display that form in modal dialog? Which modules I should use?

# Answer
> 1 votes
You can do this with a few lines of JavaScript.

All you need to do is to create a iframe that links the the clicked link and then open it in a dialog. jQuery UI has support for dialogs. There is modules for integrating jQuery UI and upgrading your jQuery version (if needed).

Once that is done, you can add the JavaScript to your theme to create the wanted effect.

---
Tags: 6, entities
---


# Question
Title: CSV node import using feeds module on a Mac
I'm using the feeds module to try to import several thousand nodes, but I'm getting mixed results: sometimes it seems to work, sometimes it doesn't.
I understand there are some sort of issues related with the line endings in the CSV files when they are created on a Mac. I tried saving my CSV for Unix (LF) and Windows (CRLF), but that doesn't seem to fix the problem entirely either.

Does anyone else have this problem? Is there a definitive solution or workaround for this?

# Answer
I've had the most success importing CSV files by importing them into Google Docs (spreadsheet) first and then exporting from Google Docs as a CSV file. It might seem like a silly workaround but Google spreadsheets seems to handle inconsistencies in CSV files a little better than Excel or Numbers.

Give it a shot. I've just used the same method for a Feeds CSV import.
> 7 votes

---
Tags: 7, nodes, feeds, importing-exporting
---


title: Gallery with Album Covers

text:
# Question
Title: Gallery with Album Covers
I currently have two node types: Album (CCK), and Image (image module, using Image FUpload module).
A user creates an album, simply a title. When they create Image(s), the album is node-referenced.

I have a view of Albums, and I would like to pick one Image from each album to show as a cover photo. I cannot just add a CCK field to the Album for this; the image needs to appear in the view of album images, and every image can be voted and commented on, as well as have their own references (tags).

I tried a few relationships in the View, nothing seemed to pull the image for an album. Is this possible using the Image module?

# Answer
I finally decided to add a 'Cover' cck field to the Album type. I could not find a way in Views to correctly relate an Album to a View of photos for this purpose using Relationships.
> 0 votes

---
Tags: views, media
---


title: Video conference module

text:
# Question
Title: Video conference module
I have some doubts about the Video Conference module.

* Can we integrate the video conference module in Drupal 6?
* Can we use Dokeos for video conference?

# Answer
> 2 votes
It looks like that module is in the very early stages of development and is not widely deployed.

There is an abandon dokeos module as well, but I think that you may be out of luck with this particular feature?

---
Tags: 7, files
---


# Question
Title: Output the field as $<field_name>_rendered in the node page
When a CCK field is added, we get the rendered output in the node page as `$<field_name>_rendered`.
How can we get a variable in the same way when we alter the form and add new field?

# Answer
To load the data back to the node and render them, you first need to implement a hook\_nodeapi load. Here some a short example:

```
function satya_module_nodeapi(&$node, $op, $teaser, $page) {
  switch ($op) {
    case 'load':
      // retrieve the p1 value from custom_table (it's better to use vid instead of nid to allow revisions.
      $p1 = db_result(db_query('SELECT p1 FROM {custom_table} WHERE vid = %d', $node->vid));
      return array('p1' => $p1);
      break;
  }
}

```

Then you will have a `$p1` variable available in your `node.tpl.php`.

If you don't know yet the Examples modules, I'll definitely recommends it to have great examples and developer documentation for a lot of hooks.
> 2 votes

---
Tags: 6, entities, nodes
---


# Question
Title: What would be the reason for a registration page to hangs after submit?
For some reason whenever i try to submit a new user registration (on a fresh drupal 7 install), the data is correctly sent to the Back end but the page doesn't seem to redirect to the intended location (by default the home page)but instead seems to endlessly submit.

I am pretty sure this come from my testing server as it does it even on a fresh drupal install. Is there anything that would come to your minds on what could be the cause of this problem ? We are using ubuntu server with all latest software updates.

# Answer
> 0 votes
Drupal uses a lot of files so make sure the real\_path\_cache in php.ini is increased dramatically.

> max\_execution\_time to around 120
>
> realpath\_cache\_size to 512K, 1M or even 2M.
>
> max\_input\_time to around 120.

# Answer
> 1 votes
Check `memory_limit` for your Drupal instance.

On `settings.php` add this line

```
ini_set('memory_limit', '128M');

```

---
Tags: users
---


title: Theming user-edit form drupal 6

text:
# Question
Title: Theming user-edit form drupal 6
After installing tons of modules like guestbook, subscriptions etc. It also added tons of settings on `user/$uid/edit` page. How can I disable or rearrange them?

I guess `theme_fieldset()` would help me, but I have no idea how to use it correctly. And where to `print_r($form)` and in which template?

# Answer
devel themer will help you understand what you can over ride and what variables are available.

hook\_form\_alter() can be used to trim fields that you don't want and to re order the form, put things into groups etc.
> 3 votes

# Answer
hook\_form\_alter

```
function hook_form_alter(&$form, $form_state, $form_id){
    switch($form_id)
        case 'user-profile-form':
        // Change $form array to alter form components
        break;

```
> 1 votes

---
Tags: theming, users
---


# Question
Title: Integrate Radioactivity with Apache Solr (sort by popularity)
Has anyone integrated integrated Radioactivity with Apache Solr?

I'm using the apachesolr module for search and would like to add the ability to sort by popularity. The Radioactivity module assigns points to a module based on 'hotness' (fivestar ratings, comments, views, etc). I want to submit the points Radioactivity gives a node to Solr to use as a popularity index.

I believe that means I'll need to modify the schema.xml file on the Solr end and add some sort of hook on the drupal end. Can anyone point me in the right direction?

# Answer
You should be able to do this without modifying `schema.xml`. At a minimum, you'll need to implement `hook_apachesolr_update_index()`, and you may also need to implement `hook_apachesolr_modify_query()` to add the Radioactivity data to each query.

Good examples for this can be found in the apachesolr\_search.module file itself (and the apachesolr\_date module that comes bundled with apachesolr), and also in the additional contrib modules apachesolr OG and apachesolr attachments.

The apachesolr\_date module in particular has some code related to adding an available sort option.
> 1 votes

---
Tags: search
---


# Question
Title: RSS feed not updating using feeds module
I have an RSS feed that has not been updated after the initial import. I actually managed to get it to update once using cron, but even that has since stopped working. Looking at the original feed, I see it is being updated, but I'm not getting the updates on my site.

My feed importer settings are as follows:

* It is attached to a specific content type
* The minimum refresh period is 15 minutes
* The option "Import on submission" is checked
* The fetcher is "HTTP"
* The parser is set to "common syndication parser"
* The processor is "node processor"
* I respecify the content type in node processor settings
* The input format is the default one
* "Expire nodes" is set to "never"
* "Update existing nodes" is set to "Update existing nodes (slower than replacing them)"

Is there anything else I need to do, maybe configure something in Job Scheduler? I couldn't find a UI for it.

EDIT: Upon checking `admin/reports/dblog` as per Jeremy's suggestion I found the following error:

> Download of failed with code -1003.

Does anyone know what this means or how I can fix it?

# Answer
> 2 votes
If you look at /admin/reports/status does it say that cron is running?

If cron is running then looking at the watchdog entries ( admin/reports/dblog) around the time it is running may give you an insight.

If that dosn't work then you may have to start putting debug into the modules code to work out what is going wrong.

---
Tags: 7, feeds, updating
---


title: Custom home page with block and jqDock

text:
# Question
Title: Custom home page with block and jqDock
I'm a newbie in Drupal, and I have a really important web site to build. I've started with a Zen template, so I can build the entire theme from scratch.

I've looked around for better practices and best ways to do this, and finally decided to start by doing the "Master-Layout" on the "page.tpl.php" (I've figured that it's the best place for the global website structure), plus, I'm using the default CSS's files do arrange the things on the page.

But now, I need to start the "home page" content section. It will have a few "blocks" and I still have some things that isn't clear what I can do to build this way.

For example, I have a "News" structure, that the authors use it to insert the news articles. I need to list the news on the home page much like an accordion style, with the image related.

Other example, the site will have a dynamic menu, using a jQuery plug-in like this: http://www.wizzud.com/jqDock/, and each item on this dock, will come from the Drupal database. Should I create a modulo to accomplish this? Can you guys help me??

# Answer
> 0 votes
For home page:

* Clone your page.tpl.php as page-front.tpl.php in order to customized work for your home page.

Listing nodes in accordion: * Use views to build a list for you * User Views Accordion to format them in accordion

jqDock menu: jqDock menu can be build using your content templates. But it should be clear what type of data coming from your database.

For custom data you will have to build your own module to fetch data.

---
Tags: 7, theming
---


title: Passing nid into a context view

text:
# Question
Title: Passing nid into a context view
I have a context that is fired when it is on a node page. I wish to pass the nid of the node being viewed, into a view to display on the page. Is this possible? How would you go about doing this?

# Answer
Node id can be accessed by `arg(2)` function call on node page view. It would even work if you have defined a url alias using path/auto\_path modules.

On the view, where you manage argument options, Try with `Provide default argument option` as `Node ID from URL`
> 0 votes

---
Tags: views, 6
---


# Question
Title: Uploading images in a node with WYSIWYG and TinyMCE 3.4.3
I am trying to put images in a node with the WYSIWYG editor and TinyMCE 3.4.3.
I uploaded an image, and with the editor I inserted the image in a node; the problem is that at first click the image doesn't appear in the node, and I must try another time to see the image. Is it a bug?

# Answer
Check your `Input Filters` field-set while editing your node, in case of `filtered html` your image would not be presented. Try with `full html`.
> 1 votes

---
Tags: 7, wysiwyg
---


title: Placing Panels Content Above Menu

text:
# Question
Title: Placing Panels Content Above Menu
I am trying to use panels to implement something that in the past I had done with blocks. My theme has a region called "content top", this displays content above the secondary menu (the tabbed menu that every node has with view edit etc). When I switch over to panels, I can't figure out how to place content in any other region except for the main area ... any ideas

# Answer
> 2 votes
Panels are page nodes and can not be put into regions as we do with blocks. Try mini panels to create panels for regions or itself panels.

# Answer
> 1 votes
You can disable all standard Drupal blocks in the panel page settings and add menu directly to panel.

---
Tags: routes, blocks, nodes, panels, theming
---


# Question
Title: Is Drupal 4.7 compatible with Mysql 5.1 and PHP 5.3
I am having some strange problems with Drupal 4.7.11 on my local machine. Before I get into it I should give you some context. I am running PHP 5.3.4 and MySQL 5.1.54.

If I try to run Drupal 4.7 without any DB info it comes up to a screen that asks me to put in the DB connect info. Once I do that I get a white screen in my browser and in terminal running cron.php I get a DB connect error.

Now as I was writing this I realized that PHP 5.3 is probably a problem here. But I might as well ask anyway.

So thoughts on compatibility?

UPDATE: I realized that my machine is running two different versions of PHP because I am on a Mac and it has 5.3. However, my Apache is running from Zend Desktop which is 5.2. So the site is setup in 5.2 right now.

# Answer
> 6 votes
I think that both may be an issue. PHP definitely is. I'm not sure about Mysql.

Drupal 4.7 is quite a few versions out of date and it is no longer being maintained. You really should be looking to use a more recent version.

# Answer
> 3 votes
Only Drupal 6 (from 6.14 onward) and Drupal 7 are compatible with PHP 5.3.

---
Tags: database
---


# Question
Title: Preserve Current Paths before rolling out new Pathauto Alias
I'm just about to roll out a new Pathauto Alias to include a new taxonomy term, which will modify about 1000 nodes. Is there a way to preserve the current path aliases I have now, and then bulk update all my nodes to the new pattern?

I assume I'll need to use Path Redirect in conjunction with Global Redirect somehow to keep the old paths pointing to the new paths?

Thanks!

# Answer
To preserve AND redirect existing aliases when you implement a change like that:

* install the Path Redirect module
* open the 'Automated Alias Settings' in URL Aliases (admin/build/path/pathauto)
* open the 'General' fieldset
* change the radio button for 'Update action' to 'Create a new alias. Redirect from old alias' (see screenshot below).

http://img705.imageshack.us/img705/2738/redirectaliasleaveintac.png
> 2 votes

---
Tags: 6, redirection, path-aliases
---


# Question
Title: "Invalid argument main.js" Gmap error in IE
I have GMap Module and GMap Location version 6.x-1.1; in Internet Explorer (any version), on the GMap page I see this error:

> Message: Invalid argument.
> Line: 401 //in IE8, and 942 in IE6 Code: 0
> URI: http://maps.gstatic.com/intl/fa\_ALL/mapfiles/310c/maps2.api/main.js

I found a question on Stack Overflow, but the answer doesn't apply in my case, as the lat attribute is true.

What is problem?

# Answer
> 1 votes
i solved this problem. in Gmap Module setting and Google Map Initialize check default center and enter valid coordinates. in my case default center was setted to 0,NAN. problem was with **NAN**. at now it works in IE.

---
Tags: 7, google-maps
---


title: Letting anonymous user to see fields?

text:
# Question
Title: Letting anonymous user to see fields?
I just created a content type with a field:images. Then I added some content and I create a View to show these content. Then the view shows the images (from the images field) Everything works fine but when I logout the anonymous user can not see the images.

As you can see in this picture I have "checked" Access content for anonymous user. But it doesn't work...

.

What I need to do to make the images visible for anonymous users is to have 'checked' View field\_images. You can see the picture.

my question: do I need to checked on every field I create to make them visible to anonymous users? Is there any way to set that any new create field should be visible to anonymous users.

Thanks

# Answer
> 4 votes
If there is no field permission module installed, all fields are always visible. So if you don't want to restrict *any* fields, then disable the content permissions module.

Once such a module is installed, it works as implemented by that module. And there is no way for such a module to guess the permissions you want (should it be visible to auth users only, or anon users too.. maybe only a specific role?), so it can only chose the safe way and does not grant anything automatically.

That is consistent with all other permissions, when you install a new module.

---
Tags: users
---


# Question
Title: Can I stop D6's email sending to blocked users?
I have a few actions. They send email to authors. The problem is, I don't want emails to be sent if the user is blocked.

Any suggestion is appreciated.

ps: I couldn't create a tag on drupal.stackexchange.com . So tagging this custom-module for posting sake.

# Answer
> 1 votes
You could use hook\_mail\_alter() to check the mail before it's send and filter it depending on your conditions.

---
Tags: 7
---


title: drupal and php code

text:
# Question
Title: drupal and php code
is it standard or good way to put code in block with php fiter format and use another drupal benefit (handling users,contents,roles,another modules)?

for example i need to use jquery ui dialog. i can use this module. another way is to paste jquery ui dialog script in php code block.

or

i need a special query from database for admin. i have create a page and use content access module and paste my code (including html,jquery.php) in php code block.

or inserting user in drupal database with query in block

# Answer
It is in most cases a bad idea, unless there is no other way. See What are the downsides of using PHP Filter code in blocks, nodes, views-args, etc?, which is pretty much the same question.

Instead of creating a block/page/... with PHP code, I suggest you create a module that exposes a block or uses hook\_menu() to expose a page.
> 6 votes

# Answer
I would say it depends. If you want to have the code editable via the UI this is ok. In that case the code may be seen as part of the *content* and I think it fits. Another case would be if you don't want to write/update an own module or theme.

In every other case I would always try to bring the code into the filesystem instead of the database. There are multiple reasons for that:

* reuseability of code (keep it DRY)
* use of version control (like git or svn)
* better maintainability of codebase

Apart from that I think many things simply can't be done without writing own modules (and implement drupal hooks and stuff like that) and themes but the other way around I don't see such limitations. Correct me if i'm wrong.
> 4 votes

---
Tags: blocks, input-formats
---


# Question
Title: Is it possible with Drupal Views to have AND and OR in a filter set?
I am attempting to build a view with four filters (A, B, C, D). With Views 3 it is possible to select whether you want these filters to be chained with AND statements or OR statements. Is there a way to configure views so as to chain some of them with AND and others with OR?

For example, ending up with a query that is similar to:

```
SELECT *
FROM {table}
WHERE A = 0
  AND B = 0
  AND (C = 1 OR D = 1)`

```

# Answer
Looks like this is entirely possible with the Views 3.x branch. You can create custom Filter groups directly in the Views UI itself, and set the AND/OR for each group separately.
> 5 votes

# Answer
If you still wish to use views2 you can write your own filter as I did.

Though, in my case the only requirement was to place `OR field IS NULL` in the query.. so it worked for me.. i hope it could be extended further.. If someone likes the idea.. I could upload the code.. here..!!
> 0 votes

---
Tags: views
---


title: Views vs Performance

text:
# Question
Title: Views vs Performance
I'm designing a huge media site. It would need to have about 20 views on the homepage and should attract about 100,000 visitors daily. The site is hosted on a dedicated server. Other than setting up Drupal caching and Boot module, should I be doing anything else to optimize performance? Should I be worried about using Views?

# Answer
> 9 votes
Performance is very subjective and varies widely from site to site, depending on how much custom code you have, how many logins you have, and what your expected usage patterns are.

The first thing you should do is figure out what your expected usage patterns are going to be, put them in a spreadsheet and estimate how many concurrent visitors you'll have on various pages, etc (for example, how many logins will happen at one time, which pages have the highest traffic, are your users authenticated or not).

The second thing you should do is prepare some kind of load test using something like LoadStorm, or even something very basic like JMeter. Set up some scenarios that mimic or exceed your expected traffic patterns. Then run the tests.

When you start load testing you will very quickly see where the bottlenecks in your site are. You can take cachegrind dumps of your site while you are load testing to see where the performance bottlenecks are using the XDebug profiler. You can also watch your database performance (CPU/memory and disk I/O are easy things to keep an eye on).

Once you've done all that, you can look into the following:

Drupal has a decent listing of caching modules/options and how they perform for authenticated and unauthenticated users here.

# Answer
> 3 votes
20 Views on one page sounds excessive. Views isn't great on performance. I have pages with 5 views and they are not fast.

Even with the views results cached loading the views into memory and processing them can still take time. Obviously when the page is cached this issue goes away, but on a busy site the time it takes for a cached page to be built can be an issue.

Caching and tuning can help a little. But you still need to get the page to display in a reasonable time if it is uncached. You may find you can write custom blocks to do the work of the views with a much lighter overhead. It is worth trying it to see what difference it makes.

Using XHprof can help you see what is taking the most time on a page load.

What are effective optimization techniques for Views 3? explains the issues I was having with views

---
Tags: views, 6, performance, caching
---


# Question
Title: Field template in theme based on Garland
I have problem with template for field "field\_is\_new" in Drupal 7. My\_Theme is a modification of the Garland theme. (I don't know if it's important.)

I have created a template for this field in my theme folder ("My\_Theme/templates/field--field-is-new.tpl.php").

In template.php, I added:

```
function My_Theme_preprocess_field(&$variables, $hook) {
  // Add specific suggestions that can override the default implementation.
  array_unshift($variables['theme_hook_suggestions'], 'field__' . $variables['element']['#field_name']);
}

```

I cleared the cache, and rebuilt the theme.

I was thinking it's good way to do this, but it's not working. What's wrong?

# Answer
> 1 votes
Your preprocess function is not necessary in this situation because Drupal's default behavior is using this sort of files. Try `print_r($variables['theme_hook_suggestions']);` and see all relevant suggestions.

Your problem is the wrong filename; try field--field\_is\_new.tpl.php instead.

The general recommendation is using theme functions:

```
function theme_field__field_taxonomy($vars) {
  $output = '';

  foreach ($vars['items'] as $delta => $item) {
    $array = explode(';',$item['#markup']);

    if (count($array)) {
      $output = '<ul class="' . $vars['classes'] . ' clearfix"' . $vars['attributes'] . '>';
      foreach ($array as $value) {
          $output .= '<li>' . trim($value) . '</li>';
      }
      $output .= '</ul>';
    };
  }

  return $output;
}

```

---
Tags: 7, entities, theming
---


title: Translate untranslated words in Drupal

text:
# Question
Title: Translate untranslated words in Drupal
I'm using calendar module and I noticed when browsing web that some words are not translated (e.g. "prev," "next," "day," "week," "month," "year"). Is it possible to write somewhere the translation for these words?

# Answer
Content Translation module can help us using Translation Interface (example.com/admin/config/regional/translate/translate) in this regard to search the string and then define a translation against appropriate language.

The strings can only be translated if they are not hard coded and used with `t()` function.

`t()` always searches for appropriate translation with respect to currently selected language otherwise it returns the original string.
> 1 votes

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


# Question
Title: Drupal's built-in xss filters vs. HTML purifier module
Does the htmlpurifier module for Drupal provide better security against xss (and possibly other vulnerabilities) than Drupal's built in functionality such as filter\_xss?

Looking for some guidance on why I should use htmlpurifier module for Drupal if I'm purely concerned with security (NOT concerned with preserving inline styles).

# Answer
> 4 votes
I trust the filter\_xss function a bit more than htmlpurifier simply due to the complexity of the htmlpurifier code. Neither function is easy to understand, but at least filter\_xss is shorter and more stable.

It is true that htmlpurifier is a general library used by other systems and therefore it could have "more eyes" on it. If you look at the HTMLPurifier Summary they claim that kses (which is what filter\_xss was originally based on) is "Probably" XSS safe but misses out on other features of HTMLPurifier. The Drupal input format system handles many of the other features that HTMLPurifier mentions in that table so it's not an apples-to-apples comparison.

By the way, you may want to post questions like this to https://drupal.stackexchange.com/ in the future.

---
Tags: 7, security, input-formats
---