# Question
Title: HDI display the human readable node type at the end of the breadcrumb
I want to modify the default breadcrumb to append the machine readable string of the current node type to the breadcrumb. I believe I can do this via template.php.

I am using drupal 7.

# Answer
> 0 votes
I'm not used to doing stuff in the theme layer, so my solution would be to use a module. Have you seen this one: http://drupal.org/project/custom\_breadcrumbs ? I think it would allow you to do what you want.

---
Tags: theming
---


# Question
Title: A module to limit number of posts a user can make during a set period of time?
I have a number of sites that allows users to post nodes and comments, however bots are getting a hold of these and having their way with my site. I recall seeing a module a while back (but cannot remember it's name) that allows admins to set a time limit between posts. Basically denying posts that made within minutes or seconds of eachother. Any ideas?

# Answer
> 2 votes
Maybe Node limit module can help? I haven't used it but it seems that this may be what you need.

# Answer
> 2 votes
Honeypot seems to be your solution. I discovered it after i used mollom but it seems very useful.

Honeypot uses both the honeypot and timestamp methods of deterring spam bots from completing forms on your Drupal site (read more here). These methods are effective against many spam bots, and are not as intrusive as CAPTCHAs or other methods which punish the user

---
Tags: 7, advertising
---


# Question
Title: Why doesn't adding results in hook_views_pre_render work?
In the docs for hook\_view\_pre\_render http://api.drupal.org/api/views/views.api.php/function/hook\_views\_pre\_render/7 it states "Altering the content can be achieved by editing the items of $view-\>result."

Removing elements from this array is reflected in the final output, but appending to it, rewriting parts of it, or reordering it results in no change to the final output.

Does anyone know what's going on? How do I use this hook to alter or add to the results of the view post-query but before rendering?

# Answer
> 5 votes
Don't know what the deal was with hook\_views\_pre\_render, but adding to the result array works fine in hook\_views\_post\_execute, and accomplishes the same thing.

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


title: Drupal Commerce: Print order?

text:
# Question
Title: Drupal Commerce: Print order?
Is there any module that would give option to print order in commerce?

Im trying to create option to print orders for packaging department but can't find a way that would allow customer details and order line items.

# Answer
Through Rules module you can achieve this:

1. First step create a custom rule at /admin/config/workflow/rules/reaction/add
2. Select the React on event: "Completing the checkout process"
3. Add a new Action: "Send mail"
4. Once you add the email addresses from/to, than add the replacement fields in the body text of the email. I suggest: \[commerce-order:order-number\], \[commerce-order:type\], \[commerce-order:commerce-line-items\]. But you can figure that part out.

Save your Rule.

Get a Beer and celebrate you are now forwarding new orders to your customer fulfillment department.
> 3 votes

---
Tags: commerce
---


title: Adding Additional login security

text:
# Question
Title: Adding Additional login security
Considering login security for user logins, I would like an additional option such as a PIN option for all aspects of user login. This seems quite common now across a number of portals out there such as personal banking, social security/gov. tax sites and I would like possibly to offer this as an option to those who do not want to use Facebook, Twitter etc logins which I use on my projects. I appreciate it could simply be an additional field in the system config, but I would be keen to hear any comments on such features, or possibily a popular D7 module which most people use which for me as a Drupal 'plumber' can just drop in for easy of setup, or a generalistic 'how-to'.

Thanks in advance.

# Answer
## Is there an existing "pin" login module?

I'm not aware of any module that does this itself. There are some pin-related modules, but most of them are related to using 2-factor authentication authentication.

## Is a pin field actually useful to improve security?

My sense is that adding a pin would not be worth it.

First, pins are easily guessed: this article on commonly used pins shows how only 20 pins would break over 26% of accounts!

Second, if you were to just require the pin to be on the end of the password that actually makes it harder to break than making it a separate field because they would both need to be cracked at the same time rather than serially. That is in addition to the problem above of pins not being well distributed among the 10^4 potential combinations.

Third, you would have to build, audit, and then maintain this additional code for managing per user pins. That's a new database table, some form fields, and at least a few hundred lines of code that can be buggy that overall adds very little extra security.

## Alternate improvements to login security

So, I have some other suggestions on how to improve login security in general:
> 3 votes

---
Tags: security
---


# Question
Title: Why timestamp format was chosen for users.created field
When I looked into users.created field in the database, it says, that is has type int. Does anybody know, why Drupal team chose this format instead of datetime? Cause timestamp will end with the end of UNIX epoch:

http://en.wikipedia.org/wiki/Year\_2038\_problem

As they are setting it to this value:

$account-\>created = REQUEST\_TIME;

http://api.drupal.org/api/drupal/includes!bootstrap.inc/constant/REQUEST\_TIME/7

And datetime is unlimited. So, why was this inferior variant chosen?

# Answer
> 2 votes
Date/time types vary widely among different DB types. The purpose of the Schema API is to achieve some compatibility at the data definition level.

If you see this http://drupal.org/node/159605 the date/time is not supported in some database type.

So I would prefer to go the way the date module does it and use int if you want to make it compatible across multiple database types.

---
Tags: database
---


title: Appoitment Module

text:
# Question
Title: Appoitment Module
I'm working on a site in which I'd like a simple calendar that people can choose a day, then choose a time-slot to schedule an appointment. Pretty simple. Doesn't have to be robust or very configurable. I haven't had any luck in finding something like this. Does anyone know of one that exists?

# Answer
Calendar module with the signup module worked perfect. Signup module is key.
> 1 votes

# Answer
Date module does the job ;)

But if you want more flexible solution can use calendar (as Krister Andersson commented) or Availability Calendars.
> 0 votes

---
Tags: 7
---


# Question
Title: How can I get webform file upload to display a thumbnail instead of a link?
I have a webform with a file field. When I upload the file I want to return a thumbnail of the file.

Is this possible? If so how can I achieve this?

# Answer
> 0 votes
I eventually used a bit of JavaScript to replace the link with an image tag that used the path in the link for it's source.

---
Tags: 7, webforms, files
---


# Question
Title: How to render multiple values of node reference in the form of an ordered list without views?
I have a node reference field that references another node and has multiple values. I want to get an ordered list of the output of that field and display it in the custom node template. I am rendering the node reference as a cck block. Any help or guidance would be greatly appreciated. Thanks.

# Answer
> 0 votes
In D6, you could do something like this:

```
print '<ol>';
foreach ($node->field_whatever as $foo) {
  print '<li>';
    $bar=node_load($foo['nid']);
    print l($bar->title, 'node/' . $bar->nid);
  print '</li>';
}
print '</ol>';

```

In D7 you'd have to throw in the node language stuff and there might even be something more exciting built in as well but I think they all use divs instead of lists. (In both you could also create a content field template for this instead of hardcoding it in your node template)

# Answer
> 0 votes
It sounds like the Text List Formatter module will do what you want.

> This module provides a field display formatter to render field values as HTML or comma-separated lists. This can currently be used on all core field types (text, long text, number, list, and taxonomy reference etc..) and some contributed fields. (see below).
>
> For multi-value fields, each field value becomes a list item. For long text fields, each line becomes a list item.

---
Tags: nodes
---


# Question
Title: Prevent enabling module if private streamwrapper not set
I need to create a subdirectory in the private files folder. I can check if the folder is available with `variable_get('file_private_path', FALSE)` in hook\_install or hook\_enable.

But how can I prevent my module from getting enabled? And preferably, I want hook\_uninstall to run in case this happens so that the user can first setup the private files directory and then try again.

I played with module\_disable and drupal\_uninstall\_modules, but (understandably) those don't seem to work if they target the module they are called from. I'm using Drupal 7.

# Answer
The hook\_requirements(), what do you need.

Implement it your own modules .install phase. Here is an example from one of my module: http://drupalcode.org/project/jquery\_localscroll.git/blob/refs/heads/7.x-1.x:/jquery\_localscroll.install#l20
> 0 votes

---
Tags: 7, hooks, installation
---


# Question
Title: D7 : Views exposed form with three taxonomy term fields as filters (checkboxes)
Any help would be very much appreciated please.

I have a content type named restaurant and I have three taxonomy term fields (cuisines, neighborhoods and occasions) in it. I've created a view to expose these 3 fields as checkboxes for users to search restaurants accordingly.

Cuisines and Neighborhoods are required fields in the node, but not occasions. The problem is that if there is a restaurant that has not been tagged with an occasion, that restaurant will not show in the search results because in my filter criteria, I've selected "is one of" \> all the terms in occasions.

I need help to turn this occasion filter as an optional one, where a node that has not been tagged with an occasion will appear when the user select a cuisine or neighborhood where this node is listed in.

I believe that this can be done via hook\_views\_query\_alter but I don't know how.

# Answer
In your view I would not select any of the occasion field items and allow all the items with or without this field to populate. If the user wants to drill down into restaurants with this information you can have them use the select menu or whatever mechanism to choose the specific occasion. I think that starting off with no filter on the occasion field might be the way to go.
> 0 votes

---
Tags: 7, views
---


# Question
Title: Module/code to automatically generate an id number for title of page
I want to automatically generate a project id. (To go where the title would go on a drupal webpage)

I am guessing this might be possible with php? But i don't know whether it is possible to do it for a title because I have only managed to acheive php in the code.

I want the title to identify a project and each project to have sub cases (also with unique identifiers).

I don't want the number to be randomly generated but rather it have some attributes that can be used to determine characteristics about the project.

Ideally, I want t end up with an id which is something like this eg

```
 Ldn101201

```

where ldn is the city 10 is the start month 12 is the start year and 01 is the project number.

Ldn will be inserted because the user opening the project is based in london 1012 will be inserted because this was the date when the project was made and the last number will be the generated number tagged on.

I really would be happy if I can at least get an ascending ids for when projects are created but if anyone has ideas about the more complicated part that would be great help also.

Hope that makes sense.

# Answer
> 2 votes
Have you seen the Automatic Nodetitles module? From the description:

> "auto\_nodetitle" is a small and efficient module that allows hiding of the content title field in the form. To prevent empty content title fields one can configure it to generate the title by a given pattern.
>
> When the token module is installed it's possible to use various node data for the auto generated title - e.g. use the text of a CCK field (since 5.x).
>
> Advanced users can also provide some PHP code, that is used for automatically generating an appropriate title.

---
Tags: 7
---


# Question
Title: Can you dynamically request a (cached &) scaled image via imagecache in css?
Is there a way to request a scaled image via imagecache by adding width/height parameters or a preset-reference to the image url within css? For example:

Obviously, to scale down an image in css, you can do the following:

HTML:

```
<figure id="logo"></figure>

```

CSS:

```
#logo {
  background: url('path/to/image.jpg') no-repeat;
  width: 50%;
  height: 50%
}

```

This will still load the full sized image and scale it down on the client side. I am wondering if something like the following is possible within CSS, so you dynamically request a scaled image via imagecache:

```
#logo {
  background: url('path/to/image.jpg?width=50px&height=50px') no-repeat;
}

```

or

```
#logo {
  background: url('path/to/image.jpg?preset=existingimgpreset') no-repeat;
}

```

Which will scale down the image on the server side and hopefully will return a cached version of it when possible.

# Answer
The URLs imagecache produces are pretty reliable, and contain the name of the preset. Looking at the code in `imagecache_create_url()` you could build up a path in your CSS that looks something like this:

```
/sites/default/files/imagecache/preset-name/path/to/image.jpg

```

Assuming that your files are stored at /sites/default/files
> 3 votes

---
Tags: 6, theming, media
---


# Question
Title: Add Commerce Checkout progress bar and extra stage
I believe as such there is no template file for checkout? So how I want to add the following graphical navigation to the top of commerce checkout?

Can i target checkout with a page.tpl.php? Alternatively a hook in template.php?

At each stage/page of checkout the navigation images will change.

# Answer
> 2 votes
You want the Commerce Checkout Progress module.

---
Tags: 7, commerce
---


# Question
Title: Database administration site on Drupal: entities vs. manual programming
I've been asked to build a small database administration site based on Drupal. The site should have basic editing possibilities of the existing database with several tables. (The structure is not complicated).

To get it more clear, one table contains books being sold in the publishing center. The book has a set of identification numbers, title, e.g. The structure of book is very similar to basic node with fields.

The question is: Is it a good idea creating a custom entity with described architecture and process data in terms of 'book' entity (and therefore the database will be automatically modified according to current architecture) OR it's better to implement simply some interface and update database manually using db\_query etc. ?

# Answer
> 4 votes
While I can't see any significant benefits to doing this with Drupal, I think this should generally work. I've converted old systems that were using db\_query and custom code to Drupal 7 Entities with the Entity API module with success, and I've been pretty pleased with the results. As long as the schema is solid, without issues, or you can modify it as needed, this will work fine.

Depending on the data structures and the normalization of related entities/properties you may need to create your own EntityController to override the loading (and saving if using Entity API module) to ensure that the data is queried and updated properly.

---
Tags: entities
---


title: Fieldable entity issue

text:
# Question
Title: Fieldable entity issue
I currently have an event entity, which is fieldable. My question is, how do I make it appear under admin/structure, and how can I access the Manage Fields page from the admin menu? Is there a tutorial on this? Any help is highly appreciated since I could not find anything related.

# Answer
> 2 votes
You'll need to provide a menu item and page that lists information about your entity type (typically settings). If you provide multiple bundles you'll need to provide a page for each bundle.

After you've done that you can add a simple snippet to your hook\_entity\_info similar to the foreach loop at the bottom of node\_entity\_info(). Specifying the 'admin' info under your bundles will provide the "Manage Fields" and "Manage Display" tabs for the path specified. Note that if you do not have multiple bundles, the only two required keys under the 'admin' section are 'path' and 'access arguments'

Keep in mind that the path referenced in the \['bundles'\]\[BUNDLE\_NAME\]\['admin'\]\['path'\] section has to exist and be defined elsewhere in your hook\_menu. Field module will only take care of the two tabs and the pages they link to.

---
Tags: entities
---


# Question
Title: How to list most viewed nodes using Statistics module?
How to list most viewed nodes using Statistics module in Drupal 6?

I'm looking for the PHP code to use in a custom theme.

# Answer
> 0 votes
I should have enabled this feature in admin panel before using the following code:

```
$number_of_hot = '10';
$hot_result = db_query_range("SELECT nid FROM {node_counter} ORDER BY totalcount DESC", array(), 0, $number_of_hot);
while ($hotid = db_result($hot_result)) {
$hot = node_load($hotid);
print $hot->title;
}

```

---
Tags: 6, theming, nodes
---


# Question
Title: Prepopulate node-add form with search terms?
I would like users to be able to create band profiles (which will be a content type), and then those profiles will be associated with their user accounts via Entity Reference. However, I only want one profile per band, so I don't want each member of the band to be able to create a page for the band (but I'd like to have all members of the band be able to be related to the band page via Entity Reference).

So, before a user is able to create a band profile, I want them to search current bands on the site (either via Views or Search API, not sure which yet...probably whichever method allows me to solve the issue below). If the band does exist, then the user will select it and a reference will be created. However, if a profile for the band does not yet exist, I want the user to be presented with a link to the node add page to create a band.

This is where my question comes in. When a user creates a new band, how can I populate the node-add form with the terms that they searched for to begin with? So if a user searches for a band from "San Diego, CA" called "The Band", how can I populate the creation form with "San Diego, CA" and "The Band" without him having to enter the information again on his own?

# Answer
I don't know of a module that solves exactly the problem you're describing out of the box, but you might be able to come close with Entity Reference View Widget and/or Node Reference URL Widget.
> 1 votes

# Answer
You can achieve using following hook\_form\_alter() steps:

**1.** In the **hook\_form\_alter()** function get the entities in which logged in user is referenced, this can be achieved by using the the view which i shown below. Get the query of the view and check whether logged in user is referenced in any band content type or not.

**2.** If any user is referenced in any node of Band content type then don't display node form and return directly

**3.** If user is not referenced then display content creation form of **Band** node type

In the following view i have kept field\_referenced\_users field which contains the referenced users in nodes. So change your field accordingly. Just import the below view and get the query, use this query in **hook\_form\_alter()** and check it. I have created view for **article** node type. You can change it accordingly.

```
$handler = $view->new_display('default', 'Master', 'default');
$handler->display->display_options['title'] = 'Entities in Which Logged in User is Referenced';
$handler->display->display_options['use_more_always'] = FALSE;
$handler->display->display_options['access']['type'] = 'perm';
$handler->display->display_options['cache']['type'] = 'none';
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['exposed_form']['type'] = 'basic';
$handler->display->display_options['pager']['type'] = 'full';
$handler->display->display_options['pager']['options']['items_per_page'] = '10';
$handler->display->display_options['style_plugin'] = 'default';
$handler->display->display_options['row_plugin'] = 'node';
/* Sort criterion: Content: Post date */
$handler->display->display_options['sorts']['created']['id'] = 'created';
$handler->display->display_options['sorts']['created']['table'] = 'node';
$handler->display->display_options['sorts']['created']['field'] = 'created';
$handler->display->display_options['sorts']['created']['order'] = 'DESC';
/* Contextual filter: Content: Referenced users (field_referenced_users) */
$handler->display->display_options['arguments']['field_referenced_users_target_id']['id'] = 'field_referenced_users_target_id';
$handler->display->display_options['arguments']['field_referenced_users_target_id']['table'] = 'field_data_field_referenced_users';
$handler->display->display_options['arguments']['field_referenced_users_target_id']['field'] = 'field_referenced_users_target_id';
$handler->display->display_options['arguments']['field_referenced_users_target_id']['default_action'] = 'default';
$handler->display->display_options['arguments']['field_referenced_users_target_id']['default_argument_type'] = 'current_user';
$handler->display->display_options['arguments']['field_referenced_users_target_id']['summary']['number_of_records'] = '0';
$handler->display->display_options['arguments']['field_referenced_users_target_id']['summary']['format'] = 'default_summary';
$handler->display->display_options['arguments']['field_referenced_users_target_id']['summary_options']['items_per_page'] = '25';
/* Filter criterion: Content: Type */
$handler->display->display_options['filters']['type']['id'] = 'type';
$handler->display->display_options['filters']['type']['table'] = 'node';
$handler->display->display_options['filters']['type']['field'] = 'type';
$handler->display->display_options['filters']['type']['value'] = array(
  'article' => 'article',
  'page' => 'page',
);
$handler->display->display_options['filters']['type']['group'] = 1;

/* Display: Page */
$handler = $view->new_display('page', 'Page', 'page');
$handler->display->display_options['defaults']['hide_admin_links'] = FALSE;

$handler->display->display_options['path'] = 'users-referenced-entity';

```
> 0 votes

---
Tags: views, nodes, search
---


title: Adding parameters to $header links

text:
# Question
Title: Adding parameters to $header links
Is there a way we can specify which link to use to sort a drupal table, or atleast, specify some parameters to the header links?

To be more clear, my table uses the following link when I click on the headers to sort the table: http://mysite.com/node?sort=asc&order=Name

What I would like the header link to look like is this: http://mysite.com/node?nid=123&pager\_element\_id=3&sort=desc&order=Name

Is there any way we can give the parameters to the header links?

# Answer
> 0 votes
The code that outputs the links for the table header is contained in tablesort\_header().

```
$cell['data'] = l($cell['data'] . $image, $_GET['q'], array('attributes' => array('title' => $title), 'query' => array_merge($ts['query'], array('sort' => $ts['sort'], 'order' => $cell['data'])), 'html' => TRUE));

```

The function is called from theme\_table(), which is the theme function used to render a table.

What you can do is implementing your theme function that is then used to render the table your module is outputting. There isn't any other method, as `theme_table()` is not getting any parameter that changes the URL for the table header; as such, implementing `hook_preprocess_table()` would not achieve anything.

To implement a theme function, you need to declare it using hook\_theme().

```
function mymodule_theme($existing, $type, $theme, $path) {
  return array(
    'mymodule_table' => array(
      'variables' => array('header' => NULL, 'rows' => NULL, 'attributes' => array(), 'caption' => NULL, 'colgroups' => array(), 'sticky' => TRUE, 'empty' => ''),
    ),
  );
}

```

Once you declared the theme function, you can use it as you used `theme_table()`, simply replacing any call to `theme('table', /* the rest of the arguments */)` with `theme('mymodule_table', /* the rest of the arguments */)`. Notice that in `hook_theme()` the theme function is referred as mymodule\_table, but the PHP function is `theme_mymodule_table()`.

The code you need for your theme function is the same used by `theme_table()`, except that instead of calling `tablesort_header()` it will call your own function.

```
foreach ($header as $cell) {
  $cell = tablesort_header($cell, $header, $ts); // Replace it with the call to your function.
  $output .= _theme_table_cell($cell, TRUE);
}

```

---
Tags: theming
---


# Question
Title: Preventing frequently updated nodes from keeping them on the top of View
I have a view that lists content profile node and set the `sort criteria` to `node:Updated date`.

However, the problem is that some of the users updates their content profile node everyday to keep it on the top of the list.

I need to user `sort criteria` to `node:Updated date` but is there any way to prevent their nodes from being on the top of view?

