# Question
Title: Wrapping javascript code conditionally using a cookie
I want to include the following code in page.tpl.php only once during first site visit and for subsequently not. I mean this will pop-up an ad only once. I want to set it based on a cookie. How to conditionally include this code based on a cookie? I need the sample code.

```
<script language="JavaScript">
        var zflag_nid="1185"; var zflag_cid="3307"; var zflag_sid="823"; var zflag_width="1"; var zflag_height="1"; var zflag_sz="15";
        </script>
        <script language="JavaScript" src="http://d8.zedo.com/jsc/d8/fo.js"></script>

```

**EDIT:**

Will this work in page.tpl.php ? I want add it before \</head\> so that the js file is included only once in user session.

```
<script type="text/javascript">
    if(!jQuery.cookie('myCookie'))
    {
    $.cookie('myCookie':'myValue');
    <!-- Javascript tag: -->
<script language="JavaScript">
var zflag_nid="1185"; var zflag_cid="3307"; var zflag_sid="823"; var zflag_width="1"; var zflag_height="1"; var zflag_sz="15";
</script>
<script language="JavaScript" src="http://d8.zedo.com/jsc/d8/fo.js"></script>
    }

</script>

```

# Answer
> 1 votes
you can add javascripts files using javascript you need to do something like this:

```
<script type="text/javascript">
  if(!jQuery.cookie('myCookie')) {
    $.cookie('myCookie':'myValue');

    var zflag_nid="1185";
    var zflag_cid="3307";
    var zflag_sid="823";
    var zflag_width="1";
    var zflag_height="1";
    var zflag_sz="15";

    //building the script:
    var js = document.createElement("script");

    js.type = "text/javascript";
    js.src =  "http://d8.zedo.com/jsc/d8/fo.js";

    //inserting into the body document
    document.body.appendChild(js);
  }
</script>

```

Or you can use the jQuery's getScript function: http://api.jquery.com/jQuery.getScript/

You can look more in deep about this here:

https://stackoverflow.com/a/950146

# Answer
> 1 votes
This StackOverflow question should contain enough information to solve your issue.

I would go with the one that suggests using `setcookie()`. `$_SESSION` information is cleared when the user's session ends, generally at the close of the browser. Here is a recent example of me using cookies to remember an anonymous user's submission of a Webform and redirect them to the completion page if they tried to visit the Webform again:

```
    <?php
    define('REQUEST_TIME', $_SERVER['REQUEST_TIME']);

    function _mymodule_manage_cookie($nid, $type = 'my_cookie_type') {
      $matches = (bool) $nid == variable_get("mymodule_{$type}_webform_nid", FALSE);
      if (empty($_COOKIE["Drupal_visitor_mymodule_{$type}_submitted"]) && $matches) {
        mymodule_cookie_save(array("mymodule_{$type}_submitted" => TRUE));
      }
    }

    /**
     * Drupal 7 yoink!
     */
    function mymodule_cookie_save(array $values) {
      foreach ($values as $field => $value) {
        // Set cookie for 365 days.
        setrawcookie('Drupal.visitor.' . $field, rawurlencode($value), REQUEST_TIME + 31536000, '/');
      }
    }

    function mymodule_cookie_delete($cookie_name) {
      setrawcookie('Drupal.visitor.' . $cookie_name, '', REQUEST_TIME - 3600, '/');
    }
    ?>

```

You need to put this in a module or in `template.php` in your theme. You can conditionally include the code in a manner similar to the following:

*template.php*

```
    <?php
    function THEMENAME_preprocess_page(&$variables) {
      // THEMENAME_get_first_visit_cookie() would refer to a function
      // you have to write that retrieves if the cookie
      // is set. You could alternatively try just using
      // $_COOKIE['my_cookie_type'].
      if (THEMENAME_get_first_visit_cookie()) {
        $variables['first_visit'] = TRUE;
      }
    }
    ?>

```

*page.tpl.php*

```
    (skip to wherever you want to embed the code)
    <?php if ($first_viist): ?>
      // Paste your code here
    <?php endif; ?>

```

Now, one more point. The way I just showed you *isn't* the best way. You should add your Javascript properly using `drupal_add_js()` in a module or by adding a separate Javascript file in the theme that reacts to a class on the `<body>` tag and displays your first visit message (or whatever you're doing). You would still need the `$first_visit` variable to determine whether to add the class or not.

# Answer
> 0 votes
You are mixing your metaphors so to speak in trying to use jQuery and script tags like php if/thens to include code in your templates.

If you want it all done in the browser, then do it all in the browser, eg, if I haven't been here before, add or execute such and such code to/in the DOM, otherwise don't do anything, eg,

```
if ( ! // whatever you need to do in javascript to determine if you've been here before) {
  alert("Welcome New User!");
}

```

in your js.

---
Tags: 6, theming, javascript
---


# Question
Title: Contextual filter in Views for taxonomy browsing
I'm having a problem with setting filter value from the URL. What I want to do is to list all terms in a taxonomy node, so I list all terms whose parent ID equals what's provided by URL. I have the relation set, I have the contextual filter set, but unfortunately when I enter %1 as the parent term ID value to be matched by the filter, it's treated literally and returns nothing. That's because no term has the ID of '%1'. However, when I expose the filter and type in the term ID, works as expected.

How do I use the placeholders in the filter definition?

# Answer
> 0 votes
Since that moment I have messed with my views to a fubar state. But looks like I pinpont the rule of thumb that I haven't heard anywhere: when you set up a context filter, eg. for "Content: nid", you don't add it to the regular filter list on the left hand side. And you don't have to bother with %-style placeholders. At any rate, thanks JoeS for your readiness to help. I bet you will have a bunch of chances to help me out, as I seem to attract all kind of Drupal surprises ;-)

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


title: Build a blog archive block with code

text:
# Question
Title: Build a blog archive block with code
I want to build a "Blog Archive" block with a custom module. How do I do it?

# Answer
> 4 votes
* create a new folder in /sites/default/modules
* create a custom\_blocks.info file inside that folder
* add this content in the file:

