title: add sharethis button to a slideshow

text:
# Question
Title: add sharethis button to a slideshow
I'm trying to add a button Sharethis to a slideshow "views\_slideshow" that shows the whole content to the specific element in the slideshow. the problem is I can't add this button to the slideshow, and I have it to show inside a block.

# Answer
> 1 votes
Figured it out, you just add "shareThis" to your content type you want this to show in a slide show, and since we are showing the whole content it will show with the rest of the node.

---
Tags: javascript, social-network
---


# Question
Title: How do I create templates in my custom module?
I've created a custom module that has a bunch of PHP functions whose main purpose is basically to output HTML. For example:

```
function showRecentActivity($tid, $recordStart, $count){
    //do some db_select stuff to get an array of node IDs...

    foreach($nids as $nid){
        $node = node_load($nid);

        //now that we've loaded the node, 100 lines of if, echo, etc. will follow in order to output the HTML to the page
}

```

Perhaps you can already see the problem. While echoing HTML is fine for small pieces of markup, constructing full pages with echo statements is horrible to code, maintain, and very bug-prone.

Obviously what is needed is a pre-defined template file, written in HTML with just small places for echoing the necessary PHP variables. Just like my theme's template files.

But I have no idea how to do this with my custom module.

# Answer
hook\_theme is your friend, it allows you to modularize your markup in two ways:

1. Allows you to define a template file for your markup.
2. Allows you to define a theme function.

No matter which way you go, you will call for the markup the same way. so lets say you wish to modularize markup for recent activity. You will do the following in your custom module:

```
function custom_module_theme() {
   return array(
     'activity' => array(
       'variables' => array('variable1' => NULL, 'variable2' => NULL),
       'template' => 'custom-module-name-recent-activity',
     ),
   );
 }

```

You will create `custom-module-name-recent-activity.tpl.php` in your module directory where you will have $variable1 and $variable2

Your `custom-module-name-recent-activity.tpl.php` will look something like this:

```
<div class="some class"> <?php print $variable1; ?> </div>
<div class="class2"> <?php print $variable2; ?> </div>

```

And then from your module when you have done your processing and have established `$variable1` and `$variable2` (you can pass as many as u want), you will simply do:

```
theme('activity', array('variable1' => $variable1, 'variable2' => $variable2));

```

Hope this helps, I wonder now if I should have linked to some tutorial. But hey its Saturday :)

(And if you are using Drupal 6, change 'variables' to 'arguments' in the code above.)
> 14 votes

---
Tags: theming
---


# Question
Title: Very simple but working drush extension?
I want to implement my own Drush command, and struggle because while the "Make me a sandwich" example is very good, it's also quite complex, and for someone that has never made such an extension it's easy to loose track of what is mandatory, and what is optional.

I would like to see a basic Drush extension implementation.

# Answer
> 5 votes
This is valid for Drush \>= 4

```
<?php
/**
 * @file EXAMPLE.drush.inc
 * Provides a simple drush extension example
 */

function EXAMPLE_drush_command() {
  return array('COMMANDNAME' =>
    array(
      'description' => 'My example command',
      'bootstrap' => DRUSH_BOOTSTRAP_DRUSH,
    ),
  );
}

function drush_COMMANDNAME_validate() {
  // Return
  // drush_set_error('MACHINE_NAME_OF_FAIL', dt('Command failed because [reason]'));
  // on error.
}

function drush_COMMANDNAME() {
  echo 'Extension working!';
}

```

---
Tags: drush
---


# Question
Title: JPG user photos not displaying in Drupal 7
In D7, when I upload a photo to a user profile page, the image displays if the original extension was a \*.png file, but not if it was a \*.jpg file. Uploading the files places them in sites/example.org/files/pictures, which indicates that the permissions are correct. But jpg files don't diplay on users' profile or forum posts. Instead the words "username picture" is displayed.

In admin/config/people/accounts, enable user pictures is enabled. However, I did not add a existing image field in admin/config/people/accounts/fields.

Basic page, articles and forum has an image field (field\_image), with allowed extensions png, gif, jpg, jpeg.

# Answer
> 1 votes
"username picture" is likely the alt text applied to the image. So it's trying to render an image, but failing because the web server can't find it. If you check the page source, is it trying to show the image with a .png extension instead of .jpg? If not, is the path correct?

If either the extension or the path are wrong, this could be a problem with the template. Perhaps it was hard coded in the past and settings have changed since?

---
Tags: media, users
---


# Question
Title: How do I get the Subscriber UID in Simplenews to Create Personalized Newsletters?
I am using the insert view module to create a personalized newsletter, now I need to pass the subscriber uid as a parameter to the view but I am not finding a way to do that. Any ideas ?

Thanks !

# Answer
> 2 votes
This isn't possible in Drupal 6.

Simplenews 7.x-1.x now provides a simplenews\_subscriber variable for the body template. It also automatically switches the global user to the one that is receiving the mail while it is generated.

---
Tags: views, emails
---


title: Using views_embed_view and jquery

text:
# Question
Title: Using views_embed_view and jquery
I'm calling a block in a template like so:

```
echo views_embed_view('sessions_by_track', 'block_1');

```

where the block is actually a view display. It's set to output html lists, and I want to do some jquery stuff to it, including hiding certain elements until something else is clicked on.

Here's what the list code looks like:

```
<ul data-role="listview">
  <li data-role="list-divider"><a href="/tracks/big-picture-0">Big Picture</a></li>

  <li class="views-row">
    <div class="views-field-title">
      <span class="field-content"><a href="/sessions/tracks/partnering">Partnering for Success</a></span>
    </div>
  </li>

  <li class="views-row">
    <div class="views-field-title">
      <span class="field-content"><a href="/sessions/tracks/the-shopper-economy">The Shopper Economy</a></span>
    </div>
  </li>
</ul>

```

I have a scripts.js file that looks like this:

```
$(document).ready(function() {
  alert('test');
 $('li.views-row').hide();
});

```

The alert works; the hide doesn't. However, when I run that line in Firebug's console after the page has finished loading, the hide does work. So it seems that the view renders after the document.ready fires. I seem to recall reading something about this before, and there was a solution, but of course now that I need it I can't for the life of me find it. What do I need to do to get around this?

Edited to add: Drupal 6, Views2

Edited again to add: I've also tried this: in template.php added this function:

```
function mobile_jquery_preprocess_page(&$vars, $hook) {
  $vars['embedded_sessions'] = views_embed_view('sessions_by_track', 'block_1');
  $vars['scripts'] = drupal_get_js();
}

```

and then calling it in my page template like so:

```
print $embedded_sessions;

```

Same result.

Edited yet again to add that I've tried adding a new region to my template, assigning the block to that region, and then printing it with `print $mobileContent;` in the page template. Same result - the alert runs on load, but the hide does not. The hide runs just fine in Firebug's console, so I know the selector is OK.

**Edited once more for @tim.plunkett**

To a file called scripts.js, located in sites/all/themes/mobile\_jquery/scripts, I added this (right now there's nothing else in the file):

```
(function ($) {
  console.log('behavior triggered');
  // Store our function as a property of Drupal.behaviors.
  Drupal.behaviors.myHomeHideLists = function (context) {
    // Find all the li items inside context that have our desired class
    $('li.views-row)', context)
      // hide them.
      .hide();
  };

}(jQuery));

```

In template.php, I added this (based on this answer):

```
function mobile_jquery_preprocess_page(&$vars, $hook) {
  $vars['embedded_sessions'] = views_embed_view('sessions_by_track', 'block_1');
  drupal_add_js(drupal_get_path('theme', 'mobile_jquery').'/scripts/script.js', 'theme');
  $vars['scripts'] = drupal_get_js();
}

```

The console.log does get triggered and printed, but the list items that match the selector do not get hidden.

# Answer
> 1 votes
Drupal provides a specific way to add JS to a page, to ensure that it is run whenever content is loaded into the DOM. This way, it will run after the document is loaded, but also after AJAX operations.

They're called Drupal behaviors.

---
Tags: views, 6, javascript
---


# Question
Title: Construct POST data and send it to an external page
Is there any way to construct post data and send it to an external URL, like how a form will send POST data to action URL?

I am aware of `drupal_goto()` function, but it is not possible to send POST data using it. I am also aware of `drupal_http_request()`, but I do not want a response from the URL here. I just want to submit data to the URL from my custom module. How can I achieve this? Any help is appreciated.

# Answer
> 1 votes
This is a PHP question, really. But here's an answer: http://wezfurlong.org/blog/2006/nov/http-post-from-php-without-curl/

Many many caveats; read the comments.

# Answer
> 0 votes
CURL is th swiss army knife to do such things. CURL stands for client URL library. It allows you to do everything programmatically what you can do manually in a browser (and a lot more).

---
Tags: 6, forms
---


title: Custom login page with redirect

text:
# Question
Title: Custom login page with redirect
I've set up a custom login page witht the difference that that one should redirect the user to another page.

I use the default drupal login form so I dont really now how to fix the form alter for my custom form without it to change the default login form too.

What could I do to fix this?

My code:

```
function mymodule_cv_login() {
    // Print the user login form
    $form = drupal_get_form('user_login');

    $form['redirect'] = 'cv';

    return $form;
}

function mymodule_form_alter(&$form, &$form_state, $form_id) {
    if ($form_id == 'user_login') {
        $path = 'profil';
        $form['#action'] = url($_GET['q'], array('query' => array('destination' => $path)));
    }
}

```

# Answer
> 2 votes
You can check what page you are on by looking at $\_GET\['q'\] (or using the arg() function) so you could base your alter on that.

# Answer
> 1 votes
There is always the Login Destination module http://drupal.org/project/login\_destination which I will probably handle the cases you want to cover as well.

---
Tags: users, forms
---


# Question
Title: Is there a module that will add an image field that displays an image from an off site source?
Im on d7. I'm looking for a way to have images displayed on my site from another image hosting site such as imgur or imageshack. Right now I've been using the media module for uploading images to my site and it works great, but I don't want to store the image on my server. I need the ability to "source" where the image came from, but the media module doesn't store that info, it just downloads the file. thanks for your suggestions.

# Answer
> 2 votes
You should take a look at the remote stream wrapper module and this issue that explains how to do it.

# Answer
> 1 votes
Unless Media Flickr does exactly that, I don't think what you ask for is available to this point.

The best suggestion I have, is to write a module that extends media, to do what you want. I've been involved in a project to integrate media with a media bureau's photo repository, so I know that it can be done. Unfortunately, there is no code from that project I can point you to at this point. The media flickr module may be a good source of inspiration though. This is the best solution because once understood, will require little work to extend to a second service, and it can be contributed back to the community. The problem here is that media seems to be a moving target at this time.

The second best suggestion, is to wrap an imagefield with a custom widget (for node edits) and a custom formatter (for node views) that does what you want. This will unfortunately become a specific re-implementation of media, and as such, not a general solution.

---
Tags: 7, entities, media
---


# Question
Title: User cannot change password due to lack of "current" password
If a user signs up & login with a 1-time login link (Since the site is configured to moderate users), and if they don't set their password and navigate away, they can no longer come back and set a password as Drupal will now require their "current" password (which obviously does not exist).

Is there any way around this? Not have Drupal ask for a "Current password" when none is set, perhaps?

# Answer
I side stepped this issue by tracking the last change time of the user's password in a new db table, and then checking to see if a time stamp exists for their last change. If not, then ignore the Current Password field validation (don't even bother checking), and thus the user can change their password without running into that issue.