Lest's say for example, within one week after their last update even if they update it again it stays where it is now and doesn't get to the top or somthing.

# Answer
Not possible using views out of the box! Because updated date is stored as a single value in the database. If a user updates again the new value overrides old value.

So, there is no way views can track ***within one week after their last update even if they update it again*** .

You need to use hook\_nodeapi either to track all updates in separate table and query that table to list users.
> 0 votes

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


# Question
Title: is there a way to find out which quicktab tab is active?
I would like to know which tab is active so I can set it to default until another tab is active then that will be set to default

my problem is that I cant seem to find a way to see which tab is active at the moment and getActiveTab seems to always return the default tab

any help well be greatly appreciated

thanks in advance

# Answer
> 3 votes
After much consideration and a ton of tries I decided to go with cookies,I added this to my script file from http://drupal.org/node/1454486

```
Drupal.behaviors.quicktabsHistory = {
attach: function(context, settings) {
  // enable accordion memory
  $('.quick-accordion', context).each(function() {
    var id = $(this).attr('id');
    var accordion = $.cookie(id);

    if (accordion != '') {
      $(this).find('h3 a[href="' + accordion + '"]').click();
    }
    $(this).find('h3 a').click(function() {
      $.cookie(id, $(this).attr('href'));
    });
  });

  // enable tab memory
  $('.quicktabs-wrapper', context).each(function() {
    var id = $(this).attr('id');
    var tab = $.cookie(id);

    if (tab != '') {
      $(this).find('ul.quicktabs-tabs a#' + tab).click();
    }
    $(this).find('ul.quicktabs-tabs a').click(function() {
      $.cookie(id, $(this).attr('id'));
    });
  });
}
};

```

thanks for your time and efforts

---
Tags: blocks
---


# Question
Title: Changed my theme name without disabling it. Can't re-enable, please help
Like an proper idiot I changed my theme name using .info file without disabling it first in the admin area. Now, I cannot re-enable as it does not show in the Appearance part of the administration area.

I have already tried resetting to the default garland theme and clearing all the caches to no avail. Any idea on how I could fix this?

I am using Drupal 7 and Omega as the base theme.

# Answer
> 1 votes
You probably forgot to change folder name where theme is located.

Also see if you have changed all occurances of theme name in .info file.

It would be good also if you change name occurances in template files of that theme (template.php)

---
Tags: theming
---


# Question
Title: should I use str_replace() or is there a better drupal way for that?
Some background info: I'm Building a D7 module that also sends out a message to users of the site. I want the site maintainers to be able to define the message by using 'tokens' like this:

```
$string = "hello :username, there is a new node called :nodenodename_with_a_link on the :website"; // defined in the GUI

```

I could use str\_replace to replace those 'tokens' like so:

```
$find = array(':username', ':nodenodename_with_a_link', ':website');
$replace = array($username, $node, $sitename); // generated form the db
$newstring = str_replace($find, $replace, $string);

```

But I'm wondering if this is also the correct way to go in Drupal (7)?