```
name = Custom blocks
description = "A short description of your module"
package = My modules
files[] = custom_blocks.module
core = 7.x

```
* create another file: custom\_blocks.module (note that you've specified this in the info file)
* add this PHP code:

```
<?php
  function custom_blocks_block_info() {
    $blocks = array();

    $blocks['unique_id_for_your_block'] = array(
      'info' => t('block info'),
      'cache' => DRUPAL_NO_CACHE,
    );

    // You can add more blocks here.

    return $blocks;
  }

  function custom_blocks_block_view($delta = '') {
    $block = array();

    switch ($delta) {
      case 'unique_id_for_your_block':

        // Put your logic here and generate the HTML you want to display in your block.
        $block['subject'] = t('block title');
        $block['content'] = 'Put here the HTML generated above';
        break;

      // Add more case statements here if you defined more than one block.

    }

    return $block;
  }

```

# Answer
> 1 votes
Hi this solution is not "drupal way" way of doing this, but it does the job. Here is the code that needs to be put into a custom block where and input type needs to be PHP.

```
<?php

drupal_add_library('system', 'ui.accordion');
drupal_add_js('jQuery(document).ready(function(){jQuery("#archivetree").accordion({ active: "h3:last" });});', 'inline');

$result = db_query("SELECT DATE_FORMAT((DATE_ADD('19700101', INTERVAL node.created SECOND) + INTERVAL -18000 SECOND), '%Y%m') AS created_year_month, COUNT(node.nid) AS num_records
FROM
{node} node
WHERE (( (node.status = '1') AND (node.type IN  ('blog')) ))
GROUP BY created_year_month
ORDER BY created_year_month ASC");

foreach ($result as $record) {

    $created_year_month = $record->created_year_month;
    $num_records = $record->num_records;
    $year =  substr($created_year_month, 0, 4);
    $month = substr($created_year_month, -2, 2);
    $month_name = date( 'F', mktime(0, 0, 0, $month) );

    $archive_tree[$year][$month] = array(
        'month'            => $month,
        'name'             => $month_name,
        'num_records'      => $num_records,
        'year'             => $year,
    );
}
$i_year = 0;
foreach ($archive_tree as $list_year) {
    if ($i_year == 0){
        $output = "<div id='archivetree'>\n";
        $i_year++;
    }

        $i_month = 0;
        foreach ($list_year as $list_month) {

            if ($i_month == 0){
                $output .= "<h3><a href='#'>";
                $output .= $list_month['year'];
                $output .= "</a></h3>\n";
                $output .= "<ul>\n";
                $i_month++;
            }

            $text = $list_month['name'];
            $text .= " (";
            $text .= $list_month['num_records'];
            $text .= ")";
            $path = "blog/archive/";
            $path .= $list_month['year'];
            $path .= "/";
            $path .= $list_month['month'];
            $link = l($text,$path);
            $output .= "<li>$link</li>\n";
        }
        $output .= "</ul>\n";

}
        $output .= "</div>\n";
print $output;

?>

```

I am currently working on implementing this as a custom module, but am not quite there yet.

---
Tags: blocks
---


# Question
Title: When using views to create a list of nodes, how can I eliminate the link from the node title?
I am using views to create a list of nodes. I am using the "Unformatted" style, with the "Node" row style.

This is perfect for my need *except* that it automatically creates a link from each node title to the node page. I would like to not have those links.

How can I most easily do this? Would the best way to be to switch to "Field" row style and simply include the fields I want, styled the way I want? Or is there a simpler way?

# Answer
> 2 votes
When you select node style, it uses your node.tpl.php file to create the node, so if that has a link in the title, it's gonna be there. You can choose the "style" of node, eg, teaser or full, to change this behavior, and include or not include links and comments, etc. Or, as you ask, go to Fields and have a lot more flexibility.

# Answer
> 1 votes
A very good option to have reusable rendering templates is to use Display Suite, it allows you to define arbitrary view modes for your node types and use them easily in views. The issue with the linked title is very easy to solve in display suite by just editing the options for the title field in the appropriate view mode.

Note: to use arbitrary view modes in D6 it's necessary to select the Display Suite node renderer for the row style, not the default one.

---
Tags: views, 6
---


# Question
Title: Converting PHP code dumped in a custom block into a Proper drupal custom module (drupal 7)
Hi here is the code that works when i put it in a custom block as PHP

```
<?php
drupal_add_library('system', 'ui.accordion');
drupal_add_js('jQuery(document).ready(function(){jQuery("#archivetree").accordion({ active: "h3:last" });});', 'inline');

$result = db_query("SELECT DATE_FORMAT((DATE_ADD('19700101', INTERVAL node.created SECOND) + INTERVAL -18000 SECOND), '%Y%m') AS created_year_month, COUNT(node.nid) AS num_records
FROM
{node} node
WHERE (( (node.status = '1') AND (node.type IN  ('blog')) ))
GROUP BY created_year_month
ORDER BY created_year_month ASC");

foreach ($result as $record) {

    $created_year_month = $record->created_year_month;
    $num_records = $record->num_records;
    $year =  substr($created_year_month, 0, 4);
    $month = substr($created_year_month, -2, 2);
    $month_name = date( 'F', mktime(0, 0, 0, $month) );

    $archive_tree[$year][$month] = array(
        'month'            => $month,
        'name'             => $month_name,
        'num_records'      => $num_records,
        'year'             => $year,
    );
}
$i_year = 0;
foreach ($archive_tree as $list_year) {
    if ($i_year == 0){
        $output = "<div id='archivetree'>\n";
        $i_year++;
    }

        $i_month = 0;
        foreach ($list_year as $list_month) {

            if ($i_month == 0){
                $output .= "<h3><a href='#'>";
                $output .= $list_month['year'];
                $output .= "</a></h3>\n";
                $output .= "<ul>\n";
                $i_month++;
            }

            $text = $list_month['name'];
            $text .= " (";
            $text .= $list_month['num_records'];
            $text .= ")";
            $path = "blog/archive/";
            $path .= $list_month['year'];
            $path .= "/";
            $path .= $list_month['month'];
            $link = l($text,$path);
            $output .= "<li>$link</li>\n";
        }
        $output .= "</ul>\n";

}
        $output .= "</div>\n";
print $output;
?>

```

I am trying to convert it to proper Drupal Block created through a module here is my .module code:

```
<?php

/**
 * @file
 * Archive Accordion will give you a new block for the blog content type.
 */

 /**
 * Implements hook_help.
 *
 * Displays help and module information.
 *
 * @param path
 *   Which path of the site we're using to display help
 * @param arg
 *   Array that holds the current path as returned from arg() function
 */
function archive_accordion_help($path, $arg) {
  switch ($path) {
    case "admin/help#archive_accordion":
      return '<p>'.  t("Archive Accordion will give you a new block for the blog content type") .'</p>';
      break;
  }
}

/**
 * Implements hook_block_info().
 */
function archive_accordion_block_info() {
  $blocks['archive_accordion'] = array(
    'info' => t('Archive Accordion'), //The name that will appear in the block list.
    'cache' => DRUPAL_CACHE_PER_ROLE, //Default
  );
  return $blocks;
}

/**
 * Custom content function.
 *
 * @return
 *   A result set of the targeted posts.
 */
function archive_accordion_contents(){

  //Later fix Use Database API to retrieve current posts.
  /*
  $query = db_select('node', 'n')
    ->fields('n', array('nid', 'title', 'created'))
    ->condition('status', 1) //Published.
    ->condition('created', array($start_time, $end_time), 'BETWEEN')
    ->orderBy('created', 'DESC') //Most recent first.
    ->execute();
  return $query;
  */
  $result = db_query("SELECT DATE_FORMAT((DATE_ADD('19700101', INTERVAL node.created SECOND) + INTERVAL -18000 SECOND), '%Y%m') AS created_year_month, COUNT(node.nid) AS num_records
    FROM
    {node} node
    WHERE (( (node.status = '1') AND (node.type IN  ('blog')) ))
    GROUP BY created_year_month
    ORDER BY created_year_month ASC");
}

/**
 * Implements hook_block_view().
 *
 * Prepares the contents of the block.
 */
function archive_accordion_block_view($delta = '') {
  switch($delta){
    case 'archive_accordion':
      $block['subject'] = t('Archive Accordion');
      if(user_access('access content')){
        //Use our custom function to retrieve data.
        $result = archive_accordion_contents();
        //Array to contain items for the block to render.
        $items = array();
        //Iterate over the resultset and format as links.
        foreach ($result as $record) {

    $created_year_month = $record->created_year_month;
    $num_records = $record->num_records;
    $year =  substr($created_year_month, 0, 4);
    $month = substr($created_year_month, -2, 2);
    $month_name = date( 'F', mktime(0, 0, 0, $month) );

    $archive_tree[$year][$month] = array(
        'month'            => $month,
        'name'             => $month_name,
        'num_records'      => $num_records,
        'year'             => $year,
    );
}
$i_year = 0;
foreach ($archive_tree as $list_year) {
    if ($i_year == 0){
        $output = "<div id='archivetree'>\n";
        $i_year++;
    }

        $i_month = 0;
        foreach ($list_year as $list_month) {

            if ($i_month == 0){
                $output .= "<h3><a href='#'>";
                $output .= $list_month['year'];
                $output .= "</a></h3>\n";
                $output .= "<ul>\n";
                $i_month++;
            }

            $text = $list_month['name'];
            $text .= " (";
            $text .= $list_month['num_records'];
            $text .= ")";
            $path = "blog/archive/";
            $path .= $list_month['year'];
            $path .= "/";
            $path .= $list_month['month'];
            $link = l($text,$path);
            $output .= "<li>$link</li>\n";
        }
        $output .= "</ul>\n";

}
        $output .= "</div>\n";

        if (empty($items)) { //No content.
          $block['content'] = t('No posts available.');
        }
        else {
          //need to fix to Pass data through theme function.
          $block['content'] = $output;
        }
      }
  }
  return $block;
    drupal_add_library('system', 'ui.accordion');
    drupal_add_js('jQuery(document).ready(function(){jQuery("#archivetree").accordion({ active: "h3:last" });});', 'inline');
}

```

and i am getting the following errors on my page:

```
Warning: Invalid argument supplied for foreach() in archive_accordion_block_view() (line 79 of /whatever/sites/all/modules/archive_accordion/archive_accordion.module).
Notice: Undefined variable: archive_tree in archive_accordion_block_view() (line 95 of /whatever/sites/all/modules/archive_accordion/archive_accordion.module).
Warning: Invalid argument supplied for foreach() in archive_accordion_block_view() (line 95 of /whatever/sites/all/modules/archive_accordion/archive_accordion.module).
Notice: Undefined variable: output in archive_accordion_block_view() (line 126 of /whatever/sites/all/modules/archive_accordion/archive_accordion.module).

```

Any help is really appreciated... :)

# Answer
*EDIT* You are not returning any thing from `archive_accordion_contents()`, you just set a variable named `$result`.

Here is the correct code:

```
function archive_accordion_contents(){
   return db_query("SELECT DATE_FORMAT((DATE_ADD('19700101', INTERVAL
                    node.created SECOND) + INTERVAL -18000 SECOND), '%Y%m') AS created_year_month, COUNT(node.nid) AS num_records
                    FROM
                    {node} node
                    WHERE (( (node.status = '1') AND (node.type IN  ('blog')) ))
                    GROUP BY created_year_month
                    ORDER BY created_year_month ASC");
}

```
> 4 votes

---
Tags: 7, blocks
---


# Question
Title: 1 parent nodetype with 2 subnodetypes - show all subnodes in a viewlist
Here is the situation: Using D7 and views 3.

I have made a nodetype 1.

I have two nodetypes 1a and 1b (node referenced to nodetype 1).

I want to show all nodes (1a and 1b) attached to nodetype 1 in a views-list when showing nodetype 1.

Contextual filters can only show one subnodetype correct.

Any suggestions?

# Answer
You will have to use `Relationships` to pull in data from your other nodes. When you have defined your relations then you will be able to use these in each fields setting:

```
Relationships:
field_1a
field_1b

Fields:
// Uses no relation
// Will display title from content-type 1
Content: Title
// Relation field_1a
// Will display title from content-type 1a
Content: Title
// Relation field_1b
// Will display title from content-type 1b
Content: Title

```
> 1 votes

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


# Question
Title: Single Drupal installation with multiple websites
Currently, I have two static HTML folders: 1 for English webiste , and 2 for Thai website. They have the same look and feel but different menu and content. To be precise, the menu and content in the www.example.org/th are not translated versions of the English site, they are totally different.

URL for the English website is http://www.example.org and http://www.example.org/th for the Thai website. I want to switch to Drupal 7. So, here's what I have in the to-do list:

Theme:

* Create a parent theme (www.exaple.org)
* Create a sub theme for (www.example.org/th)

Panel:

* I will create a Panel with "th" path for www.example.org/th and then make it use the subtheme (not sure if this is the correct approach)
* Create a different menu and will put it in the Panel (not sure if this will work out that way)

Should I create Panel and different menu or Should I go with single Drupal installation that can be used to power multiple websites to get the same result as I currently have with static HTML sites? If so, please show me some tips or sample to get started.

Thank you.

# Answer
> 1 votes
Yes, if these two sites are really separate and have nothing in common, I would go with a multi-site setup and a single Drupal installation.

This is supported out of the box, see the Multi-site documentation on drupal.org for more information.

---
Tags: 7, theming, panels, multi-sites
---


# Question
Title: Bringing modules into project as git submodules - .info file doesn't have version info
I'm adding modules into my git-enabled Drupal project as git submodules. Things seem to work fine except that when I bring in a git submodule and use the version I want, by doing a 'git checkout 6.x-1.1' for example, the resulting .info file doesn't have the following information (with this example taken from zen):

```
; Information added by drupal.org packaging script on 2011-04-05
version = "6.x-2.1"
core = "6.x"
project = "zen"
datestamp = "1302017816"

```

Whatever is added by this drupal.org packaging script is apparently added when the archive is prepared for download on drupal.org, and isn't added when the commit is tagged with a certain version in git. Now will these modules even be considered valid by Drupal when I try to enable it? And if so, I'm sure this would screw up the update process because update won't know what versions of existing modules it's comparing against.

So how can I fix this? I must have missed something, because clearly there's no way every git user can be expected to manually add in this metadata for every module every time they update.

# Answer
Check out the Git deploy project.

It exposes the version information by looking at the git information. I am not 100% if it supports git submodules, but it's worth a try.
> 1 votes

---
Tags: 7, version-control
---


# Question
Title: How to reference identical files on multiple nodes?
I have created two nodes that contain a File Upload. Is it possible to reference files common to both nodes or do I have to create duplicates? I want to reduce the overhead of managing large number of uploaded files.

# Answer
> 1 votes
One way to do this is to use the Media suite which provides a media browser from which you can select existing files. Media also allows to add fields to your files to add additional meta data to them. The current UI in Media 7.x-1.x is unfortunately not what you could be, there are e.g. no filters in the media browser.

An alternative, as suggested in the comments, is to create a content type with just the uploaded file and then reference that node instead of the file. I'd say this is more the 6.x-like way to do this, but it does work as well...