Probably not the most 'secure' way to go about it, strictly speaking. But this is technically the *same* behaviour Drupal exhibits by default if a user uses a 1-time login link. If they decide to walk out right then and there to grab a coffee with their computer wide open in a public space, then hey, no amount of server-side security is going to protect them from their own stupidity.
> 1 votes

# Answer
Not requiring the current password seems like a huge security problem. Anyone who turns their back to the computer for a moment can have their password changed without their knowledge.

A user that finds oneself in this situation will need to request a new one time login link.

I would also suggest the box where a new password is entered should be better highlighed if this is a common problem.
> 1 votes

---
Tags: 7, users
---


title: Add a class to a panels pane

text:
# Question
Title: Add a class to a panels pane
Is it possible to add a class to single pane (like the left side) on a panels page? I'm using a grid based theme and it would be nice if i can just add things like 'grid-5 alpha' to a certain pane.

# Answer
In the Panels UI, every Pane has a little cog. Click it, and menu appears. There is an entry called "CSS Settings". There you can add per pane classes.
> 3 votes

---
Tags: theming, panels
---


title: Language selection in Panels?

text:
# Question
Title: Language selection in Panels?
I have a panel node and in it I added a node. Is there any way to make Panels load the translation of the node based on the user current language. This is easy to do with Views adding a filter, but I can´t see how to do it with panels (if possible).

# Answer
Panels should always respect the current users language, I've built several multilingual Panels sites, and never had to tell Panels which language to load.

In fact, the node "task handler", which is responsible for rendering nodes, doesn't even do a lot of work, but hands that responsibility over to Core, and as such, language to the Locale module.
> 1 votes

---
Tags: panels, i18n-l10n
---


# Question
Title: drupal running really slow on apache mac os x
I'm running drupal sites on my localhost with virtual host. everything was running perfect but then it suddenly stopped working, I tried to restart apache to fix the error but still not working. It takes about 30 seconds to load the home page, and about the same for other pages. I'm running mac os x with Apache MySQL "no MAMP". thats really confusing me more is that it runs only on firefox, on safari it takes forever and never loads.

# Answer
I went to /etc/apache/users/saad.conf and added the virtual host in this form "www.x.dev" to the top of my virtual hosts list. this temporarily fixed the problem. hope this helps
> 0 votes

# Answer
Install devel module in your drupal site. After enabling devel module, you need to enable query log and page timer in devel configuration page. by doing this you will see how much time each function is taking to load and will able to analyze you site.
> 2 votes

# Answer
First thing I would check is the apache error log, for any ressource that is 404. It very well could be a logo or an image that is 404 (not found), your page request will try loading the ressource for a certain time depending on your time-out settings, before giving up and closing the request.
> 1 votes

---
Tags: database
---


# Question
Title: How can I hide node titles only for displayed nodes, and not node edit forms?
I have a little function to hide my node titles via template.php:

```
function mytheme_alpha_preprocess_page(&$vars) {
  if (isset($vars['node']) && $vars['node']->type == 'episode') {
    $vars['title_hidden'] = TRUE;
  }}

```

This function hides the title on the node edit form too, but for that form I need a title.

How can I avoid changing the node edit form in my function?

# Answer
> 5 votes
You could add a check to see if you are editing the node, like

```
function mytheme_alpha_preprocess_page(&$vars) {
  if (isset($vars['node']) && $vars['node']->type == 'episode') {
    if(arg(2) != 'edit') {
        $vars['title_hidden'] = TRUE;
    }
  }
}

```

---
Tags: theming
---


# Question
Title: How to solve tput problem when installing drush on Windows?
I am trying to get Drush running on my local development site. Drush & Cygwin are installed and the cygwin command prompt responds to Drush commands such as "Drush topic" but precedes the command output with:

> "which: no tput in + a long list of directory paths"

and then gives the topic list. When I respond with 16 (Drupal help for error messages) I get:

> fwrite(): supplied argument is not a valid stream resource \[warning\] output.inc:29

I believe I have to add path definitions, but am not certain where to define them. My current configuration on a windows OS has apache & php under C:/Program Files/acquai drupal/ (I used their setup for php and apache, but not their Drupal Site setup.) I have Drush located under C:/Drush and my site located under `C:/Documents and Settings/admin/my-site`.

# Answer
> 3 votes
Ashlar seems to have found a solution to the tput problem in his own bug report 'by adding the add-on gygwin command tput from the cygwin installation program "setup.exe". The actual command i not on the list. Look for the "ncurses" package which includes the Tput utility.' ... see http://drupal.org/node/1361510#comment-5327144

# Answer
> 1 votes
Have a look at Drush Windows Installer (old instructions).

This package installs a standalone Drush, and adjust the Windows PATH to point to itself and its supporting executables. You can use this to learn how to set the PATH.

---
Tags: drush
---


# Question
Title: Display taxonomy terms differently by content type
Is there any way to display the taxonomy terms slightly differently depending on the content type they appear in? For instance, I have two content types that I'd like to have use the same vocabulary, but the terms represent slightly different things to end users.

Example: a node field asks an organization "how are you interested in connecting with a campus?" and answers include "lead an interactive workshop" and "participate on a panel". When a different content type asks a teacher "how are you interested in organizations connecting with you?" the answers include "have an organization lead a workshop" and "host a panel". Obviously those answers correspond 1:1, so I'd like to use the same vocabulary. But they need to present themselves slightly differently in each content type.

# Answer
> 1 votes
Since vocabularies are linked to nodes via fields you'd be best off handling this in `hook_preprocess_node()` in your theme file:

```
function MYTHEME_preprocess_node(&$vars) {
  $node = $vars['node'];

  // Only make the change if this is a certain node type
  if ($node->type == 'my_type') {
    // Extract the term IDs from the field
    $tids = array();
    foreach ($node->field_vocab[$node->language] as $value) {
      $tids[] = $value['tid'];
    }

    // This example adds the taxonomy terms to a simple list, you'll
    // want to replace this with whatever theme function you need
    $items = array();
    foreach (taxonomy_term_load_multiple($tids) as $term) {
      $items[] = l($term->name, "taxonomy/term/$term->tid");
    }

    // Replace field_vocab in the vars with the new content
    $vars['field_vocab'] = theme('item_list', array('items' => $items));
  }
}

```

That might need to be changed/added to depending on your needs but it should give you a place to start from. Once you've added the new hook to the template.php file make sure you clear Drupal's hooks so the registry will be updated.

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


# Question
Title: How can I let registered users upload images using a form in Drupal 7?
I'm using Gallery formatter on my Drupal 7 site which allows administrators to upload images to my articles that are then shown on the article body. So great so far, but what I want is for the registered users themselves to upload images to the article using a form. I've been searching for a while, but haven't been able to find anything that would allow me to do this.

Is there a module that would allow image upload using a form that integrates with Gallery formatter (or just Drupal Image - both would work, I think, as the images are stored in a field), or do I have to create a custom module?

# Answer
You need the field permission module. Everything is already contained in Drupal core.

1. Create a content type.
2. Add an image field and allow multiple instances of this field.
3. With help of the field permission module make sure registered users have the right to edit your image field.
4. Configure ImageCache to output the images the way you want.

As an add on you might have a look at views, wich allows you to output many nodes with their images, sorted and/or filtered the way you want.
> 1 votes

---
Tags: media, forms, files
---


# Question
Title: Limit certain users from filling webform based on their location
I have a contact us form, that I want only users from the US to see, fill and submit. And the other users to see that form but a message says "web form is not available in your country" if the user is from outside the sates. Is there a module to do so? or I just have to make my own? thanks.

# Answer
You can use a module like Smart IP http://drupal.org/project/smart\_ip, GeoIP http://drupal.org/project/geoip or just the Maxmind Geolite http://www.maxmind.com/app/geolitecountry table to look use the IP address of the user to determine the country.

Then use hook\_nodeapi() or hook\_node\_view(), depending on if you are using Drupal 6 or 7, to redirect the person based on the country.

The pseudo code would look something like this (Drupal 6, using Geoip):

```
function MYMODULE_custom_nodeapi(&$node, $op) {
  switch ($op) {
    case 'view':
      if ($node->nid == 'NODEID OF WEBFORM') {
        $country = geoip_country_code();
        if (isset($country) && $country != 'us') {
          drupal_goto('node/' . NODEID OF REDIRECT PAGE');
        }
      }
     break;
  }
}

```

edit: When I saw 'webform' I assumed you meant using the webform module, hence the nodeapi, but if you are using the basic site contact form you can use hook\_menu and create a new callback for the path of the form you are using and create the same kind of check as above.
> 3 votes

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


# Question
Title: Help with #text_format and field widgets
I'm struggling with #type 'text\_format' for a widget form field as this field gets expanded two separate elements, one holding the orignal element and the other the format selector. The orignal element is moved into a child element.

All of this is fine, but as the orignal field is now moved into a child when the widget form is saved is tries to save the child element (array). As the widgets fields have to be at the root of the form with names that match 1:1 with db columns.

From form.inc:

> If the property #text\_format is set, the form element will be expanded into two separate form elements, one holding the content of the element, and the other holding the text format selector. The original element is shifted into a child element, but is otherwise unaltered, so that the format selector is at the same level as the text field which it affects.

I've looked at the text.module but I can't work out how it is getting around the issue of the field being expanded?