# Answer
> 2 votes
You can either create your own tokens in a custom module or use `strtr` (it's easier for multiple search and replace operations than str\_replace).

To see how to create custom tokens and integrate with token module see `token_example` module in Examples.

---
Tags: tokens
---


# Question
Title: Changing the target path of a Views more link
Drupal 6, Views 2.

I would like the "View" link to point somewhere completely different than it normally does.

I've implemented `hook_views_pre_render()` and dug around in the `$view` object, but I can't seem to find the path in there.

How can I change the "View" link?

# Answer
> 3 votes
If all else fails, just edit the views template. Go into the views theming information and select the template and edit the more link for it. It would be named along the lines of `views-view--MYVIEWNAME--MYVIEWDISPLAYNAME.tpl.php` and inside you can edit the more link area in the template. (There is also a `more` template you can modify but I've not done it that way before)

```
<div class = "more-link">' .
l(
  t('See more'),
  'internal/path/' . $view->args[0],
  array('options' => array('HTML' => TRUE))
) .
'</div>';

```

# Answer
> 6 votes
I used this method (views 3.x):

```
 <?php
 // get the $view object somehow and alter the display_handler options
 // see views_plugin_display.inc ~ render_more_link() method
 $view->display_handler->set_option('link_display', 'custom_url');
 $view->display_handler->set_option('link_url', 'node/!1/somewhere');

```

# Answer
> 1 votes
Although views templates are very powerful, if all you need is a link, you could just put one in the footer field and use the same css class views does for read more links.

# Answer
> 1 votes
Just building on what was mentioned above (I didn't feel comfortable just editing the original answer).

For Views 3: You can do the following....

* Add a More link with custom text
* Create your views tpl file using hte 'Display' style
* Within the views tpl file change the More code to:

```
if ($more):
    print str_replace('/front', '/latest-news', $more);
endif;

```

*Note:* You will need to add the proper php code around each line (I couldn't figure out how to do that in the editor :(

---
Tags: views
---


# Question
Title: Would using hash_pbkdf2() be more secure than the actual code used from Drupal 7?
Drupal 7 allows a module to implement a different way to create a password hash. It is sufficient the module changes the content of the Drupal variable password\_inc, and implement the required functions in the include file it provides.

If a module would use hash\_pbkdf2(), would the hash would be more secure than the one generated from Drupal 7?

The actual code used to generate a password hash is the following. (The code is part of \_password\_crypt().)

```
  // Convert the base 2 logarithm into an integer.
  $count = 1 << $count_log2;

  // We rely on the hash() function being available in PHP 5.2+.
  $hash = hash($algo, $salt . $password, TRUE);
  do {
    $hash = hash($algo, $hash . $password, TRUE);
  } while (--$count);

```

# Answer
> 5 votes
If you take a look at user\_hash\_password, you can see that the hashing algorithm being used is SHA512. This is something different than the encryption algorithm though, which in its own could use a hashing algorithm.

The way Drupal 7 encrypts passwords actually is PBKDF2, using SHA512.

From Wikipedia:

> PBKDF2 applies a pseudorandom function, such as a cryptographic hash, cipher, or HMAC to the input password or passphrase along with a salt value and repeats the process many times to produce a derived key, which can then be used as a cryptographic key in subsequent operations.

Since lots of passwords can be generated in the blink of an eye by modern hardware, it's all about making an algorithm slow. This means generating rainbow tables becomes more expensive.

The problem with SHA-algorithms is that they can still be generated quite fast on GPUs. Some algorithms, like bcrypt are slow by design, which, in my opinion, means it would be a better fit.

> When the standard was written in 2000, the recommended minimum number of iterations was 1000, but the parameter is intended to be increased over time as CPU speeds increase.

In Drupal 7: assuming DRUPAL\_HASH\_COUNT is being used in the default encryption algorithm, 32768 iterations (1 \<\< 15) would be used to encrypt a password. This means encrypting a password is quite slow, hence more secure (compared to just 1 iteration). You can adjust the count with the password\_count\_log2 variable, with a maximum value of 30 (1073741824 iterations) and a minimum value of 7 (128 iterations).

It's not worth it to change encryption algorithm; just let Drupal do its job.

**Update**: how it's done in D8: https://drupal.org/node/1850524

---
Tags: 7, security, users
---


# Question
Title: Adding a "title" field to video thumbnails in the Video Module
I would like to attach a textfield field to the video field. How can I go about doing that programmatically?

How do you attach a field of a field?

# Answer
> 1 votes
You can use hook\_form\_alter(), there is no any built-in option to do that.

You can also use the Field collection module to create a new field collection with a text field, and the video field.

> Provides a field-collection field, to which any number of fields can be attached.
>
> A field collection is internally represented as an entity, which is embedded in the host entity. Thus, if desired field collections may be viewed and edited separately too.

# Answer
> 0 votes
You can implement hook\_field\_widget\_form\_alter() to add a `#process` function to the widget. This is what the Image field does in image\_field\_widget\_form(), by adding image\_field\_widget\_process() as `#process` function.

```
// Add all extra functionality provided by the image widget.
$elements[$delta]['#process'][] = 'image_field_widget_process';

```

If you need to save the content of the form field you add, and the field doesn't provide a database field to save it, there is nothing much you can do, until No hook\_field\_schema\_alter() gets implemented for Drupal 7 too.

---
Tags: 7, entities, files
---


# Question
Title: How can I get the name of the currently logged in user in Drupal 7?
I need to display the full name of the user logged into my Drupal 7 site.

How can I do this? Where should I make the changes? I don't need PHP filter module to write a PHP line to enable as it block.

Please give me a good solution to get the logged in user's name at the top right hand side.

# Answer
> 3 votes
```
<?php
global $user;
print $user->name;
?>

```

These are other attributes which you can get form $user object.

Just refer this link for your updated question: http://www.victheme.com/blog/drupal-7-creating-horizontal-login-bar-without-module

---
Tags: 7
---


# Question
Title: prevent drupal from redirecting to created nodes
as you know after publishing a node Drupal redirects to that node. How Can I change this functionality ? I want to force it to stay on the same page or maybe redirect it admin page instead of nodes.

# Answer
> 3 votes
You can use rules to achieve this easily, here:

Add a new rule and give it a name.

**Event:**

After saving new content

**Conditions:**

Content is of type - and chose your content type you want this rule to react on.

**Actions:**

Page redirect - and enter your destination.

here is an export of a rule that will redirect to homepage after insert a new node of type article.

```
{ "rules_test" : {
    "LABEL" : "test",
    "PLUGIN" : "reaction rule",
    "REQUIRES" : [ "rules" ],
    "ON" : [ "node_insert" ],
    "IF" : [
      { "node_is_of_type" : { "node" : [ "node" ], "type" : { "value" : { "article" : "article" } } } }
    ],
    "DO" : [ { "redirect" : { "url" : "\u003Cfront\u003E" } } ]
  }
}

```

---
Tags: 6, theming, nodes
---


# Question
Title: Using db_query() or db_select() to connect to multiple databases
How can I execute a query that connects to different databases?

I have the following query, and I need to rewrite it for Drupal.

```
SELECT a.empid, b.empname FROM db1..empidmaster a, db2..emplist b
WHERE a.empid = b.empid

```

How can I rewrite the query using `db_query()`, or `db_select()`?

# Answer
If the settings.php file defines the information to connect to the other database as `$databases['extra']['default']`, then you can use the following code, which is possible because SelectQuery::join() accepts also another `SelectQuery` object as `$table` argument.

```
$subquery = Database::getConnection('default', 'extra')->select('emplist', 'b');
$query = db_select('empidmaster', 'a');
$query->join($subquery, 'b', 'b.empid = a.empid');
$query->addField('a', 'empid');
$query->addField('b', 'empname');

```

A better code would be similar to the following one. In this case the alias used for the table used for the subquery is the one returned from `SelectQuery::join()`.

```
$subquery = Database::getConnection('default', 'extra')->select('emplist', 'b');
$query = db_select('empidmaster', 'a');
$alias = $query->join($subquery, 'b', '%alias.empid = a.empid');
$query->addField('a', 'empid');
$query->addField($alias, 'empname');

```

`SelectQuery::join()`, and `SelectQuery::addField()` don't return the `$query` object; that is the reason you cannot the following code.

```
$query = db_select('empidmaster', 'a')
  ->join($subquery, 'b', 'b.empid = a.empid')
  ->addField('a', 'empid')
  ->addField('b', 'empname');

```

PHP would return an error about a method not being called on an object. In fact, `SelectQuery::join()` and `SelectQuery::addField()` return a string: the alias for the table, or the field.
> 9 votes

# Answer
If both database are in the same server and same user, you can do this:

`db_query("SELECT a.empid, b.empname FROM {empidmaster} a JOIN database2.emplist b ON b.empid = a.empid");`

Table `a` represents drupal database, and `b`, the external database.
> 2 votes

---
Tags: 7, database
---


# Question
Title: Is it possible to build a site without Users and Node?
It's hard for me to imagine any site that could be built without the Users and Node modules. Having them as modules makes it possible to replace them with alternatives, I suppose, but they are so fundamental to how Drupal works that I would suspect that anyone who wants different behavior would probably just skip Drupal altogether, since replacing these might break most of the other modules you might use.

Is it possible to build a Drupal site without Node and Users? Has it actually been done, or is it just a *theoretical* possibility?

# Answer
With Drupal 7 and a reasonable amount of effort, I don't actually believe it's possible.

Drupal 8 however will further decouple the modules, so that you can (hopefully) truly build a site without it.

A good use case for disabling `User`, is as a security hardening mechanism. Have your production site completely disallow logging in by not having the module, and push content from an internal stage environment instead with the help of something like Deploy.

A good use case for disabling `Node` could be a file handling API. One would need the file entity, but then only communicate with the world through a REST based API. No nodes (or even theme) needed.
> 5 votes

---
Tags: nodes, users
---


title: Entity reference field in a block

text:
# Question
Title: Entity reference field in a block
So I have a custom content type where I use an entity reference to store a node and then display it a a teaser on a page.

I now want to achieve a similar thing with a block. I've create a basic block module where it outputs HTML, but now want to allow a user to configure it in admin.

I want to create a select list in the configuration where a user can choose a node of content type 'X' and it will save this preference. Then in the block module view I want to retrieve this value.

How would I go about this?

# Answer
Something along the lines of Bean or Boxes would probably be your best options (assuming one of the many Node in block modules aren't good enough).

I've got more experience with Bean, so I'll give a general idea based on that.

Both modules allow blocks to be created as fieldable entities. You should simply be able to add an entity reference field as one of the fields on your block and set it up to display in exactly the same way as you currently do with your node/entity reference combo.

Looking through the issue queue, these modules *may* merge at some point, but I couldn't see anything that says which one is better. My personal preference is Bean.
> 2 votes

---
Tags: 7, blocks
---


# Question
Title: Load existing form and use hook_form_alter to create a custom submit handler?
I have an existing webform in admin and I want to now render that form on other pages. I have a template page *node--download\_resource\_protected.tpl* that prints a hidden CSS pop-up box onto pages that show a teaser for content type *Download Resource - Protected*. When you click on the teaser, this pop-up shows. It currently includes a static form, asking for data-input before access to the download is allowed. See the screenshot here:

Now in place of this static form I want to render an existing webform with the API. The two teasers on the are defined as entity reference fields: Call to Action 1 and Call to Action 2.

After successful completion of the webform I want to post the data to the node URL of the teaser. For example if the page is displaying a teaser of node 34: the user clicks the teaser and the pop-up appears (this already happends), within the popup a webform is rendered (in place of the current static form) and on completion of the form it posts the data and loads URL *node/34* (this needs to be dynamic i.e automatically directing to the correct node URL depending on node\_id of the teaser).

I want to use hook\_form\_alter() to set a custom submit handler like this.

```
 if ($form_id == 'webform_client_form_112') {
    $form['#submit'][] = 'my_custom_submit_handler';
  }

```

But I need to pass the teaser node id in which the block webform was called, to this custom function (this will then allow me to to redirect to the node URL), any ideas?

Thanks for your time!

# Answer
> 3 votes
This is how I'll do it:

* Create the webform adding a hidden field with the default value of %get\[teaser\_node\_id\]
* Load the webform with AJAX from the link node/webform\_nid?teaser\_node\_id=teaser\_nid

Then use `hook_form_alter`:

```
if ($form_id == 'webform_client_form_112') {
  $form['#submit'][] = 'my_custom_submit_handler';
}

```

Now in your submit function you'll know the teaser ID and know where to redirect the user

# Answer
> 3 votes
You can use the 'Available as block ' for webform settings. This option can find at 'form settings'-\>Advanced settings of your webform. Once it enabled you can render this webform block, instead of your static form as follows.

You can define custom submit handler for the webform, ex: $ form\['#submit'\]\[\] = 'my\_custom\_submit\_handler'; in form alter, in that function you can write the necessary code to save and redirect etc;

hope this may help you.

# Answer
> 0 votes
You can pass node id through url and can access using `$node_id = arg(1);` from the submit function

---
Tags: 7, webforms, forms
---


# Question
Title: How to render a Drupal 7 field in stand alone PHP file?
Hi this is probably a really basic question, but hopefully you guys can help me out...

I have a javascript client application (Separate to my main Drupal 7 website) and rather than maintaining a duplicate select list with a large number of values, I would like to use an AJAX call to a PHP file on the Drupal server which will render the HTML for the list I need.

The list is configured as a custom field (Text List type).

Can I create a PHP file in the root of the website, and include the required module files?

An example would be fantastic!

Thanks!

# Answer
> 5 votes
You could definitely bootstrap Drupal in a standalone file, but if you're doing it inside the same document root as the Drupal installation you'd be better off implementing a custom menu path in a module, and using the callback for that path to output the necessary value.

If you print directly from a page callback function and don't return anything, the standard theme wrappers won't be included and you'll just be left with the value you've printed.

A basic example might look like this:

```
function MYMODULE_menu() {
  $items['custom-path'] = array(
    'title' => 'Custom page', // Required, won't actually be displayed anywhere
    'access arguments' => array('access content'),
    // 'access callback' => TRUE, // This is an alternative to the access arguments if you don't need any access control for this path
    'page callback' => 'MYMODULE_ajax_page',
    'type' => MENU_CALLBACK
  );

  return $items;
}

function MYMODULE_ajax_page() {
  $output = function_to_produce_field_output();

  print $output;
}

```

After you clear Drupal's caches any request for http://mysite.com/custom-path should produce the un-themed results from your page callback; you can then use that path as your AJAX callback.

You might also want to look at `drupal_add_http_header()` to set an appropriate content type before you print the output.

As far as getting the field output goes, it's a bit of a pain but this should work:

```
$entity_type = 'user';
$bundle = 'user';
$field_name = 'field_field_name';

// Get field info for the allowed values
$field_info = field_info_field($field_name);

// Get instance info for label/required/description/default value
$field_instance = field_info_instance($entity_type, $field_name, $bundle);

// Build the select list
$select = array(
  '#type' => 'select',
  '#value' => $field_instance['default_value'],
  '#options' => $field_info['settings']['allowed_values'],
  '#required' => $field_instance['required']
);

// Build the element wrapper
$wrapper = array(
  '#title' => t($field_instance['label']),
  '#description' => t($field_instance['description']),
  '#children' => theme('select', array('element' => $select))
);

// Get the fully rendered element
$rendered = theme('form_element', array('element' => $wrapper));

print $rendered;

```

---
Tags: entities, ajax, javascript
---


title: How to Override CSS for a core module?

text:
# Question
Title: How to Override CSS for a core module?
I would like to make some changes to the core toolbar module across all my sites, and I don't want to modify the actual core's css. It looks like I should be able to override the core css found in **modules/toolbar/toolbar.css** by simply copying this file into my sites directory at **/sites/modules/toolbar/toolbar.css**. I tried doing this, cleared the Drupal cache, but nothing happened. What am I missing?

# Answer
I did this: http://drupal.org/node/176046

Basically copied the core toolbar directory into the /sites/all/modules directory. Then made the changes I needed. For some reason I had to try this a few times before it actually worked. I don't know if it was due to errors on my part or some extreme server caching.
> -1 votes

# Answer
Ben Your solution is not ideal, as you now have your own version of the toolbar module, and should there be any bug fixes and security fixes, you will not benefit from those, without upgrading your version of the toolbar module.

# Solution 1.

CSS will by it's design overwrite itself, since the theme CSS files will be included last, any rule you make in your theme that is identical to what's in the toolbar will take presedence.

# Solution 2.

Sometimes it can be a pain to revert styles to browser default, if that is the case, creating a css file with the same name as the one you want to remove and including it in your theme, will make Drupal skip the one in the module and use the one in your theme. In this case creating a `toolbar.css` file anywhere in your theme and adding it in your info file, will remove the `toolbar.css` file from the toolbar module and fix your problems.
Remember to clear cache

# Solution 3.

If by some reason you have problems making solution 2 work, you can instead remove the css file using `hook_css_alter`, this only works in Drupal 7+
> 4 votes

# Answer
> I am running multiple sites on a single Drupal install, so I need a way to have a single style sheet file I can edit that will be applied to all sites in all themes.

There's two solutions for the multi-site situation you describe:

1) Create a custom module that implements hook\_css\_alter() to replace core css files with your own css file overrides. Enable this module on all of your sites.

2) Create a "base theme" that essentially does the same thing, but uses the \*.info file to override the css files from core. (Technically speaking you could also use hook\_css\_alter in the theme instead too). All of your sites' respective themes should specify this parent theme as their base theme in their respective info files and those overridden css files from the base theme will be inherited.
> 1 votes

# Answer
There is no need to override the whole file to make changes. You can replace any of the core css settings by entering the specific items into a custom css in your theme folder. It will override the individual settings for that theme. Make certain that the file is identified as a stylesheet in the info file for the theme .
> 0 votes

# Answer
No need to change the core .php files you should: 1. write the css in your style.css/ example.css file 2. add !important after the property you want to override. for example you want to override font size which is 12px so:font-size:14px !important;
> 0 votes

# Answer
You can simply redefine all the id's and classes's of the CSS in your themes styles.css that you wanna override and remember after defining id's and classes's importantly mention all the property again with your desired value, it won't work only when its defined as '!important' for an instance 'display: block !important;'

Hope this might help you, if any assistance needed in that just drop your comment :)
> 0 votes

---
Tags: 7, theming
---


title: Get all current tabs (node view)

text:
# Question
Title: Get all current tabs (node view)
How to get all node tabs (MENU\_LOCAL\_TASK type) which available for current node?

I mean node/%/edit, node/%/translate, node/%/devel etc.

I've tried to use menu\_local\_tasks() but it shows only empty array.

# Answer
Got it!

```
if ($node = menu_get_object()) {
    $tabs = menu_local_tabs();
}

```
> 3 votes

---
Tags: 7, routes
---


title: How to call a search block

text:
# Question
Title: How to call a search block
I am newbie to drupal i have integrated the Apache solr search module and its working fine. I have disabled the drupal's core search.

Now I am creating my own custom module. How can I make the Apache Solr module search functionality work with my custom module? I need sorting and pagination along with search.

# Answer
What are you doing in your module?, If you are building a new entity, you would to use hook\_apachesolr\_field\_mappings() http://drupalcontrib.org/api/drupal/contributions!apachesolr!apachesolr.api.php/function/hook\_apachesolr\_field\_mappings/7

An example is the implementation in http://drupal.org/project/apachesolr\_commerce

Regards!
> 1 votes

---
Tags: 7
---


# Question
Title: How to create a Default Argument based on Tags
I need to create a view block where users who have entered a specific tag on their personal profile page are displayed. I have the page set and it works properly. I just need to know how to set up the default argument based on context when associating that specific tag.

There are 2 types of profiles:

* business (has a tag field X)
* employee (has same tag field X)

Business owners have personal and a business profile access. Employees just have access to the personal profile.

For those employees that have a matching tag with the business profile I need them listed in a block as employees on that company/business profile page.

# Answer
At first glance I think you should create a taxonomy view with relationship to the content type where it was use by the user, then create a contextual filter to filter the nodes where the user is the author.

I am not sure if the tags created by the user will get the uid of the user that created out of the box, but if you can control that then the view will be even simpler just a taxonomy view with a contextual filter to the field holding the uid by the login user.
> 1 votes

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


# Question
Title: Textfields and values with a value of 0 get blanked out if stepped forward/backwards
I have a multipage form programmed with the drupal FAPI having in total 3 pages of fields consisting of textfields, textareas and radios, the form can be stepped forwards and backwards.

On page 2 of the form i have a few textfields where the user needs to enter numeric values. If these fields are not applicable, the user is asked to enter a **0**.

The problem I have now if the user fills out that page No. 2, fills in a few **0** in these textfields and steps forwards/backwards, and afterwards steps back to that very page, the fields formerly filled with **0** are blank.

I really have no clue how to solve that as I need to use numeric values.

I now could set the default value to **0** instead of an empty value, but that would force the initial form to have already a **0** set. I do not want to solve it like this.

I have the feeling that the **0** is probably treated as a **NULL** (but actually in PHP **0** and **NULL** are different), but I am not sure. Dumping out the form array shows that indeed that 0 values are blank.

A textfield looks like this:

```
$form['t_2_1_2'] = array(
    '#type' => 'textfield',
    '#title' => t('... label text ...'),
    '#description' => ' ... desc. text ...',
    '#required' => TRUE,
    '#default_value' => !empty($form_state['values']['t_2_1_2']) ?
        $form_state['values']['t_2_1_2'] : '',
);

```

The structure of the entire form handling is very much based on the drupal multipage form example in the `drupal form examples` package!

Is there any way how I can solve that issue, that a value of **0** persists in the form, even stepping forward/backward?

I already tried to investigate similar problems, and found one where where the suggestion was to prepend a space to the 0 value, but that is a hack and I do not / can not use that as such!

Any hints are greatly appreciated, as I am sitting on this problem too long now and my time is running out to solve that issue. Thanks in advance for your hints!

**Update:** As nobody could help me here and my time is running, I solved the problem by using an '**x**' instead of the '**0**' value, changed the validation to check for either a numeric value or an '**x**'. Now the values all persist in the form fields, when I jump backwards/forwards in that multipage form. If the user used '**x**', the value will be converted into an '**0**' value in the submit handler because the data is stored into mysql, and these fields are of type integer. At least a way I can live with.

# Answer
> 0 votes
You could also simply allow users leave the field empty and convert any empty “numeric” fields to a '0' in your submit handler. That might be a better user experience since it would save users the trouble of having to enter *any* values in those fields.

---
Tags: forms, 7
---


# Question
Title: Setting the admin theme only inside the overlay
On my site, I have the Overlay module enabled, and I have selected an admin theme that is different from the theme used as default.
Sometimes, a page for which the admin theme is set is accessed with a direct link, and the admin theme is used. I would like to show the page with the default theme, and use the admin theme only with the overlay.

Is there a way to achieve this (module, or code to use in a custom module)?

# Answer
> 1 votes
The Overlay Theme module would probably be ideal:

> Overlay theme is a small module that provides an option to set the theme of modal frames provided by the core Overlay module, different from the default which is the Administration theme.

Using that you could set your default admin theme to the same as the front end, and set the overlay theme to what ever you like.

---
Tags: 7
---


title: Drupal testing with DrupalGetAJAX

text:
# Question
Title: Drupal testing with DrupalGetAJAX
I'm working on writing some automated tests for an AJAX API, and getting strange results. If I directly view the page, I see the following output, sent by drupal\_json\_output:

```
{"guid":"8e2a179e-c901-8744-05fc-e80de9500dd6","success":1}

```

My unit test hits this same URL. Here's the test function:

```
 public function testInit() {
    $response = $this->drupalGetAJAX('plugin/init', array('query' => array('guid' => $this->registered_user->uuid)));
    $this->assertEqual($response['guid'], $this->registered_user->uuid, 'GUID Loaded');
    $this->pass(json_encode($response));
  }

```

When I initiate the test run, it goes to the usual batch API progress page. Rather than moving directly to the test results page, I get "An error has occurred, please continue to the error page". Here's the output that follows:

```
An AJAX HTTP error occurred. HTTP Result Code: 200 Debugging information follows. Path: /batch?id=64&op=do StatusText: OK ResponseText: {"guid":"a06f78ec-1368-f4c4-c9ac-a710b3e941b5","success":1}{"status":true,"percentage":"100","message":"Processed test 1 of 1 - \u003Cem class=\u0022placeholder\u0022\u003EPlugin\u003C\/em\u003E.\u003Cdiv class=\u0022simpletest-fail\u0022\u003EOverall results: 7 passes, 1 fail, 0 exceptions, and 1 debug message\u003C\/div\u003E\u003Cdiv class=\u0022item-list\u0022\u003E\u003Cul\u003E\u003Cli class=\u0022first last\u0022\u003E\u003Cdiv class=\u0022simpletest-fail\u0022\u003EPlugin: 7 passes, 1 fail, 0 exceptions, and 1 debug message\u003C\/div\u003E\u003C\/li\u003E\n\u003C\/ul\u003E\u003C\/div\u003E"}

```

This reads to me like some sort of error within the test runner, as you can see the response from the AJAX API module is there. It looks like it's showing my module's JSON output concatenated to the output of the batch call to the test runner.

The output for $response is always "1" when viewing the test results page. In the detailed test result page, the call is listed as follows, returning 1 byte:

> GET http://platform.dev/plugin/init?guid=5b299683-49d8-7754-f9ca-3fb88e79ff0f returned 200 (1 byte).

For experimentation sake, I also ran the test suites for AJAX commands and the batch API. The same thing happens. My best guess is that this is a bug in Drupal 7.15.

# Answer
The issue is a known one, and a patch fixed the issue - http://drupal.org/files/drupal.simpletest-curl-cookiejar.33.patch
> 0 votes

---
Tags: 7, testing
---


# Question
Title: Coupon calculates but doesn't sent correct amount to payment gateway (Cybersource)
SUMMARY: Below are the details to the question. The issue at hand is that any coupon that is above 8% discount. Sends the UNDISCOUNTED amount to cybersource. On the checkout page, the calculations are done correctly no matter the percentile discount from the coupon.

Relevant Modules & Versions:

* Cart 7.x-3.2
* Discount Coupons 7.x-2.1-alpha7
* Token 7.x-1.4
* Entity API 7.x-1.0-rc3
* Views 7.x-3.5

Modules Enabled:

* ALL of UC core.
* Catalog, Payment, Product Attributes, Reports, Shipping, Shipping quotes, Tax Reports, Taxes
* Product Kit, Stock
* Flat Rate
* Credit Card, Cyber Source, Discount Coupons

Payment Gateway: Cyber Source Payment Method: SOAP Toolkit API - Everything here is configured correctly here.

Shipping: Flat Rate (We add $30 for next day air)

Coupon Settings:

* Coupon is Active is checked.
* Discount amount \[we are using percentage based discounts. If the discount is BELOW 9%. It works as it should. If its 9% or HIGHER, it sends the undiscounted amount to the payment gateway.\] The calculations on the checkout page are ALWAYS correct. No matter the amount of the coupon percentile.
* Apply Discount to: We have tried with Order Subtotal, and Total of matching products. Both cause the same results.
* Redemption Amounts Restrictions are both blank.

This link mentions a similar issue except it is with paypal.

We have also tried with a FRESH & completely bare Drupal 7, UC 7.x-3.2, & Discounted Coupons 7.x-2.1-alpha7. It still did not work.

QUESTION: Why does the uc\_coupon calculate correctly on the checkout page. But, any discount of 9% or more sends the undiscounted amount to the payment gateway?

UPDATE:

The problem lies between these lines;

```
// Add the order total information.
$purchaseTotals = new stdClass();
$purchaseTotals->currency = $currency;

// Specify the total to charge if it's less than the order total.
if ($amount < $order->order_total) {
  $purchaseTotals->grandTotalAmount = $amount;
}
$request->purchaseTotals = $purchaseTotals;

// Separately add products and line item into the request items object if
// we're charging the full order total.
if (round($amount, 2) == round($order->order_total, 2)) {
  $request->item = array();
  $counter = 0;

  // Add the products to the item array.
  foreach ($order->products as $product) {
    $obj = $request->item[] = new stdClass();

    $obj->productName = $product->title;
    $obj->unitPrice = $product->price;
    $obj->quantity = $product->qty;
    $obj->productSKU = $product->model;
    $obj->productCode = 'default';
    $obj->id = $counter;

    $counter++;
  }

  // Add the line items to the item array.
  $discount_amount = 0;
  foreach ((array) $order->line_items as $line_item) {
    // Handle negative line items.
    if ($line_item['amount'] < 0) {
      $discount_amount += -$line_item['amount'];
    }
    // Skip subtotal line items.
    elseif (strpos($line_item['type'], 'subtotal') === FALSE) {
      $obj = $request->item[] = new stdClass();

      $obj->productName = $line_item['title'];
      $obj->unitPrice = $line_item['amount'];
      $obj->quantity = 1;
      $obj->productSKU = $line_item['type'] . '_' . $line_item['line_item_id'];
      $obj->id = $counter;

      $counter++;
    }
  }
}

// Add the total order discount into the request.
if ($discount_amount != 0) {
  $request->purchaseTotals->discountAmount = $discount_amount;
}

```

Here is a successful order w/ a discount of 8%:

```
[purchaseTotals] => stdClass Object
    (
        [currency] => usd
        [grandTotalAmount] => 321.58
        [discountAmount] => 23.92
    )

[item] => Array
    (
        [0] => stdClass Object
            (
                [productName] => Signature Pendant - 14K Yellow Gold
                [unitPrice] => 299.00000
                [quantity] => 1
                [productSKU] => USI2541YR5J
                [productCode] => default
                [id] => 0
            )

        [1] => stdClass Object
            (
                [productName] => Next Day Air
                [unitPrice] => 30.00000
                [quantity] => 1
                [productSKU] => shipping_158
                [id] => 1
            )

        [2] => stdClass Object
            (
                [productName] => FL TAX
                [unitPrice] => 16.50480
                [quantity] => 1
                [productSKU] => tax_160
                [id] => 2
            )

    )

```

Here is what a failure looks like with a 10% discount. The threshold to break it is 9% thou;

```
[purchaseTotals] => stdClass Object
    (
        [currency] => usd
        [discountAmount] => 29.9
    )

[item] => Array
    (
        [0] => stdClass Object
            (
                [productName] => Signature Pendant - 14K Yellow Gold
                [unitPrice] => 299.00000
                [quantity] => 1
                [productSKU] => USI2541YR5J
                [productCode] => default
                [id] => 0
            )

        [1] => stdClass Object
            (
                [productName] => Next Day Air
                [unitPrice] => 30.00000
                [quantity] => 1
                [productSKU] => shipping_155
                [id] => 1
            )

        [2] => stdClass Object
            (
                [productName] => FL TAX
                [unitPrice] => 16.14600
                [quantity] => 1
                [productSKU] => tax_157
                [id] => 2
            )

    )

```

The difference is that "grandTotalAmount" is getting populated on 8% or less of a discount. Anything after that and "grandTotalAmount" doesn't get generated. Not sure but is this correct?

```
// Add the total order discount into the request.
if ($discount_amount != 0) {
  $request->purchaseTotals->discountAmount = $discount_amount;
}

```

Almost seems like something is missing inside the if statement.

# Answer
> 0 votes
Ended up changing the code to the following in the uc\_cybersource.module;

```
    // Specify the total to charge if it's less than the order total.
if ($amount <= $order->order_total || $amount >= $order->order_total) {
  $purchaseTotals->grandTotalAmount = $amount;
}
$request->purchaseTotals = $purchaseTotals;

```

Lets see how long the maintainer takes to patch this.

# Answer
> 0 votes
Few troubleshooting tips:

1. Hack the  `uc_cybersource`  and  `uc_coupon`  modules temporarily and log the values at each step throughout the whole process. Only this way you can find out what is exactly going on and where the values are changed and not calculated properly. You can save everything using  `watchdog()`  function.
2. Make a clone of the site, disable all other modules and try to replicate the same issue.
3. Do this on a clean install but with the same UC setup.

Also - do you have any custom modules that deal with the checkout process or orders?

---
Tags: 7, ubercart
---


# Question
Title: open_basedir restriction in effect despite file directory within web root
When trying to upload a logo to my Zen 3.1 subtheme (Appearance \> Settings) I get the following error:

```
Warning: is_file(): open_basedir restriction in effect. File(/tmp/phpillr69) is not within the allowed path(s): (/home/testwww/web/) in image_get_info() (line 126 of /home/testwww/web/informator/includes/image.inc).
Warning: realpath(): open_basedir restriction in effect. File(/tmp/phpillr69) is not within the allowed path(s): (/home/testwww/web/) in drupal_realpath() (line 2177 of /home/testwww/web/informator/includes/file.inc).
Warning: getimagesize(): Filename cannot be empty in image_gd_get_info() (line 349 of /home/testwww/web/informator/modules/system/image.gd.inc).
The specified file logo.gif could not be uploaded. Only JPEG, PNG and GIF images are allowed.

```

It happens even though I have the paths in Configuration \> Media \> File System set to be inside the web root.

* Public file system path: sites/\[my directory\]/files \[permission 775\]
* Temporary directory: sites/\[my directory\]/files/tmp \[permission 755\]

**It seems that Drupal tries to save a temporary file in /tmp/ although the temporary directory is set to something different.**

How can I fix the problem to be able to upload a file?

# Answer
> 4 votes
The key here is that PHP is attempting to create the temporary file in a public directory. If you refer to the your PHP settings, find out what is specified for the 'upload\_tmp\_dir'. Use a phpinfo() call to display this, also available in the Status Report by clicking on the PHP version number. This directory has special privileges that open\_basedir will not block. Set your drupal temp directory to this path explicitly and it should work.

# Answer
> -3 votes
Sometimes it's caused by eaccelerator. Just remove it from PHP.

---
Tags: 7, files
---


# Question
Title: How to show an input field on node view, not just on node edit / add?
I would like to show an input text area field with filtered html on node view (not on node/add !).

(I would like to show editable text in a tinymce editor here http://proofreadbot.com/proofreading/132)

What would be the easiest way of achieving this? Is there a contrib module perhaps?

# Answer
> 0 votes
You can use Webform: http://drupal.org/project/webform

Just install the module and add it as a block on the node that you want. It will be displayed on node view.

Create a Webform

Select the Webform tab

Select the Forms settings tab

Select Advanced settings

Switch on Available as block

Configure the block to be displayed on the node that you want

---
Tags: nodes, forms
---


title: Views2 Sub-Query Filter

text:
# Question
Title: Views2 Sub-Query Filter
I am trying to recreate the following query in Drupal 6 Views2...

```
SELECT m.PartnerID, m.PartnerName, mc.Description
FROM member AS m
     LEFT JOIN membercategory AS mc ON m.PartnerID = mc.PartnerID
WHERE mc.DirectoryID = %d
  AND mc.CategoryID = (
         SELECT m_xref.CategoryID
         FROM memeber_membercategory_xref AS m_xref
         WHERE m_xref.WebCategoryName = '%s'
      )
```

I have been able to create the LEFT JOIN by creating an implicit join on my hook\_views\_data. **I am currently stuck on how to create the sub-query on mc.CategoryID in the WHERE clause. Any suggestions?**

Would the only option to be a custom handler for the filter? Or is there a way to get the relationship defined?

My current hook\_views\_data...

```
function member_display_views_data(){
    $data = array();

    /****
     * Members Table
     ***/
    $data['member']['table']['group'] = t('Member Data');
    $data['member']['table']['base'] = array(
        'field' => 'PartnerID',
        'title' => t('Members'),
        'help' => t("Member data."),
    );

    $data['member']['PartnerID'] = array(
        'title' => t('Partner ID'),
        'help' => t('The Partner ID.'),
        'field' => array(
            'handler' => 'views_handler_field_numeric',
        ),
        'argument' => array(
            'handler' => 'views_handler_argument_numeric',
        ),
        'filter' => array(
            'handler' => 'views_handler_filter_numeric',
        ),
        'sort' => array(
            'handler' => 'views_handler_sort',
        ),
    );

    $data['member']['PartnerName'] = array(
        'title' => t('Partner Name'),
        'help' => t('The Partner Name.'),
        'field' => array(
            'handler' => 'views_handler_field',
        ),
        'argument' => array(
            'handler' => 'views_handler_argument_string',
        ),
        'filter' => array(
            'handler' => 'views_handler_filter_string',
        ),
        'sort' => array(
            'handler' => 'views_handler_sort_string',
        ),
    );

    $data['member']['Alias'] = array(
        'title' => t('Alias'),
        'help' => t('The alias to identifiy the record.'),
        'field' => array(
            'handler' => 'views_handler_field',
        ),
        'argument' => array(
            'handler' => 'views_handler_argument_string',
        ),
        'filter' => array(
            'handler' => 'views_handler_filter_string',
        ),
        'sort' => array(
            'handler' => 'views_handler_sort_string',
        ),
    );

    /****
     * MemberCategory Table
     ***/
    $data['membercategory']['table']['group'] = t('Member Category Data');
    $data['membercategory']['table']['base'] = array(
        'field' => 'PartnerID',
        'title' => t('Member Category'),
        'help' => t("Member Category data."),
    );
    $data['membercategory']['table']['join'] = array(
        'member' => array(
            'left_field' => 'PartnerID',
            'field' => 'PartnerID',
        ),
    );

    $data['membercategory']['PartnerID'] = array(
        'title' => t('Partner ID'),
        'help' => t('The Partner ID.'),
        'relationship' => array(
            'base' => 'member',
            'field' => 'PartnerID',
            'handler' => 'views_handler_relationship',
        ),
    );
    $data['membercategory']['DirectoryID'] = array(
        'title' => t('Directory ID'),
        'help' => t('The Directory ID.'),
        'field' => array(
            'handler' => 'views_handler_field_numeric',
        ),
        'argument' => array(
            'handler' => 'views_handler_argument_numeric',
        ),
        'filter' => array(
            'handler' => 'views_handler_filter_numeric',
        ),
        'sort' => array(
            'handler' => 'views_handler_sort',
        ),
    );
    $data['membercategory']['CategoryID'] = array(
        'title' => t('Category ID'),
        'help' => t('The Category ID.'),
        'field' => array(
            'handler' => 'views_handler_field_numeric',
        ),
        'argument' => array(
            'handler' => 'views_handler_argument_numeric',
        ),
        'filter' => array(
            'handler' => 'views_handler_filter_numeric',
        ),
        'sort' => array(
            'handler' => 'views_handler_sort',
        ),
    );
    $data['membercategory']['Description'] = array(
        'title' => t('Description'),
        'help' => t('The Partner Description.'),
        'field' => array(
            'handler' => 'views_handler_field',
        ),
        'filter' => array(
            'handler' => 'views_handler_filter_string',
        ),
    );

    /****
     * memeber_membercategory_xref Table
     ***/
    $data['memeber_membercategory_xref']['table']['group'] = t('Member Category xRef');
    $data['memeber_membercategory_xref']['table']['base'] = array(
        'field' => 'PartnerID',
        'title' => t('Member Category xRef'),
        'help' => t("Member Category Cross Reference data."),
    );
    $data['memeber_membercategory_xref']['table']['join'] = array(
        'membercategory' => array(
            'left_field' => 'CategoryID',
            'field' => 'CategoryID',
        ),
    );

    $data['memeber_membercategory_xref']['CategoryID'] = array(
        'title' => t('Category ID'),
        'help' => t('Partner Category ID.'),
        'relationship' => array(
            'base' => 'membercategory',
            'field' => 'CategoryID',
            'handler' => 'views_handler_relationship',
        ),
    );
    $data['memeber_membercategory_xref']['WebCategoryName'] = array(
        'title' => t('Partner Category Name'),
        'help' => t('The Partner Category Name.'),
        'field' => array(
            'handler' => 'views_handler_field',
        ),
        'argument' => array(
            'handler' => 'views_handler_argument_string',
        ),
        'filter' => array(
            'handler' => 'views_handler_filter_string',
        ),
        'sort' => array(
            'handler' => 'views_handler_sort_string',
        ),
    );

    return $data;
}
```

# Answer
> 0 votes
I found that using the Table Wizard module allows Drupal Views to load a database view. After install of Table Wizard, go to /admin/content/tw and select your database view from the list of tables to add to Table Wizard. The Drupal view type is prepended with 'Database table'.

---
Tags: 6, views
---


# Question
Title: How to programmatically submit the file system settings form?
I am trying to enable private files via features, in code, or with drush but am getting errors.

With drush:

```
drush vset file_private_path sites/default/files/private

```

In code:

```
variable_set('file_private_path','sites/default/files/private');

```

The problem is that when you set this configuration manually, the file system settings form gets saved and it creates an .htaccess file in that location. When you set it in code, it doesn't create the .htaccess file until you visit the admin/config/media/file-system page, which it returns an error the first time:

```
Warning: file_put_contents(private:///.htaccess) [function.file-put-contents]: failed to open stream: "DrupalPrivateStreamWrapper::stream_open" call failed in file_create_htaccess() (line 502 of /sandbox/d7/includes/file.inc).

```

Is there a correct way to be doing this programmatically? Thanks in advance.

# Answer
I would not re-create what the form does by hand as @Ayesh does. There is a small chance this form will do more things in a future minor drupal release date (maybe that should never happen, i'm not 100% sure).

What you want to do is look at drupal\_form\_submit() to programmatically submit a form -- its like visiting the form in a webpage and submitting it without ever opening a browser window. Whatever logic that form does upon submission -- will still happen, eg. create an .htaccess file for you.

You would put the following code into your module install() hook, or you could `drush ev` this code or make a small php script and run `drush php-script myscript.php`

Code:

```
$form_state = array();
$form_state['values']['file_private_path'] = 'sites/default/files/private';
$form_state['values']['op'] = t('Save configuration');
drupal_form_submit('system_file_system_settings', $form_state);

```

You can then re-submit the form and set the default file serve mode from public to private. Or I would use `drush vset` or just `variable_set` somewhere in PHP to set the default file serving mode in drpual. My point is that this is the correct way to programmatically submit a form.
> 3 votes

# Answer
variable\_set() simple saves the value to the database and clear internal cache. Nothing else.

So, before setting the value, you must verify that path is writable and prepare it (.htaccess stuff).

```
<?php
$path = 'sites/default/files/private';
if (is_dir($path) && is_writable($path)){
  file_create_htaccess($path); // for private dir. Use file_create_htaccess($path , FALSE); for public dir.
  variable_set('file_private_path',$path);

}

```

you can also drupal\_mkdir() and drupal\_chmod() $path if you want to make sure it's writable.
> 0 votes

---
Tags: drush, forms, files
---


title: Sliding Popup in Drupal 6

text:
# Question
Title: Sliding Popup in Drupal 6
Im trying to create a sliding popup using jQuery in my drupal module .

Referring the code from:

http://karlagius.com/2009/02/08/creating-a-sitepoint-like-sliding-popup-in-jquery/

My popup window, defined in the module, is a html string (using divs, a, img etc) .

How do I pass this html string to .js file. It gets used there in .get(url, function(data)).

Tried using drupal\_to\_js and drupal\_json, both returns the value 0, not the string.
Need some suggestion on how to proceed.

# Answer
> 1 votes
You need

1. a hook\_menu() implementation that will provide you with the url:
2. a page callback funtion that does `print()` or `echo` on the html snippet, then `exit()`. So no `drupal_to_js()` or `drupal_json()`.

# Answer
> 1 votes
You can pass it using drupal\_add\_js

Example

```
  // This will add variables in the Drupal.settings object
  drupal_add_js(array('my_module' => array('my_setting' => 'this_value')), 'setting');

```

You can access this variable like `Drupal.settings.my_module.my_setting`

---
Tags: 6, javascript
---


# Question
Title: What is the best way to add a comment policy to the comment form?
Surely this is a common use-case... I would have thought? Underneath "Add new comment" heading I would like to add a block of text like "Comments are pre-moderated and may be edited before publication". I have an internationalised site so the text must be translatable.

# Answer
> 1 votes
You can do this easily with a form\_alter hook.

```
<?php
function MODULENAME_form_comment_node_NODE_TYPE_form_alter(&$form, $form_state, $form_id) {
    //drupal_set_message('<pre>'.print_r($form, 1).'</pre>');
    $form['privacy-note'] = array(
          '#markup' => t('Comments are pre-moderated and may be edited before publication');

        );
}

```

Yes it sounds a little silly to make a module for this. But making a little module for every little work is also not a smart option. If you have never created a module before, See this: http://drupal.org/node/1074360 Don't forget to change MODULENAME and NODE\_TYPE with actual values. if you have any questions, I'd be happy to answer them here :)

# Answer
> 1 votes
There are 2 ways to do it.

Option 1

Implement hook\_form\_FORM\_ID\_alter in your custom module.

Option 2

Use the markup module.

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


# Question
Title: Invoking AJAX on a form messes up my form_alter function
I am altering the "Add node" form for one of my types so that I can set the title and disable the text box. The (shortened) code looks like this:

```
function mytheme_form_node_form_alter(&$form)
{
    $form['title']['#default_value'] = 'Some value';
    $form['title']['#disabled'] = true;
}

```

On the node form, I have a field with "Unlimited values" where a user can click "Add another item" to add another row to the items grid on the form.

**The problem:** When I click this button and the AJAX request happens, it adds the row to the table as usual. **But when I save the form, Drupal thinks the Title is empty, and throws a validation error back.** The title is still set and greyed out *after* the AJAX request happens (like it should be), but it seems to "unset" itself somehow behind the scenes when the AJAX request happens, because when the form gets saved, the title gets cleared and the validation error occurs.

I hope I made that clear... so does anyone know why the AJAX related to unlimited fields might interfere with `theme_form_X_form_alter`?

# Answer
> 1 votes
```
function mytheme_form_node_form_alter(&$form){
    $form['title']['#default_value'] = 'Some value';
    $form['title']['#value'] = $form['title']['#default_value'];
    $form['title']['#disabled'] = true;
}

```

This should solve the problem. In HTML, disabled form elements' value will not be sent back to the server so server gets nothing back, which result in a form error if the value is required. Storing value in #value overrides any browser input which is a must (for security purposes) when you disable a form element *and* expect its value back.

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


# Question
Title: drupal_static and cache_set combo , is this overkill?
I have been using this snippet lately here and there, but after re-thinking , it seems like it could be a good example of over-engineered code:

```
<?php
function my_module_function() {
  $my_data = &drupal_static(__FUNCTION__);
   if (!isset($my_data)) {
    if ($cache = cache_get('my_module_data')) {
      $my_data = $cache->data;
    }
    else {
      // Do your expensive calculations here, and populate $my_data
      // with the correct stuff..
      cache_set('my_module_data', $my_data, 'cache');
    }
  }
  return $my_data;
}
?>

```

Is this truly an optimal way to cache things? I am not clear on the low-ends of it all but it seems the drupal\_static call is overhead since the static call would get only called once before the data would be cached. Maybe I am seeing it wrong, and rather the cached variable would be set static for the whole request, and static access is faster than cache access?

I am also not clear if the cache is global for all users or on a per user basis. I would imagine the cache is global, but ***please*** correct me if I am wrong!.

# Answer
> 2 votes
I don't see this a overkill.

`drupal_static()` caches results over the lifetime of a single request. It is typically used for things that may be needed several times during page generation, but will (likely) not change. For example, if a node is loaded, it gets saved in memory in case multiple functions need it.

`cache_set()` / `cache_get()` caches things in the database (or another storage backend with the proper module), so the data persists (up to the TTL) between page requests. This gets used for things that change infrequently, and is global for all requests. As far as I can remember, the normal implementation always goes out to the cache backend and doesn't store results in memory with `drupal_static()` or `static`.

Given the overhead, I would be judicious as to whether caching really improves things.

---
Tags: caching
---


# Question
Title: Add HTML5 required attribute to webform fields set as required
Could someone advise me how to use a hook to add the HTML 5 required attribute to all inputs that have been selected as 'required' within webforms.

Webforms already adds class 'required' but the HTML 5 required attribute provides great instant validation in Opera, Firefox and Chrome browsers.

# Answer
You will need to create a module for this. Note that, this answer assumes you need to set required attribute on all form elements which are required in web form settings. you will need to implement a different hook and/or add conditions to make this strict.

Create a file named `webform_formalters.info` and put following to it.

```
name = webform form alters
description = a collection of custom form alters for webforms.
core = 7.x
package = Custom
dependencies[] = webform

```

Create another file named 'webform\_formalters.module' and put following in it.

```
<?php
/*
 * implements hook_form_BASE_FORM_ID_alter.
 */
function webform_formalters_form_webform_client_form_alter(&$form){
  //dsm($form);
  foreach ($form['submitted'] as &$field){
   if (is_array($field) && isset($field[#required]) && $field['#required'] == 1){
     //dsm($field);
     $field['#attributes']['required'] = 'required';
   }
  }
}

```

Put both files to a folder named `webform_formalters` and upload to your site's module folder and enable the module. See if it works.

Unlike other forms, web forms' fields are stored in $form\['submitted'\] array. So we go through each item (which should be an array of form definitions) and check if the element has marked as required. if so, we add or **merge** required attribute. We are altering an existing form, so we are not going to pop out existing attributes.

Good luck!
> 4 votes

---
Tags: 7, hooks, webforms
---


# Question
Title: Remove drupal message "field is required" from webform validation
So when a webform is validated it sends a drupal message "X field is required", and creates a red border around the field.

For our project the red border is enough, how would I go about removing Drupal messages from triggering during validation?

# Answer
> 2 votes
You can remove it using CSS in that particular page !

Check for specific div's the page body is using and set the div.error to display:none;

OR

Override theme\_status\_messages to exclude or alter the status messages.

In your case,

```
function your_theme_status_messages($variables) {
  $display = $variables['display'];
  $output = '';

  $status_heading = array(
    'status' => t('Status message'),
    'error' => t('Error message'),
    'warning' => t('Warning message'),
  );
  foreach (drupal_get_messages($display) as $type => $messages) {
    $output .= "<div class=\"messages $type\">\n";
    if (!empty($status_heading[$type])) {
      $output .= '<h2 class="element-invisible">' . $status_heading[$type] . "</h2>\n";
    }
    if (count($messages) > 1) {
      $output .= " <ul>\n";
      foreach ($messages as $message) {
        if (strpos($a,'required') === false) {  // Check for any other conditions here
          $output .= '  <li>' . $message . "</li>\n";
        }
      }
      $output .= " </ul>\n";
    }
    else {
      $output .= $messages[0];
    }
    $output .= "</div>\n";
  }
  return $output;
}

```

---
Tags: 7, webforms
---


# Question
Title: My tab links turned into /user/%/edit, node/%/edit, etc
Links on tabs turned into `/user/%/edit`, `/user/%/contact`, `node/%/edit`, `admin/structure/types/%/fields`, etc. Also, the links on Administration Menu module have the same issue.

Here's what I did so far.

1. I've cleared all cache via Admin Menu -\> Flush all cache, via Development -\> Performance and via emptying MySQL cache\_\* tables. Didn't solve.
2. I noticed that tabs are themed by the `menu_local_tasks()` function. I traced the function to `includes/menu.inc`, where I found the following snippet, which makes me think it might be related to this function.

```
* For example, the ancestors of node/12345/edit are:
 * - node/12345/edit
 * - node/12345/%
 * - node/%/edit
 * - node/%/%
 * - node/12345
 * - node/%
 * - node

```

UPDATE: Where is `'%'`, of the above URLs, being populated? I want to be able to trace it.

# Answer
Line 775 of `/include/menu.inc` was commented out.
> 0 votes

---
Tags: 7, routes
---


# Question
Title: Display images twice in a node with different image cache settings
I have a node type where I'd like to display images as both thumbnails and full size images, so I'd like to use different image cache settings on the two image types. I don't want to use views to do this. I know that I can output a field twice using "print render($content\['field\_name'\]); " in my node.tpl file, however I wouldn't be able to manage the display separately on the two outputs.

Does anyone have a solution?

# Answer
> 1 votes
You can get the image path by using following code:

```
<?php
var_dump($node);
?>

```

Now find the path of the image and write the following code:

```
<?php
theme('image_style', array('style_name' => 'stylename', 'path' => 'image path', 'alt' => 'image alt', 'title' => 'image title', 'width' => 'some width', 'height' => 'some height')));
?>

```

Where you can define your own style name. I hope you know how to create image styles. Just Goto **admin/config/media/image-styles** and add your style and use it in above code. Use above code twice to print images in two different style.

Entire code:

```
// filename relative to files directory
// e.g. 'masthead.jpg'
$filename = $node->field_image['und'][0]['filename'];

// relative path to raw image in 'scheme' format
// e.g. 'public://masthead.jpg'
$image_uri = file_build_uri($filename);

// relative path to 'styled' image (using an arbitrary 'banner' style) in 'scheme' format
// e.g. 'public://styles/banner/public/masthead.jpg'
image_style_path('banner', $filename);

// html for a styled image
// e.g. '<img typeof="foaf:Image" src="http://mysite.com/sites/default/files/styles/banner/public/masthead.jpg" alt="" />'
print  theme('image_style', array('style_name' => 'banner', 'path' => $image_uri));

```

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


# Question
Title: How to send notification when node similar to flagged one is posted
I want to send notifications to the user when a new node similar to one he has flagged is posted.

# Answer
> 0 votes
You need to user RULES module to achieve this functionality. Drupal flag module has full integration with rules modules.

By creating a rule saying condition is "Node is flagged" add an action saying "Send email to author of node."

---
Tags: flags, notifications
---


title: Revision history summary

text:
# Question
Title: Revision history summary
I am looking for a solution to show a summary of revision history for all nodes in one place. The out of the box solution is to show a revision history for each node apart. I want to be able to track my content admins' changes in one place (I couldn't find a module that does what I want) Thanks!

# Answer
> 3 votes
If you don't mind to use Views module, you can configure any list of revisions. You also can add filter/sort logic, pager, configure access and much more useful things.

You always can export your solution with Views export or with Features module and reuse it on other Drupal sites.

More information about Views: http://nodeone.se/en/node/20

# Answer
> 0 votes
There are severel modules that extend revision, one of this is Revisioning.

Another way is create a view of revisions.

---
Tags: 7, nodes
---


# Question
Title: How to reset a site to its profile installation? D7
I installed the Commerce Kickstart distribution and I've made some modification. Now I'd like to reset the site to remove all my modification and get the site restored.

Do I need a module to do this? Maybe this one: http://drupal.org/project/drupal\_reset

# Answer
> 3 votes
Yep. You can also check out Demo as it is very very much helpful during testing and playing around in local development. You can create a snapshot of a clean website with your settings and then do whatever you want; if necessary with a click you can roll back to the initial settings without reinstalling the whole site.

Keep in mind though that you can use and setup Demo only before you start playing around - it will save the current site in a snapshot.

---
Tags: 7
---


title: Condition module

text:
# Question
Title: Condition module
I want to use the Virtual site module, but it requires the Condition module I cannot find for Drupal.

Where should I download that module? Do you have a link I can use to download it?

# Answer
> 1 votes
You don't need the condition module for D7. It is already added to VS module itself. Here is the snapshot of the description of its project page:

> The D7 version is the Virtual Sites module and the Condition module it depends **on rolled into one package**. While it retains all the functionality from the D6 version (even added a new condition to check for the user's browser, useful to recognize visitors with mobile devices), changes in Drupal itself made its setup slightly different. Installing it will enable the dependent VS Conditions module automatically.

---
Tags: 7
---


title: Can't enable panels in page-node

text:
# Question
Title: Can't enable panels in page-node
Hello I'm building a multilingual (en/el) website using views panels taxonomy etc etc and other modules.All was fine with the world when suddenly I decided to customize the page-node by adding a panel layout which I created. The problem is that even when I saved the panel layout and the content on /node/%node nothing happened when I view an article. The article page ?q=node/3 for example remains unchanged.

I'm trying 2 says to find the solution but no luck at all. Any info will be greatly appreciated, thnx in advance.

# Answer
> 0 votes
I recreated the website and added multilingual modules at the end. Now it works fine... still though I have no idea what was wrong...

---
Tags: views, nodes, panels, i18n-l10n
---


# Question
Title: jquery hover function in views template (drupal 6)
I have a views template called: **views-view-fields--video--block-1.tpl.php**

Inside that file i have:

```
<script type="text/javascript">
  $(document).ready(function() {
    $('.last-vid-poster').hover(function() {
        $(this).parents('.last-vid-block').find('a.play_button').fadeIn('slow');
      }, function() {
        $(this).parents('.last-vid-block').find('a.play_button').fadeOut('slow');
      }
    );
  });
</script>

<?php

print '<div class="last-vid-block">';

print '<div style="float: left; margin-right: 8px;">'. $fields['field_video_embed']->content.'</div>';

print '<h3 class="video-block">'. $fields['title']->content .'</h3>';

$hover_play = l('<img src="/' . path_to_theme() . '/img/play-button.png" />', 'node/' . $row->nid, array('attributes' => array('class' => 'play_button', 'style' => 'display: none'), 'html' => true));

print $hover_play;

print '</div>'; // vgrid

?>

```

As you can see in my JS code at the top of the template, i'm printing `$hover_play` when user hovers over `.last-vid-block .imagecache` object, so it fades In then fades Out, that works, yeah.

But the problem is -\> i have in that views block 4 nodes with that markup, so when i hover over just one `.last-vid-block .imagecache` that $hover\_play shows on all 4 objects... How to separate them - if i hover just 1st object `$hover_play` shows only at 1st object etc... Thanks in advance!

```
ATTENTION! Edited js code at the top! It works as intended, is there any erros in that code?

```

# Answer
> 1 votes
The original issue was that you were targeting all play buttons at once with your JS, the second problem that came up in the comments below is that your play button is on top of your `.imagecache` object and your `.play_button` is taking away the mouse focus, thus firing "hover out"

Try this:

```
<script type="text/javascript">
  $(document).ready(function() {
    $('.last-vid-block').hover(function() {
      $(this).find('a.play_button').fadeIn('slow');
    }, function() {
        $(this).find('a.play_button').fadeOut('slow');
      }
    );
  });
</script>

```

The downside to this, however, is that if you hover over the title on the right side (outside of the `.imagecache`) object, your still going to get the fade in/out effect triggered...

If that is not what you want then you could try altering the template:

```
<script type="text/javascript">
  $(document).ready(function() {
    $('.last-vid-poster').hover(function() {
      $(this).find('a.play_button').fadeIn('slow');
    }, function() {
        $(this).find('a.play_button').fadeOut('slow');
      }
    );
  });
</script>

<?php

print '<div class="last-vid-block">';

print '<div class="last-vid-poster" style="float: left; margin-right: 8px;">';

print $fields['field_video_embed']->content;

$hover_play = l('<img src="/' . path_to_theme() . '/img/play-button.png" />', 'node/' . $row->nid, array('attributes' => array('class' => 'play_button', 'style' => 'display: none'), 'html' => true));

print $hover_play;

print '</div>';

print '<h3 class="video-block">'. $fields['title']->content .'</h3>';

print '</div>'; // vgrid

?>

```

# Answer
> 1 votes
Your binding is too wide. You should use context

```
<script type="text/javascript">
  $(document).ready(function() {
    $('.last-vid-block').each(function() {
      var $block = $(this);
      $('.imagecache', $block).hover(
        function() {
          $('a.play_button', $block).fadeIn('slow');
        }, function() {
          $('a.play_button', $block).fadeOut('slow');
        }
      );
    });
  });
</script>

```

It's better to place the js into views-view--video--block.tpl.php (you should check the exact name) as in your current scenario the code is executed #videos times.

---
Tags: views, javascript
---