# Answer
> 1 votes
You might want to look at FileField Sources that allows you to upload, choose files on the server or add remote files to re-use files where ever they live... Handy.

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


# Question
Title: Drush package handler - recommendations?
After a day of cursing drush for refusing to update anything, I finally discovered that using --package-handler=wget instead of =git\_drupalorg allowed everything to run smoothly. I suspect there were still problems with my git settings.

Why would I want to use git\_drupalorg as the package handler? I see that most examples online use it, but perhaps people are defaulting to it on the basis that they're versioning with Git. Sure, I'm versioning my projects with Git too. But that versioning still happens, regardless of what technique is used to download core or modules. I just can't see what advantage there is in using git as the package handler.

But since everybody else is doing it... have I missed something?

(I don't ever contribute code to drupal.org. I can see why using git would be necessary for that. But then presumably contributors keep a totally separate installation for code development.)

# Answer
Using the git\_drupalorg package handler is best if you want to track the latest HEAD of the dev release. If you just want to download stable releases, the wget package handler is preferable.
> 1 votes

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


title: Vertical Tabs in Front End (Drupal 7)

text:
# Question
Title: Vertical Tabs in Front End (Drupal 7)
I am trying to use Vertical Tabs on the front end of my site.

Normally, I would just add a jQuery plug-in to my theme. However, vertical tabs are built into Drupal 7, so it seems silly to use a plugin, when the functionality already exists.

I'm just not sure how to call the built-in vertical tabs.

Dan Silver's blog has an excellent tutorial on how to call the built-in tabs. However, his tutorial is for horizontal tabs. I am not sure how to convert them to vertical ones.

I would appreciate if anyone could give me some hints.

(P.S. I am aware that modules exist to do this. However, for my purposes it seems overkill to use a module when I can achieve it with a few simple lines of theming).

# Answer
The examples module will provide you some custom code to implement this, have a look at the API documentation which add a vertical tab to the node form.

The only restriction I can think of is that this code is for forms so if you want to theme a node output you should use jQUery UI tabs. The tutorial you linked seems fine, but you'll need to change a little its CSS classes in order to output vertical tabs, compare its code tho this demo.
> 1 votes

---
Tags: 7, theming, forms
---


# Question
Title: How to retrieve a query result in a computed field?
I'm trying to run the following select in a computed field, but it doesn't work: any clue on what is going wrong ?

```
$nid = $node->nid;

$result = db_query('SELECT description FROM {taxonomy_term_data} AS ttd
                    LEFT JOIN {taxonomy_index} AS ti ON ti.tid = ttd.tid
                    WHERE ttd.vid = :vid AND ti.nid = :nid',
                  array(':vid' => 16, ':nid' => $nid));

$entity_field[0]['value'] = $result;

```

# Answer
> 2 votes
`db_query()` doesn't return a column, to do this you need to fetch it using `fetchField()`:

```
$nid = $node->nid;

$result = db_query('SELECT description FROM {taxonomy_term_data} AS ttd
                    LEFT JOIN {taxonomy_index} AS ti ON ti.tid = ttd.tid
                    WHERE ttd.vid = :vid AND ti.nid = :nid',
                  array(':vid' => 16, ':nid' => $nid));

$entity_field[0]['value'] = $result->fetchField();

```

# Answer
> 0 votes
Assuming you have only one row (the first one returned) that you are concerned with, you can wrap your db\_query() in db\_fetch\_array() (or db\_fetch\_object() if you prefer objects) to access the contents of the row it returns, eg,

```
$row = db_fetch_array(db_query( /* whatever */ ));

```

and now $row is an associative array representing the contents of the row based upon your query.

Check out http://api.drupal.org/api/drupal/includes--database.pgsql.inc/function/db\_fetch\_array/6 for more info.

---
Tags: database, entities
---


# Question
Title: unset form elements with hook_form_alter()
I've created my module, but I have a problem when its code executes the following code:

```
dpm($form);

```

I can't see the notifications fields (from the Notifications module); also, I can't remove the "Format" fieldset from the node create page ("node/add/question"; my content type is called "question").

The following snippet works great, but is there any other method to print all the form's fieldsets? I just stuck at this notifications field set, as I can't remove it.

```
unset($form['menu'], $form['comment_settings']);

```

# Answer
Notification does add its own form elements in its own `hook_form_alter()`, which is probably executed after yours.

Check the module weight in the {system} table, and set your module to a higher value to have it run later.

Note: Instead of using `unset()` to hide form elements, you should instead set the `#access` property to `FALSE`. This keeps them in the form build tree, which avoids problems if other modules try to access or alter that information.
> 5 votes

# Answer
Another option would be to do what you need to do using the `#after_build` form property.
> 1 votes

---
Tags: forms
---


# Question
Title: Is there a module that provides payment processing but not a shopping cart?
I am building a website that allows users to "upgrade" their content. The user can choose a "premium" listing and once paid for their node will appear higher in a list of nodes.

I'm looking for a module that can do this, or a module that can at least provide the payment page so that I could customise the node editing process and direct them to this page, take their payment then update the node.

I know something like Ubercart can provide the payment processing but it has a very set payment checkout process that is more oriented to a shopping cart checkout process and would take a lot of time to customise for what I want.

Any recommendations on how to do this?

Im running Drupal 7.

# Answer
> 1 votes
Have you tried some of those ?

* lm\_paypal:

> This module provides an interface to PayPal using Instant Payment Notifications (IPN). It currently supports paid memberships (subscriptions), donations (tip jar) and paid adverts (classified ads).
* Payment API: this one need a specific module for the payment platform

> This module can be used by other modules to collect and track payments. Through this API, any module can provide a payment form and payments can be handled and tracked centrally.
* How to build a paid membership site with Drupal 7 (paid module)

---
Tags: 7, payment-gateways
---


title: taxonomy cck pathauto

text:
# Question
Title: taxonomy cck pathauto
Can anyone tell me how to set the taxonomy in the following order

1. super Category---eg(Area)
2. Category--- eg(food)
3. sub category --- eg(fruits)

if a visitor chooses a super category area, then the fruits in that area should be shown And the path should be http://www.example.com/supercategory/category/subcategory/apple.php

# Answer
It seems that you're asking more than one question, but let me try and address the paths one. If you organise your taxonomy to be hierarchical then using the token \[catpath-raw\] will give you the path you require.
> 1 votes

---
Tags: taxonomy-terms, path-aliases
---


# Question
Title: Image style settings for scaling an image
What settings can I use for the image style module that will make all thumbnails in a gallery of a consistent width and height? Thus, if an image's width is smaller than the thumbnail width when scaled, the width of the thumbnail remains consistent.

# Answer
> 1 votes
Have you tried the *Scale and crop* option ? Go to `admin/config/media/image-styles/add` add a new style and then select *Scale and crop* with, for example, 100px width and height. This will produce some square thumbnail with 100px sides.

---
Tags: media
---


# Question
Title: Upload a file to Drupal server from (external) desktop client application (in c#)
I have an application written in Winform (dotNet) and I would like it to Upload File to Drupal 7. I'm newbie in Drupal. Can somebody help me please?

# Answer
> 1 votes
You may want to create something with the Services module. The services module gives you an easy way to add REST / XMLRPC services to your drupal site. http://drupal.org/project/services

See also the documentation: http://drupal.org/node/736522

# Answer
> 0 votes
On Drupal 6 you've the built-in module Blog Api that fellows XML-RPC Blogging Standards. For Drupal 7 is now a contributed module that you can find easily here.

# Answer
> 0 votes
I am pretty sure you cannot transfer files using a web service. I had tried it but was not able to do it.

What you have to do is create a simple MENU\_CALLBACK using hook\_menu(). Something like this,

```
function my_module_menu(){
 $items['upload'] = array(
    'title'             => 'Transferfile',
    'description'       => 'Allows client to upload.',
    'access arguments'  => array('access content'),   //or whatever else you want to check
    'access callback'   => 'user_access',
    'page callback'     => 'upload',
    'type'              => MENU_CALLBACK,
   );
  return $items;
 }

function upload(){

//use file_move() api here and take the details about the uploaded file from $_FILES.

}

```

Thats it on server side.

On the client end you will want to hit the menu callback and pass on your file. A simple Html code to simulate the transfer will be following.

```
<html>
<form enctype="multipart/form-data" action="http://mydomain.com/upload" method="POST">
<input type="hidden" name="MAX_FILE_SIZE" />
Choose a file to upload: <input name="uploadedfile" type="file" /><br />
<input type="submit" value="Upload File" />
</form>
</html>

```

You will get the details of the uploded file in the $\_FILES array. the name o fthe key here will be same as the name of your file input element, in our case it will be "uploadedfile".

This should work, give it a try. :)

---
Tags: files
---


# Question
Title: How to strip html comments plus all tags inside it?
Any idea how can I remove this in $vars\['closure'\]; ?

```
<!-- SiteCatalyst code version: H.19.4 Copyright 1997-2009 Omniture, Inc. More info available at http://www.omniture.com -->
<script type="text/javascript" language="JavaScript" src="/sites/all/themes/mytheme/js/s_code.js"></script>
<script type="text/javascript" language="JavaScript"><!--
/************* DO NOT ALTER ANYTHING BELOW THIS LINE ! **************/
var s_code=s.t();if(s_code)document.write(s_code)//--></script>
<script language="JavaScript" type="text/javascript"><!--
if(navigator.appVersion.indexOf('MSIE')>=0)document.write(unescape('%3C')+'\!-'+'-')
//--></script><noscript><a href="http://www.omniture.com" title="Web Analytics"><img src="http://server.122.2O7.net/b/ss/frisky/1/H.19.4--NS/0/4256542"
height="1" width="1" border="0" alt="" /></a></noscript><!--/DO NOT REMOVE/-->
<!-- End SiteCatalyst code version: H.19.4 -->

```

I tried the methods explained by kiamlaluno in this thread but I cant remove the above code in the view source using preg\_replace but no luck.

```
//Remove omniture tags in unpublish node
  if(arg(0) == 'node' && $vars['node']->status == 0) {
    $vars['closure'] = theme('closure');
    $omnitureTags = preg_replace( "/\<!-- SiteCatalyst code version: H\.19\.4 Copyright 1997-2009.+\<!-- End SiteCatalyst code version: H\.19\.4 --\>/si", "", $vars['closure']);
    $vars['closure'] = $omnitureTags;
  } else {
    $vars['closure'] = theme('closure');
  }

```

The above code is now working according to what I need.

# Answer
This is what theme\_closure() does (in theme.inc):

```
function theme_closure($main = 0) {
  $footer = module_invoke_all('footer', $main);
  return implode("\n", $footer) . drupal_get_js('footer');
}

```

which means it's going to ask every module to run its footer hook plus get all the js to be put in the footer and return it:

$variables\['closure'\] = theme('closure');

to populate the closure variable. So.... if you can't preg\_replace() or regex() it out, why not just find what module is putting in there in the first place (seems pretty obvious) and kill it off there?

EDIT/ADDITION: IF it's a bug, fix it here, otherwise if it's just something you want different, preprocess it. But it seems to me that a node status check might be in order in the module's footer hook.
> 1 votes

---
Tags: hooks, theming
---


title: Gallery with jQuery 1.6.4

text:
# Question
Title: Gallery with jQuery 1.6.4
How do I implement a gallery like the following one with jQuery 1.6.4 and Drupal 7?

# Answer
There is more than one way to do it - for instance, it depends on where the images are coming from. You could do it with Views for instance, creating a list of images, adding the correct classes, and applying the js from your custom theme.
> 1 votes

---
Tags: javascript
---


# Question
Title: Rendering view output into a separate region
For the sake of theming, I need to render the output of a view into a separate region. I could create a view block, but this way I lose the ability to pass contextual arguments to it. Any suggestions?

# Answer
> 1 votes
There are a lot of hook for views, you can use hook\_views\_pre\_execute or another one it depends of what you need to do.

See here the list

# Answer
> 1 votes
I've had to do something along these lines recently. Here's what I did:

1. Create your view and add the Contextual argument "Has taxonomy term ID"
2. Under "When the filter value is not available" select Provide Default Value-\> PHP Code
3. Enter the code below:

```
$node = node_load(arg(1));
if($node) {
  $tag = $node->field_primary_tag['und']['0']['tid'];
return $tag;
}
else {
  return;
}

```

On another note - this only works for one taxonomy term, but you should be able to modify the code to fit your needs.

**NOTE\***

I would suggest that nourcy's answer is a more Drupal friendly one, and my answer was only a quick fix to my/your problem - PHP in blocks/views etc is generally a bad idea :-p

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


# Question
Title: Count nodes that referenced current node in VIews
How do I count how many nodes have referenced the current node In Views?

# Answer
In the *Advanced* section of the view's configuration, there is a subsection *Other*. This subsection holds an item *Use aggregation*. Turn this item on. This allows you to configure the *Aggregation settings* for each field in the *Fields* section. One option is to use COUNT.

What remains is to navigate from the current node to the nodes that reference the current node. In Drupal 6, this could be done with the Reverse Node Reference module, which suggests the References module for Drupal 7. I think you have to add a Relationship then add a Node:Nid field that uses this relationship and is aggregated using COUNT.
> 2 votes

---
Tags: 7, views
---


title: Templatization for different countries

text:
# Question
Title: Templatization for different countries
Which is the best module to do a multilingual site for different countries. This is the exact word from client requirement.

"Site created for ABC country can be quickly adapted for country XYZ"

They are mainly looking for reuse of code. Like they create a website for one country and they reuse the same code and same DB fro different county but language will be different.

# Answer
Drupal has user interface localisation out of the box. For user generated content, I18N module will be your friend. This module offers an interface for translation and contains submodules to translate your menus, paths, variables, including your node content. You can even hook-up to IcanLocalize and have your content translated by professional translators.

Be aware, with all this power comes a small cost: there is some tweaking and configuring to do before everything plays nice, first time *can* be painful. I *very* highly recommend you read the documentation before diving in, to have an idea of how the pieces work together.

Good-luck, happy coding!
> 1 votes

# Answer
You can maybe try something like this:

```
function phptemplate_preprocess_node(&$vars, $hook) {
    $language = $vars['language']->language;
    $vars['template_file'] = 'page-'. $language;
}

```
> 1 votes

---
Tags: 7
---


title: How NOT to cache a hook_menu callback

text:
# Question
Title: How NOT to cache a hook_menu callback
I wrote a callback in my hook\_menu() implementation, wich won't work the way it is intended to because of caching. The callback just returns some text depending on a cookie. Something like that:

```
function _show_logoutpage(){
    if($_COOKIE['foo'] == true) {
        return 'foo';
    }
    else {
        return  'bar';
    }
}

```

The code is called after the user is logged out so I would say the user is anonymous. Problem is the the output is cached (since the last menu cache clear) so the logic won't work. Any idea how to fix this in a simple way?

# Answer
> 3 votes
Change return to echo and exit; or disable the page cache.

```
function _show_logoutpage() {
    if ($_COOKIE['foo'] == TRUE) {
        echo 'foo';
        exit;
    }
    else {
        echo 'bar';
        exit;
    }
}

```

OR

```
function _show_logoutpage() {
    global $conf;
    $conf['cache'] = CACHE_DISABLED;
    if ($_COOKIE['foo'] == TRUE) {
        return 'foo';
    }
    else {
        return  'bar';
    }
}

```

# Answer
> 5 votes
`$GLOBALS['conf']['cache'] = FALSE;`

See also module CacheExclude, here are some more details about it:

> This module provides a simple way to exclude certain pages from being cached. Sometimes you want all pages to be cached for anonymous users except for one or two pages that have dynamic or random or rotating content. If those pages are cached, the dynamic parts cease to be dynamic. This module allows an administrator to selectively exclude certain paths from being cached so that dynamic content is actually dynamic.

# Answer
> 1 votes
I don't believe the problem is that menu items are cached. Could it be that the page result of that menu path is cached for anonymous users (thus disregarding the $cookie status for all users except first one to visit the page)?

What version of Drupal are you using? What are you page caching settings?

# Answer
> -2 votes
That could be done using JavaScript (client side on page load), instead of PHP (server side on cache build).

---
Tags: 6, routes, caching
---


# Question
Title: Creating a node type module in Drupal 7.x
I am having some deep trouble getting around creating a node type with Drupal 7.x. My aim is to create a node type that has some form elements within a table grid. Using any of the existing modules is coming across as a challenge because I can't find anything specific to my needs, hence I decided to explore module building and then enabling it as a node.

The tutorial I have is : http://drupal.org/node/231019 (Create new content type for Drupal 6.x) .. .there isn't any exact tutorial available for Drupal 7.x

I have followed every step but am unable to see the content type appear in my node module.

Anybody has pointers to any resources for this?

Thanks

# Answer
Download and look at those wonderful examples
> 2 votes

---
Tags: 7, nodes
---


# Question
Title: How to add custom plugin controls to CkEditor
I have made custom plugin for ckeditor in drupal ckeditor module. The page where I am displaying CKEDITOR is loaded through AJAX and I am doing a replace div to show the CKEDITOR. the code for replaceDiv is:

```
function replaceDiv( div )
{
    if ( editor )
        editor.destroy();

    editor = CKEDITOR.replace( div ,
    {
        toolbar : 'Basic'/*'Basic'*/
    });
}

```

But, the problem is that in this way I am not getting my custom plugin displayed, I tried adding my control name in the toolbar definition in the array but it seems that I am not doing in the right way since it is not working!

# Answer
In `ckeditor.config.js` you need something like this:

```
CKEDITOR.editorConfig = function(config) {
  config.extraPlugins = 'vicheck';
  CKEDITOR.plugins.addExternal('vicheck', '/sites/all/plugins/ckeditor/vicheck/');
  config.toolbar_DrupalBasic = [ [ 'Bold', 'Italic', '-', 'vicheck' ] ];
}

```

where vicheck is a plugin.

This works for me using an old CKEditor module. I don't know if the latest versions have any change.
> 1 votes

---
Tags: ajax, wysiwyg
---


# Question
Title: How to create anchor link to another page
I want to set an anchor link on a page to an anchor on a *different* page. I have been able to do this using CKEditor, specifying the target anchor and then specifying an href for the link in CKEditor to, for example, `/training/classes/#puppy-training`.

This works, but the resulting URL obviously includes the `#`, instead of `/training/classes/puppy-training`. Is there any way to remove the # mark from the URL?

This is using nodes built with custom content types in Drupal 7. I've also noticed the *Links module*, and wonder if it might be of any any help setting up anchors?

I'm also wondering how to approach this if I was using Views.

# Answer
If 'puppy-training' is a section on the '/training/classes' page then there is not a way to remove the '#' symbol. The '#' symbol is a fragment identifier. It is supposed to refer to a location within a resource (i.e., the '/training/classes').

If you would like to have a URL without the '#' symbol, I would recommend creating a separate node for that piece of content.
> 2 votes

---
Tags: navigation
---


# Question
Title: Group of CCK fields assigned to the same NID without an additional Node type and Node referrence
I want to implement a 1 to N relation of a group of CCK fields into the same Node type

Picture this: I have some projects and some expenses per year I have to define each year and it´s total expenses and provide a short description and some images for each year...

I wanto to make it into the same page... not define two types of content to implement a node referrence where I define the years and it´s corespondent description and images

something like this:

I don´t know how can I implement this with Drupal... There is a matrix/array type of CCK field but it doesn´t support the installed CCK it has it´s own stadard types..integer, text etc... so it won´t do ..

Is there any way to obtain this?

the main functionality (ignore the layout ..it can be horizontaly as well)

when I click Add More, ... to add All those fields grouped so I can edit them.... It´s like embeding the other content type into the related NID upon creation of the NID...

Using Drupal 6 and the last CCK available upgrades are not a problem, I can use the latest versions as long they are for D6

---

## re-edit

I have to explain myself better because what I´ve described I see is not very understandable...

Picture the following requirements (based on a relational database concept) I have a content type named Project Expenses (title, description, project status)

Now I want to describe for each year how much I´ve spent for the project and add a gallery of images with the projects achievements for that particular year.

Now, the common thing would be to add another content type with the following CCK fields (year, amount, image (unlimited multiple values) and a node referrence to the project itself )

The problem I have is at data input.. you have to first create the project...save it then add another node for each year and selecting the project in the node reference dropdown doing the relation between the node and the other (1 to N relationship in therms of a database)

So 2 forms instead of one... 2 saves... This is not cool for the user experience, because normal users don´t know the steps or it results too complicated..(this is a simple example but it can get really complicated with having to fill in a lot of nodes if we have more relations)

Ok, so the solution: embed into one form everything..(multiple pages input would be also a solution) but my ideal would be something like in that image that i gave you

define on the same page the other node as well automaticaly making the relation when saving the main node (the project)

I don´t have any ideea how it´s possible (I could find only one module that does that but the values arren´t in fact CCK fields so can´t use them propperly it´s called matrix field )

Show how is the best way to do this?

# Answer
It appears to me you are needing a compound CCK field type.

If so, take a look at http://poplarware.com/articles/cck\_field\_module for a rather in depth discussion of how to write your own.

If you don't want to do that, the 3.0 branch of CCK for Drupal 6 apparently has a Multigroup Module. Check out How to add cck custom date field? for discussions about that option.
> 1 votes

---
Tags: entities, nodes
---


# Question
Title: How can I make a page with only blocks but without node content ?
I simply removed the $content variable from the tpl.php file and placed only some blocks in several regions. Then the blocks are displayed fine but the message "Page not found" appears. So I suppose this is not the right way to achieve this.I know that for example Views and Panel can make pages with paths defined by their own without node content. But can I still have a page which has its own path and with only blocks but no node content without using Views or Panel?

# Answer
You can use the the Empty Page module to allow you to have pages solely for placing blocks.

> The Empty Page module is a simple empty page solution. It provides an interface that assists in managing "empty" menu callbacks, mostly used for pages that only consist of blocks.
> 4 votes

# Answer
You can create a page.tpl.php to handle your page. The documentation at Drupal.org is older but can get you started. There are also a lot of good books that can bring you up to date on writing templates. Remember that the 'print' statements used in tpl.php files have been replaced by 'render' in D7.

The question that interests me is why do you want to do this without using established and flexible modules? If you are looking to modify their results, both views and panels have hooks to allow you to do so.
> 0 votes

# Answer
Empty Page is a good choice, but if it's too simple for your use-case then have a look at Panels \+ CTools \+ Page Manager (sub-module of CTools).

Heavier-weight than Empty Page, but they can do what you need and much more -- handy if you need variants of a page for different user types, themes etc, or you want more control over appearance, caching and other more advanced stuff.
> 0 votes

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


# Question
Title: Create the pdf version of a node programatically (and attaching that pdf version to that node)
I have installed the print module. Every time I create a node of type X a print version can be generated each time I click the print link.

The thing is that I need that pdf to be generated programatically, and not by hand every time I click on the link.

I need (I´ve tried with rules module, without any success) to create the pdf version of that specific nodetype X, and attach that pdf version to the node that is being created.... without me clicking to the print link, downloading the file, editing the node and then attaching that file to it.

Is there a way to do that?

Thanks for your insight!!!

Rosamunda

# Answer
> 0 votes
You can could start by taking a look at the PHP PDF extension and see how that works out for you. If it does, then you can implement a hook\_node\_save() - assuming you are in D7, and every time that a node is saved, call your custom PDF functions to generate the PDF.

After your PHP PDF implementation creates the PDF file, you should use Drupal's File API to place the file in the proper place. You would use the File API because it creates an entry in Drupal's file table, and it automatically handles permissions for you - so you can for example, support both public and private (session-protected) files.

Once you upload the file to your web server with the File API, you can then use the Field API to put a reference to the newly created PDF file in one of your node's custom fields. The node's custom field would be of type "file field", and what you would save to that field programatically is the newly created file's **fid**. The Field API will provide you with the fid.

Finally, you will need to implement a theming function that accepts the node id as a parameter, loads the node in question, looks for the custom field holding the file (using again the Field API), turns the fid inside that custom field into a link with the proper access-level (using the File API), and returns the themed link to your theming layer so it can be printed with the page, and clicked with the users.

In conclusion, unless somebody suggests a contrib module that does this, you would end up implementing at least two Drupal APIs, one external PHP API, and creating some theme hooks. If you are an experienced developer, it should take at least a few hours (or a pair of days).

---
Tags: rules
---


# Question
Title: Tag & vocabulary module or technique that mimics stack exchange tag behavior?
I am looking to recreate the tagging functionality of stack exchange: \- enter tags on a single text input line, with comma separation. \- add new tags to the taxonomy \- increment count of existing tags \- inline suggestion based on initial character entry

Is there a Drupal module or set of tools that provides this functionality?

# Answer
> 1 votes
The Autocomplete Deluxe module is perfect for this. It adds an enhanced autocomplete element, that uses the JQuery UI autocomplete. Although it will not provide the term count, the behaviour is similar to stack exchange in every other way.

# Answer
> 1 votes
Ditto on the Active Tags module. Here is a quote about it (from its project page):

> ... adds a new option to free tagging taxonomies. If selected the taxonomy widget is replaced by a new jQuery enabled tag entry widget. Works with core Taxonomy module and Content Taxonomy module.

# Answer
> 0 votes
chosen is a similar module to checkout, however it's not as powerful as ACD

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


# Question
Title: How to create a module as a wrapper for js
I do a lot of theming but I don't have much in the way of php skills. So when I use or create a cool piece of javascript, I put it into my theme layer. The problem is, 90% of the time it doesn't belong there, and I really can't share what I've done with others.

So, how can I create a module, basically as a wrapper, for js code? I need to know more about that basic custom module structure and also the php used to insert js and css. Bonus would be basic info about creating blocks, content types and views with the module rather than creating them on the site UI.

# Answer
> 3 votes
If you've done work with themes and template.php, writing a module will be a snap. Review Creating Drupal 7.x modules for the basics, but at a minimum you need a *yourmodulename*.info and a *yourmodulename*.module file to get going. Declaring the block specifically will start you off on being able to define your blocks. As for including css and js, use the drupal\_add\_css and drupal\_add\_js functions respectively.

---
Tags: 7, javascript
---


# Question
Title: What are the security trade-offs between Organic Groups and other methods?
I'm in the early stages of implementing a community site that will be made up of many sub-communities/groups. Most content will be shared between all groups (e.g. community-wide announcements and news), but there will be several sections of the site private to each group. For the sake of discussion, let's say that every group has its own private wiki, blog, and address book.

Very generally, there appear to be two options:

The site will be *exactly* the same (theme, menus, layout, etc.) for every group except that each group's private sections (blog, wiki, and address book) contain content accessible only within their group.

Content in the private sections will make up an *extremely* small portion of the overall content, which feels like one site to me. However, as security of a group's private content is my primary concern, I'm leaning towards multiple sites.

What are the main security trade-offs between the available methods and modules?

**Edit:** I am not necessarily using separate domains to accomplish this, but it is an option I'm considering.

# Answer
> 2 votes
It sounds like you are going to need to use Domain Access and set your organic group permissions to fit your use case.

Here are key points to Multisite vs. Domain Access.

Multisite \- One database/prefix per site, possible to share users, tables but requires tweaking. \- Separate install for each but can share modules and themes

Domain access \- Single Database \- shared content, users

---
Tags: 7, organic-groups, multi-sites, domain-access
---


# Question
Title: Is it redundant to use the "boost" module if varnish is used?
We run our Drupal instances behind a Varnish server, but we're looking at alternative/additional ways to speed up the site. Boost is a module that is frequently named for this purpose; it appears to generate static versions of pages and serve those to avoid regeneration time, but—if we're already caching with varnish—does this give us any benefit?

# Answer
No, with the correct configuration, Boost and Varnish can work together. The combination is said to speed up your site even more than just Boost or Varnish (I haven't tried it myself yet).

See Will Boost conflict with Varnish and Use Varnish for cache storage instead of file system. If you're visiting DrupalCon London, check out the Boosted Varnish talk.
> 18 votes

# Answer
Although the other answers are technically correct, I would agree with @mikeytown2 in stating that all you are doing by running boost together with varnish is adding (unnecessary) complexity to the caching on the site.

We used to run boost and varnish together on http://www.health.govt.nz/ but because varnish would cache the HTML pages that boost was making, all that boost ultimately added was additional files on the disk (certainly no extra performance).

Also there are benefits to running varnish standalone:

* Integration with expire and purge modules - this means you can wirte rules for intelligent flushing of content from varnish based on certain rules. E.g. when a new piece of content of type 'announcement' is published, purge both the node published and the frontpage from varnish
* Varnish is faster that boost - as varnish can be configured to store its cache in memory, it is inherently faster than a file system based solution (such as boost). This was especially apparent as we normally run boost over NFS (web cluster)
* When there is caching problems, they are easier to track down - we often found using boost together with varnish, that when varnish would miss, it would then serve an ultimately stale version from boost. This can be frustrating for your content authors
> 6 votes

# Answer
If you already have an effective Varnish cache in place, the only additional performance gain Boost could give you is making pages cacheable.

Instead of having Drupal generate static pages, though, I'd rather make the effort of migrating to Pressflow Drupal, Cocomore Drupal or Drupal 7. Unlike vanilla Drupal 6, those distributions send HTTP responses that enable Varnish to cache not only static assets like images and CSS but also complete rendered pages.

We're achieving decent performance gains and heavily reduced web server load by making use of page caching with Varnish.
> 1 votes

---
Tags: performance, caching, proxies
---


# Question
Title: Drupal says "e-mail sent" but I don't receive
I have installed my webserver from a computer at home. On Ubuntu Server, LAMP, everything works fine except email sending.

First I was getting:

> Unable to send email

then I followed these directions.

Then I still got same error. I checked Apache logs and I found

```
sendmail: fatal: file /etc/postfix/main.cf: parameter myhostname: bad parameter value: myservername.{null}

```

I changed the file and wrote my website domain like domain.com

At last, Drupal says "Email sent" but I receive no email. What is the problem?

# Answer
Have you used a devel php input to do a sendmail test? there is a question already answered here. How to programmatically send an email?

Also here is a great article on debugging emails... http://www.drupalcoder.com/blog/how-to-debug-outgoing-mails-in-drupal
> 2 votes

---
Tags: 7, emails
---


title: Node reference URL in Drupal 7

text:
# Question
Title: Node reference URL in Drupal 7
How can I make a node reference URL visible only to the person who created the page/article?

# Answer
You can do it by setting the appropriate permissions. For Drupal 6, content\_permissions is part of CCK, and lets you set permission for every CCK field of your content type. For Drupal 7 you can use the Field Permission module.
> 3 votes

# Answer
Gosh, I just looked at this and assumed you are talking about Views. I don't know why.
In any case, this may or may not make any sense.

You will obviously have to put some PHP around it that checks if `$node->uid == $user->uid` and output the field only if true.

In Drupal 6, I'd do that in the Views template that formats that field. I find that information out by looking at what templates Views uses for the view from the Styles Settings/Theme Information links.

Drupal 7 does all sort of things differently, but the Views Module there does have similar templates; whether or not this is best practice, there or not I am not one to say, but this should set you on one path of how to do it.

**EDIT:** If this is just a field in a node you want formatted differently, look at system module field/theme/field.tpl.php and do the above in there (copying it of course).
> 1 votes

---
Tags: nodes
---


# Question
Title: What is the equivalent of hook_user with $op='form' in Drupal 7
What is the equivalent of `hook_user` with `$op = 'form'` in Drupal 7?
According to the documentation of `hook_user`, `'form'` means:

> form: The user account edit form is about to be displayed. The module should present the form elements it wishes to inject into the form.

But I couldn't find any equivalent hook in Drupal 7 `user.api.php`.
Thanks

# Answer
> 5 votes
hook\_form\_user\_profile\_form\_alter(&$form, &$form\_state) I think its what you need

---
Tags: 7, hooks, users
---


title: Panels or Context module?

text:
# Question
Title: Panels or Context module?
Can I please get some input on the differences between the two?

I'm building a website where using 'context' is very important. After watching this video series about Page Manager by NodeOne, I feel that Panels 'context' and its ability to securely pass arguments to Views is very important. However, the Context module has a plugin that does a similar type of function called the View Default Argument From Context module.

# Answer
> 8 votes
I prefer **Context** module in most cases. I find it simpler and less heavy-handed than Panels, which takes over entire pages. A good use case for **Panels** is when site admins will be rearranging landing pages themselves or for sites with a lot of unique layouts.
I pick between Panels and Context for a given site when evaluating wireframes or designs. In some cases it makes sense to use both.

I can usually handle the Views arguments I need within Views itself (often by setting the default argument) and don't need the Panels side to do it.

# Answer
> 4 votes
**My opinion**

Paired with the delta module there isn't really a need for panels.

The User interface for panels is overly bloated (imho).

I've outlined the pros and con's; a lot of the ideas are taken from the lullabot slideshare . I've added my own ideas in there as well:

# Case for using Both Panels and Context

* Exportable
* Faster then creating separate layouts
* More Granularity
* No more dependencies on Drupal's Core Block System

# Panels

**Pros**

* Drag and drop interface
* More powerful than blocks
* Built in cacheing mechanism
* (As you said) passing arguments from views
* Integrates well modifying output from: views, blocks, nodes, menu module
* Provides an interface to create different layouts easily

**Cons**

* Slight Learning Curve
* Extraneous markup produced by panels output
* A lot of overhead in creating a layout.

# Context

**Pros**

* Delta module allows any theme to be modified dependent on any reaction and trigger different layouts
* Flexibility to join multiple complex contexts (negative url matching)
* Eventually will integrates with rules

**Cons**

* Not ideal for client friendly / low-level ui; requires developer knowledge

Resources:

# Answer
> 0 votes
I think the Context ability to change theme layouts 'on-the-fly' certainly overrides any preference for using the Panels custom layouts. I find it exceptionally useful with grid-based themes such as Fusion where you can alter fixed width columns without complicated CSS changes.

---
Tags: views, panels, 7
---


# Question
Title: hook_apachesolr_process_results having no impact on results
I've posted this at d.o, but I'm hoping maybe someone here might be able to help. (The documentation on apachesolr for D7 is so far rather depressing.)

I wrote a module for a D6 site implementing hook\_apachesolr\_process\_results to modify the snippets of text shown on the search results page. That worked like a charm. We've now moved on the D7. I've again written a module to implement the same hook. This is a lowest-comment-denominator version of the function:

```
function mysearch_apachesolr_process_results(&$results, $query){
  foreach($results as $id => $result){
    $results[$id]['snippet'] = "FOOBAR";
  }
  debug_to_file($results);
}

```

The call at the end debug\_to\_file is a utility function I use to print\_r a variable to a file. That call proves that a) my code *IS* indeed getting run and b) that the $results variable has been changed internally. However, my search results page has nary a `FOOBAR` to be found!

