# Question
Title: split/divide main content region to columns or create another custom layout
I am building a theme and I want my main content region to be divided in 3 fixed columns. I have produced all my .css code and I just want to dynamically produce the markup (3 columns) and attach my styles to them. I know 'use panels or display suite' is the easy answer but I haven't till found a way to use them effectively.

Ideally I would have regions: content-left, content-center, content-right and when I create content I can choose where to place it. this `<?php print render($page['content']); ?>` needs some tweaking! Anyone?

# Answer
> 1 votes
After hours of searching, I was lucky (and persisent enough!) to come across this: http://www.youtube.com/watch?v=gmX2jnH9Kdg which describes how to achieve what I am after using panels indeed. I feel covered by that excellent video. I can leave my Q up for anyone frustrated as to how to translate his/her layout to dynamic drupal code

---
Tags: theming
---


# Question
Title: Change frontpage pagination to use a more/previous style
The standard pagination on my site looks like this:

I'd like to alter the config (or install a module, etc) that will help me use this simpler type of pagination:

How can I reconfigure my site to use this kind of pagination? Do you know of a module that will let me choose this style?

# Answer
You just need to use theme\_pager()

Place this function in your template.php file and clear theme registry:

```
/**
 * Implementation of HOOK_pager().
 * $variables: An associative array containing:
 *  tags: An array of labels for the controls in the pager.
 *  element: An optional integer to distinguish between multiple pagers on one page.
 *  parameters: An associative array of query string parameters to append to the pager links.
 *  quantity: The number of pages in the list.
 */
function YOURTHEME_pager($variables) {
  $tags = $variables['tags'];
  $element = $variables['element'];
  $parameters = $variables['parameters'];
  $quantity = $variables['quantity'];
  global $pager_page_array, $pager_total;

  $li_previous = theme('pager_previous', array('text' => (isset($tags[1]) ? $tags[1] : t('‹ Previous Posts')), 'element' => $element, 'interval' => 1, 'parameters' => $parameters));
  $li_next = theme('pager_next', array('text' => (isset($tags[3]) ? $tags[3] : t('More Posts ›')), 'element' => $element, 'interval' => 1, 'parameters' => $parameters));

  if ($pager_total[$element] > 1) {

    // PREVIOUS
    if ($li_previous) {
      $items[] = array(
        'class' => array('pager-previous'),
        'data' => $li_previous,
      );
    }

    // NEXT
    if ($li_next) {
      $items[] = array(
        'class' => array('pager-next'),
        'data' => $li_next,
      );
    }

    // OUTPUT
    return '<h2 class="element-invisible">' . t('Pages') . '</h2>' . theme('item_list', array(
      'items' => $items,
      'attributes' => array('class' => array('pager')),
    ));
  }
}

```
> 2 votes

---
Tags: 7, paging
---


# Question
Title: How can i display a environment indicator notice on my dev and staging when browsing the site?
I know there is a environment\_indicator module that displays a bar on the bottom of the website showing if your on staging or dev. http://drupal.org/project/environment\_indicator

I want to know if there is a way to do this without having to install a module, by doing it via the settings.php file where I can make it output some html to indicate im on staging or dev.

# Answer
> 3 votes
You can't output HTML (or text) directly from `settings.php` without throwing an error, since `settings.php` is interpreted during bootstrap.

Provided you have a clean install, on your staging site, have the following line in `settings.php`:

```
$conf['site_name'] = 'This is a staging site';

```

All assignments to the `$conf` array you do in `settings.php` will override whatever value you set the in the administrative GUI for the site.

An alternative solution, if you don't have a clean install and the site's name is no longer displayed by default, is to add your *own* conf variable to `settings.php`:

```
$conf['is_staging_p'] = TRUE;

```

and modify your theme to output some indicator if this predicate is TRUE;

---
Tags: staging
---


# Question
Title: How to add .active class in to the menu item?
I am developing a theme for Drupal 7 and I am struck up with the following issue. I can see there are fixes through jQuery. But I would like to do it in the Drupal way.

My current HTML

```
<ul class="menu sf-js-enabled">
<li class="first leaf">
    <a href="/" class="active">Home</a></li>
<li class="last expanded">
    <a href="/node/57">About Us</a>
        <ul class="menu sf-js-enabled" style="display: none; visibility: hidden;">
            <li class="first leaf"><a href="/node/69">Contact Us</a></li>
            <li class="last leaf"><a href="/node/73">Typhygraphy</a></li>
        </ul>
</li>

```

And I want something like this

```
<ul class="menu sf-js-enabled">
<li class="first leaf active">
    <a href="/" class="active">Home</a></li>
<li class="last expanded">
    <a href="/node/57">About Us</a>
        <ul class="menu sf-js-enabled" style="display: none; visibility: hidden;">
            <li class="first leaf"><a href="/node/69">Contact Us</a></li>
            <li class="last leaf"><a href="/node/73">Typhygraphy</a></li>
        </ul>
</li>

```

The "active" class needs to be there in the `<li>` also.

# Answer
You can achieve your goal without jQuery. Just use theme\_menu\_link() function, or (my suggestion) **theme\_menu\_link\__your\_menu()**

Place this function in your template.php file:

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

    if ($element['#below']) {
        $sub_menu = drupal_render($element['#below']);
    }
    $output = l($element['#title'], $element['#href'], $element['#localized_options']);

    // if link class is active, make li class as active too
    if(strpos($output,"active")>0){
        $element['#attributes']['class'][] = "active";
    }
    return '<li' . drupal_attributes($element['#attributes']) . '>' . $output . $sub_menu . "</li>\n";
}

```

You can use this function only for menus displayed as a block. If you're theming main menu:

1. go to `admin/appearance/settings/yourtheme` and turn the main menu off.
2. go to `admin/structure/block` and place main menu block in header region
3. customize ul with theme\_menu\_tree() and li elements with theme\_menu\_link()
> 11 votes

---
Tags: theming, hooks
---


title: Send emails to users

text:
# Question
Title: Send emails to users
I want to send email to the users of my site, individually or to all of them at once.
Is there any available module?

I am using Drupal 6.

# Answer
Use this Mass Contact module it will match your requirement.

> The Mass Contact module allows anyone with permission to send a single message to multiple users of a site, using its roles functionality.

or

The Advanced User Module allows users who have "administer users" permission to send mail to selected groups of users, and that includes selection by role.
> 1 votes

# Answer
For an overview and comparion of Drupal newsletter modules, see this page on Drupal.org: Comparison of email newsletter oriented modules.

For an advanced solution that let you send HTML-styled newsletters, look at Simple news. For a basic mass mailing module, my choice would be Mass contact.
> 1 votes

---
Tags: 6, emails
---


# Question
Title: How can I easily verify if a core or module update has not broken anything?
When I update drupal core or even a couple of modules, I'm always afraid if something breaks. What easy way is there to test a site if anything has broken? Its not feasible for me to test a site that has over 1000 pages.

# Answer
> 2 votes
In general Drupal core updates should not break Drupal core. If you upgrade `stable` community modules to a newer `stable` release -- again you should not encounter regression error problems.

That being said and long as your not the edge with alot of modules it shouldnt be such a huge worry -- but I similar worries. Backup, Backup, Backup always.

I doubt you have 1000s of *unique* pages. There are tools like Selinium, or JMeter or Java's The Grinder that let you script interactions with a webpage for known results. You could script your set of possible necessary functionalities on a handful of generic pages.

There's no way around testing if you really have to test and assure error-free site usage.

# Answer
> 0 votes
I use Selenium, which has nothing to do with Drupal but is open source. I use the Selenium IDE Firefox extension on my machine locally, but Sauce Labs also offers paid services (I'm not a customer but I've heard good things).

Basically, with these tools, you define a series of tasks step-by-step. Then, when you update core/modules, you run the tests and make sure they return the correct results (you define what the correct results are).

This takes significant time to set up. When I was first starting out, it took me about three days to get a decent set of tests. However, now I can quickly check for all the past known problems whenever I update my site, so I think the investment was worth it.

---
Tags: updating, testing
---


# Question
Title: How do you disable Cron on a staging / dev server?
I have a staging and dev setup, but I wonder if I can disable cron on these as I don't want cron firing. It's mainly because I have backup migrate module scheduled to backup my site everyday, but I don't want this executing every time.

# Answer
> 17 votes
Yes, you can do this in your settings.php file (as you have mentioned that is the only difference between versions).

You would do it like this (in your settings.php file):

**Drupal 7:**

```
// Disable drupal's built in cron trigger.
$conf['cron_safe_threshold'] = 0;

```

**Drupal 8/9:**

```
// Disable drupal's built in cron trigger.
$config['automated_cron.settings']['interval'] = 0;

```

For more information see Defining variables in a site's settings.php $conf array.

**Edit** How this works is:

1. Variables are loaded from the database (or the cache if they have already been cached).
2. If those variables were not already in the cache they are saved to the cache.
3. The $conf variables from the settings file are added to the variables and take precedence over variables from the database.

So variables from the database are cached, but variables from settings.php are not.

# Answer
> 5 votes
Go to /admin/config/system/cron and set it to 'Never'. If you have an external crontab task, disable it.

# Answer
> 5 votes
As others have said there are modules out there to switch environments between different servers. For example a development server vs testing server vs production server.

A few are: Environment and Drush Environment.

Environment for example lets you write your own hook to easily manage what happens when you switch to a new environment. From the module page:

```
/**
 * Implementation of hook_environment_switch().
 */
function YOUR_MODULE_environment_switch($target_env, $current_env) {
  // Declare each optional development-related module
  $devel_modules = array(
    'bulk_export',
    'context_ui',
    'devel',
    'devel_generate',
    'devel_node_access',
    'imagecache_ui',
    'update',
    'spaces_ui',
    'views_ui',
  );

  switch ($target_env) {
    case 'production':
      module_disable($devel_modules);
      drupal_set_message('Disabled development modules');
      return;
    case 'development':
      module_enable($devel_modules);
      drupal_set_message('Enabled development modules');
      return;
  }
}
?>

```

You could with little trouble write a line of PHP that turns off Cron if your in the `Testing` environment server. I'm using Environment's hook on 1 project to perform the following tasks on a non-production server:

```
  module_enable($devel_modules); // A list of modules to enable.
  drupal_flush_all_caches();
  drupal_set_message('Enabled development/staging modules');

  // Configure Enviroment Indicator Module
  variable_set('environment_indicator_color',"#d00c0c");
  variable_seT('environment_indicator_margin', 1);
  variable_set('environment_indicator_position', "right");
  variable_set('environment_indicator_text',"MY STAGING SERVER");
  variable_set('environment_indicator_enabled','1');
  drupal_set_message(t('Configured environment indicator.'));