# Answer
Good luck with that. What a head-scratching nightmare. See Missing hook\_field\_widget\_form\_submit()? for an idea of how to make this easier.

I got this to work once in a module, but then had to remove it for other reasons. The code is still there, look at this older version of flashcard.install and flashcard.module, especially `flashcard_field_widget_form()` and `flashcard_field_formatter_view()`.
> 2 votes

# Answer
After hours, I finally solved it, taking in account the post by tim.plunkett; I have added a validator to the widget form, and then added the values to `$form_state` in the validator.

```
function ldn_panels_field_widget_form(&$form, &$form_state, $field, $instance, $langcode, $items, $delta, $element){
  $element['#element_validate'] = array('_ldn_panels_widget_validate');

  $element['title'] = array(
    '#type' => 'textfield',
    '#title' => 'Título',
    '#default_value' => isset($items[$delta]['title'])?$items[$delta]['title']:'',
  );

  $element['content'] = array(
    '#type' => 'text_format',
    '#title' => 'Contenido',
    '#format' => isset($items[$delta]['content_format'])?$items[$delta]['content_format']:NULL,
    '#default_value' => isset($items[$delta]['content_value'])?$items[$delta]['content_value']:'',
  );

  return $element;

}

function _ldn_panels_widget_validate($element, &$form_state){
  if($form_state['complete form']['#form_id'] == 'field_ui_field_edit_form') return;
  $field_name = $element['#field_name'];
  $values = $form_state['values'];
  $language = $element['#language'];
  $delta = $element['#delta'];
  $form_state['values'][$field_name][$language][$delta]['content_value'] = $values[$field_name][$language][$delta]['content']['value'];
  $form_state['values'][$field_name][$language][$delta]['content_format'] = $values[$field_name][$language][$delta]['content']['format'];
}

```

Note the content element in the widget splits in 2 values: value, and format. All I had to do was to modify my field schema to storage these 2 values, `content_value` and `content_format`.
> 2 votes

---
Tags: 7, entities, input-formats
---


# Question
Title: How to theme the $content variable's contents?
I am trying to theme the teasers of a particular content type.

I have gotten to the point where I created a file of name `node-content_type-teaser.php`, where `content_type` is the relevant name.

The trouble is, I am unable to style the actual $content. It outputs the teaser of the text in a `<p>` tag, and an image thumbnail (I get it from a CCK field). I just need to change the order, and output the image first, so I can float it.

To summarize, how do I control the order in which $content is output?

# Answer
> 1 votes
If all you want to do is change the order, you do that in the edit content/manage fields form where you can drag and drop the fields in whatever order you want them to be output.

If that's not exactly what you want, you can also change how they are displayed in the "display fields" form.

If all of the above doesn't do exactly what you want, you can print out each field however you want inside the template itself, eg, instead of printing $output, you can print out each field you want when and how.

So, if for example, you have a text field called `field_description,` you can output it by putting a `print $node->field_description[0]['safe'];` in there since the entire $node is available inside the template to play with.

To see all there is to work with in your specific case, a quick `drupal_set_message('<pre> . print_r($node,true) . '</pre>');` in your template will show you lots of information.

---
Tags: theming, 6
---


# Question
Title: Display main menu vertically (Drupal. 7.9)
I am not sure how this has happened. but wherever I render the block of my main menu, it displays it's links horizontally rather vertically. Essentially I want to create a main menu that displays its links vertically.

Anybody have a lead on how this can be done ? I am tempted to go into the CSS and alter the theme myself but given that Drupal probably has a switch that allows me to alter the way a main-menu is listed, I want to caution myself.

Thanks!

# Answer
> 2 votes
You need to use Firebug and find the style rule that is being applied to the `<li>`elements that will be displaying them inline. Firebug will tell you where the CSS is being loaded and this will lead you to the culprit. One tip is to make sure you're not aggregating CSS so you can find the correct stylesheet. If it isn't theme specific it may be CSS being loaded by a module, but I am confident that there is some CSS there that is creating the result you're seeing.

# Answer
> 1 votes
Sounds a lot like a css issue my friend. Have you changed anything recently in your css that may be cascading into your menu? It is likely that your block elements have been set to inline or floating.

---
Tags: theming, routes
---


# Question
Title: Views Fields and Relationship with Aggregation
I have three content types :
Content type A (= leg)
Content type B (= transport)
Content type C (= ticket)

B has a node reference to A.
C has a node reference to B.

I have a views list with the following and aggregation setting is on;

> > **FIELDS**
> > Content: Nid
> > Content: From
> > Content: To
> > (field\_transport) MIN(Content: Price) (for)
> > (term from field\_transport\_type) Taxonomy term: Name (by)
> >
> > **FILTER CRITERIA**
> > Content: Published (Yes)
> > Content: Type (= Leg)
> > Content: From (exposed)
> > Content: To (exposed)
> >
> > **SORT CRITERIA**
> > Content: Post date (desc)
> >
> > **RELATIONSHIP**
> > (field\_transport) Content: Leg (field\_leg) - reverse
> > (field\_leg) Content: Transport (field\_transport) - reverse
> > (field\_leg) Content: Transport Type
> > (term from field\_transport\_type) Taxonomy term: Content using Transport Type

The result with 3 records is shown as below :

> > **RESULT**
> > How to go from Bangkok to Singapore:
> > for $150.00
> > by Plane
> >
> > How to go from Bangkok to Singapore:
> > for $200.00
> > by Train
> >
> > How to go from Bangkok to Singapore:
> > for $80.00
> > by Bus

I want the result with the only last line ( for $80.00 by Bus ). The result is correct before I have no relationship with `term from field_transport_type`.
How can I do that with aggregation setting `MIN` which I already applied in the field list?
I'm using drupal 7.10.

**\[Edit\]**
Here is the screen cast of my view :

Another thing is that the content type **B** (=transport) has a taxonomy term field (=transport type) which needs to be displayed in the field list. You can see them in the result - by Bus, by Plane, etc.

To be more clear, I attached another screen cast of my results :
The result should be 2 records above. The last three lines is the group of a leg ( Bangkok to Singpore ). This cannot be done by changing the pager settings. Pager is 10 for the page, meaning - latest 10 legs with cheapest tickets.

**\[Edit\]**
When I changed `field_transport_type` in FIELDS into `COUNT(DISTINCT Taxonomy term: Name)`, I got the result with the first two lines, but I lost the transport type names.

> > How to go from New York to London: for $120.00 by 1
> > How to go from Bangkok to Singapore: for $80.00 by 3

# Answer
> 0 votes
My previous answer using MIN aggregation did not give me a correct result.
So, I had to write a query with subquery by myself. This query took me a few minutes to write and it gave me a exact result what I want.
I tried to create this with views for a week, but failed. What I can done with views is inner query only. May be I was missing something.

```
$result = db_query("SELECT leg.*, ( SELECT COUNT(*) from field_data_field_leg WHERE field_leg_nid = leg.nid AND bundle = :bundle ) AS reviews  FROM (
                SELECT n.nid, n.created, title,
                    field_from_value origin,
                    field_to_value destination,
                    field_price_value price,
                    term.name transport
                FROM node n
                JOIN field_data_field_leg l ON n.nid = l.field_leg_nid
                JOIN field_data_field_from ff ON n.nid = ff.entity_id
                JOIN field_data_field_to ft ON n.nid = ft.entity_id
                JOIN field_data_field_transport t ON l.entity_id = t.field_transport_nid
                JOIN field_data_field_price p ON t.entity_id = p.entity_id
                JOIN field_data_field_transport_type ttype ON t.field_transport_nid = ttype.entity_id
                JOIN taxonomy_term_data term ON ttype.field_transport_type_tid = term.tid
                WHERE n.type = :type
                ORDER BY n.created DESC, field_price_value ASC
            ) AS leg GROUP BY nid
            ORDER BY created DESC LIMIT 10", array(':bundle'=>'review', ':type' => 'leg'));

```

By doing like this, I had to create a page with a template from a sketch with all features which drupal views provides, such as exposed filter, etc.
I think it is not a good idea, but I had to do as I have no time enough.
If you have any better idea, you are welcome.

# Answer
> 0 votes
Perhaps you want to remove the post date sort criteria, and add an ascending sort criteria for content: price. If you only want one result value, change that in the Pager area.

# Answer
> 0 votes
Finally, when I changed the last field in field list with aggregation MIN, I achieved the result.

> > (term from field\_transfport\_type) MIN(Taxonomy term: Name) (by)

---
Tags: views, css-js-aggregation
---


title: Drupal 7 Views, List, Filters and User

text:
# Question
Title: Drupal 7 Views, List, Filters and User
I have three content types :
Content type A
Content type B
Content type C

**B** has a node reference to **A**.
**C** has a node reference to **B**.

I have also 2 roles :
Role 1
Role 2
**Role 1** is belong to **Content type B**.
**Role 2** is belong to **Content type C**.

I'm creating a view list in which

1) Content type A (nid) is passed from URL. Filter nodes of type B with nid of type A. ( done with contextual filter )
2) Criteria content type == B ( done with criteria )
3) Join content type C with content type B. ( done with relationship )

I have successfully got a list with above three.

But I have one more thing to do :
If logged-in user is Role 1, I want to filter nodes of type B of the logged-in user.
If logged-in user is administrator, show all nodes of type B which is filtered with node of type A.

How can I do that ? I'm using D7.7

**\[Edit\]**
I think filter criteria don't need for user role. It can be done with user filter for content type B. But I can only select all users associated the type `B`. I cannot select the current logged-in user id from views filter.
I may need to use this module : http://drupal.org/project/viewsphpfilter
Unfortunately, it has no update for D7.

# Answer
I've done with `hook_views_query_alter()`.

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