Could it possibly be an interaction between apachesolr and another module? Apachesolr and my theme (fusion 7.x-1.x-dev)?

It'd even be helpful here to get an indication of what to try next as far as debugging. Any advice would be useful!

FTR, I'm using Drupal 7 with the ApacheSolr Search and Framework modules at version 7.x-1.0-beta12.

# Answer
> 1 votes
Grr. Someone outside of StackExchange suggested a few routes of debugging that would weed out issues having to do with interaction of my code with other code. One of those suggestions was to go back to a default theme and see if my change showed there. It did. I talked to my themer to see if he had any insight.

And, that's when we hit the "a-ha" moment: We were using a custom theme based off of Fusion. (Incidentally, when I switched to stock Fusion, everything worked correctly.) At that point, it was just a matter of flipping through all of the "Appearance" settings to find that under search results none of the checkboxes were ticked. Guess what happened when I ticked the "snippet" checkbox?? Yeah....

Though, we did learn something good here, at least: If you create a new theme as a custom sub-theme of an existing theme, your subtheme does **not** inherit the settings of its parent theme.

# Answer
> 0 votes
Maybe you want to implement `hook_preprocess_search_results()`. As for the individual search results themselves, you will be able to use `hook_preprocess_search_result()`. You use the former when you want to modify the block that contains the search results. The later is used when you want to modify each individual result. I rely on them both for my Solr theming in D7.