```

# Answer
> 0 votes
If your concern is just Backup and Migrate, you can export Backup and Migrate settings to settings.php (2.x branch) or export Backup and Migrate settings using the Features module (3.x branch).

I do this myself because I want to keep things as close to production as possible but can't have Backup and Migrate running all the time.

---
Tags: staging
---


title: Patching together a Drupal project

text:
# Question
Title: Patching together a Drupal project
I'm trying to basicly glue/patch/fix a Drupal project so that I can edit it simpler. There's too much duplicated code which I want to make into the same function.

To do this I have to, from my own knowledge, handle `modules`. What I'm curious about is: What is the ideal way to structure these new functions?

Should I create a module called `global_fixes`, or should I add new functions to the existing modules? Feel free to share your solutions if you have been given a similiar situation.

# Answer
Assuming that you inherited the custom modules along with the site, and there is no external maintainer of those, you should refactor the modules.

For contributed modules (i.e. modules maintained - or in some cases not - at drupal.org/projects), the options are more complicated. I don't recommend creating yet another module (`global_fixes`) to deal with this. You'll have problems keeping this in sync with new releases of the contributed modules you feel the urge to "fix".

Instead:

* If you're community oriented person, raise an issue in the module's project issue queue for what you consider duplicated code (or other defects). If you fix the problem yourself, make your fix a patch, and add the patch to the issue queue.
* If you don't want the hassle of dealing with module maintainers and the community, make a local fork where you essentially turn a contributed module into a custom one, and do whatever you like with it. This also means that you will no longer be able to download improved versions of this module drupal.org/projects. You'll have to maintain it yourself (just like any other custom module).

If you want to follow the community route, you'll probably notice that not *all* Drupal project maintainers are prepared to resolve your issues or commit your patches in a timely manner. So if you decide to create and submit patches, I strongly recommend that you install *git* and maintain a local repository that let you work with the code locally (independent of the repository at Drupal.org). Just do a merge whenever there is a new commit available at the central repository.

If you're *really* community minded, and discover that all the fine patches you create and submit to a project's issue queue appearently fall into a black hole, you may want to read up on this: Dealing with unsupported (abandoned) projects.
> 0 votes

---
Tags: 7
---


title: Using flags to approve user account

text:
# Question
Title: Using flags to approve user account
I'm using the flag module to provide my site admins with a simple "Approve Membership" button. When the button is clicked the system automatically associates the new user account with several roles and then changes the accounts status from "Blocked" to "Active.

So far the roles assign perfectly. The problem is that I can't figure out how to switch an account from Blocked to Active using flags.

Any ideas?

# Answer
> 3 votes
You can switch users from blocked to active upon flagging with the Rules module, which integrates with Flag. Create a rule on the **Event** "User is flagged with approval flag." Then add the action *Unblock a user* (under **Users** in the list).

---
Tags: users, flags
---


# Question
Title: Best practice for template theming - #markup vs safe_value
When doing complex display logic and breaking apart a renderable array in a field collection template, what's the best string output to use from the array: #markup, or safe\_value? Presumably #markup is already run through the right filters... right?

# Answer
You actually want to use the `render()` function like so:

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

```

See http://api.drupal.org/api/drupal/includes%21common.inc/function/render/7 for reference. Also, be sure to use `hide($content[FIELD_NAME])` right before you render `$content` or you will render the field a second time (unless you've hidden it in the view mode on the Manage Display tab of the content type).
> 1 votes

---
Tags: entities, theming
---


# Question
Title: wrapping menu items with span in Drupal 6
I need `<span>` tags around strings on my menu items. Trying to use this answer but it does not work for me. I probably just need some guidance in terms of naming things (just started on Drupal).

My theme folder name is `sub_website`, it is inheriting from theme called `website` (set by `base theme = website` in `sub_website/sub_website.info`). The menu in question is named 'Primary menu', it is selected as "source for the primary links" in the settings, and it is accessible via `/admin/build/menu-customize/primary-links` URI.

I tried adding the following into the sub-theme's `template.php`:

```
function sub_website_links__system_primary_links_menu($variables) {
  foreach ($variables['links'] as $link) {
    $output .= l('<span>'. check_plain($link['title']) .'</span>', $link['href'], $link);
  }
  return $output;
}

```

What am I doing wrong? Am I not clearing the cache properly? Did I not name the function correctly? Is there no such hook in Drupal 6? Documentation is very fragmented and is further complicated by two major versions existing side by side.

# Answer
> 0 votes
The answer that you found is for Drupal 7 not for Drupal 6.

In Drupal 6 you can't override `theme_links()` for a specific target.

You need to override `theme_links()` function itself to add `span` tag as the following code:

```
function sub_website_links($links, $attributes = array('class' => 'links')) {
  global $language;
  $output = '';

  if (count($links) > 0) {
    $output = '<ul'. drupal_attributes($attributes) .'>';

    $num_links = count($links);
    $i = 1;

    foreach ($links as $key => $link) {
      $class = $key;

      // Add first, last and active classes to the list of links to help out themers.
      if ($i == 1) {
        $class .= ' first';
      }
      if ($i == $num_links) {
        $class .= ' last';
      }
      if (isset($link['href']) && ($link['href'] == $_GET['q'] || ($link['href'] == '<front>' && drupal_is_front_page()))
          && (empty($link['language']) || $link['language']->language == $language->language)) {
        $class .= ' active';
      }
      $output .= '<li'. drupal_attributes(array('class' => $class)) .'>';

      if (isset($link['href'])) {
        // Pass in $link as $options, they share the same keys.

        // check if menu id attribute is set to primary-links
        if(isset($attributes['id']) && $attributes['id'] == 'primary-links') {

          // add html to link options
          $link['html'] = true;

          // wrap text with span
          $output .= l('<span>' . $link['title'] . '</span>', $link['href'], $link);

        } else {
          $output .= l($link['title'], $link['href'], $link);
        }

      }
      else if (!empty($link['title'])) {
        // Some links are actually not links, but we wrap these in <span> for adding title and class attributes
        if (empty($link['html'])) {
          $link['title'] = check_plain($link['title']);
        }
        $span_attributes = '';
        if (isset($link['attributes'])) {
          $span_attributes = drupal_attributes($link['attributes']);
        }
        $output .= '<span'. $span_attributes .'>'. $link['title'] .'</span>';
      }

      $i++;
      $output .= "</li>\n";
    }

    $output .= '</ul>';
  }

  return $output;
}

```

Then edit page.tpl.php and add **id** attribute for `$primary_links` menu

```
print theme('links', $primary_links, array('id' => 'primary-links', 'class' => 'links clearfix'));

```

---
Tags: routes, theming
---


title: More Pager not showing on Front page

text:
# Question
Title: More Pager not showing on Front page
I'm not sure what I've done wrong, but I just noticed that the front page of my site isn't showing the pager at the bottom so that visitors can get to older posts.

http://www.theresatutors.com/

I don't remember changing anything to hide this anywhere. What would cause this? Where can I look to turn it back on?

I've been searching trying to find a solution, but all of the pages that show up in my searches are people trying to hide the pager, not show the pager. :/

As far as I can tell I'm not overriding the mainpage in anyway or using Pages or anything like that. Just the standard Drupal homepage with standard Drupal blocks.

My theme settings for Bartik are set to allow 10 posts per page. I have 16 posts which are Published and Promoted to Front Page.

Any help is appreciated.

# Answer
> 1 votes
Found the problem.

I had a View in the Featured section which showed an image gallery. The Views configuration had a pager on that data and so it was overriding the main pager on the page. I changed the Pager config on the View to "Display All Items" and the main pager is showing now.

---
Tags: 7, paging
---


title: Sending mail to detailed groups?

text:
# Question
Title: Sending mail to detailed groups?
Ok, I need a bit of help with this one.

I have a website where I created a newsletter using Simplenews - works just fine, I'm sending some welcoming text + attached views of new things on site. But now I need to make something more with it.

I want to create new type of newsletter, that would be sent irregularly - or manualy as some would say. That is not a problem. Question appears here: I want admin to be able to create groups of users (manually again adding mails to the group etc.) for example, let's say I want to have two new groups for start:

* group a
* group b

And from time to time, admin needs to send a mail to all the email addresses in the selected group. How can I achieve that? Is even Simplenews a good idea in this situation? Or maybe there's some better tool?

Thanks in advance

# Answer
> 0 votes
I guess **Simplenews Roles** modules can help you for creating the groups.

You can assign users to a specific role and then based on this roles you can send Simplenews.

For Eg.

User 1 and User 2 can be assigned to role A

And

User 3 and User 4 can be assigned to role B

Now you can use role A and B for sending Simplenews.

I guess this helps.

# Answer
> 0 votes
Simplenews exactly has this feature:

1. First create groups here "admin/config/services/simplenews/add"
2. Edit new content type and in "Publishing options" check "Use as simplenews newsletter"

---
Tags: 7, emails
---


# Question
Title: Difficulty getting Rules Scheduler in D7 to publish a node in the future
I've set up rules to defer publishing on node save to a specified date. The rules component successfully runs at the later date and sends an email alert to the node author to let them know that their node has been published. **But the rules component does not succeed in actually publishing the node.**

I am pretty confident that the component works OK, because if I **execute** it directly, providing the node id as the content identifier (using direct input mode), it works as expected, i.e. sends the email alert **and** publishes the node.

The issue arises only when the component is run by cron. My best guess - drawing on this stackoverflow Q&A \- is that this may be connected to cron, on D7, always being run as the anonymous user.

I'm puzzled, however. There are several D7 discussions around of how to use Rules to defer publishing, e.g. this Drupal Answers Q&A or this drupal.org comment (about using this approach on D7 - it is a comment on a D6 page). The fact that neither of these mention any issue with the anonymous user, make me wonder if I'm getting something very basic wrong and/or have an unusual configuration. It would seem odd that Rules Scheduler couldn't, more or less out of the box, achieve deferred publishing.

I've looked at the 'Configure access for using this component with a permission' option for the component and tried out various settings of that without fixing the issue. I'm not clear I understand the function of this option and haven't found any documentation / Q&As so far that have helped.