function mymodule_views_query_alter(&$view, &$query){
    global $user;
    switch($view->name){
        case 'my_view_name' :
            if(!in_array('administrator', $user->roles) || array_key_exists(4, $user->roles)){
                $result = db_query('my_query_here');
                $nodes = array();
                foreach($result as $row){
                    $nodes[] = $row->entity_id;
                }
                $query->where[0]['conditions'][] = array(
                    'field' => 'node.nid',
                    'value' => $nodes,
                    'operator' => 'in'
                );
            }
            break;
}

```
> 1 votes

# Answer
You can add a relationship in your views.

* Edit your view
* Open the `Advanced` tab
* **Add** a relationship
* Choose your relationship and name it

Now, go to the `Filter Criteria` and choose the *user*-filter. Now choose the *User: Roles* option, select your relationship and select your role.

And I think the best way to go it to make 2 blocks. One for Role 1 and one for administrator. But be aware, a Drupal admin had the `bypass content access control`-permission, so there is no use filtering the results.
> 0 votes

---
Tags: views
---


# Question
Title: Are there existing modules to group nodes and give sequential access to them in Drupal 7
I want to be able to select a set of nodes, put those in a specific order (or make them dependent on each other) and give a group of users access to the set. However, I want the nodes to be read sequentially so users cannot start reading node 2 if they have not seen/read node 1.

I would very much like to use existing modules to accomplish this if possible. I have just spent an hour on the Drupal modules site and I'm a bit overwhelmed by the possibilities. I have not found one that does exactly what I want and although it seems possible by combining a few, most require a more in-depth understanding of the module to make a good assessment.

If you have a suggestion for one of my requirements, that would also be very welcome.

# Answer
> 1 votes
For in order reading you should create **story**.
**Organic Group** is good option for your requirements.

# Answer
> 2 votes
I would recommend the following modules:

* Views: Views is a powerfull query and report generator. You can filter and sort your nodes or show individual nodes based on any criteria.
* Rules: Rules allows you to take action on a lot of ocations. Let's say you can change data, roles or access rights on nodes when a user sees a node or confirms to have read the contents.
* Fields (built in core): Is a little bit like Access: Create your data structures without coding.

It's very likely that you can do 90%-100% of you requirements with this (and may be some more helper) modules. Sometimes some glue code in a custom module is necessary.

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


title: How to track errors in view

text:
# Question
Title: How to track errors in view
I write some PHP code in my views, i.e. in contextual filters and the PHP area of view, but when something goes wrong, it becomes very difficult to find errors as line numbers thrown in error does not holds good.

Which way can I trace it ,or is it not advisable to write PHP code in views directly?

# Answer
Views is created in a very object oriented way, which is really great. What this means is that if the default Views behavior doesn't work for you, you can extend the classes that Views supply and alter only what you need to overwrite. I wrote a blog post about this focusing on filters, but the principle is the same for contexts, sorting ...

In views lingo a context is called an `argument`.
> 3 votes

# Answer
Eval'd PHP is generally a bad idea, debugging being just one of the reasons. Here is a link that gives more reasons to avoid it.
> 1 votes

---
Tags: 7, views
---


# Question
Title: How do I highlight an element in a view result?
I have a "Collection" content type, and a "Product" content type.

Each "Product" node has a node reference to a "Collection" node, and a "Collection" node can have several "Product" nodes referring it, while a "Product" node can only belong to one "Collection" node.

I created a view to list all collection as photo thumbs with link to collection node. I display this list as a footer in collection nodes and products nodes.

What I want to do as "special" is to highlight current collection in the collections footer when I display a product node which belongs to this collection. Same thing when I display the collection itself.

Is it possible to do this using views and as possible without Javascript?

# Answer
First check the thumbnail is passing your condition then simply just add a unique class to that field using the tpl file for that field.
> 1 votes

---
Tags: views, 6
---


# Question
Title: Displaying content according to the OG membership of the creator
In our Drupal 7 site, we are using Organic Groups to create private groups. Users are also able to upload content to a gallery (using custom Content Types "Gallery image" and "Gallery video"). On users' profile pages, we are showing a carousel of their *N* most-recent uploads, with a View using a Contextual Filter on Author `uid`.

We would like to add a similar carousel to each OG group page, showing the most-recent *N* uploads by members of the group. \[**Edit:** This is uploads to the general Gallery, the OG groups do not have their own galleries.\] If it makes a difference, almost all users will be members of more than one group (for reasons that are unimportant, there are two kinds of group: geographic groups and interest-based groups).

This seems like it's probably very easy, but I just can't see how to do this, either from the View's *Contextual Filters* or the View's *Relationships*.

Am I missing something obvious?

# Answer
In Drupal 6 you would add a relationship to the Organic Group: node then filter by Organic Group: user and use the relationship. I believe it should be something very similar by using the contextual filters...
> 1 votes

---
Tags: 7, organic-groups, views, media
---


title: Repeating date (multiple values)

text:
# Question
Title: Repeating date (multiple values)
I need to add multiple values to the repeating date field.

I have to make the schedule for a university classes. So I might have multiple groups with different schedule (different hours for each group) for the same class.

Now it's dificult to assign the schedule for each group on the same node (I don't think it is even posible), but I think at least I could have multiple values on each repeating date, e.g. each thursday at 12:00 and 14:00, and each friday 10:00 and 16:00.

I'm using the latest Drupal 6 and CCK. I can't use Drupal 7 at the moment for this project, but minor version upgrades can be possible.

# Answer
You should take a look at the office hours module. While it might not be created for your use case, it allow you to store repeatedly dates for stuff like each friday 10:00-16:00.
> 1 votes

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


title: D7 join on cck fields in views

text:
# Question
Title: D7 join on cck fields in views
I have 2 content types which are imported via feeds; One is "user" with a cck field referencing its primary key: user.id

The second is "time\_entry", which has a cck field for the fk reference to user id: time\_entry.user\_id

Now that they are coming into drupal, i am trying to create a view which would have: time\_entry.id, time\_entry.user\_id, **and** user.fname, user.lname, which are in the user nodes.

I tried a few different things; I am not too familiar with d7 so entities, bundles, the relations module, etc. are confusing me. I got tangled up trying to even create a php field in views which would get the nid of the user referenced in the time entry table and load that user.node. Any help would be greatly appreciated.

# Answer
> 1 votes
Some questions first. What's the data model?

1. "Time Entry" -\> "User Node" or
2. "Time Entry" -\> "User Node" -\> "User Entity"

Are you using "User Reference" and "Node Reference" fields for the reference fields? If so, no need to use PHP to do it. You can use the Views UI for this functionality.

First, make sure the View's Row Style is "Fields" the format is Table and the view type is Node. Filter by "Time Entry" type.

Then, on the Advanced Tab, add a "New Relationship" and choose the reference field you use to reference the "User Node". By doing this, it'll enable you to access the "User Node", aside from the original "Time Entry" data.

If you have 3 entities related, you have to add another relation to access the 3rd entity's data. Follow the same procedure as above (adding a new relationship) and use the "User Node" reference field to access the "User Entity" data.

Then you can just add the fields you want, namely user name, last name and so on.

Hope this helps.

---
Tags: 7, entities
---


# Question
Title: How to programtically queue a function for 48 hours (to change webform Author)
The code below changes the submission author to that of a user referenced in the webform (pulls username:uid). However now need this to change after 48 hours.

I am unsure how to effectively queue this for 48 hours before it runs or even if that is possible (I guess I will have to change the hook to "hook\_webform\_submission\_update")..

I was thinking of rules but is there a hook which would help? Also if rules is the answer could anyone shed some light on how I can implement it into my code?

```
// change submission author to the submitted user lookup
function helper_custom_webform_submission_presave($node, &$submission) {

    // get uid from user_lookup
    $user_lookup_cid = 1;
    $user_string = $submission->data[$user_lookup_cid]['value'][0];
    $user_string = explode(":", $user_string);
    $uid = $user_string[1];

    //change submission to be saved by user
    $submission->uid = $uid;
}

```

# Answer
Implement hook\_webform\_submission\_insert() such that it saves `$node->nid`, `$submission->sid` and the current time to a designated table (e.g. *newsubmissions*).

Implement hook\_cron() such that it goes through all records in the *newsubmissions* table, that are more than 48 hours old. For each such record, you should

1. load the submission by calling webform\_get\_submission(),
2. change the owner of the submission,
3. save the submission by calling webform\_submission\_update(),
4. delete the record from the *newsubmissions* table.

Implementing hook\_webform\_submission\_presave() the same way as hook\_webform\_submission\_insert() will not work, because

1. `$submission->sid` is not yet set and
2. hook\_webform\_submission\_presave() is also called for old submissions.
> 2 votes

---
Tags: 6, rules, webforms
---


title: Clues integrating jcart in Drupal 7

text:
# Question
Title: Clues integrating jcart in Drupal 7
jcart is a great shopping cart that uses a php class inside a jcart.php file. The cart is being displayed

```
<div id="jcart"><?php $jcart->display_cart();?></div>

```

I managed to create a module to list the product items and the form with 'add to cart' button, also to include the jcart.css and jcart.js inside everypage. The only thing I need to include more are:

1. the mymodule/jcart/jcart.php

I tried to include it in my header of html.tpl.php but I get an error while displaying `$jcart->display_cart()`. The error is:

> Fatal error: Call to a member function display\_cart() on a non-object in...

1. To add a class to the form: class

If there is someone could help I would appreciate it.

# Answer
You need to include the file itself, `module_load_include` can help you with that. Then you need to instantiate the class, you should read the docs about jcart to figure out how to do that, but something like

```
 $jcart = new jCart($args);

```

This can be done in your theme, or ever better create block in your module than will display the cart and that will invoke `display_cart`.

Note I don't know anything about jcart, and as such the code is just an illustration.
> 1 votes

---
Tags: 7
---


# Question
Title: How can I check for a duplicate node when rendering a view?
This question is closely related to my other question posed a few hours ago: How to make a node appear across \*all\* Taxonomy terms?

As a solution, I plan to create a functionality, where my new nodes are added to every country in my 'countries' vocabulary, when a 'check all' button is clicked (this is in addition to a single term in the 'main' classification taxonomy they are assigned to).

But I have a view for the display of these nodes. It accepts a term ID from the main taxonomy via URL, and provides a Hierarchical Select "exposed filter" for further filtering by geography within the displayed nodes.

I will now have the same node teaser multiplied by the number of countries in my vocabulary, when the user first enters this view (because that many nodes were created).

Is there a way I can tell my view to just notice such nodes only once, in the unfiltered state?

# Answer
If I'm not mistaken, in your view-settings, you can select a `distinct` query in your **Advanced** settings in the view. It set under **Query settings**. I'm not sure if it's already there in D6.
> 3 votes

# Answer
Try "use distinct", this filters the results to only include 1 item per result.
> 3 votes

---
Tags: 6, views
---


# Question
Title: how to use URL_ALIAS for search result of apachesolr module?
I am using apachesolr in drupal 6.22 module to search. the links of the results look like http://mywebsite.com/node/NID , how can i manage it to show the url alias instead of displaying node/NID representation.
Thanks for your help

# Answer
> 0 votes
I am running the same configuration as you and this has the SEF urls by default.

Have you checked your URL Aliases? Does this problem occur for ALL nodes in SERPS? I would try rebuilding your aliases

---
Tags: uri, search
---


# Question
Title: How to make a node appear across *all* Taxonomy terms?
I am creating and classifying nodes by:

1. A main taxonomy
2. A secondary geographic location taxonomy

I created a View for the display of these nodes. It accepts a term ID from the main taxonomy via URL, and provides a Hierarchical Select "exposed filter" for further filtering by geography within the displayed nodes.

I notice that if a user does not select any location from the exposed filter, all nodes from across the world are displayed. But when I select USA, only USA nodes are displayed.

That is the desired behavior, however, I need to create some nodes that have "Worldwide" scope, and appear in the view even when the geographical filter is activated. It would be a great hassle to create nodes for each and every location.

I could hardcode this in some way: I even considered a separate taxonomy of worldwide nodes, and creating a block which is always displayed on top of the filtered results. But the problem with this is that the order of node-creation is also important, and my solution would appear disjointed.

Any ideas to nudge me in the right direction would be greatly appreciated.

# Answer
> 2 votes
Assuming I understand you correctly... why don't you create a custom checkbox field "Worldwide?" for the node type? Then in any views you could insert an OR checking if the node has it set. Still, you would be able to group the results by another field, such as geographical region name.

This is where you get the dialog in Views3

# Answer
> 1 votes
We had a similar problem, we had to distribute nodes by brand \> department and country. Sometimes we would need to broadcast to all...

The solution for us was changing the taxonomy to a cck "Content Taxonomy Fields" and using the tree widget, that way we could apply a node to all (or worldwide). Then we added some custom js which allowed check all. (after all world wide rather than being a single selection is actually all of the countries in the taxonomy).

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


title: Creating a full site package

text:
# Question
Title: Creating a full site package
I found that the ST Conch theme has a full site installation package with that theme.

How do I go about doing this? And would it be possible to populate the database with the data as well...?

Thanks

# Answer
What you are wanting to create is a Drupal Installation Profile. This is a method of packaging together multiple Drupal contributed modules and/or themes, plus potentially custom code and functionality, into a neat package that can be distributed and installed with the same resulting "full" website every time.

You'll want to refer to the drupal.org documentation on building installation profiles to get the basics behind how this is done.

Also very helpful will be the Features module. Features allows you to easily package together different sets of Drupal configurations, such as content types, views, and system variables. There are many different documentation and tutorial resources for Features. This is a good video tutorial on the basic concepts of Features.

There are a lot of additional extensions for Features that will help you package additional items into a Feature, such as node content, taxonomy terms, theme settings, etc.

In addition, some of the work you want to do in your installation profile (re: "populate the database with the data as well...") may need to be executed within custom code - either a custom module or as part of your installation profile's install tasks and/or install script. You can even set up a form to allow users to choose from a set of options during the installation.
> 3 votes

---
Tags: 7, theming
---


title: HowTo - Image Style's 404 image

text:
# Question
Title: HowTo - Image Style's 404 image
How could I define an image for those images that are not found (404's). In other words, if image which is displaying with image style is not found, provide an another image?

If someone is interested here is my solution:

```
function themeName_image_style($variables) {
  // Determine the dimensions of the styled image.

  $dimensions = array(
    'width' => $variables['width'],
    'height' => $variables['height'],
);

  image_style_transform_dimensions($variables['style_name'], $dimensions);

  $variables['width'] = $dimensions['width'];
  $variables['height'] = $dimensions['height'];

  // Determine the url for the styled image.
  $variables['path'] = image_style_url($variables['style_name'], $variables['path']);

  // Load default image for 404's
  if(!file_exists($variables['path'])) {
    $variables['path'] = file_create_url('/sites/all/themes/custom/lsa/css/images/404.png');
  }

  return theme('image', $variables);
}

```

# Answer
> 2 votes
Go to Administration -\> Structure -\> Content Types, select the name of your content type, then click on Manage Fields. Find the image field, click edit for that field, then scroll down until you see the Image Field Settings section. Click the default image button, and select what image you want to show by default.

---
Tags: 7, media
---


# Question
Title: limit amount of upload images (through imagefield module) to only 1 by code/programmatically
I use image field with possibility to upload unlimited images. BUT under the user registration, I want to limit the possibility to just one image. So that the anonymous user, who wants to become a registered user, can only upload one image. After they become users, then they can upload as many images as they wish.

Does anybody know how to do that?

# Answer
> 1 votes
You want to use a hook\_form\_alter to process this for just that form, ex.

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

    if ($form_id == 'user_register') {
        // do stuff here
    }

}

```

The 'stuff' is the real challenge, especially since you are allowing for unlimited uploads. There is a previous post on this with a solution for a limited set (\<10):

https://stackoverflow.com/questions/5701488/change-fields-number-of-values-per-role

My suggestion for resolving this (though not ideal) would be to add a custom handler as part of your logic that would check to see if one already exists and gently prod them not to add more than one.

```
if ($form_id == 'user_register') {

    $form['<image field name>']['#element_validate'] => array('_mymodule_only_one_image'),

}

```

and then for your validation function, you could simply test whether a 2nd image exists and prod the user to only submit one. Rough psuedo-code example here, haven't tied this to an actual form.

```
function _mymodule_only_one_image($element, &$form_state) {

    if (!empty($element['<image_field_name>'][1])) {
        form_error($element, t('Please only upload one image');
    }

}

```

Another option would be to try and disable the ajax handler that initiates the 2nd upload through your own custom jquery override, which you could also add in to this custom form through the above form\_alter.

---
Tags: 7, media
---


title: Alternate webform UI is buggy

text:
# Question
Title: Alternate webform UI is buggy
I have been experimenting with the Webform Alternate UI module for Drupal Webforms. As you would know it requires a few excess modules like options\_element, ux element and form builder. The thing is, the webform alternate UI shows up but it does not really work when I attempt to drag and drop the form fields onto it. Its' clearly buggy. And it seems like it has some unfixed issues persistent along with it.

I want to check on stackoverflow with anyone who has played along with the webform Alternate UI and found it to be buggy and has a fix for it?

Thanks much

# Answer
I have found Webform Alternate UI to be quite buggy as well and have opted to use just the Form Builder module by itself, which gives a good UI for users to build forms (and is not buggy).
> 3 votes

---
Tags: webforms
---


title: Debugging hooks that fired?

text:
# Question
Title: Debugging hooks that fired?
I'm somewhat new to module development.

Is there a way to currently output what hooks have been run on certain nodes?

Would this be done with xdebug?

# Answer
Unless you get a fatal error (or blank screen) it's pretty easy to get a list of modules that will invoked when a special hook is called:

```
$modules = module_implements($hook);
foreach ($modules as $key =>  $module) {
  $function = $module . '_' . $hook;
  if (!function_exists($function)) {
    unset($modules[$key]);
  }
}
// $modules is now an array containing all the modules that will be invoked by $hook.

```

You could use stuff like xDebug to track the flow of the Drupal, but this can be overwhelming, especially if you are new to Drupal.
> 9 votes

---
Tags: debugging
---


# Question
Title: Different fields of same content type to different roles
I have a content type 'new resource'.

I have the form displayed as a page. I would like to make it so that form contains an image field for the admin role, but have this field hidden for any anonymous user filling out the form.

I have been trying to use 'Rules':

EVENTS content is viewed

CONDITION content is of type... Parameter: Content: \[node\], Content types: new resource AND... NOT User has role(s)... Parameter: User: \[node:author\], Roles: administrator

ACTIONS Remove an item from a list Parameter: List: \[node:field-web-resource..., Item to remove: \[node:field-web-resource..

This might be completely the wrong way to do it, and there is a simpler way, or the Rules approach might work.

When I try to add the ACTIONS the dropdown box keeps showing me things like this: node:field-web-resource-image-main:0 (Image) node:field-web-resource-image-main:1 (Image) node:field-web-resource-image-main:2 (Image) node:field-web-resource-image-main:3 (Image)

I'm guessing that this is because I have an unlimited amount of images available for upload in this field.

Any help would be most welcome.

# Answer
You need the field permission module to set permission on the field level.
> 1 votes

# Answer
Go to /admin/build/modules/list and enable "Content Permissions" under the cck group.

Then go to /admin/user/permissions. Here under "content\_permissions module" section enable permissions for the fields you want to be displayed for authenticated users or anonymous users.
> 1 votes

---
Tags: entities, rules, actions
---


# Question
Title: What is the recommended method to add an RSS icon to an Open Scholar scholar site?
I would like to add a linked RSS icon to the footer of a scholar site using Open Scholar. I know that the URL to an RSS feed will be: example.com/professorname/feed

However, I'm unsure of how to programmatically get the URL to the scholar site ("example.com/professorname") so I can build the link and insert it into the page.tpl.php for a few scholar sub-themes. Is there a recommended method for this?

# Answer
> 0 votes
Turns out this was an easy to do in the GUI:

1. Go to the Control Panel for the scholar site
2. Click on Site Building
3. Click on Layout
4. Drag the various feed option icons to where you want them to display
5. Have a beer

# Answer
> 0 votes
If you have a footer menu, you could add the RSS feed to it, and then attach a bit of CSS to your theme. The exact selectors would depend on what is being output, but you could do something like:

```
ul#footer-menu li.menu-1234 {
  padding-left: 20px;
  background: url(/path/to/rss.png) left center no-repeat;
}

```

You may need to adjust other styles to get the whole icon to appear.

There are bunches of sites with royalty free RSS icons.

# Answer
> 0 votes
In your theme's template\_preprocess\_page() function, you can pass in the base URL of the site in a custom variable... then in page.tpl.php you can access the base url.

Something like this:

```
<?php
function THEMENAME_preprocess_page(&$variables) {
  global $base_url;
  global $base_path;
  $variables['site_base_url'] = $base_url . $base_path;
}
?>

```

...and in page.tpl.php:

```
<?php
  // Wherever you want to print out the path, use $feed_path:
  $feed_path = $site_base_url . 'feed';
?>

```

---
Tags: 6, theming, feeds, distributions
---


title: Theme template and hook_theme

text:
# Question
Title: Theme template and hook_theme
I have a content type 'leg' and a template node--leg.tpl.php.
I'm using sky theme. I have a custom module as well, let's say for example, `mymodule`.
I put the template file into `sites/all/modules/mymodule/theme`. And I created a `hook_theme` and `hook_preprocess_node`.
But my template is not invoked as expected. I cleared all caches.

```
function mymodule_theme(){
    // The base theme registers node.tpl.php.
    $templates['node'] = array(
        'arguments' => array('elements' => NULL),
        'path' => drupal_get_path('module', 'mymodule') . '/theme',
        'template' => 'node--leg',
        'preprocess functions' => array(
          'template_preprocess',
          'mymodule_preprocess',
          'mymodule_preprocess_node',
          'mymodule_process',
        ),
    );
    return $templates;
}

function mymodule_preprocess_node(&$vars, $hooks){
    if($vars['type'] == 'leg'){

    }
}

```

When I put my template file into `sites/all/themes/sky/templates` and changed path in `hook_theme` to that location, it works.

```
function mymodule_theme(){
    // The base theme registers node.tpl.php.
    $templates['node'] = array(
        'arguments' => array('elements' => NULL),
        'path' => drupal_get_path('theme', 'sky') . '/templates',
        'template' => 'node--leg',
        'preprocess functions' => array(
          'template_preprocess',
          'mymodule_preprocess',
          'mymodule_preprocess_node',
          'mymodule_process',
        ),
    );
    return $templates;
}

```

I would like to know it is a right way or not.
I should not place my template in the sky theme folder, am I right ?

# Answer
I resolved this by following :
> 0 votes

# Answer
`drupal_get_path('theme', 'mymodule')` should be `drupal_get_path('module', 'mymodule')`.
> 1 votes

---
Tags: theming
---


title: Blocks per user setting/individual

text:
# Question
Title: Blocks per user setting/individual
I am having my navigation links in my utility bar which is in a block named 'tray'; however, some users prefer to have the navigation links in the normal position and that is in a side panel inside a block named 'second sidebar'.

How can I make it so that the users can choose on their profile to either use the utility bar and navigate from there, or leave it as it is and have the links in the sidepanel.

**Update**: I mentioned panels, but it should have been blocks.

# Answer
You can add per user preference settings. Check this for a working example of how to add a preference setting in the user profile form and how to store and read it.
> 1 votes

---
Tags: blocks
---


# Question
Title: Built in cache system doesn't work in Drupal 6
Recently, I have selected "Normal" (recommended for production sites, no side effects) of the Caching mode at admin/settings/performance; I can see the CPU usage is drop from 60-70 to 6-8 by accessing the Drupal site on the same PC. However, when I use another PC to access the Drupal site, the CPU usage is risen to 60-70 again. So is there any mis-configure on my Drupal site?

# Answer
Drupal generates cache when a node, block, or view is rendered the first time. How much cache is served versus how much is generated on that request can depend on both that visitor's role and specific user account.

If two anonymous users hit the same page, the first anonymous user will trigger the cache to be generated for elements on that page, then the second anonymous user will receive those cached elements and the page will load faster for them.

However, if one authenticated user hits a page, then an anonymous user hits the same page, two different versions of a selection of elements on that page will be cached (for instance, if authenticated users are allowed to see a block, but anonymous users aren't).

Therefore, Drupal's caching mechanism works best when there are lots of visitors with the same permissions hitting the same non-personalized pages. If it's a site with users who sign in, and there are lots of permissions (especially field-level permissions) at play, Drupal's cache will be fairly ineffective for anything but static content nodes and blocks.
> 1 votes

---
Tags: 6, caching
---


# Question
Title: How to use the Rules module to flag a node that has just been created?
I need to automatically flag a node after it has been published. All nodes of a certain content type will be flagged.

In order to solve that problem, I have installed the Rules module hoping that I would be able to automatically flag the nodes that are created. Rules module does not come prepacked with flag actions.

Is it possible to flag an item that has just been created?

# Answer
To flag a node when it is published, you need to:

* In admin/config/workflow/rules, create a new rule selecting "After saving new content" as event
* Create a "Content is of type" condition selecting the content type you want to be flagged
* Click on the "Add and" link that appears on the bottom of the conditions table
* On the "AND" row, click on "Add condition"
* Create a new condition choosing "Content is published" as condition type
* Add a new action selecting "Execute custom PHP code" as type
* Use the following code as custom PHP code

```
$flag = flag_get_flag('published'); // Replace "published" with the name of the flag you want to add.
$flag->flag('flag', $node->nid);

```

On Drupal 6, Rules exposed the custom actions set on admin/config/system/actions, but the version of Rules for Drupal 7 doesn't seem to have that possibility. Flags for Drupal 6, as far as I remember, exposed some actions to Rules, but I doesn't seem it does it on Drupal 7.
That is the reason I used a custom PHP action to flag the node.
> 0 votes

# Answer
FYI, after a lot of search I discovered that Rules2 support in Flag for Drupal7 is already in dev. I tried it and it works well!

There is also a patch as stated here: http://nodeone.se/blogg/learn-flag-with-nodeone-part-7

Not easy to google out! :P Bye!
> 1 votes

# Answer
Yes, this can be done with Rules 2 through the Rules UI without creating custom PHP.

> I need to automatically flag a node after it has been published.

If you are also 'creating' the node in the same action you will need to modify your Rules actions to be able to flag the node without using custom PHP code.

Create a new rule and add your 'create new entity' action. See image below:

Next you will need to **save the entity (force immediate save)** and then flag the entity. See image below:

Without first saving the entity I was receiving all kinds of SQL errors and such. The above settings work for me and does not require custom PHP.
> 0 votes

---
Tags: 7, rules, flags
---


title: Set default length for node id

text:
# Question
Title: Set default length for node id
Is there a way to set the node ID length for a specific content type?

I want to have a specific content type have an ID of 8 digits long so that it can be used as a claim number for the clients paper work.

How would I go about setting this default?

# Answer
> 3 votes
It's generally considered bad database design to give primary keys any business meaning. Just think what will happen if your business changes and your claim number format isn't the same anymore. Changing primary keys in DB is very hard to do.

Malks advice is very good. Add a specific claim ID field to your content type and use token and Automatic Node Titles module and maybe Pathauto to get nice URLs.

# Answer
> 0 votes
There is no way that I know of to do that as the id is an autoincrement column in the base table. What you could do is use something like Automatic Nodetitles and hide the title field so that the title becomes your key.

---
Tags: nodes
---


title: db_select based on userid: uid

text:
# Question
Title: db_select based on userid: uid
I have a dilemma i just can't figure out, and i need your help. The thing is, I wish to display the ip address of the logged in user in my custom form. The problem i have is how do i make it based on the logged in user?

The following is the code i used:

> $hostname = db\_query("SELECT hostname FROM {accesslog} WHERE uid = :uid LIMIT 1', array(':uid' =\>33));
>
> echo "Hostname:" . $hostname . "
> ";

# Answer
If you want the logged in user info, try the following (I have not tested, but it should work).

```
global $user;

$hostname = db_query("SELECT hostname FROM {accesslog} WHERE uid = :uid LIMIT 1', array(':uid' =>$user->uid))->fetchField();

```

The global $user object will return information from the currently logged in user. You might want to put some authentication in to check that the user is logged in if this is used in an area where anonymous users can visit. Maybe wrap it in an if statement like I've done below:

```
if (user_is_logged_in() == TRUE) {

  global $user;

  $hostname = db_query("SELECT hostname FROM {accesslog} WHERE uid = :uid LIMIT 1", array(':uid' => $user->uid))->fetchField();

  echo 'Hostname: ' . $hostname;
}
else {
  echo 'You are not logged in.';
}

```
> 2 votes

# Answer
The logged in user is available in the global `$user` variable:

```
global $user;
$uid = $user->uid;

$args = array(':uid' => $uid);
$hostname = db_query("SELECT hostname FROM {accesslog} WHERE uid = :uid LIMIT 1", $args)->fetchField();

```

Note the use of `fetchField()` above...it's a handy utility method to grab a single field result from a compatible query. Since you're requesting a single row and a single field you might as well use this method for brevity.
> 0 votes

---
Tags: users, database
---


# Question
Title: How to add a new CSS class to a Drupal7 <form>?
Hello I created the following form iterating for each node:

```
...
$render['my_list'][] = drupal_get_form('shop_form_item_'.$node->nid, $node->nid);
...

```

$render will output the form on the page. The forms will be shop-form-item-20, shop-form-item-21 etc...

```
function shop_forms($form_id, $args) {
  $forms = array();
      if(strpos($form_id, 'shop_form_item_') === 0) {
        $forms[$form_id] = array('callback' => 'shop_form',);
      }
  return $forms;
}

function shop_form($form, &$form_state, $nid) {
  $form = array();

    $form['my-item-name'] = array(
    '#type' => 'hidden',
    '#title' => t('Name'),
    '#value' => isset($node->title) ? $node->title : '',

  );

  return $form;
}

```

Now I need to add a class: `<form method="post" action="" class="cart">` How do I insert it?

Thanks

# Answer
You need to add it to the `#attributes` key of the `$form` array:

```
function shop_form($form, &$form_state, $nid) {
  $form['#attributes']['class'][] = 'cart'; // Classes are added to an array and internally converted to a single string by Drupal later on

  $form['my-item-name'] = array(
    '#type' => 'hidden',
    '#title' => t('Name'),
    '#value' => isset($node->title) ? $node->title : '',
  );

  return $form;
}

```
> 4 votes

---
Tags: 7
---


# Question
Title: Add CSS-class to current node in module logic
In a custom module, I add some logic to the node rendering. Based on this, I would also like to add some appropriate CSS-classes to the current node. The below code expresses what I would like to do, but don't know how to do.

```
$node->classes[] = $class;

```

Because I already have the appropriate logic in my module, it seems to me like the adding of classes should be handled in the same place. I could do this in a template instead, but that would require me to duplicate all the logic.

# Answer
> 2 votes
Would hook\_preprocess\_node help you for this?

Example:

```
function mymodule_preprocess_node(&$variables) {
  $variables['classes_array'][] = 'blah';
}

```

The variables array contains all information about the ndoe as well, so you can run logic to dictate which classes should be added to which node types/IDs etc.

If you run dpm (with the Devel module enabled) then you can print everything in that array that you can alter/add to.

I agree that `$node->classes` would be a really useful addition though.

---
Tags: theming
---


# Question
Title: Profile2 and profile fields by user role
I have some profile fields created with the Profile2 module, which creates a main profile containing all the fields.
In the user/%/edit/main path, I see a new tab which displays a form to edit profile fields.

I have also three user roles, ( e.g. role A, B and C), and I want to remove that menu path for the role C. Alternatively, I want to restrict the access to those profile fields by user role.

Can I use the module Profile2 Privacy to achieve the goal?

# Answer
I've done with `hook_process_page()` and removed the variable `secondary_local_tasks` before rendering to the template if the logged-in user is role C. No need additional module.

```
function mymodule_process_page(&$vars, $hooks){
    global $user;
    if(array_key_exists(6, $user->roles) && arg(0) == 'user' && arg(2) == 'edit'){
        # if user role C, hide profile tab
        $vars['tabs']['#secondary'] = array();
        if(isset($vars['secondary_local_tasks'])){
            $vars['secondary_local_tasks'] = array();
        }
    }
}

```

I have also tried this from `hook_preprocess_page()`, but it did not work on the sky theme.
Related question is here : Menu local tasks and hook preprocess
> 4 votes

# Answer
To restrict access to the fileds, I used the module Field permissions to set each field individually for each user role.
> 1 votes

---
Tags: users
---


title: Print raw field data

text:
# Question
Title: Print raw field data
I have a long text (plain text) field connected to my content type. The field contains plain html code.

Is it possible to print this field without sanitizing it's content. I mean raw html output of it's content.

And the main thing is to do that without coding, just from admin area. :)

# Answer
It is possible to do it without coding from the admin area.(Disclaimer: a bit hacky).

Go to the "admin/config/content/formats" area and disable all the filter formats except "Plain Text".

Go to your content type display settings tab and change the format in the dropdown to "Default" and save the settings.

If you view your node now, you will be able to see its raw content form without all the sanitation.
> 0 votes

---
Tags: 7, entities
---


# Question
Title: How can I theme some blocks with the same theme?
I'm seeking the best practises for theming some blocks using a same template file, but my problem is that blocks may not be used in a same region, and they can also be used in one module that has a bundle of different blocks with different themes.

How can I achieve this?

# Answer
Block Theme module will be really helpful. You have a select box where you can choose different tpl.php files for each block you configure
> 1 votes

# Answer
The `block.tpl.php` is the only template that matches all blocks, but the only thing it effects is the wrapping html. This is good if you want to theme blocks to have round corners, or stuff like that. The actual content of the block will not be effected by this.

Since modules can render a block in many ways, you can't really create a single template file where you can handle how the output should be. If you want to alter the output of many different blocks, the only way to go it to handle them on a case by case basis.

You should be aware that CSS goes a long way and you might not need to alter any output or use any template to *theme* the blocks, if you write the needed CSS.
> 0 votes

---
Tags: 6, theming, blocks
---


# Question
Title: Why we go for template files and why we go for theme function?
> **Possible Duplicate:**
> When should I add a new tpl.php file, and when should I implement a theme function?

To theme a form: There are two ways.

1. using function theme\_themename\_form($form)
2. Assigning to a variable in preprocess and printing it in the template files.

My question is:

1. **Why two ways?**
2. **Which way is best for which case ?**

That is for which type of cases we should go for function theme and for which cases we should go for template files.
3. **What is all time best way?**

# Answer
I always think of it like this:

If you need to write a fair bit of HTML for your theme then you want a template file. This way you can maintain as much separation HTML and PHP as you'd like.

If you theme is just accepting data and putting that data through (say) another theme function, then you're not going to be writing any/much HTML. In this case a `theme_*` function is more appropriate in my opinion.

I don't think there really is an "all time best way", both methods are appropriate for different situations.
> 2 votes

# Answer
Both theme functions and template files are useful under different contexts. Tpl files are used if there isn't much preprocessing logic involved. These are the views equivalent in an MVC architecture. So, the maximum allowed logic here is "if-else" constructs, and even that is debatable.

Example use cases for tpl: If you want to change the basic structure of an entity, like print the taxonomy tags as CSV links instead of the default div structure.

Theme functions OTOH, allow for more granularity like augmenting class and other attributes. Preprocessing logic mixes well here as it is till in the "Controller" part of MVC and is not rendered yet. Example use case for theme functions: add a class based on the taxonomy term value

In the real world, the demarcation between views and controllers is really thin. Drupal gives the provision(flexibility rather) of having themeing done at both levels for different contexts.
> 1 votes

---
Tags: theming, forms
---


# Question
Title: Assign different weights for different displays
I am already guessing the answer is that it can't be done but any input on this would be much appreciated.

So I have my Content Type, say... **Cakes!** Now, I have a view named **ALL Cakes!** and they are sorted alphabetically on that.

I also have a view called **Popular Cakes**. Those can be sorted by weight and the *awesome* weight changer view integration.

Now, for some bizarre reason I also need a **Recent Cakes** view which is sorted in it's own way as the name reveals.

Now my question is, is there *any* way to add *another* weight for that view's use?

I know I can sort by date created but that would require going to every single node and manually changing the date; in short I am losing the drag and drop functionality Weight offers.

# Answer
> 0 votes
Turns out with the newest (dev) release of Draggableviews, I was able to use both modules (previously collided with each other) to sort my views choosing either method. So as long as I want to sort 2 views sharing the same content type, this will do. For 2+... well... I'll cross that bridge when/if I ever get to it :)

# Answer
> 0 votes
Poking around in the Weight module, it seems they only allow you one weight per node.

However, you can just keep adding Sort Criteria to the View, based on fields you've added to the content type. So you could add a How Many Layers? numeric field and also sort by layers, in addition to weight and/or popularity and/or whatever.

---
Tags: views
---


title: Problem dynamically calculating field

text:
# Question
Title: Problem dynamically calculating field
I am using Drupal 6, Ubercart 2.7, and Views 2.16 for an e-commerce site.

Using Views with the Bonus: Views Export module, I am producing an atom feed for Google Shopping. This works perfectly.

I am trying to produce a second feed for a different currency, and for my purposes, it is OK to simply multiply the sell price by 1.1 and add the currency code onto the end of the value. However, I've hit a brick wall. I've tried the following options:

**Theming**

I tried creating a template file for that specific field (views-view-field--google-shopping-export--page-2--sell-price.tpl.php - lol). To get this working I had to change Field Output type to "Raw" for the feed, which caused all sorts of other problems. If Field Output was set to "Normal", the template was ignored.

**Dynamic Fields**

I tried using the Dynamic Field and Computed Field modules, but I couldn't get either of these working - both fields were empty within the feed when I tried to pull $node-\>field\_sell\_price in any way. This makes me think that I wasn't referring to the value properly, but I tried many, many combinations - $node-\>field\_sell\_price, $node-\>field\_sell\_price\[0\]\['value'\], $node-\>sell\_price, $node-\>sell\_price\[0\]\['value'\] etc. I was able to pull in $node-\>nid and $node-\>type, but nothing else worked.

Are there any other options to do this? Or have I missed something obvious in the solutions above? I feel like I'm making this much more complicated than it needs to be!

Thanks for any help.

# Answer
> 1 votes
Resolved this by writing my own module implementing hook\_views\_pre\_render and manually changing $view-\>result.

---
Tags: views
---


# Question
Title: How to ensure that features dont get overidden
I tried many times with many setting in features but when i add it and enable it always its overridden and i have to go and revert it. Basically block settings and strongarm have to reverted. So is there anything that i ensure while creating features such that it does not get overridden.

# Answer
> 3 votes
There are a number of reasons why Features may automatically show as overridden after being installed and not manually changing any Drupal configurations related to the Feature. There is a documentation page about this issue: Troubleshooting: Reasons Features May Be Stuck as Overridden. That documentation page is not complete, but it links to a Features issue queue thread where a lot more of the possible problems are outlined.

# Answer
> 2 votes
When you create a feature, you create it from what's defined in your database. After enabling the feature the Feature module will detect you have a version in code and a version in database and will most often display this as the feature being overwritten. This is simply how the module works, and I don't think it would be possible to change that. Not without a lot of effort and a lot of skill/knowledge.

---
Tags: 7, features
---


# Question
Title: How to count the number of post by author in D7?
I am using the following code in drupal 6 but now this code does not work with Drupal 7.

```
<?php
$uid=$node->uid;
$results=db_query("select COUNT(nid) AS count from node where uid=$uid");

while ($res = db_fetch_object($results)) {
print "<p>" . $node->name . " has submitted <em><strong>" . $res->count . "</strong></em>          source code / articles.</p>";
}
?>

```

My primary problem is on how to query the number of post like the sql statement above as:

`db_query("select COUNT(nid) AS count from node where uid=$uid");`

Anyone know the equivalent to this on D7?

BTW, I want to use the code in display suite module.

# Answer
> 2 votes
The result of `db_query()` should now be iterated over directly, `db_fetch_object()` isn't part of Drupal 7.

You could also make use of the `fetchField()` method to get the result of your `COUNT` query:

```
$uid = $node->uid;
$args = array(':uid' => $uid);
$count = db_query('SELECT COUNT(nid) FROM {node} WHERE uid = :uid', $args)->fetchField();

print "<p>$node->name has submitted <em><strong>$count</strong></em> source code / articles.</p>";

```

The above example uses the preferred method of passing arguments to a database query, it's safer than including them directly in the query string.

If you did want to loop over the results (for a query with more than one row/field) you'd do it like this:

```
$result = db_query('SELECT * FROM {node}');
foreach ($result as $row) {
  $nid = $row->nid;
}

```

# Answer
> 2 votes
Or even nicer... in Drupal 7 you can also get the result like this:

```
$count = db_select('node', 'n')->fields('n', array('nid'))->condition('uid', $uid)->execute()->rowCount();
print "<p>user has submitted <em><strong>$count</strong></em> articles.</p>";

```

---
Tags: display-suite
---


# Question
Title: call_user_func() and external functions problem
I'm trying to create some logic in order to have my code better organized, so I am creating a module and trying to separate functions in different files according to it's content type.

For example, I have a module called my\_module and I'm creating two content\_types content\_type1 and content\_type2

So I created this structure:

* my\_module.install
* my\_module.module
* my\_module.content\_type1.inc
* my\_module.content\_type2.inc

This logic inside install:

```
function my_module_install() {
  // During installation, the t() function is unavailable, so we use get_t()
  // to store the name of the translation function.
  $t = get_t();

  //List of objects to be created
  $nodes = array('content_type1','content_type2');

  //Create all the content-types from the array
  foreach ($nodes as &$node_name) {
    error_log('Create: '.$node_name, 0);
    call_user_func('_'.$node_name.'_create_node',$node_name);
  }

  unset($node_name);
}

```

And this logic inside each file ( content\_types )

```
function _content_type1_create_node($node_name='type1') {}

function _content_type2_create_node($node_name='type2') {}

```

Since I added this lines to the my\_module.info:

```
files[] = my_module.content_type1.inc
files[] = my_module.content_type2.inc

```

I was expecting to have all the logic working as it should but

```
//content_type1_create_node()
call_user_func('_' . $node_name . '_create_node', $node_name);

```

It cannot find the callback and I think it's because the callback.

Am I over engineering, or doing it wrong?

# Answer
> 2 votes
Your functions are in files that haven't yet been included, try changing your code to this:

```
foreach ($nodes as &$node_name) {
  module_load_include('inc', 'my_module', 'my_module.' . $node_name);

  $func = '_'.$node_name.'_create_node';
  if (function_exists($func)) {
    call_user_func($func, $node_name);
  }
}

```

I've never been able to get the `files[]` key in the `.info` file to work, I don't think it's used for arbitrary files but rather those that will form part of Drupal's code registry (using `hook_hook_info()` or something like that), but I haven't delved too deeply so it's worth checking yourself.

To answer your final question, yes I think you're over-engineering this a bit :)

It would make sense to do this if your module is going to become generic (so more content types can be catered for) but if it's really just 2 content types I'd put the code inside the `.module` file to be honest.

Obviously if you think these files will end up having a lot of code it makes sense to separate them, but if not I don't think you're really getting much benefit for doing so.

---
Tags: 7
---


# Question
Title: My administration menu dissapears when installing a module
I have created a module that implements `hook_menu()` using the following code:

```
function mypbm_menu() {
  $items['pbg'] = array(
    'title' => 'Theming example',
    'description' => 'Examples of implementing theme functions.',
    'page callback' => 'pbg',
    'access callback' => TRUE
  );
  return $items;
}

function pbg($id) {
  $stringit = $id;

  return $stringit;
}

```

The module works the way it is supposed to work; when it is turned on, the Administration menu module disappears.

Does anyone know why?

# Answer
> 1 votes
The reason in my case was the character encoding of the "mymodule.module" file. Changing it back from "UTF-8" to "ANSI" solved the problem.

---
Tags: routes, hooks
---


title: Product with empty attribute values

text:
# Question
Title: Product with empty attribute values
There are a couple of attributes in my product. If the product is added to the cart without choosing one or two attributes, the product goes to the cart, but unselected attributes are also showing up.

I want that attributes without values are not shown. How can I do this? I tried using `hook_product_description()`, but it doesn't help.

I'm using Ubercart 6.x-2.7, and its Product attributes module.

# Answer
> 2 votes
Create a module to customize the cart form. Here's how I usually do it.

```
function custom_cart_form_alter(&$form, $form_state, $form_id) {
  if ($form_id == 'uc_cart_view_form') {

    for($i=0;$i<count($form['items']);$i++){
       //these are rows in your cart... that includes the "total" line etc, so make sure to check that the row has the data you need

       //I believe what you're looking for is in $form['items'][$i]['desc']['#value']
       //you're going to need to look for the empty tag, probably using a regex pattern and remove the whole <li> element
    }

  }
}

```

---
Tags: ubercart
---


# Question
Title: How to associate an image node with taxonomy term?
I know this is going to be a very easy answer, but I've been trying to build on someone else's code and am frustrated as hell. I need to link an image type node with a taxonomy term (or a couple terms) for categorizing them. The table is term\_node and I just need to know how this table is populated, and how I can link a node (nid) with a term (tid).

When I go to mysite.com/categories/tags/tag\_name I can view image nodes linked with that taxonomy term, but there was never a good interface built to add them and I'm not sure how they where added before. His code is a mess. I believe he may have used the Image Assist module, but I'm not sure.

I thought I should just be able to set the taxonomy when adding an image, but there is no such option when adding or editing the node.

# Answer
> 1 votes
why don´t you use the taxonomy image module then simply get the taxonomy id from the node (use node\_load(nid) then identify with var\_dump how can you refer to the taxonomy..he might be using the CCK or the taxonomy module ) then get the id(s) of the term, load that term with and see it´s image (again use var\_dump to know it´s structure)

---
Tags: 7, nodes
---


title: Add a class to a row in a view

text:
# Question
Title: Add a class to a row in a view
i'm trying to create a module that adds a 'new' class to a row based on the date it was published.

So i thought of doing something like

```
if ($data > 10 days ago){
  $this_row addclass new
}

```

But whats the best way to do this? I would like to put this in a module so i can simply turn it on and off and avoid problems with template files from ds.

I can only find a way using hook\_views\_pre\_render to add a class to all the rows, but nothing about adding it to one specific row. Maybe i need to use another hook?

# Answer
> 1 votes
Writing a view handler would be the perfect way to do this. The handler itself will be almost as simple as your example code.

However getting everything right to get the handler called from views isn't easy. A good example to learn from is the maillog module. It integrates its log table with views and adds a custom handler.

---
Tags: views, theming, hooks
---


# Question
Title: Apply coupon from an affiliate link to ubercart
Modules involved

1. Cart Links
2. uc\_discounts\_alt or uc\_coupon (I like uc\_discounts\_alt better)
3. uc\_affiliate2
4. Ubercart

I need to give the ability to have a coupon applied to the cart if the user came through an affiliate link.

Example:

I have a coupon giving 10% off to "Product 1". I have a partner "Affiliate 1".

I have a link http://site.com/affiliate/1/cart/add/p1?destination=cart/checkout (which there is an issue there since the destination is redirected before the add to cart is applied)

I want to make it so that when that link is followed the coupon is added to the order.

I figured to do this with Conditional Actions, but the predicates/conditions/actions don't seem to exist.

I guess I need to build a predicate for "Item aded to cart", a condition of "Is there an affiliate" does seem to exist, an action for "Add discount". But I also seem to need something to tie discounts to affiliates.

Any ideas on how to proceed here? Are there any modules out there for this? Any alternatives?

# Answer
> 1 votes
Try ECO (Extra Customization Options for Ubercart).

> ECO (Extra Customization Options for Ubercart) provides additional ("extra") options to customize Ubercart.
>
> Some of the functionality provided also includes a degree of integration with other contributed modules like Legal, Webform, and Ubercart Discount Coupons. Among the customization options are using URL parameters to auto-apply coupons in checkout, requiring new customers to choose a password, and integration with the Webform module to pre-populate address fields in checkout.

---
Tags: ubercart
---


# Question
Title: Importing Nodes to D7 with all custom fields
I've got a Drupal site with an obscene about of content that has been given to me in CSV format. I'm toying with the idea of building a module to let me do this but if there's one already out there that I can use to just get this site out of the way that would be awesome.

My question is: Is there anything out there that allows you to import a CSV file into D7 that will populate the node table and all the custom fields tables as well?

Thanks.

# Answer
The Feeds module (sucessor to the FeedAPI module) has that functionality built in.

For your needs specifically it offers:

* Import or aggregate CSV files
* Create nodes, users, taxonomy terms or simple database records from import
* Granular mapping of input elements to Drupal content elements
> 1 votes

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


# Question
Title: How to change default registration form?
By default, user registration form in Drupal 7 takes 2 fields: "Username" and "Email."

I want users to set their password directly upon Registration.

Take 4 fields: \- Username \- Password \- Confirm Password \- Email

How can I do so?

# Answer
In *Administration » Configuration » People » Account settings*, uncheck the *Require e-mail verification when a visitor creates an account.* option. This will allow user to directly enter their password on the registration form.
> 9 votes

# Answer
Theres a module called logintoboggan that can really save you tons of time.
> 2 votes

---
Tags: 7
---


# Question
Title: Insert Block Inbetween Paragraphs of the Content Body Field
I have a block I am trying to insert into the body field, catch is I want it to appear after the first two paragraphs. I tried using something similar to this in my **node.tpl.php**:

```
<?php
$array = explode ("</p>", $content['body']);
$array[2] = $myBlock . $array[2];
$content['body'] = implode("</p>", $array);
?>

//Important: This code snippet needs to be inserted before

<?php
print $content['body'];
?>

```

This code does insert my block in the body field, but also overwrites all the content in the field.

I'm using Drupal 7.10, any help is appreciated.

# Answer
> 1 votes
I think you want to be doing this on `$body[0]['value'];` And then in your output put `echo render($content['body']);` see the answer to this post on rendering fields.

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


# Question
Title: Get the node ID from the "node/add" menu item and hook_form_alter()
I want to set a unique 7-digit code to a custom content type and display it in a disabled textfield when a node is created. I created a CCK textfield and set it to disabled in hook\_form\_alter, great.

I think that a good way to make this unique ID is just to use the node id and fill it out to the required length (eg. 0000012). It doesn't look like $nid is available at the node/add form though. How can I set this ID field to default to the `$nid`? Can I access the `hook_form_alter()` as the content is created (on form submission)?

# Answer
Implement a field in PHP.

It can keep its own serial counter in a variable, and auto-fill itself with that. You can create formatters for all the different use cases yourself.

Field example code here: http://drupal.org/project/examples

Also I made a UUID field you could hack on: http://drupal.org/sandbox/Mile23/1326218
> 1 votes

# Answer
You're right, the nid is not available at this point, it's assigned only after the the node is saved.

The easiest solution is most probably to use `hook_node_insert` and resave the node after having added the value to the field you have created.
> 1 votes

# Answer
Looking at the code of node\_save(), which the function used to save a node, the hooks that are invoked after drupal\_write\_record(), which is the function used to set the node ID, are the following ones (when the node is created):

```
// Call the node specific callback (if any). This can be
// node_invoke($node, 'insert') or
// node_invoke($node, 'update').
node_invoke($node, $op);

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

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

```

> Can I access the `hook_form_alter()` as the content is created (on form submission)?

`hook_form_alter()` is invoked for a node edit form whenever the node is being created, or the node is being updated. You can add a custom submission handler from `hook_form_alter()`, which then is able to alter the node being saved.
The hooks I have reported should be sufficient for what you want to do, though.
> 0 votes

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