---
Tags: 7, search
---


title: Form preview before submission

text:
# Question
Title: Form preview before submission
I have written a form using the form API, and I want the user to preview the form before submission. How can this be accomplished?

# Answer
Effectively this is a multistep form. Display the form showing a "Preview" button. On submit save something to the session or $form\_state and redisplay the form. If the value has been set in the session show a "Submit" button. On this submit you can save the form values to the database and clear whatever flag value you had in the database.
> 1 votes

---
Tags: forms
---


title: Panel Pages and Taxonomy Term Arguments

text:
# Question
Title: Panel Pages and Taxonomy Term Arguments
I am working on a new Drupal 7 site that is making heavy use of Panels to build pages.

I have a page where a view will be added to a content pane. For various reasons, the view cannot be its own page. This particular view has a Contextual Filter on it, Content: Has taxonomy term ID. View works great with numeric arguments.

I would like my panel page to use the term name as the argument for the view instead of the term ID. And, for various reason, I cannot use the `taxonomy/term/%taxonomy_term` override that comes with Panels.

If I set up the context option for the page (Settings / Arguments) to use Term Name, I can get the argument to work. My problem is that the vocabulary I need to use has terms with lots of capitalization and spaces in it. So, the URLs end up unreadable.

We have a custom ctools arguments plugin that can handle pathauto-style term names, where the term is lowercased and spaces are converted to dashes, but it was done for Drupal 6. Before I spend the time to rework it for Drupal 7, I wanted to see if there is a better and/or existing solution.