For reference, the rules component (that works when executed manually using the node id, but send the email without publishing the node when triggered by cron) is (when exported) as follows:

```
{ "rules_publish_content" : {
    "LABEL" : "Delayed publish action",
    "PLUGIN" : "rule set",
    "REQUIRES" : [ "rules" ],
    "USES VARIABLES" : { "delayed_node" : { "label" : "Delayed node", "type" : "node" } },
    "RULES" : [
      { "RULE" : {
          "IF" : [
            { "node_is_of_type" : {
                "node" : [ "delayed-node" ],
                "type" : { "value" : { "news" : "news" } }
              }
            },
            { "NOT node_is_published" : { "node" : [ "delayed-node" ] } }
          ],
          "DO" : [
            { "mail" : {
                "to" : [ "delayed-node:author:mail" ],
                "subject" : "Your item, \u0022[delayed-node:title]\u0022, has been published.",
                "message" : "Your item, \u0022[delayed-node:title]\u0022, has been published.\r\n\r\n[delayed-node:url]\r\n\r\nnode id: [delayed-node:nid]\r\n\r\nnode date: [delayed-node:field-date]\r\n\r\nnode status: [delayed-node:status]\r\n",
                "language" : [ "" ]
              }
            },
            { "node_publish" : { "node" : [ "delayed-node" ] } }
          ],
          "LABEL" : "Delayed publishing: publish and alert"
        }
      }
    ]
  }
}

```

# Answer
> 0 votes
It turns out the concern about cron running under Anonymous user was a red herring. Thanks @Patrick Kenny for encouraging more persistent logging.

Diagnosis: the *reaction rule* that was scheduling the *component* was triggered by a 'Before saving content' event. In my testing - because of my faulty theory about the cause of the problem - I was repeatedly using an already created node. As such, the node nid was successfully passed to the *component* and so in logging (and in inspecting the list of scheduled rules) everything looked OK. And the alert email was even correctly generated. It turns out, however, that when the *component* is scheduled from a *reaction rule* triggered by a 'Before saving content' event, then changes to the node are not saved when the *component* executes. So **some things works** with the parameter passed from a 'Before saving content' triggered *reaction rule*, but not others. And for the things that don't work **no error or issue is flagged in logging**. Glad to know that now.

For anyone coming here just wanting some Rules to import to get delayed publishing up and running, here is the exported component and two exported rules that do the job.

**Component to publish a node**

In my use case, I also had a check for a specific node type. If you need to add that, add an extra condition after importing the component. (Import the component at: admin/config/workflow/rules/components)

```
{ "rules_publish_content" : {
    "LABEL" : "Delayed publish action",
    "PLUGIN" : "rule set",
    "REQUIRES" : [ "rules" ],
    "USES VARIABLES" : { "delayed_node" : { "label" : "Delayed node", "type" : "node" } },
    "RULES" : [
      { "RULE" : {
          "IF" : [ { "NOT node_is_published" : { "node" : [ "delayed-node" ] } } ],
          "DO" : [
            { "node_publish" : { "node" : [ "delayed-node" ] } },
            { "mail" : {
                "to" : [ "delayed-node:author:mail" ],
                "subject" : "Your item, \u0022[delayed-node:title]\u0022, has been published.",
                "message" : "Your item, \u0022[delayed-node:title]\u0022, has been published.\r\n\r\n[delayed-node:url]\r\n",
                "language" : [ "" ]
              }
            }
          ],
          "LABEL" : "Delayed publishing: publish and alert"
        }
      }
    ]
  }
}

```

**Rule to trigger delayed publication when authored on date is in the future**

In my use case, I also had a check for a specific node type. If you need to add that, add an extra condition after importing the rule. (Import the component at: /admin/config/workflow/rules). In addition, in my use case, I looked at a specific date field on the content type rather than the node:created, i.e. 'Authored on', value. If you want to do that then, after doing the import, add a new condition that checks your added date field and remove the condition that checks the standard Drupal created date field.

```
{ "rules_publish_node_future" : {
    "LABEL" : "Publish node (in the future)",
    "PLUGIN" : "reaction rule",
    "REQUIRES" : [ "rules", "rules_scheduler" ],
    "ON" : [ "node_insert", "node_update" ],
    "IF" : [
      { "data_is" : { "data" : [ "node:created" ], "op" : "\u003E", "value" : "now" } }
    ],
    "DO" : [
      { "node_unpublish" : { "node" : [ "node" ] } },
      { "schedule" : {
          "component" : "rules_publish_content",
          "date" : [ "node:created" ],
          "identifier" : "Delay publication of node: [node:nid]",
          "param_delayed_node" : [ "node" ]
        }
      },
      { "drupal_message" : {
          "message" : "\u003Cstrong\u003EPublishing will be delayed until (up to 3 hours) after: [node:created:long].\u003C\/strong\u003E This is because the \u0027Authored on\u0027 date you entered for your item is in the future. If you need to publish now then edit the item, change \u0027Authored on\u0027 date to now or earlier, set the item to be \u0027Published\u0027, and save.",
          "type" : "warning"
        }
      },
      { "mail" : {
          "to" : [ "node:author:mail" ],
          "subject" : "\u0022[node:title]\u0022 publication will be delayed until [node:field-date]",
          "message" : "\u0022[node:title]\u0022 publication will be delayed until (up to 3 hours) after: [node:created:long].\r\n\r\n[node:url]\r\n\r\nYou have received this message because the \u0027Authored on\u0027 date you entered for your item is in the future. If you need to publish now then edit the item, change \u0027Authored on\u0027 date to now or earlier, set the item to be \u0027Published\u0027, and save.",
          "language" : [ "" ]
        }
      }
    ]
  }
}

```

**Rule to cancel delayed publication if node is saved with a date in the past**

This rule cancels any scheduled publication of the node. It does not set the node to be published. Depending on your setup, you might want to add an action to this rule to publish the node.

```
{ "rules_publish_node_future_cancel" : {
    "LABEL" : "Publish node (in the future cancellation)",
    "PLUGIN" : "reaction rule",
    "REQUIRES" : [ "rules", "rules_scheduler" ],
    "ON" : [ "node_update" ],
    "IF" : [
      { "NOT data_is" : { "data" : [ "node:created" ], "op" : "\u003E", "value" : "now" } }
    ],
    "DO" : [
      { "schedule_delete" : {
          "component" : "rules_publish_content",
          "task" : "Delay publication of node: [node:nid]"
        }
      }
    ]
  }
}

```

---
Tags: rules
---


# Question
Title: How do you programatically render a views exposed filter form block in a tpl in Drupal 6?
I am trying to setup my views exposed filter form block in a custom tpl. How do I do this programatically? Note: My views setup display type is a page with a separate exposed filter form block.

# Answer
views\_embed\_view displays the whole views block. Therefore in your template you put:

```
print views_embed_view('most_read_today', 'block_1');

```

If you are needing to pass arguments to your 'exposed filter',add a 3rd argument.
> 1 votes

---
Tags: views, 6
---


# Question
Title: Call to a member function getLoginUrl() on a non-object in fbconnect.pages.inc on line 230
I'm using the Facebook connect module to give the users the possibility to log in in my website with their Facebook account. The configuration of the module is good, but when I click on "Log in to NameSite with Facebook account" I get this error message:

> Fatal error: Call to a member function getLoginUrl() on a non-object in fbconnect.pages.inc on line 230

I am using Drupal 7.

# Answer
> 1 votes
You need to set up the app with Facebook. The current link for doing so is https://developers.facebook.com/apps.

See http://drupal.org/node/1944522.

---
Tags: social-network
---


title: Module to manage submodules

text:
# Question
Title: Module to manage submodules
What I want to do is be able to tell what the parent of a submodule is on the admin/modules page. There is little to no indication of what it belongs to sometimes.

Example, under the Administration group, I have a module called "Actions permissions." I have no idea what this module is for, the purpose of the module, why I would want it, or what it belongs to. It's just out there. I know it's a child of something else, but there is no indication of that anywhere. I could go on the server and grep it but I think it might be helpful to people to have a way to determine the parent.

So is there a module that:

A) will group submodules in a hierarchy-type view under their parents? Or B) a module that simply lists what the parent is on the module item itself like we do with Requires:

# Answer
> 3 votes
There's no such concept as parent and sub/child-modules in Drupal. You'd have to define what *you* consider to be the parent-child relationship, pick what physical properties of the module you're going to use to describe that relationship, and code a solution from there.

Drupal's own native mechanism for grouping modules is using the `package` key in the module .info file. In the case of Actions Permissions, for example, the package is defined as "Administration", so you can find it under the "Administration" fieldset, grouped with other modules that are considered to have (loosely) related functionality by their respective authors.

On a slightly un-related note, but you can improve the UI of the modules page using Module Filter if it's becoming unwieldy.

---
Tags: 7
---


# Question
Title: How can I connect drupal 6 and activemq?
I would like to use publish subscribe technique to send updates to drupal as they happen in an external database. This database has middleware that publishes changes using a messaging system (apache camel).

# Answer
If you're willing to upgrade to Drupal 7, Services version 3 should interface to (for instance) JSON or SOAP.

Feature of version 3:

> * Response format API allows you to define response Formats for CONTENT-TYPE ie. `application/json` or `application/xml`.

Edit: I didn't know about STOMP, which the OP mentions in a comment. I add it here for searches/future reference:

> STOMP is the Simple (or Streaming) Text Orientated Messaging Protocol. The Stomp module implements an alternative Drupal Queue backend for queues supporting the STOMP protocol - such as ActiveMQ, RabbitMQ.

For Drupal 6, there is JSON server. I am not familiar with it, but you may be able to use that instead.
> 2 votes

---
Tags: 6
---


# Question
Title: How can I give the permission to edit, update, or delete a comment or a user profile to specific roles?
I am using the ACL module for Drupal 7 to give the permission to edit, update, and delete nodes to specific users. It works perfectly.

I want the same feature for comments and user profiles.

Is there any specific module or API for the same?

# Answer
There's the Comment Permissions module:

> The Comment Permissions module enables control of commenting by user role and by node type. Additional user permissions for selected node types are added to the user access system so you can configure commenting with more control than Drupal core provides.

It does have a (dev) Drupal 7 release, it's just not listed on the module page for whatever reason. You can find the archive here.

It will need testing before you can use it in a production site, but it's a very small module and a cursory glance at the code suggests it should work. I used that code as the base for a more advanced comment permissions module (including soft-deleting etc) some time back and don't remember finding any problems with it.
> 1 votes

---
Tags: 7, comments
---


# Question
Title: Question regarding rendering fields in node.tpl.php
I'm confused in how the fields can be rendered. There are 2 variables in node.tpl.php `$node` and `$content`, both of which contain fields. My task was to render all fields separately, to surround them with custom html. First I've tried

```
print render($content['field_service_summary'])

```

and got

```
array(1) { [0]=> array(1) { ["#markup"]=> string(11) "Engineering" } } Engineering

```

in result.

Trying to get rid of that array, I've taken another approach so the code became:

```
$field = field_get_items('node', $node, 'field_service_summary');
$output = field_view_value('node', $node, 'field_service_summary', $field[0]);
print render($output);

```

which actually worked, so, to clear this out I have following questions:

1) Where did that array come from when doing `print render(content['field_service_engineering']);` and how can I get rid of it(I still like this rendering approach better cause it's just shorter) ?

2) Is the second method I've used totally good, with no drawbacks ?

3) What's the point in keeping fields info both in `$content` and `$node` especially regarding that in vanilla node.tpl.php only `$content` is used for rendering fields ?

4) Just my curiosity: in `$content` array every field has value #object which seems to contain the node object itself. What is it for ?

# Answer
1. That should be `print render($content['field_service_summary']);` (notice the `$` sign prefixing the variable name).
2. It's technically OK, but unless you've customised the preprocess workflow to a large degree, what you'll find at `$content['field_service_summary']` is actually the result of a call to `field_view_value()` anyway, so you're just duplicating logic. If you find that method to be the way forward for whatever reason, at least move it into a preprocess function so it's not cluttering up the template file.
3. When nodes are loaded, they get field data attached to them. That data is in a certain format. When a field is viewed (e.g. with `field_view_field()`) that data is restructured into a render array, suitable to be run through `render()`/`drupal_render()`. The arrays might well contain the same data in some places, but they're formatted differently for their various different purposes.
4. It's a reference to the node object. It might be used by a theme/render function, or it might not. Core puts it there by convention. Remember it's just a *reference* to the object, it's not a duplicate.
> 1 votes

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


title: Drupal form submission to another page

text:
# Question
Title: Drupal form submission to another page
Below is my form and form submission function. The form is displayed in page-front.tpl.php. Using this code i could print $\_POST variable in the front page. But i would like to submit to some other page say page-result.tpl.php. How could i do that without using $\_session variables

```
    function q_search_form($form_state) {

$form['category'] = array(
    '#type' => 'select',
    '#options' => array('' => 'Any', 2 => 'Automotive', 1 => 'Real Estate'),
    '#attributes' => array('class' => 'drop-box'),
    '#prefix' => '<table width="470"><tr><td width="170">Select Category</td><td width="300">',
    '#suffix' => '</td></tr>'
);
$form['city'] = array(
    '#type' => 'select',
    '#options' => array('' => 'Any', 'kozhikode' => 'Kozhikode', 'kochi' => 'Kochi'),
    '#attributes' => array('class' => 'drop-box'),
    '#prefix' => '<tr><td width="170">City</td><td width="300">',
    '#suffix' => '</td></tr>'
);
$form['property'] = array(
    '#type' => 'select',
    '#options' => array('' => 'Any', 18 => 'Land and House', 17 => 'Land'),
    '#attributes' => array('class' => 'drop-box'),
    '#prefix' => '<tr><td width="170">Property</td><td width="300">',
    '#suffix' => '</td></tr>'
);
$form['wanto'] = array(
    '#type' => 'select',
    '#options' => array('' => 'Any', 'sell' => 'Sell', 'buy' => 'Buy'),
    '#attributes' => array('class' => 'drop-box'),
    '#prefix' => '<tr><td width="170">Want to</td><td width="300">',
    '#suffix' => '</td></tr>'
);
$form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Search'),
    '#attributes' => array('id' => 'Search', 'class' => 'srch-button'),
    '#prefix' => '<tr><td><a class="adv-srch" href="#">Advance Search</a></td><td>',
    '#suffix' => '</td></tr></table>'
);

return $form;
}

  function q_search_form_submit($form, &$form_state) {
    $wantto = $form_state['values']['wanto'];
    $property = $form_state['values']['property'];
    $city = $form_state['values']['city'];
    $category = $form_state['values']['category'];

    $sql = ' SELECT A.nid FROM node A
        LEFT JOIN content_type_item B ON A.vid = B.vid
        LEFT JOIN term_node C ON A.vid = C.vid
        LEFT JOIN term_hierarchy D ON D.tid = C.tid
        WHERE A.type = "item"
        AND B.field_tr_type_value = "'.$wantto.'"
        AND B.field_city_value = "'.$city.'"
        AND D.parent = '.$category.'
        AND C.tid = '.$property.'
      ';
   $result = db_query($sql);
  while ($row = db_fetch_array($result)) {
     $output['srch_result_nid'][] = $row['nid'];
    }

  $form_state['rebuild'] = TRUE;

  }

```

# Answer
In your `form_submit`, add `$form_state['redirect'] = <your_url>`, at the end.
> 1 votes

# Answer
This is the multi-step form problem. Try http://drupal.org/project/mforms

You end up with the data stashed into an array on each step.
> 0 votes

---
Tags: forms
---


# Question
Title: How do I display elements like the cart in a Panels page?
How can I use the Ubercart cart in a Panels page? I do not see it under any of the Contents list.

I think I am looking for a Drupal 6 version of uc\_panels.

# Answer
The uc\_panels module is a D7 port of the code in this issue which is a D6 panels integration for Ubercart. See comment #49 and the patch in #69.

Give it a try.
> 0 votes

---
Tags: 6, ubercart, panels
---


title: hook_uc_add_to_cart in template

text:
# Question
Title: hook_uc_add_to_cart in template
I'm using Drupal 7 + Ubercart 3 and am trying to run a piece of code just before the user adds a product in cart. hook\_uc\_add\_to\_cart seems to be the right function to use for it. So I'm trying to utilize it using the following syntax in `template.php` file of my template

```
function tbw_uc_add_to_cart($nid, $qty, $data){die('here: ' . $qty);}

```

where `tbw` is my template name. I've flushed all caches but the above code does not work as it doesn't `die()` when I add a product to cart. I suspect the problem is that this hook can't be implemented in a template because the documentation only talks about using it inside a module, i.e., `Some modules need to be able to hook into the process of adding items to a cart...`. Can anybody please shed some light on why it is not working and guide me in the right direction. Thanks.

# Answer
> I suspect the problem is that this hook can't be implemented in a template

Correct :)

Only `hook_theme()`, preprocess hooks, and alter hooks can be implemented in template.php. For any others, including this one, you'll need to write a custom module.
> 2 votes

---
Tags: 7, hooks, ubercart
---


# Question
Title: How can I assign pages to templates like in WordPress?
I've just made the jump from WordPress to Drupal, and though I love what I'm seeing there's a basic piece of functionality that's obvious in WordPress but is escaping me in Drupal- How does one, for a given page or piece of content, assign it to a specific template?

Please note that I'm not trying to design a template for a specific content type, rather I want the ability to choose a template at the individual content/node level, in the edit screen.

It doesn't look like this is part of out-of-the-box Drupal, so does anyone have suggestions as to how to go about implementing it?

# Answer
What I would do, is to create a Vocabulary called "template" (using the Taxonomy module in Drupal core) and add some template names to it as taxonomy terms. This will allow you to 'tag' your nodes with the template name for that node.

Next, I would create a preprocess function for the node template in my theme's template.php file and add template suggestions based on the taxonomy term. Roughly the preprocess function would look like this (not working code, just an outline):

```
function MYTHEME_preprocess_node(&$variables) {
  // Get the Term ID from the "template" vocab for the current node.
  $template_tid = ... // (figure out where that data is in the $variables)
  if (!empty($template_tid)) {
    // Tell Drupal to use the node--[template_tid].tpl.php template if it exists.
    $variables['theme_hook_suggestion'] = 'node__' . $template_tid;
  }
}

```

Note that I'm suggesting to add template suggestions based on term ID, not term name. If you build it like this, you can always change the term names without breaking your template files.

For more information about template suggestions, see Working with template suggestions.
> 7 votes

# Answer
There's a module called Custom Node Template that lets you choose a template file on a node by node basis. Unfortunately, it only seems to be available for Drupal 6 and the author has stated he can't currently spare the time to port it to D7.
> 4 votes

# Answer
I was looking for a module like this a while back and couldn't find anything, so I started to work on a way to do it for Drupal 7, which became the Template Picker module.

I didn't discover the Custom Node Template module until afterwards, but that looks like a great option for Drupal 6.
> 3 votes

---
Tags: 7, theming
---


# Question
Title: Save button missing from content type edit form
Here is what the bottom of my "leaflet" content type edit form (i.e. admin \> structure \> content types \> leaflet \> edit) looks like:

Here is what the bottom of my "testimony" content type edit form looks like:

Note that there are no save/delete buttons! Another of my content types has also now picked up this bug. This just happened. I have no idea why. I can't save changes! I tried flushing all caches and it didn't help. I'm an administrator and I have permissions for everything.

Why would this have happened and what can I do? Drupal 7.19.

# Answer
The problem was the i18n synchronize translations module. Disabling it fixed the problem. Of I have to immediately re-enable it afterwards since I actually use this module. So I filed an issue: http://drupal.org/node/2004260. Thanks to Ayesh K who gave me the idea in his comment on my question. Since it's not an answer I can't mark it correct, so I'm just answering here and will mark this correct.
> 2 votes

# Answer
Looks like an odd one, some form\_alter or theme issue.

If you try a good admin theme like

* Tao ( base admin theme )
* Rubik ( admin theme )

Download both, enable and set admin theme in

* /admin/appearance
* ADMINISTRATION THEME Choose "Default theme" to always use the same theme as the rest of the site. ( RUBIK )
* Use the administration theme when editing or creating content ( CHECK )

The buttons should show up again
> 1 votes

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


title: Link to documents from several nodes

text:
# Question
Title: Link to documents from several nodes
What would be the best way to set up several nodes so that some of the content is linked to a single document stored on the server? For example, I want a document that has some official rules on it and display it on several pages by only editing the source document.

# Answer
If you want to display a common piece of content on all the pages, you can create a block with the common content, and display that block in the content region of the required pages.

Just go to */admin/structure/block* and position the block before or after the **Main page content** block, and set it to only display on the required pages.
> 1 votes