In summary,

1. I have a panel page with path `foo/!term`
2. Panel page has a view with a taxonomy term ID argument, where the view argument should be based on the URL
3. I would like to have URLs like `foo/apple-beet-carrot` instead of `foo/Apple%20Beet%20Carrot`
4. I cannot use the system override for `taxonomy/term/%taxonomy_term`

What is the best way to go about this with Drupal 7, Views 3, ctools, and Panels, short of making a new ctools argument plugin?

# Answer
There may be better routes out there, but I am going to suggest the one I have in mind right now.

*You could create your own custom block - that wraps around the Views block display that you already created*. Why? Because that way you have full control of the arguments.

**Wrapping a Views block display with your own custom block:**

1. Implement hook\_block\_info() and hook\_block\_view().
2. Inside your hook\_block\_view() call the View display programatically. The View display should be a block (it looks like you got it already configured).
3. While instantiating the View display, you can grab the arguments from the URL using the arg() function. Since this is your own code, you can do anything that you want with those arguments. For example, you could load a term using an nid-based argument, get the term's proper name, URL-decode it if needed, and then feed it to your display.
4. Execute the View display, retrieve the results, and return them as the output of your block.

Then instead of embedding in the panel the block that was provided by your View, you embed the one that you created in your custom module. Again, since you called the View programatically, you had full control of the arguments that were passed to it.

It sounds complex, but it's really easier than you think. Here's a plain example of how to call the View (you could modify it for your needs):

```
$view = views_get_view('my_foobar_view');
$result = $view->execute_display('block_display_baz');
$term_id = arg(2); // Get the term from my-panel/foo/<term id>
$view->set_arguments(array($term_id));
$view->execute();
if(!empty($view->result)) {
  foreach($view->result as $result) {
    // Do something with $result...
  }
}

```

This G.D.O. document can provide you with more examples on how to programatically embed Views.
> 2 votes

# Answer
The hook\_menu() keys for those panels are arbitrary (defined by you), so I can't post a 100% exact example, but here's one general solution of how to "hack" or intercept an existing hook\_menu() item:

1. Go to the menu\_router table.
2. Search for the URL path that you defined for your panel. You can start by using an exact-match search, and if nothing appears, do a wildcard (%) search such as this: `select * from menu_router where path like "%bar%"` instead of \`...path = "foo/bar/baz". This will tell you everything about that menu item, what module defined it, what function it calls, what are it's arguments, and what loading function for the arguments (if any) there are.
3. Armed with this information, you can go to the module that defined the menu item. Go to the hook\_menu implementation of that module and look for that key. Take a note of the different keys that compose the menu item. Sometimes it is overkill to define your own menu item when all you need is to change is, let's say, the title callback. For this we then use the hook\_menu\_alter().
4. Implement hook\_menu\_alter in your custom module.

Example for item # 4.

```
/**
 * Implementation of hook_menu_alter.
 *
 * Intercept 'foo/bar/baz' and 'taxonomy/term/%taxonomy_term'.
 */
function mymodule_menu_alter(&$items) {
    // The string to the right is the name of the function that is going to get called
    // to determine that page's title. We just substituted what defined there by
    // someone else with our own function.
    $items['foo/bar/baz']['title callback'] = 'mymodule_panel_title_callback';

    // Here I modify a separate menu item.
    // Redirect current page workflow to my module.
    // Note that the function taxonomy_term_load() will be called with whatever argument is in the
    // third element of the path, so "taxonomy/term/123" will call taxonomy_term_load(123) and the
    // result will be passed to mymodule_taxonomy_term_page().
    $items['taxonomy/term/%taxonomy_term']['page callback'] = 'mymodule_taxonomy_term_page';
    // I'm doing this to state the "obvious" - that taxonomy_term_load() will be passed 123 in "taxonomy/term/123".
    // Also to say that there's not much you can do to to modify this particular menu item attribute.
    // Since %taxonomy_term is part of the menu item key, if you modify that to be something else, such as
    // %mymodule_taxonomy_term, you would be basically defining a new menu item (If I'm not mistaken).
    // If you find yourself in the position that you need to modify the "auto-loader wildcard component", then
    // that might be your cue to define your own menu item, and then call back 'taxonomy/term/%taxonomy_term'
    // from your own callback.
    $items['taxonomy/term/%taxonomy_term']['page arguments'] = array(2);

}