---
Tags: feeds
---


title: How to set up the following newsletter

text:
# Question
Title: How to set up the following newsletter
My nodes are broken down by taxonomy, each taxonomy term comes with a different icon, I need to set up a newsletter that sends out a title, teaser and the right icon for each node. What is the easiest way to achieve this? Simplenews? ePublish? Do either of these modules easily integrate with Views so I can output the right fields?

# Answer
> 0 votes
Newsletter can do what you need. The description on the project page:

Multiple newsletters lists configurable on existing terms Plain text or HTML out of the box. Multiple schedules Each newsletter can have more than one schedule, e.g. Daily, Monthly, Weekly, manually or even custom, eg after 10 new posts for this term. Centralized administration and configuration on a single page. Users can customize the terms in the list they subscribe to. Custom template per list. Statistics (CTR and Open-Rate). Drupal 7 only.

I'm using it on my site and it works like you've mentioned.

---
Tags: views, 6, emails
---


# Question
Title: Find and display most recent referencing entities
I have 2 different node types. The first one describes a factory and the second one describes a measurement of the water inside the factory. The measurement content type has an Entity Reference field that points to the factory that the measurement is associated with.

What I want to do is print a list of all the factories in a table format and a specific column that will contain a field from the latest measurement that references to the specific factory.

For example:

# Factory 1

field 1
field 2
field 3

# Factory 2

field 1
field 2
field 3

## Measurement 1

Refers to Factory 1
Integer Field
Date Created: 21/5/2013

## Measurement 2

Refers to Factory 1
Integer Field
Date Created: 22/5/2013

## Measurement 3

Refers to Factory 2
Integer Field
Date Created: 10/2/2012

## Measurement 4

Refers to Factory 1
Integer Field
Date Created: 23/5/2013

**What I want to print**:
Factory 1 || field 1 || field 2 || field 3 || Integer Field (from Measurement 4)
Factory 2 || field 1 || field 2 || field 3 || Integer Field (from Measurement 3)

Notice that I'm only printing the Integer field from Measurement 4 since it is the latest measurement for the specific factory. I started writing some custom code and looked into EntityFieldQuery but I can't understand how to use it in conjunction with Entity Reference.

# Answer
> 4 votes
I've made an assumption about the way you want the table to be formatted, but something like the following should get you most of the way there:

```
// Set up the table.
$header = array('Factory Name', 'Field Value');
$rows = array();

// Get some nids for the factories you're interested in. Your real query will probably be more specific (checking status etc).
$args = array(':type' => 'factory');
$factory_nids = db_query('SELECT nid FROM {node} WHERE type = :type', $args)->fetchCol();

// Load the factory nodes.
$factory_nodes = node_load_multiple($factory_nids);

foreach ($factory_nodes as $factory_node) {
  // Add the factory name to the first column of this row.
  $row = array($factory_node->title);

  // Get the latest measurement related to this factory with an EntityFieldQuery.
  // fieldCondition() and fieldOrderBy()/propertyOrderBy() are the important bits here.
  $query = new EntityFieldQuery();
  $query->entityCondition('entity_type', 'node')
    ->propertyCondition('type', 'measurement')
    ->propertyCondition('status', 1)
    // This is the entity reference condition; entity ref fields use 'target_id' as the field column name.
    ->fieldCondition('field_factory_reference', 'target_id', $factory_node->nid)
    // If the date you're interested in is in a field, use something like this...
    ->fieldOrderBy('field_measurement_date', 'value', 'DESC')
    // ...or if you're interested in the node created date, this
    ->propertyOrderBy('created', 'DESC')
    ->range(0, 1);

  $results = $query->execute();

  // Make sure there are some results.
  if (!empty($results['node'])) {
    // EntityFieldQuerys always return an array of nids even if there's only one result,
    // so it's easier to run through node_load_multiple and shift the element later
    $measurement_nodes = node_load_multiple(array_keys($results['node']));

    // Get the node
    $latest_measurement_node = array_shift($measurement_nodes);

    if ($field_items = field_get_items('node', $latest_measurement_node, 'field_some_field')) {
      // If we have an appropriate value, add it to the row.
      $row[] = $field_items[0]['value'];
    }
    else {
      $row[] = 'No data found';
    }
  }
  else {
    $row[] = 'No data found';
  }

  $rows[] = $row;
}

$rendered_table = theme('table', array('header' => $header, 'rows' => $rows));

```

# Answer
> 2 votes
How about using Views Field View module? Specifically:

Create a content view (i.e. latest\_measurement\_view):

1. Add the entity reference relationship which points the measurement type to the factory type
2. Add a contextual filter Content nid **with the above relationship**
3. Add a filter for the measurement content type
4. Add the integer field which belongs to the above type
5. Sort the view by post date descending
6. Set "Display a specific number of items" to 1 in the pager section

So this view gives you a single (integer) field that of the most recent measurement node for every corresponding factory node.

Now install and enable the Views Field View module and create another content view (lets say factories\_view) to list your factories in a table and:

1. Add a filter for the factory content type
2. Add a field of content nid and hide it from display
3. Add the fields you need from the factory type (title, fields 1, 2, 3 etc)
4. Add a global view field. In the window that pops up choose the latest\_measurement\_view and the display you want from the "Views Settings" section and finally (and most importantly) in the "Contextual Filters field" use the \[!nid\] token (replacement patterns: \[!nid\] == Content: Nid (raw))

Just be careful to always have the global view field after the content nid field.

You should now have the desired view result showing a table with the factories and a column displaying the integer field of the latest measurement next to each respective factory.

---
Tags: 7, entities
---


# Question
Title: How do I enable the "extra" stuff in the OpenPublic distribution?
OpenPublic is a Drupal distribution that is supposed to be for NGOs (and government). I've downloaded and installed the distribution as a tarball from their site using the big download button.

The tarball is about twice the size of a basic Drupal 7.22 core tarball, so I assume there are some extra stuff included in this distribution.

However, after following the instructions for installation (they refer to the standard instructions for installing Drupal 7), I am looking at a completely plain vanilla Drupal 7 website. No additional themes, no additional content types, no additional functionality.

I've been hunting high and low for documentation for what to do post-installation with this distribution and come up with nothing.

There is a support group for the distribution at groups.drupal.org, but it is not very responsive, for instance, this question was asked on Jan 18th, with no reply yet.

I am asking here, hoping that someone here is familiar with this distribution and can provide me with the recipe of how about to "unlock" whatever this distribution has to offer, or—even better—provide a link to the missing manual.

# Answer
It sounds like you've just installed the wrong profile. At the first step of the installation you get a choice like

Once you choose OpenPublic and follow the installation through, you won't have a vanilla Drupal install any more. For example your home page looks like this:

Don't forget it's still in beta so you're likely to see warnings/notices around the place; I wouldn't recommend using it for a production site yet. It's also pretty sluggish compared to a normal Drupal install so make sure you profile it before deciding whether or not to use it.
> 3 votes

---
Tags: distributions
---


# Question
Title: switch views or hide block based on content type
I have a block view that gets its contents based on a contextual filter. I only want to use this filter if it's a certain node type being displayed ie. the block would use the contextual filter on basic pages but on article and other pages I would like to set the contextual filter to a default value.

One way I thought I might do this is to change the views display based on the node type and then override the settings in the second display. Is this possible?

I created my second display for the view and I added both blocks to the same region. One of them I set to only display on basic pages. The other one I would like to set to only not display on basic pages. The block system only lets me select which content types to show the block on not which content types to exclude it from. I don't want to keep coming back to this page and having to check more boxes as I add new content types.

Is there any way to exclude a block from being shown on a certain content type?

# Answer
> 1 votes
It's possible with views:

**#1 Configure field with images:**

**#2 Add contextual filter:**

**#3 Save the contextual settings and then add "No result behavior':**

**#4 You just need to display a default image in case the other content type than basic page, so you can apply the Unfiltered text, and type the html source of the image:**

**That's it!**

# Answer
> 1 votes
> Is there anyway to exclude a block from being shown on a certain content type?

Yes, there is. Download and enable the Context module. Create a new context which assigns the view block you created to a region as a result of being on a Basic Page node.

Context is a pretty fantastic module for controlling where blocks go. Definitely check it out and explore what it can do.

---
Tags: nodes, views, blocks
---


# Question
Title: When sending a Drupal database to a developer, how can I remove users' personal info (e-mail addresses, passwords)?
How can I remove users' e-mail addresses and passwords when sending a database to a developer (for investigating a bug, etc.)? The e-mail addresses and passwords are irrelevant for the bug and, although I have not consulted with a lawyer, this seems to be a general safe practice.

# Answer
Drush supports an `sql-sanitize` function:

```
    $ drush help sql-sanitize Run sanitization operations on the current database.

    Options:

    --db-url=<mysql://root:pass@127.0.0.1/db  A Drupal 6 style database URL.
    Only required for initial install - not re-install.

    --sanitize-email        The pattern for test email addresses
                        in the sanitization operation, or
                        "no" to keep email addresses
                        unchanged.  May contain replacement
                        patterns %uid, %mail or %name.
                        Default is "user+%uid@localhost".

--sanitize-password     The password to assign to all
                        accounts in the sanitization
                        operation, or "no" to keep passwords
                        unchanged.  Default is "password".

    Aliases: sqlsan

```

You could always setup a clone of your live site using `drush archive-dump` or `drush sql-sync` then run `sql-sanitize` on that cloned sites db and get everything cleaned. I believe `sql-sanitize` provides a hook so you can sanitize custom drupal data you deem sensitive beyond the scope of the default username and password.
> 4 votes

---
Tags: users
---


title: Should I rewrite my links into aliases?

text:
# Question
Title: Should I rewrite my links into aliases?
Is it of any advantage, in addition to using Global Redirect, to rewrite html links from `/node/nid` to `/article/this-is-the-title`, even though in both cases traffic is directed to `/article/this-is-the-title` (by Global Redirect).

# Edit:

From this answer I gather that I should use Global Redirect so that aliases wouldn't cause "duplicate" content.

The same answer suggests a way to intercept links, passing them through functions to "convert from node/nid to article/title". However, I am green at coding Drupal, and have no clue as to go about it. Could some one advise on alternatives? Or ways of making this less cumbersome?

I am also adding this link to a related answer on avoiding disadvantages of 'same content/multiple URLs' for whoever's reference.

# Answer
From this answer I gather that I should use Global Redirect so that aliases wouldn't cause "duplicate" content.