```

Now to make things more complex, let's say that as part of your problem, you do need to modify the "auto-loader wildcard component" for `'taxonomy/term/%taxonomy_term'`, and that this menu item is defined by Drupal core taxonomy. Like I stated in my comments above, toying with that on your hook\_menu\_alter() could possible mess up your menu definitions.

So we are left with two options. Define your own menu item and 1) Call back the menu item defined by Core from your own menu item or 2) Just copy the code that is in the body of the function called by the original menu item to your custom function. If doing #2 and you get an error make your you include the file where the core function rests my using module\_load\_include(). *Note that I used core as an example, but the technique could be applied as well to contrib modules.*

```
/**
 * Implementation of hook_menu().
 */
function mymodule_menu() {
  $items = array();
  // Defining an arbitrary path, change it to what makes logic for you.
  // Using a simple wildcard.
  $items['mymodule/term/%']  = array(
    'page callback' => 'mymodule_taxonomy_term_page',
    // Define other arguments, skipping for the sake of brevity.
  );
  // This menu item will call function mymodule_taxonomy_term_load(), and pass
  // the results of that call to mymodule_taxonomy_term_page.
  // Note that the path I define here conflicts with the path above, and that you should use either or, but not both.
  // Else menu router will get confused and will not know which one to call. The same applies to paths created by
  // core or contrib, it is important not to define them twice.
  $items['mymodule/term/%mymodule_taxonomy_term']  = array(
    'page callback' => 'mymodule_taxonomy_term_page',
    // Stating that mymodule_taxonomy_term_load() will be passed the 3rd argument in the path (count is zero-based).
    'page arguments' => array(2),
    // Define other arguments, skipping for the sake of brevity.
  );

  return $items;
}

// Meantime, in another part of your module...
/**
 * Returns a taxonomy term object based.
 */
function mymodule_taxonomy_term_load($term) {
  // Here you could do all the custom logic you want. Depending on what you put here, you might be
  // able to even support numeric term ids and non-numeric term names in the same path. Example:

  if(is_numeric($term)) {
    $term_object = mymodule_taxonomy_term_load($term);
  } else {
    // String detected.
    // Do some cleanup first, and then try to load a taxonomy term with the cleaned string.
    $clean_term_string = somecleanup_function($term);
    $term_object = taxonomy_get_term_by_name($clean_term_string);
  }

  if($term_object) {
    // Profit!
    return $term_object;
  } else {
    // Return something we can reliably validate against in our callback...
    return FALSE;
  }
}

// And then in your hook_menu() callback...

/**
 * Render a page based on term?
 *
 * @param var $term - A term object if mymodule_taxonomy_term_load() was successfull, else FALSE.
 */
function mymodule_taxonomy_term_page($term) {
  if($term === FALSE) {
    // Degrade gracefully, e.g., show a custom error page...
  } else {
    // If our example `'taxonomy/term/%taxonomy_term'` is defined by Core, and we did not implement hook_menu_alter() for it,
    // call whatever function that callback defines. Note that we accomplished our mission here by loading $term the
    // way we wanted to in the auto-loader function, so we don't really need much processing here, but we could do more if needed.
    return somefunction_defined_bycore($term);

    // Else the other option was to copy and paste somefunction_defined_bycore()'s function body into here and return it.
    // Do some processing...
    return $something;
  }
}