The same answer suggests using the l() function to have Drupal use "pretty paths" automatically.

I am also adding this link to a related answer on avoiding disadvantages of 'same content/multiple URLs' for whoever's reference.
> 1 votes

---
Tags: path-aliases
---


title: When is taxonomy appropriate

text:
# Question
Title: When is taxonomy appropriate
If I, hypothetically, ran a business and kept data on products, part data related to those products, and service procedures for those products would it make sense to fit this into the Drupal taxonomy? Is that the Drupal way?

I'm just getting going on Drupal; I have an existing working php application that I shoved into a module without really making use of Drupal functions, to the extent that I even have a separate database. My app uses some non-trivial database organizations, lots of database views and heavy usage of inner joins. This app will be a suite of apps that will also include standard web functions, which I why I want to use Drupal/CMS. But I don't know if I should my module data into taxonomies.

Edit: 99% sure that entities will do what I need, searching on that now.

# Answer
Taxonomies are best used to define properties that:

1. are shared across multiple content items;
2. need to be grouped with similar properties.

For instance, if you're selling t-shirts, the taxonomy terms 'blue', 'red' and 'yellow' are grouped in the 'color' vocabulary. By tagging all t-shirts of the same color with the same taxonomy term, you define a relationship between those t-shirts. This makes it very easy to generate a page showing all blue, red or yellow t-shirts.

Taxonomy terms, like many other entity types, are 'fieldable', which means that you can add fields to them to contain data. For instance, if you add an image field to the taxonomy terms in the 'color' vocabulary, you could define an example image for each color term.

If this example with t-shirts and colors matches your use case, then the answer to your question is: Yes, taxonomy is the Drupal way to do it.

By the way, the word "entity" has a very broad meaning in Drupal. 'Taxonomy term' is a type of entity, just like 'node', 'user' and 'file'. Saying that "entities will do what you need" is like saying "building materials will allow me to build a house". It's a statement that (almost) can't be wrong. You need to answer the question: Which type of entity is best to solve this specific problem?
> 1 votes

# Answer
Taxonomies in drupal are used to organize and relate content. The Taxonomy module offers the ability to add Vocabularies and then to each vocabulary we can add terms by going to Structure-\>Taxonomy-\>Add Vocabulary-\>Add Term.

Example: If we've a book store then we can organize content by creating vocabularies like, Author, Publisher, Format like ebook, hard copy etc. I'd advise you to study the already available material available on the internet starting from this one.

http://drupal.org/documentation/modules/taxonomyTaxonomies
> 0 votes

---
Tags: taxonomy-terms
---


# Question
Title: Average value of integer field using views
I set up a multi value cck integer field for rating purposes. It has values

```
 1|good
 2|bad
 3|dont know

```

Users voted like so:

```
3 votes for good
2 votes for bad
4 votes for dont know

```

I want to make an average from all values. In views 3 I checked grouping and set group type average on cck field inside views. Unfortunately, Instead of 1 result I get 3 results - for every value set in cck field. Results are 1, 2 and 3 which is useless. How it is possible to get only one average number? Thank you

EDIT: the average value works the same way using simple text fields. Views group by in views 3 counts only values that are the same. And it looks like it is known issue http://drupal.org/node/903768

# Answer
> 0 votes
You could use something like Computed Field to display the average, but I would suggest going to the Voting API and something like the Fivestar module which will handle the voting and the averaging for you.

---
Tags: views, 6
---


title: views exposed "sort by"

text:
# Question
Title: views exposed "sort by"
I have a view with an exposed "sort by" form.

I don't know how to skip this sort if the user did not chose any sort mode.

My view has this exposed sort widget and the second sort criteria (not exposed) is by node sticky property. The problem is the view sorts the content by the first criteria, even though the user didn't chose something.

How can I change that? Thanks

# Answer
I just had this problem (well, similar) and I solved it the following way:

```
/**
 * Implements hook_views_pre_build().
 */
function MY_MODULE_views_pre_build(&$view) {
  // Trigger this only for the needed view
  if ($view->name == 'my_view_name') {
    // Check the exposed input array to see what the user submitted
    $exposed_input_arr = $view->get_exposed_input();
    // Write your exposed array checking logic here ...
    //if (empty($exposed_input_arr['field_sort_by']) || ...) {
      // Remove the sort field from the view
      unset($view->sort['field_sort_by']);
    //}
  }
}

```
> 2 votes

---
Tags: 7, views
---


title: Compare user field

text:
# Question
Title: Compare user field
I would like some help with the following issue. In Drupal 7, I want to activate a newly registered user when his email id is saved in a content field.

I have created a content type `email`. Now whenever a new user registers, I need to check his email id with the existing emails. If a match is found, then that user should be activated by default and the new user should be blocked.

I have tried to use the rule module, but after saving new account in the condition it's not comparing the email id with node field. Is there any other module which could accomplish this? Or any other method to do this?

# Answer
> 0 votes
> *Is there any other module which could accomplish this? Or any other method to do this?*

If you've tried the Rules module and it's not working for you for one reason or another, another option/method would be to try something like the Invite module.

I don't know what your reasoning is behind the email nodes (not that it's a bad thing... I just don't know if you save other info there or if you're just looking for a method to store email addresses), but if your reasoning is in fact solely to have a place to store a bunch of authorized email addresses, then the Invite module should do the trick.

Additionally, from what I can tell there have been some improvements made in the D7 version which sound like they might be able to suit your needs. For instance, once the module is enabled, if you go to `www.yoursite.com/admin/config/people/accounts` you'll now see an option to only allow invited people to register. You can also make it so when you "invite" someone (or maybe a better word would be "authorize" in your case), it either sends them an email with a customizable message containing their unique registration URL, or you can simply have it generate the registration URL and send it out later.

Another option would be to try the User restrictions module, which basically brings back the option to block/allow certain usernames and/or email addresses. Once enabled, if you go to `www.yoursite.com/admin/config/people/user-restrictions/add` you could then set a "Denied" rule for all email addresses (enter `%` into the `Mask` box), and afterwards add each new "Allowed" rule as needed. Examples:

---

**Denied:**

---

**Allowed**:

---

I know it's not exactly what you had set up originally, but hopefully it can point you in a better direction. :)

---
Tags: 7, users, rules
---


title: How to import a 'Feature'?

text:
# Question
Title: How to import a 'Feature'?
I have exported certain items with features module and have my \*.tar file, where do I go in drupal to import this Feature in my destination site???

# Answer
> 5 votes
I found my answer. Features creates a module that I need to import in the destination site.

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


# Question
Title: Referring to an image file uploaded as `Image` type field without /sites/
I am using a content type with `Image` type fields to hold images uploaded to a web site. I want to display these images both on distinct pages (easy) and inline on other pages (almost *even* easier).

However, I don't want to expose `/sites/default/files/` in the image URL, and I certainly don't want to include it in the image tag's `src` attribute when I refer to the image from some other page.

How do I include at an arbitrary location on an arbitrary page an image uploaded like that, without exposing the physical directory structure in the link? I tried using the `URL aliases` feature provided by the Path module, but it wouldn't let me point to anything in /sites as such.

# Answer
> 0 votes
You could create a symlink in the drupal root using:

```
ln -s sites/default/files images

```

and then set the src attribute to something like:

```
/images/myimage.jpg

```

Really not sure what you would gain by doing this.

# Answer
> 0 votes
You can use .htaccess and mod\_rewrite. Like described on stackoverflow. In my opinion it's the cleanest solution, but other ones may still be valid.

Then, in your template.php you need to rewrite rendered image addresses to reflect new ones.

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


# Question
Title: Order Status is Pending after Paypal Payment
I created an order with weekly or monthly subscription. User can purchase the subscription only through paypal.

If a user purchase the subscription he redirected to paypal site. After successfully payment the order is created. But the order status showing `pending`. It should be `completed`.

Recurring Module : UC Recurring Payments and Subscriptions

Payment Method - Paypal

(Edit) Problem was in Sandbox paypal Account. Api Credential (Password and Signature) was not there. I changed the merchant account Api Credential.

After changed the api credential same problem occured with changed account. What to do?

# Answer
Ubercart does not make orders completed on it's own. It seems to be a well known problem, already discussed on stackoverflow and on ubercart.org. It seems manually setting up Conditional Actions is a must in most cases.
> 0 votes

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


title: How can I use thre Migrate module?

text:
# Question
Title: How can I use thre Migrate module?
I installed the *Migrate* module, but I can't use it, nor can I find any useful documentation that explains how to use it. The page on /admin/content/migrate is empty.

How can I use this module?

# Answer
The Migrate module *only* provides a flexible framework for data migration into Drupal. The logic and data mappings to perform an actual migration are pretty complex. Migrate does not provides an UI to *build* or *configure* your migration. IMHO, this is good because a complete UI to build such script would be at least as complex as writing it directly in PHP.

Its documentation is pretty complete and provides all the information needed to start using it. I recently started to use it and, coming from an OOP background, find it intuitive and easy to learn.
> 5 votes

# Answer
Speaking as one of the maintainers, Migrate is kind of a pain at first with but once you get up to speed on it's really powerful. The biggest change between version 1.x and 2.x is as MPD noted the lack of of the Table Wizard. It's now all class based which makes it trickier to setup a migration but much more flexible. Instead of having to get all your data into MySQL now you can use a variety of different sources.

I've got some slides that might be helpful: http://denver2012.drupal.org/sites/default/files/Migrate.pdf
> 4 votes

# Answer
Cyrve developed the module and they have a post on the blog entitled Performing a data migration with migrate module that might be helpful.

Also, the video from the Migration: not just for the birds presentation at Drupalcon DC 2009 is probably somewhat out-of-date, but it should provide a good overview.
> 2 votes

# Answer
Migrate 2 is powerful. Just spent some time to learn it you won't regret.

Here's a full example of migrating contents to Drupal 7.

http://miss-hana.com/migrate-contents-from-drupal-6-to-drupal-7-using-migrate-2/
> 1 votes

# Answer
Very nice documentation in the answers.

Personally I found this post very helpfull

Using migrate module to handle big data imports
> 1 votes

# Answer
Are you accessing it as the admin user (uid 1)? If not, I suspect you need to explicitly assign permissions. Goto /admin/user/permissions, find the "migrate module" heading, and assign permissions as needed.

The last time we used this module, we did it in conjunction with Table Wizard.

To be honest, I just find it easier to write manual import scripts, rather than work within the confines of these modules.
> 0 votes