```
> 1 votes

# Answer
An alternate to the block based solution that I accepted is to create a custom ctools content type. This is rather sparsely documented outside the help in the module, but there is an example module that ships with ctools (normally in the `ctools/ctools_plugin_example` directory) and there is another sample is can be found here.

Essentially, this is same method that views (and other modules) use to makes themselves available to use as content for panel panes.

The advantage over blocks is that you can set them up to use a ctools context for passing in arguments (which is a weakness of blocks). We have use these with good success on many projects. Using ctools contexts, instead of directly accessing arg, menu\_get\_object, or some other method, provides a nice abstraction later to isolate the content from how it got integrated into the site.

However, in this particular case, using panel contexts is also the weakness. The proper method would be to create a ctools content plugin to translate the "pretty" term from the URL to a term ID that the content type would use. You can configure the panel content to pass in a URL argument, but the panel content type would need do the parsing/conversion, which isn't a good practice (can be seen to violate SOLID). If you create a context plugin, it would be able to be used directly with using a view as panel content.
> 0 votes

---
Tags: 7, taxonomy-terms, panels, chaos-tool-suite
---


title: comment count statistic

text:
# Question
Title: comment count statistic
Hi I'm Drupal beginner.

I'm trying to make a view which shows most commented content today, this week, this month, total in Drupal 6.

I only found the total comment count field.

Please help me.

# Answer
I believe that the total comments is the right field. You'll have to make different views to show all content from today, this week, this month....THEN sort the view by most comments (so that the highest is first), then restrict your view to show 1 item, and VOILA! (should work)
> 1 votes

---
Tags: views, 6, comments
---


# Question
Title: table content_type_answer show to merge it with node table
I have a `{content_type_answers}` and this table doesn't has a title row, how can i merge it with `{node}` to get node titles?

```
$result = db_query("SELECT {node}.title, {node}.nid FROM {content_type_answers} cta, node WHERE {cta}.nid = {node}.nid");
while($node = db_fetch_object($result) {
    $nodes[] = array($node->title, $node->nid);
}

```

Question: how can i select {node}.title from table {content\_type\_answers} if in this table no title row at all?

# Answer
> 1 votes
```
    $q = db_query("
SELECT node.title, node.nid
FROM content_type_answers cta, node
WHERE cta.nid = node.nid");
    while ($r = db_fetch_array($q)) {
      $rows[] = $r;
    }
    print theme('table', $header, $rows);

```

---
Tags: database
---


# Question
Title: Why does my drupal 7 redirect me to the home page from any link?
I have just enabled clean URLs via admin panel, but now...

it doesn't matter what I click, all my urls redirect me to my home page.

you can try for yourselves by clicking any of the links: http://www.gelpalhano.org/drupal/

and none of the admin links work either, so I can't even disable clean URLs to make sure that is the problem. logout also does not work.

any light you can shed on this will be much appreciated.

# Answer
> 4 votes
It looks like you redirected the default user login page to somwhere else.

When I go to http://www.gelpalhano.org/?q=user, I get a HTTP 302 moved temp, followed by a 301 moved perm, followed by a 200 OK to http://www.gelpalhano.org/site/ (what appears to be your homepage).

Generally clean-urls would fail because your .htaccess if not configured properly, or because your web server is not configured properly. I saw your web host's headers say that the server is of type Microsoft, so I would not be able to suggest a fix for your particular setup (I only use the LAMP stack).

I can suggest however that to regain back access to your site, you substitute `www.gelpalhano.org/?q=user` for `www.gelpalhano.org/?q=[the relative path to your user login page]`, and then once you've logged in, you can go to `www.gelpalhano.org/?q=[the path where you turn on/off clean urls]` and turn them off while you trouble shoot the issue. IMHO, this is a server setup issue, and I think you have more chances of having your issue resolved by researching and posting the same question at serverfault.com. Good luck and hope that my answer helps.

# Answer
> 0 votes
I had this issue once, I copied a site from my testing environment (with clean urls enabled) to a testing environment (without clean urls). Clean urls shows as being ON in drupal settings even though the server wasn't supporting it at the time.

So I navigated to www.example.com/q?=admin/settings/clean-urls and turned it off. All my links (though unclean) began to work.

---
Tags: uri, redirection
---


# Question
Title: What would be the Drupal way to have a preloader overlay divs untill they were finished loading?
I am trying to get a theme to have a pre-loader image run over each section of the theme until the corresponding div section is finished loading.

I am trying to refrain from a $(window).load(function()); if i can.

What would be the best approach? Thanks in advance.

# Answer
> 2 votes
Maybe it can help: queryloader2

---
Tags: 7, theming, javascript
---


title: problem in website viewing

text:
# Question
Title: problem in website viewing
> Fatal error: Call to undefined function omega\_theme() in /home/itcom/public\_html/sites/all/themes/libra/template.php on line 27

Whenever I browse my site, I get this message, and I am not able to login to the site. Clean URLs are not enabled in this site.

I would like to know how I can change the default current theme from code, and any other solution to rectify this problem.

# Answer
The Libra theme is a sub-theme of the Omega theme, but seemingly the Omega theme is not present (otherwise, omega\_theme() would be defined). Make sure that you have placed the Omega theme in /home/itcom/public\_html/sites/all/themes/omega and try again.
> 1 votes

# Answer
I guess somewhere in your template.php file in your enabled theme you're making a call to omega\_theme() function. If your theme is a subtheme of omega, you should let drupal know about that by putting this **base theme = omega** in your **.info** file in your theme folder. Also, **omega theme** should be present in your drupal themes folder.
> 0 votes

# Answer
Can you confirm that you uploaded the Omega theme properly. The first time I used Omega, I took the "Omega" directory only from the parent "Omega" folder and had similar issues but you need the entire folder that has "starterkits", "alpha" etc... See my screen capture to confirm your directory structure is correct.
> 0 votes

---
Tags: theming
---


# Question
Title: How can I get a block to display only on node view in Drupal 6
I have a block that I need displayed only on the main page of a node.

I can get it to display on `node/1/view` by putting `node/*/view` in the conditions, but that only works if view is in the URL. I want it to show whether I go to `node/1/view` or `node/1`, but NOTHING else. If I try `node/*` it shows it for every node page, not just `node/1`. I also tried `node/*/` but that didn't work at all as it appears the ending slash is being removed.

# Answer
> 2 votes
In the visibility textarea of your block, select PHP code and put the following:

```
<?php
if (arg(0) == 'node' && is_numeric(arg(1)) && (arg(2) == '' || arg(2) == 'view')) {
  return TRUE;
} else {
  return FALSE;
}
?>

```

# Answer
> 0 votes
If you really want you can simply add `node/1` *and* `node/1/view` to the visibility list. However this is not the Drupal way imho - Drupal expects that default local tasks aren't explicitly specified in the URL (and this is why for example it outputs node URLs as `node/1` and not `node/1/view` in the first place). Path based rules like this can make a system more brittle - and doing it in a way that doesn't fit in with existing Drupal behaviour is asking for trouble imho. What is it you're trying to do?

---
Tags: nodes
---


title: Media module and views

text:
# Question
Title: Media module and views
I am using Media module on a Drupal 7 installation and have created a content type called Media. I then used the Multimedia asset of the Media module, so users can upload both images and videos.

I now want to create a view with the latest videos and also latest photos, but there is not anything on the filter to select a video (or photo). How can I add such a filter?

# Answer
Try this:

* Create a new taxonomy vocabulary called 'Media Type' with terms 'Image' and 'Video.'
* Add a taxonomy field to your Media content type.
* Add a taxonomy field to your view (hidden/exposed/however you'd like)

You'll then be able to filter by the value of the taxonomy field.
> 1 votes

---
Tags: media
---


# Question
Title: How to get the nearest place from database
i am using drupal 6 gmap and location module to save the users latitude and longitude in database. I need to create a service in which i am returned the places list in the order of nearest first. I have all the rest of the code ready and would be all set to go if you guys could share the SQL

# Answer
> 1 votes
You have to play around location views. Add a filter and argument to sort by proximity.

# Answer
> 1 votes
The location module has a function called `earth_distance_sql()` that will generate the needed trig functions for an SQL distance query.

# Answer
> 0 votes
Here is some SQL I use to achieve something like this:

```
$sql = "SELECT zip_code, lat, lon, SQRT( POW( 69.1 * ( lat - " . $this->session->userdata['latitude'] . " ) , 2 ) + POW( 69.1 * ( " . $this->session->userdata['longitude'] . " - lon ) * COS( lat / 57.3 ) , 2 ) ) AS distance FROM zip_code ORDER BY distance ASC LIMIT 1";

```

This is hitting a table with rows like:

```
zip_code | lat  | lon
12345    | 40.2 | -92

```

So you would need to amend for your table.

---
Tags: database, google-maps, location
---


# Question
Title: how to see which user has assigned a content_profile content type?
I´m using the module http://drupal.org/project/content\_profile for drupal 6

I want to make a view where I show all the users and a link to their content profile, or even display some views from their profile..

Can´t seem to be able to do that, I don´t know where to pick the relation between the users and the content type

Currently my view is of the Usuer type..not Node.. I can handle PHP with customfield if I have to..don´t know where to start

# Answer
> 1 votes
According to the code of the content profile module (I didn't test this) you can use views relations between profile nodes (ordinary cck node types) and users.

I'm not sure whether you have to base your view on the cck node type for the profile or users. But with one of these you should get an option to add the other side as a relation and then use fields of the user and the profile in the same view.

# Answer
> -1 votes
In your view, in fields add User: Name

Tick "Output this field as a link" and set `users/[name]` in the "Link path" field

---
Tags: views
---


# Question
Title: Drupal commerce - same product with different formats that determine price and get added to line item titles
I have a taxonomy term select list where the administrator can add one or more formats to a product entity. The term itself has a price coefficient field that should be used to determine the price of the product in that format. On the product display page there should be a 'add to cart' button for every format of that product. The title of the product in the cart/order views should display the format and the price should be according to what was calculated using the product base price and the format coefficient.

Any generic ideas how I could implement this with the Drupal Commerce module or good alternatives that accomplish the same thing? It could be assumed that every product display has only one product entity associated with it if this makes things easier.

# Answer
> 3 votes
Googletorp's suggestion seemed like it won't give me quite the result I needed so I tried to do the whole thing with my own add-to-cart form, line item/order creation and so on, but ended up with a lot of issues and work that made me go back and try the suggested approach. Got exactly what I needed much easier in the end. Posting the entire solution here to save possible trouble for others.

First I added a format field (that referenced the same taxonomy terms as the one attached to the product) for the used line item. Set it up so it would be included in the Add to Cart forms. After that I added the pricing rule via the GUI:

* Events - Calculating the sell price of a product.
* Conditions - Entity has field (line item format field).
* Actions - Multiply the unit price by some amount (amount specified in the terms coefficient field).

To modify line item titles to show the selected format I found help here: http://digibits.org/blog/drupal-commerce-dynamic-line-item-titles. The code:

```
function mymodule_commerce_line_item_type_info_alter(&$line_items) {
  $line_items['product']['callbacks']['title'] = 'mymodule_line_item_title';
}

function mymodule_line_item_title($line_item) {
  $term = taxonomy_term_load($line_item->field_line_item_format[LANGUAGE_NONE][0]['tid']);

  return t('!product (!title)', array(
    '!product' => commerce_product_line_item_title($line_item),
    '!title' => $term->name,
  ));
}

```

Now I needed to restrict the format selection for customers depending of what the administrator has chosen for the product and display them all as add-to-cart buttons not a select list. This was doable via hook\_form\_alter():

```
function mymodule_form_alter(&$form, &$form_state, $form_id) {
  // Alter add to cart forms.
  if (strpos($form_id, 'commerce_cart_add_to_cart_form_') === 0) {
    // If the product is available for sale.
    if ($form['submit']['#value'] == t('Add to cart')) {
      // The form should only be for a single product so we can get the id from the product_id field.
      $product_id = $form['product_id']['#value'];
      $product = commerce_product_load($product_id);
      // The original submit button isn't needed.
      unset($form['submit']);

      $i = 1;
      // Create a submit button and additional markup for every given format.
      foreach ($product->field_format_types[LANGUAGE_NONE] as $format) {
        // #name will be used to determine the selected product format instead of the select list value.
        $form['submit_'.$i] = array(
          '#type' => 'submit',
          '#value' => t('Add to cart'),
          '#name' => $format['tid'],
        );
        $i++;
      }

      // This form submit handler needs to be called before any others.
      array_unshift($form['#submit'], 'mymodule_add_to_cart_form_submit');
    }
  }
}

function mymodule_add_to_cart_form_submit($form, &$form_state) {
  //drupal_set_message('<pre>'.var_export($form_state['triggering_element'], TRUE).'</pre>');

  // Get the clicked submit button name.
  $name = $form_state['triggering_element']['#name'];
  // Use the clicked submit button name to set the correct product format.
  $form_state['values']['line_item_fields']['field_line_item_format'][LANGUAGE_NONE][0]['tid'] = $name;
}

```

In the end I hid the select list via css and that was it.

# Answer
> 2 votes
The product reference field handles the add to cart functionality with the ability to select product etc. out of the box.

For the custom pricing, you should be able to handle that by setting up a custom rule that alters the price based on the term selected. It might require a few tricks to make all the variables available, but with the heavy integration Commerce has with Rules, and the special calculate sell price event, this shouldn't be possible to setup via the GUI.

---
Tags: 7, commerce
---


title: How to catch the "Login Failed" event?

text:
# Question
Title: How to catch the "Login Failed" event?
I want to show a custom block, only when log in has failed. So from visibility settings I have to put a PHP code that returns TRUE only when the login has failed.

But how could I "catch" that event? Do I have to use variable\_get(..)? And if yes, how could I use that?with what attributes?

Thank you.

# Answer
> 2 votes
You can use the rules module for this if you don't want to write PHP.

If you want it to be an ajax event you will need to write a custom login form.

The user.module has a set of functions you can call for validation: `user_login_final_validate()`.

I suggest rules module, save yourself some time.

# Answer
> 1 votes
You should have a look at `user_login_final_validate()`. Using this validate function you could set a variable that you then can check with php to show your custom block.

I guess you will have to add your own validation routine for the login form.

This link may point you in the right direction: Adding Secondary Validation to Drupal’s User Login.

# Answer
> 1 votes
Have a look at user\_login\_default\_validators(). You can add your own function to the series of validation functions. If you add your function at the end of the list you can check the values and do whatever processing your block requires.

---
Tags: users
---


# Question
Title: Migrating Contacts from Joomla to Drupal
The Joomla module in Drupal does a good job on migrating content and users, but it doesn't have functionality to pull the contacts from Joomla.

Has anyone successfully migrated contacts from Joomla to Drupal? What methods are there of accomplishing this?

I started to manually move the contacts... but there are about 100 of them =/. I started by creating a new content type with the fields for the contact, and am using the Views module to create a table for the contacts.

# Answer
Used phpmyadmin to dump the data from the table containing the content I needed, and put it into a CSV file. Then I used Drupal's Feeds module to import the CSV into the content type that I created.

Worked beautifully.
> 3 votes

---
Tags: nodes, migrations
---


# Question
Title: How can I get a block to display only on node view in Drupal 6
I have a block that I need displayed only on the main page of a node.

I can get it to display on node/1/view by putting node/*/view in the conditions, but that only works if view is in the URL. I want it to show whether I go to node/1/view or node/1, but NOTHING else. If I try node/* it shows it for every node page, not just node/1. I also tried node/\*/ but that didn't work at all as it appears the ending slash is being removed.

# Answer
In that case you need to to have `node/*/view` and `node/*` on separate lines.

Unless the node that users are customizing are a specific node type, then you should use the php code to check for a certain node type, regardless of node id or url.
> 1 votes

# Answer
You could use the PHP method and do something like this:

```
<?php

$path=$_GET['q'];
$elements=explode('/',$path);
$count=count($elements);

if (($count==2 && $element[0]=='node' && is_numeric($elements[1]) ||
    ($count==3 && $element[0]=='node' && is_numeric($elements[1] && $element[2]=='view')) {
    return TRUE;
}

return FALSE;

?>

```

If you put this in the "Show block on specific pages/ Show if the following PHP code returns TRUE (PHP-mode, experts only)" part of the block admin page, you should be all set (barring any horrible typos or brainfades on my part :)
> 1 votes

# Answer
I don't know if I've missed the point but you can enter multiple values in that field, one per line. So have `node/1` and `node/1/view` on separate lines.
> 0 votes

---
Tags: 6, nodes
---


# Question
Title: How do I get the fields of a user object
I want to know all the fields of the object returned by `user_load()`.

I can analyze it while the site is running with `var_dump()`, but I want to see the fields without running Drupal, say by opening any (.module) files.

In general, how can I see the object fields of standard objects?

# Answer
The full answer is: There's no single piece of code which can answer your question. Since PHP has weak and dynamic typing, any piece of code can access the global $user object and can remove/add something to the the object (whether this is always a good idea is an other question).

As a Java (which statically and strong typed) veteran this was the biggest difference to cope with.

BTW: Use dpm which comes with krumo support instead of var\_dump this makes the output much more readable. An other aproach is to get familiar with a debugger (Xdebug or Zend).
> 4 votes

# Answer
Take a look in your "users" table; the function returns all the columns of that table.
> 2 votes

---
Tags: 6
---


title: How to get Location as Tokens?

text:
# Question
Title: How to get Location as Tokens?
I would like to use a node location values (for example location:country-name) as tokens. Is it possible to use something like \[node:location:country-name\] ?

# Answer
> 1 votes
I think I found a solution for this is a patch to the Location module here.

---
Tags: 7, tokens, location
---