# Answer
This link might might help explain more about migration. It contains screen shots as well as examples. it gives a step by step approach to migration. http://www.lullabot.com/articles/drupal-data-imports-migrate-and-table-wizard. This link give a brief explanation on how to migrate content http://btmash.com/article/2011-02-25/migrating-content-using-migrate-module. I found think link about migrating the cck construction it. It might be worth a look as well. http://drupal.org/node/1144136
> 0 votes

# Answer
It's possible to move your website content directly from your Drupal to Joomla without using the importer module. You may try cms2cms tool that migrates site content via the connection bridge that is created between your sites. Such process requires both of your sites Drupal and Joomla being available online. Here you may watch how this converter works http://www.youtube.com/watch?v=cCkW-vwzlEg

But, if you want to move custom type posts, I'm not sure this tool will work as well with the migration of your theme.
> 0 votes

---
Tags: 7, migrations
---


# Question
Title: Using Drush without typing drush every time
This might be a dumb question and is probably more of a general question for using the command line, but how can I create a command setting where drush is set in the current terminal session. I already have the correct path set where I don't have to type the full path to drush every time, but I'd like to be able to open the terminal up with drush set in the session until I exit the terminal.

For instance instead of opening up terminal and having to type drush everytime:

$ drush dl ctools

$ drush en ctools

$ drush .... (everything else that you want to do)

I can open up the terminal where drush is already set, something like this where drush becomes the user and I don't have to type it:

drush$ dl ctools, pathauto, ... drush$ en ctools

# Answer
> 1 votes
This functionality was added in 2010 and removed in 2012. "By the book" way is to use bash with bash completion and optionally bash aliases. Or you can wrap it into a simple php / bash / c program that will automatically prepend `drush -l $yoursitename` to everything you write and execute the result, and use that as your small simple shell. But you would give up bash completion then.

# Answer
> 1 votes
I would suggest making a few aliases:

```
alias cc='drush cc'
alias en='drush en'
alias dl='drush dl'

```

Assuming you aren't using these for something else, it is an easy way to make drush commands that you use all the time much more accessible.

You can put that script in ~/.bash\_aliases and it will appear for all terminal sessions.

If you use alias.sh simply click "Use" on this alias http://alias.sh/common-drush-commands to import them into your bash profile.

---
Tags: drush
---


title: Show popup in access denied page

text:
# Question
Title: Show popup in access denied page
I want to show a popup for access denied page. Is there any module available for this? I know I can create a custom module for this but I want to know if there is any module available for this.

# Answer
Popup module allow you to display the access denied page in popup box.

> The popup suite allows builders to popup tooltip-like text, nodes, blocks, menus, forms, views and php-generated content.

or

Better Messages intends to let you control where and how you want to see your Drupal messages! Combine different animations and override

> Enable or disable popup messages at specific pages.
> 1 votes

---
Tags: users, javascript
---


title: Show webform results on same page

text:
# Question
Title: Show webform results on same page
i have a `webform` with a lot of fields(i am making some kind of calculator for my needs) and after submit i need to show custom output under my webform.

In `hook_form_alter` i have added custom submit handler `$form['#submit'][] = 'common_webform_client_form_1562_submit_handler';`

and after submit i need to show my results on same page.

```
function common_webform_client_form_1562_submit_handler($form, &$form_state) {
   //some logic here

   //redirect to node with my webform
   $form_state['redirect'] = 'node/1544';
}

```

As i can see i cannot modify or add anything to a `$form` i thought i can add `#suffix` to webform and attach my results but i can't, should i do it with `Drupal.settings` and grab it with `javascript`? or is there another option?

# Answer
> 0 votes
So after some research i have found the answer. I did this with `ajax` submit. In `hook_form_alter` i have added ajax submit callback with markup element:

```
$form['actions']['submit']['#ajax'] = array('callback' => 'common_webform_client_form_1562_submit_handler',
           'wrapper' => 'form-ajax-node-content',
      'method' => 'replace',
      'effect' => 'fade',);
       $form['markup'] = array(
            '#prefix' => '<div id = "form-ajax-node-content">',
            '#suffix' => '</div>',
            '#markup' => '',
            '#weight' => 2000, //set weight to show markup at the bottom of the form
       );

```

And in my callback i can generate any output i want to!)

```
function common_webform_client_form_1562_submit_handler($form, &$form_state) {
   $output = 'Dummy text';
   $form['markup'] = array(
            '#prefix' => '<div id = "form-ajax-node-content">',
            '#suffix' => '</div>',
            '#markup' => $output,
            '#weight' => 2000,
       );
    return $form['markup'];
}

```

---
Tags: 7, webforms
---


# Question
Title: How do I disable the Back button after logout?
I have created a quiz portal using Drupal. The issue is that, after logout, one can easily go back by pressing the browser's Back button. It is improper when someone takes a quiz and leaves the browser open. Then, another user can easily get the previous result just by pressing the Back button.

I want to disable the Back button after logout. How can I achieve this?

# Answer
> 1 votes
You can't. And you should not even try. Breaking the browser's navigation paradigm is not a recommended practice.

Having said that, there are tricks you can use to make it appear as if the back button is disabled. Users can get around those tricks, but you may fool some of the people some of the time.

Here is one page that explains those tricks: http://viralpatel.net/blogs/disable-back-button-browser-javascript/

Google will give you a lot more.

To add js to your site, look up drupal\_add\_js in the API.

---
Tags: quiz, users
---


# Question
Title: Drupal's attach behaviours : react on all newly loaded content?
I've got two different modules which in many ways work together. One of the things they work together on is that module A loads content via AJAX, and module B needs to attach event listeners to the content loaded.

However, it appears that when content is loaded via AJAX by module A, only the 'attach' function of **Drupal.behaviours.a** gets invoked, and not the 'attach' function of **Drupal.behaviours.b**. Both functions gets invoked on page load, but not on subsequent AJAX content loading.

```
// This runs every time module A loads new content.
Drupal.behaviors.a = {
  attach: function(context, settings) {
    alert('a:attach');
  }
}

// This only runs on page load, but never when module A loads new content.
Drupal.behaviors.b = {
  attach: function(context, settings) {
    alert('b:attach');
  }
}

```

How do i make the 'attach' function of **Drupal.behaviours.b** run every time any module loads new content?

# Answer
> 4 votes
This, from the comments in `misc/drupal.js`, explains how it's supposed to work:

* Drupal.attachBehaviors is added below to the jQuery ready event and so
* runs on initial page load. Developers implementing AHAH/Ajax in their
* solutions should also call this function after new page content has been
* loaded, feeding in an element to be processed, in order to attach all
* behaviors to the new content.

# Answer
> 2 votes
Try adding this in Drupal.behavior.b:

```
Drupal.attachBehaviors($(this));

```

---
Tags: 7, javascript
---


# Question
Title: How to know from which country people are accessing my website?
I am using Drupal7. I have a Chinese version of my site and I want to know whether they are using it or not. So I want to know which countries are using my website.

I tried to find that out like this -\> if I go to the Reports\>\>Recent Hits then I find the hostname for the anonymous users.

I found some website that tells the country name taking the host IP address as input.

Is there any module that shows country from which the website got accessed?

# Answer
You do not need a module for that. Simply make use of any web analytics system such as Google analytics, Piwik analytics and such like.
> 2 votes

---
Tags: 7, log-messages
---


# Question
Title: How to add extra new term into multiple nodes
I got 100 nodes. They all have Term reference field. 50 nodes are set to term 'A' and other 50 to term 'B'. So with that it helps me to filter those nodes via Views to display A nodes in one page and display B nodes in other page.

So now there's an update needed to be done. All those 100 nodes has to have a new term selected 'C' (A and B stays selected as it is). So all A's has to have now C and same with B's.

So how do I do that instead of going through all 100 nodes single by single and selecting it manually?

# Answer
1. Install the Views Bulk Operations module.
2. Create a view and add a filter to view nodes having term *a* and *b*.
3. add a *Bulk operations: Content* field and in the field settings under *SELECTED BULK OPERATIONS* select *Modify entity values*.
4. Save the view and from the *Operations* list, select *Modify Entity Values*. Choose the term field you want to add the terms to, and then select the terms you want to add
5. Select the *Add new value(s) to FIELD, instead of overwriting the existing values* check box and Submit the form.
> 3 votes

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


# Question
Title: User profile view - 2 x variants or view panes with args?
I've overridden the User profile template to display custom fields for the user view in Panels, I need to have a View listing with a filter of user comments by 'date' or 'conversation' this I am comfortable with only problem is the filter results list very different info. My approach in resolving this is to have two separate views and create two dynamic links to filter by 'date' or 'conversation'.

I know I can create two variants within the one panel or alternatively two separate panel panes which can accept arguments; only problem is Im not sure what to pass to have one panel pane or panel variant override the other. So when user clicks on 'date' variant x loads when user clicks on 'conversation' variant y loads, or something like that..

Do I achieve this using 'selection rule', 'contexts' or what? Please help...

# Answer
> 0 votes
You can either use two variants or different view panes on the same variant. It is just an organizational choice.

If you use two variants, use *Selection rules* to distinguish them. For example, on one of my sites, I have two variants for the user profile, depending on whether the logged in user is viewing his/her own profile or another user's profile. I distinguish between these two variants using a *Selection rule* of `logged in user != user being viewed`.

Alternately, within the same variant, you can use multiple content panes (created in Views). You can choose which of these are shown by clicking in the upper right corner of the respective pane (within the Panels UI) and adding *Visibility rules*. Why would you use this approach? If you only have a few panes. In my case, I used two variants instead because I had about twenty different view panes on the user profiles, and it was simpler to set two *Selection rules* then 20 *Visibility rules*.

So in short, my recommendation is: **Use different variants with selection rules when you have lots of different items. Use a single variant with visibility rules when you only have a few items.**

---
Tags: views, users, panels
---


# Question
Title: How to install a text filter for plain_text input format
The users at my Drupal 7 website discuss a card game in plain\_text comments and I'd like to format the hearts and diamonds characters by red color.

Based on the Examples module recommended to me here at "Drupal Answers" site I've added the following code to my custom module **sites/default/modules/pref/pref.module**:

```
function pref_block_view($block_name = '') {
       ... this other part of my custom module works well ...
}

function pref_filter_info() {
  $filters['plain_text'] = array(
    'title' => t('Pref filter'),
    'description' => t('Replace the ♠ ♣ ♦ ♥ characters'),
    'process callback' => '_pref_filter_process',
  );
  return $filters;
}

function _pref_filter_process($text, $filter) {
  $text = str_replace('♦', '<font color="red">♦</font>', $text);
  $text = str_replace('♥', '<font color="red">♥</font>', $text);
  return $text;
}

```

However still nothing is highlighted in comments.

The rest of my custom module works fine (it generates few blocks - for the Flash game and player rating).

How to register my filter for the `plain_text` please? I suspect that

```
 $filters['plain_text'] = array( ... );

```

is a wrong way.

# Answer
> 3 votes
Do it in GUI. http://example.org/admin/config/content/formats/plain\_text

Check it in **Enabled filters** section and then make sure it's the last one in **Filter processing order** section. If you'll put it before *Display any HTML as plain text*, your tags will get added and then in the very next step removed.

Also, `<font>` tag may be removed by HTML cleaning modules. Modern way is to make it like `<span class="red-card">` and then style it in CSS. Actually, it might be a wise idea to add `<span class="black-card">` as well, and maybe "card" class for both, and respective classes for clubs, spades, hearts and diamonds. That way you will be able to style them differently or even use image substitution, if you wish - all in CSS.

You can provide default CSS in your module. In `mymodule.info` add line:

```
stylesheets[all][] = css/cards.css

```

Create that file in `mymodule/css` directory and place all styles there. That way they will be there, and themes will be able to override them in their own CSS files.

---
Tags: 7, hooks, input-formats
---


# Question
Title: How to modify the comment body while in comment.tpl.php
At a Drupal 7 website dedicated to a card game I'm trying to color the special characters for hearts and diamonds in all plain\_text comments red.

Since I haven't found the way to modify the text filter yet, I'm trying to "hack" the file **themes/bartik/templates/comment.tpl.php** as workaround by inserting the 5 lines below:

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

    $body = $comment->comment_body[LANGUAGE_NONE][0]['value'];
    $body =  str_replace('♦', '<font color="red">♦</font>', $body);
    $body =  str_replace('♥', '<font color="red">♥</font>', $body);
    print "\n<!--\n" . $body . "\n-->\n";
    $comment->comment_body[LANGUAGE_NONE][0]['value'] = $body;

    print render($content);
  ?>

```

In the HTML comment between `<!--` and `-->` above I can see that the string substitution has worked okay.

But the comment itself isn't modified.

I've tried modifying both `$comment->comment_body[LANGUAGE_NONE][0]['value']` and `$comment->comment_body[LANGUAGE_NONE][0]['safe_value']` but the comment is still unchanged.

I've studied the output of `print_r($content)` and `var_dump($content)` but still can't figure out how to modify the comment body.

# Answer
> 1 votes
If you insist, you can always go like that:

```
 print str_replace(
   array('♦','♥'),
   array('<font color="red">♦</font>', '<font color="red">♥</font>'),
   render($content)
 );

```

But instead of deprecated `<font>`, use `<span class="">` and CSS. Consider classes for all 4 colours, for black and red, and for card marks altogether, for future styling ease.

# Answer
> 1 votes
I would suggest you don't modify the comment in the template file because that is not what the template file is for. It is for changing the way content displays, not changing the content itself.

One step better is to use the preprocessor function:

```
function THEMENAME_preprocess_comment(&$variables) {
  // Modify the variables here, before they get printed in the template.
  // The content that prints out is in $variables['content'].
}

```

However that isn't ideal either.

I would say the best solution would involve a custom module.

You can use hook\_comment\_view() to modify the $comment variable like this:

```
function MODULENAME_comment_view($comment, $view_mode, $langcode) {
  // Modify the $comment variable here.
}

```

---
Tags: 7, comments
---


# Question
Title: Add a JOIN with a subquery into a views query
Here's my SQL, which I am trying to include in `hook_views_query_alter()` to modify the `uc_catalog` view (from Ubercart 3):

```
JOIN (
   SELECT uc_products.nid, MIN(uc_products.sell_price) AS min_price
   FROM uc_products
   JOIN node as n ON n.nid = uc_products.nid
   WHERE uc_products.nid IN
   (
     # in an ideal world, this is the WHERE statement from my views query
     SELECT ti.nid AS nid
     FROM taxonomy_index ti
     WHERE ti.tid = :db_condition_placeholder_1
     AND n.status = :db_condition_placeholder_2
     AND n.type IN :db_condition_placeholder_3
     GROUP BY uc_products.model
   )
 ) AS s2
 ON node.nid = s2.nid AND uc_products.sell_price = s2.min_price

```

I am confused as to how to make this work with the tools in views\_plugin\_query\_default since this SQL has a subquery, etc. that is more complex than a simple `JOIN` statement. I am having a hard time conceptualizing using `add_relationship` or `add_table` to make this work. Is there something about `$join` building I don't understand.

# Answer
After some work this problem was solved with the Views Field View module.
> 1 votes

---
Tags: 7, database, views
---


# Question
Title: How to print all the elements of a specific column from a table from database in custom module?
I have a custom module. I would like to see all the blocks in it . For that i have written a query in my costom.module file . But it will show me the following error.

```
Query:-

 $result = db_query('SELECT *FROM  `block` ORDER BY
`block`.`delta` ASC LIMIT 0 , 30');
 while ($node = db_fetch_object($result)) {
 print_r("$result");
 }

```

Why this is not working, Where am i going wrong ?

# Answer
You made 4 errors:

1. You should use {} around table names, not \`\`.
2. print\_r does not like objects Drupal uses, for testing purposes it's way better to use

while($row = $result-\>fetchAssoc() ){ }
3. $node may be already used elsewhere, it's not wise to use common names if you don't mean it.
4. `SELECT *FROM` should be `SELECT * FROM` (kudos for Clive)
> 1 votes

---
Tags: 7, database
---


# Question
Title: How to truncating url at the word instead of limit
**Background info**: By default, Pathauto has a maximum alias length is 100.

**Request**: It would be nice if this could truncate at the last space before the limit, instead of truncating directly at the limit, so that there are no partial words in the URL.

What is the easiest way to do this Drupal?

# Answer
The pathauto module uses the core function `truncate_utf8()` to truncate the alias. This call by pathauto uses `$wordsafe=TRUE` in the call to preserve word boundaries.

If you are seeing partial words in the path, this is a core issue for `truncate_utf8`, not a pathauto issue.
> 1 votes

---
Tags: path-aliases
---


# Question
Title: How can i prevent field display on sign up while using profile 2 module
In my site, I used the profile 2 module to add some fields to the registration/sign up page. Is there a way to exclude some of these newly added fields from being displayed at sign up, so that a new user will only see them when he wants to edit his/her profile ?

Thank you.

# Answer
If you go to admin/structure/profiles and click on Edit for the desired profile type, you can configure these settings.

Simply uncheck *Show during user account registration*. You can even eliminate the profile from the account page by checking *Provide a separate page for editing profiles.* .

If you want to restrict access to particular fields only, use the Field Permissions module and set the *View* permissions on the selected fields to **Authenticated user**. On registration the user is still **Anonymous**, and will not be able to see the fields.
> 1 votes

---
Tags: users
---


title: list field type

text:
# Question
Title: list field type
I'm trying to add a new field to a product to the Drupal Commerce module. The field should be a select dropdown but the only field type I could find that would do that was term reference. So I googled and I found the documentation for a list module that does exactly what I want. The sad part is I can't find the project page for this module in order to download it.

Does anyone know how I can use this module, or if there is anything similar?

# Answer
> 2 votes
Isn't this part of drupal 7 core?

# Answer
> 1 votes
If you are using Drupal 7, the List Module described has been incorporated into core as part of the Field module. The options shown in the documentation are available when you add a field to a content type under the *Manage Fields* tab.

---
Tags: entities
---


# Question
Title: Action attribute in forms is not a url. Why?
When I check the action attribute of a drupal form, I never see a valid URL. What I see in the html code is a simple string, which usually matches the node title of the form. Given that the action attribute should contain a valid URL pointing to a server-side script, I am really confused! What are the mechanics behind the form's submission? Thanks in advance for your answers!

# Answer
If you look again, I would hazard a guess that you are using pathauto, and that the default pattern for Webform paths is `[node:title]`. If you set it to `form/[node:title]` then the action attribute would look more like a path. eg. *My Form* would have an action attribute of `action="/form/my-form"`.

In Drupal everything goes through the Drupal bootstrap. There are no calls to cgi-bin or the equivalent. Rendering a form or processing a form are done by calling the same url, which tells Drupal where to look for the form. What Drupal does depends upon the op associated with the call, and the rendering, validation, processing and storage are all defined by the modules underlying the form.
> 0 votes

# Answer
Do you have Clean Urls enabled? (admin/config/search/clean-urls)

If it can (dependent on web server used) Drupal likes to re-write its URLs to be more meaningful and human readable, so what you see in the action of a form is not the REAL URL that drupal is going to "receive" when the form is POSTed.
> 0 votes

---
Tags: forms, uri
---


# Question
Title: Primary and secondary zone's links in drupal 7
This is my website in drupal 7. The page at `http://150.254.36.80/wige/kandydaci/aktualnosci` shows the following header.

I would like that "kandydaci" in this white menu will be active (black lighted) in every page in this zone, for example on `http://150.254.36.80/wige/kandydaci/o-wydziale`.

We are in the "kandydaci" zone, but the white menu doesn't show it.

# Answer
> 0 votes
You can use the Menu Position module to accomplish this.

After installing:

1. Visit /admin/structure/menu-position
2. Click "Add menu position rule"
3. Select the parent menu item "kandydaci"
4. Add a page restriction for "kandydaci/\*"

This should keep the "kandydaci" menu link active on the correct pages.

---
Tags: routes, navigation
---


# Question
Title: Is it possible to turn on/off two layers at once with the openlayers_plus module?
Using the BlockSwitcher module that comes with the openlayers\_plus module, is it possible to create a button that turns on/off two layers at once?

# Answer
> 0 votes
I think the best way to do this would be to create a function that uses setVisibility()

For example (without toggle logic):

```
$('.my-button').click(function(e) {
  e.preventDefault();
  var ol = $('.openlayers-map').data('openlayers');
  ol.openlayers.getLayersByName('myLayerName1')[0].setVisibility(false);
  ol.openlayers.getLayersByName('myLayerName2')[0].setVisibility(false);
});

```

---
Tags: blocks, javascript
---