# Question
Title: Quick filter tabs on top of content listing page
I've downloaded and installed the Content Management Filter, but I think that the interface is a bit ugly still with all the drop downs, and it doesn't actually achieve what I had hoped.

Basically, I'm looking for a way to put a row of tabs at the top of `admin/content/node` so that a managing user can easily select to display just one type of node (or all nodes).

Is there a module for this?

If not, what's the best strategy? How do I tie in with the filtering already in place on this page?

# Answer
View Bulk Operations (VBO) is a module that, through Views, allows you to create a page similar to the page visible in /admin/content/node. As the module allows to replace the content of that page with the content of a view, you can filter the list of the nodes following all the criteria that Views allows you to set.

The features of the module are not just those; the module allows you to select all the nodes listed in the view, and apply to them the action that is selected under "Update." The module is very useful for administrators, and it allows also to change the page that lists all the user registered in a Drupal site with a view with similar functionalities.
> 2 votes

# Answer
I would just use Views to override it to get the fields I need as exposed filters that are required.
> 0 votes

---
Tags: 7
---


title: How do I write automated tests?

text:
# Question
Title: How do I write automated tests?
I saw that Drupal 7 includes some kind of testing framework (I haven't tried it out yet since my existing sites are still in Drupal 6 and likely won't migrate any time soon). How can you write automated testing for a Drupal 6 site, is there a module for this? How much can actually be tested automatically rather than requiring manual testing?

# Answer
http://drupal.org/project/simpletest \- it provides essentially the same testing API as the core D7 module and you still have to write the tests yourself. There is also http://drupal.org/project/simpletest\_automator that apparently will help you 'record' your actions on a site into a SimpleTest for you.

Additional helpful links:
> 24 votes

# Answer
For *site* testing you may not find Simpletest the best solution. It's designed to test code, rather than the behavior of a site. You may be interested in more big-picture testing tools like Selenium, as Dave Reid mentioned.
> 9 votes

# Answer
A number of contributed modules for Drupal 6 includes simpletests. If you need inspiration take a look at the Date module for instance.
> 3 votes

---
Tags: testing
---


# Question
Title: What does typical beginning mark in *.tpl.php files mean?
I'm looking into template files for theming purposes, and often at the beginning of the file there is a `// $Id$` mark.

Could you explain me what it mean, and what the purpose of it is?

# Answer
It is a placeholder, that is automatically replaced by CVS and then contains information about CVS version, author and so on of the file. For more information, see http://badgertronics.com/writings/cvs/keywords.html.

Since Drupal.org recently switched to Git as the version control system, this tag is now completely irrelevant so it can and should be removed. In fact, it has been removed automatically during the CVS -\> Git migration for all modules on drupal.org
> 7 votes

---
Tags: theming
---


# Question
Title: Form won't submit properly on the front page
I have placed a form on the front page of my Drupal 6 site using `drupal_get_form('mymodule_form')`. I have not done anything different than usual, and I have implemented a validation handler called `mymodule_form_validate()`.

The form displays properly, and posts to '/', as it should. I have put a form\_set\_error() into the validation handler to test that it is working. The validation handler is never hit when the form is submitted.

However, if I use `drupal_get_form()` to put the form on an internal page, it works as it should.

What is going on here? Is there something that is preventing forms from being used on the front page of a Drupal site?

# Answer
> 1 votes
I have discovered that I needed to make sure the form did not submit to the front page. I needed to set up a custom path for #action on the form, and make sure there was a callback defined in a module.

When landing on that callback, the validation and submit handlers successfully fire. I can then redirect users back to \<front\> if they are successful. The downside is that on error, there needs to be a separate page where the form is displayed. I couldn't find a way to show the error on the front page itself.

This is good enough for what I need. Thanks for the suggestions in the comments.

---
Tags: 6, forms
---


# Question
Title: New link added in user page but not visible to non admin user in Drupal 7
I added this module in Drupal 7 for adding new tab in my site. This new tab is not visible to non admin user. Only visible to admin. I also tried to set permission in this direction admin\> People\> permission but this there is no module by the name "New tab" is visible. Please help.

```
function newtab_menu() {
  $items = array();

  $items['user/%user/new_tab'] = array(
    'title' => 'New tab title',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('newtab_newtab_form', 1),
    'access arguments' => array('access new tab'),
    'type' => MENU_LOCAL_TASK,
  );

  return $items;
}

function newtab_newtab_form($form, &$form_state, $account) {
  // ...
}

function newtab_permission() {
  return array(
    'access new tab' => array(
      'title' => t('The title of the permission'),
      'description' => t('The description of the permission'),
    ),
  );
}

```

# Answer
> 1 votes
Most likely your problem is that you haven't defined your permission. You can demand any permission, even ones that doesn't exist.

To create permissions, you use `hook_permission`:

```
function newtab_permission() {
  return array(
    'access new tab' => array(
      'title' => t('Access new tab'),
      'description' => t('The description of the permission'),
    ),
  );
}

```

# Answer
> 2 votes
You need to declare your permission with hook\_permission().

```
function newtab_permission() {
  return array(
    'access new tab' = > array(
      'title' => t('Access new tab'),
    ),
  );
}

```

---
Tags: 7, routes, users
---


# Question
Title: What's the fastest method/implementation for an Ajax callback?
I have a map which loads markers via ajax on various/numerous map events. Currently, I define a custom page callback for my `hook_menu()` item which prints my json/js.

Since my page callback **does not return** any content and **only prints** content, Drupal does not render the full template, menu, etc, and thus allows me to return a page with *only* my JavaScript.

Although this does work, I believe that Drupal still fully bootstrapping, which means it is adding a lot of overhead I would like to drop.

I've been looking at High-performance JavaScript callback handler, which boasts itself as a "High-performance JavaScript callback handler" and which, in short, looks as though it offers a `js.php` to compliment `index.php` to direct your requests to and customize/limit/optimize the bootstrapping Drupal does by default.

*Unfortunately the js project doesn't have a D7 release yet (petition for one here), which leads us to the beginning...*

What is the fastest way to implement an Ajax callback in Drupal?

# Answer
> I define a custom page callback for my `hook_menu()` item which prints my json/js.

That is what Drupal 6 offered. The Drupal 7 AJAX framework can do a little more than that. Yes it bootstraps Drupal, but it also gives a lot of features for free. In short you can use ajax\_deliver() as a page delivery method, and send commands to the browser.

> ... Ajax may be enabled by adding classes to buttons and links. By adding the 'use-ajax' class to a link, the link will be loaded via an Ajax call. When using this method, the href of the link can contain '/nojs/' as part of the path. When the Ajax framework makes the request, it will convert this to '/ajax/'. The server is then able to easily tell if this request was made through an actual Ajax request or in a degraded state, and respond appropriately.

However if you want to sidestep the framework for performance reasons then there is nothing to stop you calling php files in your module directly from javascript. You will get no Drupal goodness but you also will have complete control over the page.
> 8 votes

# Answer
A bit late, but especially if you are using that ajax callback for polling (check for new messages for example), there is an interesting alternative: Drupal node.js integration.

Instead of polling, it allows you to build an event-like system, where users (aka the JS on their page) keep an open connection to your node.js server. If something happens, you can directly notify all users through node.js.
> 4 votes

# Answer
Since you want to implement an Ajax callback *in Drupal*, using the JS module looks like a good bet. I just took a quick look at the code, and it's basically what I would've suggested (but with a lot more attention to details). The maintainer is one of the top Drupal developers, too.

It looks like you'll have to use `module_load_include()` or perhaps a more manual `include 'sites/all/modules/contrib/...';` approach if you need to use APIs from other modules.

The very problem you're talking about has been a hot topic lately. Dries's keynote from DrupalCon Chicago talked about how Drupal 8 needs better APIs for doing callbacks and non-HTML output formats.
> 3 votes

---
Tags: 7, performance, ajax
---


# Question
Title: How to display mini panes in specific pages of my site
I need to display mini panels only in selected pages.

Where and how should I mention it?

**For Example:**

In blog listing pages **i need to display the panels** in right side.

And in it's full view page **I should not show the panels** in right side.

How can this be done?

# Answer
> 2 votes
There are many ways this can be done.

Blocks are pieces of content which can be placed in specific areas of the page called regions. You can choose where to put these blocks in the block section of the admin

The standard block admin will allow you to put conditions on who can see the blocks and what paths they are displayed or hidden on. However this can get a little difficult to manage with many blocks and conditions.

Many people use the context module for such situations. This allows you to override the standard block admin and define a context under certain conditions (path being one of them) and define blocks which are displayed under these conditions.

---
Tags: 7
---


# Question
Title: Pathauto, user profile alias from content profile fields
I created the alias `bartender/profili/[content-profile-profile-profile_name-raw]-[content-profile-profile-profile_surname-raw]` for users.
I want to have '-' between name and surname but it always turns into a white space in my URLs.

Could anybody give me any clue about this?

# Answer
> 1 votes
In the "Automated Alias" settings page there is a fieldset near the top with rules for treating special characters; check it to see how it is treating hyphens.

---
Tags: 7, users, path-aliases
---


# Question
Title: Way to integrate a latex-based wiki into a drupal 6 site
I have a website with users already designed in Drupal 6. We would like to add an area/module that would allow registered users of a certain type/category to be able to collectively edit/contribute to a set of wiki-based statistical documents, ideally written in LaTeX, but that other users (registered and anonymous) could download in the original LaTeX or exported to .pdf. (Imagine a wiki-based, open-source statistics textbook.) There are wiki modules and LaTeX modules for Drupal, but no LaTeX-wiki modules.

Is there some stand-alone wiki software that could be hosted on a sub-domain of our site but uses the Drupal user permissions to manage access? Is there a Drupal module or option I haven't found?

What we have: Drupal 6 site that anyone can visit/see, but that requires registered user status to contribute/participate on site. We can add subdomains/create any databases, etc. needed on the servers to do what we need to do.

What we envision: A wiki that allows a subset of registered users to collaboratively edit/write statistical texts easily (many of these users are already familiar with LaTeX) that will preserve mathematical equations and render them onscreen (.html) and as .pdf output.

Version tracking and attribution to particular users is necessary.

Any user can view .html of current wiki, or download the raw LaTeX file (for their own use), or choose certain wiki pages to be exported as .pdf.

Is there some stand-alone wiki software that would meet these criteria? And, if so, could we somehow use the same user database as our drupal install to set permissions? We anticipate hiring someone to do the programming necessary (our current Drupal developers do not do this level of development), but it would be helpful to know whether we're looking for someone to modify two existing tools to work together or to write a new drupal module that suits our needs.

# Answer
> 2 votes
A solution would be to have a Drupal based wiki on your website and then to allow the usage of LaTeX markup for the wiki content. DruTeX\] may allow the later, while Wikitools should provide the former. They will both need to be properly configured.

---
Tags: files
---


# Question
Title: Table locking again, am I doing it correct?
I had a problem with table locking, solved in this question:

Table 'watchdog' was not locked with LOCK TABLES on custom module

I want to share my current code, because I'm still not sure if I am doing it correct.

I have two tables:

1. eventi\_list, for storing users reservation for selected event if there are free places of this event
2. eventi\_wait, for storing users reservation if there are no free places for selected event. If any user withdraw her/his reservation, the oldest reservation for current event (if exists) from this table move to eventi\_list table.

```
function eventi_book($nid) {
    $nid = (int) $nid;
    if (_eventi_if_node($nid)) {
        global $user;
        $uid = (int) $user->uid;
        $is_booked = _eventi_is_booked($uid, $nid);
        if (! $is_booked) {
            $is_booked = _eventi_is_booked($uid, $nid, 'eventi_waits');
        }
        if (! $is_booked) {
            db_query('LOCK TABLES content_type_event WRITE, eventi_list WRITE, eventi_waits WRITE, watchdog WRITE');
            $amount =  _eventi_places_amount($nid);
            if ($amount > 0) {
                _eventi_add($uid, $nid);
                db_query("UPDATE {content_type_event} SET field_event_places_amount_value = field_event_places_amount_value - 1 WHERE nid=$nid");
              //  cache_clear_all();
            } else {
                _eventi_add($uid, $nid, 'eventi_waits');
            }
            db_unlock_tables();
        }
    }
   // _eventi_redirect_to_prev();
}

function _eventi_if_node($nid) {
    $query = db_query("SELECT COUNT(nid) as count FROM {node} WHERE nid=$nid AND type='event'");
    $result = db_fetch_array($query);
    return $result['count'] > 0;
}

function _eventi_is_booked($uid, $nid, $tbl_name = 'eventi_list') {
    $tbl_name = '{'.$tbl_name.'}';
    $query = db_query("SELECT count(nid) AS count FROM $tbl_name WHERE nid=$nid AND uid=$uid");
    $result = db_fetch_array($query);
    return $result['count'] > 0;
}

function _eventi_places_amount($nid) {
    $query = db_query("SELECT field_event_places_amount_value AS amount FROM {content_type_event} WHERE nid=$nid");
    $result = db_fetch_array($query);
    return (int) $result['amount'];
}

```

function \_eventi\_add($uid, $nid, $tbl\_name = 'eventi\_list') { $tbl\_name = '{'.$tbl\_name.'}'; $t = time(); return db\_query("INSERT INTO $tbl\_name (uid, nid, created\_at) VALUES($uid, $nid, $t)"); }

I want to make sure that I never end up with negative number of free places of selected event. So I have to atomic access to places amount:

```
$amount =  _eventi_places_amount($nid);

```

and then I can update places amount, when I am sure that $amount is greater than 0:

```
db_query("UPDATE {content_type_event} SET field_event_places_amount_value = field_event_places_amount_value - 1 WHERE nid=$nid");

```

I don't like this solution, because I must to lock many tables. Is there a better way of doing this in Drupal?

# Answer
> 2 votes
MyISAM performs a table-level lock to do any SQL on a MyISAM Table.

If you convert everything to InnoDB, row-level locking is implicitly done for you. Multiversioning Concurrency Control (MVCC) allows each user to lock only row(s) needed.

Additionally, you may want to perform all atomic writes in a BEGIN...COMMIT transaction to group together several table updates as one unit. That's what InnoDB will do for you. InnoDB is ACID complaint. The A stands for ATOMICITY, a transaction's ability to be atomic.

---
Tags: 7, database
---


# Question
Title: How can I set a placeholder variable in page.tpl.php from a page callback?
I have a value in page.tpl.php that I would like to set in page callbacks, independently from the main content.

In page.tpl.php:

```
<?php print $placeholder ?>

<?php print render($page['content']); ?>

```

What I would like to do in the page callback:

```
function my_module_page_callback_foo() {
  $placeholder = 'foo';
  return 'Page Content';
}

```

Obviously, that isn't going to get me very far.

I'm hesitant to use hook\_preprocess\_page because then I'll have unnecessary conditional logic to determine what the menu item is (won't I?). Is there another, 'drupal way' of doing this?

I'm coming from a more 'Zend-y' world where I have access to my view and my layout variables from the controller.

# Answer
There are a few possibilities, not sure which one would work best for you. There isn't a really easy way to do that.

I would say the "drupal way" of doing that would be to expose your additional content as a block. You can configure that to only show up on specific pages and place it above the main content.

There is also hook\_page\_alter(), but that requires the same conditonal checks as a template\_preprocess.

You could also return a render array in your page callback and then display it separately in your page.tpl.php, something like `render($page['content']['system_main']['part_a'])` and so on. You could do that only in a template suggestion for a specific page, like page--yourpath.tpl.php.

To avoid messing with page.tpl.php too much, there is also the possibility of overriding the so called 'delivery\_callback' (see menu\_execute\_active\_handler() in your menu router item for that page. The default delivery callback is drupal\_deliver\_html\_page().
> 2 votes

# Answer
Since you're adding this directly into your page.tpl.php it seems like this should stay part of your theme and not deviate in origin. Not that I actually advocate adding things directly into the page template at all. Why not just create a region and place what you need into a programmatic block?

Anyhow, here is a theme only approach...

```
function MYTHEME_preprocess_page(&$vars, $hook) {
  $vars['placeholder'] = MYTHEME_build_placeholder();
}

function MYTHEME_build_placeholder() {
  $output = 'Hello!'
  return $output;
}

```
> 0 votes

---
Tags: 7, theming
---


# Question
Title: Printing the correct date value in a view
I have a content type with a Date CCK field that prints the correct date/time specified in nodes (using the correct timezone, format, etc.). I also created a view that uses this date field, but the time I am getting from the view date data is (+)4 hours off. The date information is being printed in a views template using the `$row` object (specifically, the `raw` array key inside of the date field array). This array provides the 'to' and 'from' dates (and time), the timezone, and all other relevant information, but the values are 4 hours off as I said above.

Is there something I need to do when printing these kinds of values in a view in order to get the correct time? I'm assuming the Date module does some sort of processing that the views data isn't getting. Any guidance would be great because I have no idea why this is happening.

# Answer
> 2 votes
1. Double check that your **site's timezone** is accurate at: Site Configuration \> Date & Time
2. Double check that your **user timezone** is accurate in your profile. Perhaps turn off user timezones (on the same admin pages as above.)
3. Confirm how timezones are handled on the specific **CCK field.** There are 5 options: Site's time zone, Date's time zone, User's time zone, UTC, and No time zone conversion.

---
Tags: 7, views, datetime
---


# Question
Title: I created a new content element: how do I print it out?
I created a new content element for the page content type.
How would I print out the content of that text area in page.tpl.php?

# Answer
> 1 votes
Your question hints that you're not quite yet understanding some of the basics of the Drupal CMS. I'd recommend you do a little reading about nodes, content types and paths.

The page.tpl.php template is the master page template for your entire theme. That means every page output regardless of node type or non-node page altogether.

Your node.tpl.php template is the template for specific nodes. You can create node-MYTPE.tpl.php to control a specific node type.

For further details, see Theming Drupal 6 and 7, and Drupal 6 Template Suggestions.

---
Tags: 7
---


# Question
Title: Layering fields on top of each other in views
I use Drupal 6 with Views 6.x-2.10.

I have a spotlight region on my page where I want to display a picture and a description of the next upcoming event.

I want the description text to be on top of the image, in a div with half transparent background, sort of `[---image--[description]-]`.
The image and description are fetched with a view. How do I style it so that one field in the view (the description) is on top of the picture field?

It would be easy to do if I could get the content in `<div class="picture"><div class="description"></div></div>`, but the view puts a hell of a lot of other divs around it, making it impossible to have the description inside of the picture div.

What should I do?

# Answer
> 3 votes
I find that the easiest and simplest solution is pure css. All you need to know, is the height of the box with text, then it's a simple matter of using `margin-top: -?px;` and creating a background with opacity. One option could be an image.

# Answer
> 1 votes
I have found using `position:relative;` instead of negative margins works more uniform in all browsers, you may want to try this if `margin-top` is giving you some issues in IE.

---
Tags: 6, views
---


# Question
Title: Best approach for [back][next] form submitting
I've been doing a **\[back\]\[next\]** to **\[finish\]** set of forms for user input fields, think of it like a questionnaire for user info where the user can still go back to the previous pages to update their info.. until it reaches the end of the pages to \[finish\]

I've done this before (hardcoded) but my code is too long and all the debugging gave me a headache. My first approach was:

* Use a PHP case to find out which phase/step the user is in now
* If the user clicks on \[next\], the page variable appends a +1 to the page count
* If the user clicks on \[back\], the page var deducts -1 to the page count, until it reaches \[finish\]
* If the user leaves the page for some reason and comes back to it, the session/cookie saved fills in the form values and which phase/step the user is in

This method of mine isn't very dynamic as the php case is hardcoded to a set of page numbers & phases, if the client wants to add another page; that can be a problem.

I'm new to Drupal; maybe Drupal already has some part of the API that makes this \[back\]\[update\]\[next\]\[finish\] easier, or a easier way to store cookies? If by PHP only, is there a better approach?

# Answer
You should always use the Form API for forms, unless you really wanted to use the Webform module. The learning curve it steeper but you gain more maintainability (everything is in code from the start) and flexibility. You can create multisteps form with the API. See form\_example\_wizard.inc and *Drupal 7 multistep forms using variable functions* (also with Drupal 6) for examples. Another solution, is to use the CTools' wizard API.
> 2 votes

# Answer
Try using the webform module like so: http://drupal.org/node/324779
> 1 votes

---
Tags: forms
---


title: How to make complex taxonomy searches

text:
# Question
Title: How to make complex taxonomy searches
How do I make complex taxonomy searches? Simplifying my drupal database to the following example (number in quotes are the taxonomy numbers assigned by drupal):

Nodes = Blogs, Stories, Questions, Forums

The following are taxonomy dropboxes

Author = A.Tan(1), B.Chua(2), C.Smith(3), D.Perez(4) Category = Gadgets(5), Food(6), Movies(7), Entertainment(8)

I want to make a complex search for example all Blogs by B.Chua pertaining only to Movies category? I could almost do this with the advance search since it allows checkboxes to search particular nodes and taxonomy however would not accept a blank or asterix as a search word.

# Answer
You can do that with Views. Create view for nodes, add a filter for these two vocabularies and expose them, so that they can be selected by the user.
> 2 votes

---
Tags: taxonomy-terms
---


# Question
Title: Using AJAX in Drupal 7 to change a form action
I would like to update the Drupal save\_edit module to add an auto-save feature. This would look similar to the Stack Exchange auto-save (draft saved). So far I've gotten the save portion working (saving the new node) but when I save again, it creates another node (this is not a surprise since I've not told it to do anything else).

I'm looking for how to tell the form that the node has already been saved and what the node id is.

I think I need to update the form action to point to /node/$nid/edit this way when the user clicks on the normal submit button, the node will be published (if set to).

Obviously I'm not wanting to refresh the page after these saves, that would be too easy ;-)

# Answer
For more examples, here is the link to Lullabot's jQuery and JavaScript in Drupal video tutorial source files. I would pay attention to the Drupal 7 quickview.module example.

Here they use a page callback that passes either 'nojs' or 'ajax' as the second argument. The Drupal ajax framework will change the links on the page from 'node/\[id\]/nojs' to 'node/\[id\]/ajax' if the client has ajax enabled. The page callback function tests for the presence of ajax. If not, it will use drupal\_goto() to gracefully degrade and reload the page. Or, if the ajax framework changed the link to ajax it will construct the HTML can send it back to the page with json headers and all using the new command() to manipulate markup, javascript Drupal setting, or CSS on the page.

I image with a tweaking this same technique can be used for Form API.
> 1 votes

# Answer
The URL doesn't matter, that is not what is relevant here.

What does matter is the node object in $form\_state, see http://api.drupal.org/api/drupal/modules--node--node.pages.inc/function/node\_form/7. You need to update that, then it should automatically update the form (and since the nid and so on are saved in value form field, they probably don't need to be sent to the client at all).

There might be other things necessary, but that should get you started..
> 1 votes

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


# Question
Title: What's the best way to spell-check a complete Drupal site?
I'd like to spell-check a complete site (some 300 pages) and my plan is this:

1. Spell-check complete site to collect all misspellings from all pages
2. Make a spelling dictionary to be shared by all editors
3. Rerun spell-check to get list of pages with misspellings
4. Install TinyMCE spell-check module over aspell, using spelling dictionary from 2
5. Get the editors to go over all misspelt pages and fix them

How can I run the complete spell-check in 1 and 3? I can hack it with wget, aspell and perl but is there an easier solution?
Can I present the misspellings from 3 in context, highlighted in the page?

# Answer
I considered CheckDog but then hacked a quick perl script using curl & aspell:

```
#!perl

use constant SITEMAP => "http://www.example.com/sitemap.xml";
use constant MAX_PAGES => 10;

$npages = 0;
for (qx{curl --silent @{[SITEMAP]}}) {
  m{<loc>(.*?)</loc>} or next;
  $page = $1;
  ++$npages > MAX_PAGES and last;
  print "$page\t"; # here so if aspell crashes, we know which page
  $typos = qx{curl --silent $page | aspell --mode=html --home-dir=. --personal=dict.txt list};
  $typos =~ tr{\n}{ };
  print "$typos\n"
}

```

Add valid words to dict.txt, where the first line is:

```
personal_ws-1.1 en 500

```

As per @Berdir and @kiamlaluno suggestion, we'll also try TextReview. The following use cases would be of interest to us:

1. Differences: hopefully better than a module that displays raw html side by side
2. Spell check: showing misspellings in context will be wonderful!
3. Similarity percentage: maybe we can use this to warn on duplicate pages?
4. Manually configured blacklists and whitelists: eg to avoid UK spellings "customise" in favor of US spellings "customize"
> 3 votes

# Answer
I haven't used them, but Text Review and Spellcheck could be helpful.
> 1 votes

---
Tags: 7
---


# Question
Title: Is there a module for site explanation messages?
Many sites have text areas which appear to explain things to new users. With an option to hide the message in future.

I haven't seen such a module for Drupal, does one exist?

I have tried googling but to be honest I have no idea what terminology to use when searching for one.

# Answer
The closest module I know is the Legal module, this is more for showing the terms of service or similar for users before registering, but it might be close to what you need.
> 1 votes

# Answer
The Advanced Help Injection and Export module is probably what you are looking for.

From project page, "This module assists you in writing help texts suitable for use with the Advanced Help module by allowing you to write your help texts in Drupal books. Once you've written the help texts you can inject help icons into any page, form or form item, linking them to the book page that should later appear. The final step is to export all of the help texts as well as the injection data into a new module consisting of Advanced Help files and a simple generated module. The module has all of the information needed to inject the help icons into the right pages, forms, and form elements. The new generated module is ready for distribution as a standalone project or a submodule in a larger project."
> 1 votes

# Answer
Hey Jeremy: I use a very simple jquery routine to create what you appear to be seeking. The idea is to place "teaser" explainer text on the various pages, with embedded links that trigger a jquery in-place expansion of the additional information.

For example, some initial high level explainer text appears below a form widget, with a link at the end of that one line beneath the form widget saying "more detail please"; clicking that link causes additional markup of any sort to expand in place where ever on the page you want it - with other elements moving aside to make room.

After expansion, that markup can contain additional links that also expand in place.

Using my super simple routine, one can create a single hierarchical page with dynamic, collapsing divs showing and hiding information complexity at will. Once you start using it, the finished pages really feel like how the web was original described (to me) as a hierarchical information platform - which hardly anyone actually implements.

Anyway: this logic is tiny, easy to use, and you can dink around with in and tell if it will do what you need in 30 minutes. http://www.missingubercartmanual.com/The-Basics-of-using-Java-Script-in-Drupal

I describe the code on a tutorial page for understanding how to use Java Script in Drupal.
> 0 votes

---
Tags: 7, forms
---


title: Can you do anything about the div soup?

text:
# Question
Title: Can you do anything about the div soup?
All the sites I have seen that build on drupal looks like it's hit by div soup. There are so many unused divs produced by the content and some templates I have looked on contribute more by adding even more terrible markup.

I know most people with some knowledge about drupal know about this issue. For instance, here is a dump from drupal.org:

So why does Drupal need all these divs? Is there any rational behind them or is it just a flawed design?

Is there anything that could be done with this issue or are there some plans to improve on all these divs? Maybe a module that remove the divs that are not required and append the class statements so that markup will look better?

Are there some modules or solution that tries to address this annoying issue?

# Answer
If you want to output a particular page element without burying it in DIVs, you can always put the relevant tag or `print render()` statement inside a strip\_tags() function. Admittedly, this is a bit of a kludge, but it works for many common cases.
> 1 votes

# Answer
This is the result of a flexible content management that tries to be everything to everyone. Adding more divs upon request would be difficult, so it provides everything anyone will ever need.

Every template can be overridden as you see fit. For an example of a theme that really clears out a lot of cruft, see Mothership.
> 9 votes

---
Tags: theming, forms
---


title: Putting a form into a menu

text:
# Question
Title: Putting a form into a menu
I've started learning Drupal (I'm starting with Drupal 7) and the best way to do that seemed to me to be in creating a custom theme from scratch.

I'm trying to create a menu in which the login form is displayed if the users are not logged in and the user menu if they are logged in. How do I go about doing this in proper Drupal fashion?

# Answer
Drupal already has a login block, which displays the login form, which by default only is displayed for anynomous users. So all you really need to do is add a block with the User menu (all menus has a block with the items) next to the login block and have it show for only authenticated users.

This is one of the things where configuration will get you all the way.
> 1 votes

---
Tags: 7, routes, forms
---


# Question
Title: Is it possible to make hook_view() the same as hook_edit()?
My current client does not like the separation between viewing their custom content types and having to travel to a different page to edit. They are pushing for the View page and the Edit page to be the same. Are there any negative ramifications of simply redirecting from `hook_view()` over to `hook_edit()`?

The client is a desktop application developer, with a large installed base of clients, and I'm making the first "web version" of their desktop software. They want their webapp to behave as close as possible to their last desktop version. Their application is sorta like a CAD/3D-Modeler, and "viewing a model" without the ability to make any edits makes no sense for their users. Hence the request to get rid of `hook_view()` and make `hook_edit()` triple functional (create,edit & view).

# Answer
Supposing that "model" is the content type you are referring, then I would use code similar to the following one.

```
function mymodule_menu_alter(&$items) {
  $items['node/%node']['title callback'] = 'mymodule_node_title';
  $items['node/%node']['title arguments'] = array('view', 1);
  $items['node/%node']['page callback'] = 'mymodule_node_page';
  $items['node/%node']['page arguments'] = array('view', 1);
  $items['node/%node']['access callback'] = 'mymodule_node_access';
  $items['node/%node']['access arguments'] = array('view', 1);
  $items['node/%node/edit']['title callback'] = 'node_node_title';
  $items['node/%node/edit']['title arguments'] = array('edit', 1);
  $items['node/%node/edit']['page callback'] = 'mymodule_node_page';
  $items['node/%node/edit']['page arguments'] = array('edit', 1);
  $items['node/%node/edit']['access callback'] = 'mymodule_node_access';
  $items['node/%node/edit']['access arguments'] = array('edit', 1);
}

function mymodule_node_access($op, $node) {
  if ($node->type == 'model') {
    return ($op == 'view') ? node_access('edit', $node) : FALSE;
  }

  return node_access($op, $node);
}

function mymodule_node_page($op, $node) {
  if ($node->type == 'model') {
    return node_page_edit($node);
  }

  if ($op == 'edit') {
    return node_page_edit($node);
  }
  if ($op == 'view') {
    return node_page_view($node);
  }
}

function mymodule_node_title($node) {
  if ($node->type == 'model' || $op == 'view') {
    return node_page_title($node);
  }

  if ($op == 'edit') {
   return t('Edit');
  }
}

```

Using this code, the node edit form is always show accessing /node/%node, or /node%node/view for the "model" content type.
> 1 votes

# Answer
There is a module which in effect does the desired. At least I like it and want to mention it.

> Reviser is an inline wysiwyg editor, meaning you can edit the node body content without going to the edit page. Just click anywhere on the node body and start editing. Since you are actually editing the HTML DOM on the same page where the content is actually viewed all changes you make will appear exactly the same when you hit save. A true what-you-see-is-what-you-get experience that a wysiwyg editor should provide
>
> This really is finally a wysiwyg editor that you will want to use. There is no need to go between the edit and view pages to make sure everything looks right. Just edit away until it 100% correct, hit save and then you are done.
> 1 votes

---
Tags: 7, hooks
---


title: Show all terms of a vocaboulary

text:
# Question
Title: Show all terms of a vocaboulary
I have this function that I used in a similar situation (Drupal show all terms of different vocabulary) that prints the terms of a node with a corresponding parent (if applicable). In my template.php file:

```
function theme479_print_terms($node, $vid = NULL, $ordered_list = TRUE) {
     $vocabularies = taxonomy_get_vocabularies();
     if ($ordered_list) $output .= '<ul>'; //checks to see if you want an ordered list
     if ($vid) { //checks to see if you've passed a number with vid, prints just that vid
        $output = '<div class="tags-'. $vid . '">';
        foreach($vocabularies as $vocabulary) {
         if ($vocabulary->vid == $vid) {
           $terms = taxonomy_node_get_terms_by_vocabulary($node, $vocabulary->vid);
           if ($terms) {
             $links = array();
             $output .= '<span class="only-vocabulary-'. $vocabulary->vid . '">';
             if ($ordered_list) $output .= '<li class="vocabulary-'. $vocabulary->vid . '">' . $vocabulary->name . ': ';
             foreach ($terms as $term) {
              // Check for terms parent, if found assign to $parent variable
              if ($get_parents = taxonomy_get_parents($term->tid, 'tid')) {
                foreach ($get_parents as $parents) {
                  $parent = $parents->name . '/';
                }
              }
               $links[] = '<span class="term-' . $term->tid . '">' . l($parent . $term->name, taxonomy_term_path($term), array('rel' => 'tag', 'title' => strip_tags($term->description))) .'</span>';
             }
             $output .= implode(', ', $links);
             if ($ordered_list) $output .= '</li>';
             $output .= '</span>';
           }
         }
       }
     }
     else {
       $output = '<div class="tags">';
       foreach($vocabularies as $vocabulary) {
         if ($vocabularies) {
           $terms = taxonomy_node_get_terms_by_vocabulary($node, $vocabulary->vid);
           if ($terms) {
             $links = array();
             $output .= '<ul class="vocabulary-'. $vocabulary->vid . '">';
             if ($ordered_list) $output .= '<li class="vocabulary-'. $vocabulary->vid . '">' . $vocabulary->name . ': ';
             foreach ($terms as $term) {
              // Check for terms parent, if found assign to $parent variable
              if ($get_parents = taxonomy_get_parents($term->tid, 'tid')) {
                foreach ($get_parents as $parents) {
                  $parent = $parents->name . '/';
                }
              }
               $links[] = '<span class="term-' . $term->tid . '">' . l($parent . $term->name, taxonomy_term_path($term), array('rel' => 'tag', 'title' => strip_tags($term->description))) .'</span>';
             }
             $output .= implode(', ', $links);
             if ($ordered_list) $output .= '</li>';
             $output .= '</ul>';
           }
         }
       }
     }
     if ($ordered_list) $output .= '</ul>';
     $output .= '</div>';
     return $output;
}

```

I have this vocabulary structure:

* Foods
    + Fruits
    + Fruit\_with\_seeds

This function only shows:

* Fruits
    + Fruit\_with\_seeds

Is it possible to show the entire hierarchy of a vocabulary?

# Answer
I'm not sure what exactly you are looking for. The taxonomy terms for a node are normally nested inside `$node->taxonomy`. If you want all the terms "above" the terms inside the node, you should take a look at taxonomy\_get\_tree(). To the code above: I would urge you to seperate the tree-logic from the output; first create the array, then render the output.
> 2 votes

# Answer
```
$result = db_query('SELECT DISTINCT(tn.nid), t.tid, t.name, n.nid, n.title
FROM {node} n INNER JOIN {term_node} tn ON n.nid = tn.nid
INNER JOIN {term_data} t ON tn.tid = t.tid ORDER BY n.nid DESC');

while ($o = db_fetch_object($result)) {
  $items[$o->tid][] = l($o->title, 'node/' . $o->nid);
  $terms[$o->tid] = $o->name;
}

if (isset($items)) {
  foreach ($items as $tid => $item) {
    echo theme('item_list', $item, $terms[$tid]);
  }
}

```
> 0 votes

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


title: Multiple user avatars

text:
# Question
Title: Multiple user avatars
I'm looking at putting together a Drupal 7 installation for a community website. One of the features of the website will actually be in specific user profiles, which will double as "About" pages in a catalogue of team members. Anyway, the site is currently designed in such a way that a user has a detailed photo on their page. I'm looking at one of two different options, and would like some input as to how best to carry out this task.

1. After a user uploads a profile picture (with the ImageStyle profile\_picture) , have the system create a duplicate photo for the forum avatar based on what was just uploaded, only resize and crop the photo to be 200x200 pixels, and have the duplicate be named under the image style forum\_avatar.
2. Provide an additional upload form for avatars in the user configuration settings with Drupal 7.

Obviously, the first one would take a little bit of doing, but I'm really curious: what would be the best way to carry out one of these two processes?

# Answer
> 1 votes
Assuming that you want to use the same avatar image, just in different sizes, you do not have to duplicate anything.

Being able to display the same image with different styles is the whole point of having different image styles. "Styled" images are created on demand, according to the request. This already works out of the box for normal image files (For example, you can chose a different image style for teaser and default view modes).

The user avatar image can be displayed with different image styles too, the only problem right now is that you can't select the image style when using theme\_user\_picture(). There is however already a patch for that. And if you're using Views, it should already be possible to choose the image style for the user picture.

---
Tags: 7, users, media
---


# Question
Title: My module adds a CCK field to an existing content type. How do I then modify an existing view to sort using the new field?
I am building a new module ('best\_answer') that builds on the functionality an existing module ('answers').

The new module adds a new CCK field ('best\_answer\_p') to a CCK content type ('answer') that was defined in the original module.

The original module also defined a view ('question\_answers') which lists answer nodes, sorted by several factors. I'd like to modify this view so that it also sorts by the new field 'best\_answer\_p'.

I *could* do this by simply overriding the view, using the Views UI. However, what this means is that if any other module also wants to override the view in some way, my 'best\_answer' sort will be lost.

So, I'd like to do this in a way that programmatically alters the existing view instead of overriding it. I am trying to do this using Hook\_views\_query\_alter. But I run into an error.

Could anyone point me in the right direction?

Here is my code:

```
function best_answer_views_query_alter (&$view, &$query) {

  if ($view->name == 'question_answers') {

    // add the best answer field to the query
    $query->tables['node']['node_data_field_best_answer_p'] = array(
      'count' => 1,
      'alias' => 'node_data_field_best_answer_p',
    );

    // sort answers so that the best answer is displayed first
    $new_orderby[0] = 'node_data_field_best_answer_p_field_best_answer_p_value DESC';
    foreach ($query->orderby as $key => $value) {
      $new_orderby[$key+1] = $value;
    }
    $query->orderby = $new_orderby;

  }
}

```

Here is the error:

> user warning: Unknown column 'node\_data\_field\_best\_answer\_p\_field\_best\_answer\_p\_value' in 'order clause' query: SELECT node.nid AS nid, votingapi\_cache\_node\_points\_vote\_sum.value AS votingapi\_cache\_node\_points\_vote\_sum\_value, node.created AS node\_created FROM node node LEFT JOIN votingapi\_cache votingapi\_cache\_node\_points\_vote\_sum ON node.nid = votingapi\_cache\_node\_points\_vote\_sum.content\_id AND (votingapi\_cache\_node\_points\_vote\_sum.content\_type = 'node' AND votingapi\_cache\_node\_points\_vote\_sum.value\_type = 'points' AND votingapi\_cache\_node\_points\_vote\_sum.tag = 'vote' AND votingapi\_cache\_node\_points\_vote\_sum.function = 'sum') LEFT JOIN content\_type\_answer node\_data\_field\_answer\_question ON node.vid = node\_data\_field\_answer\_question.vid WHERE (node.status \<\> 0 OR (node.uid = 1 AND 1 \<\> 0) OR 1 = 1) AND (node.type in ('answer')) AND (node\_data\_field\_answer\_question.field\_answer\_question\_nid = 2) ORDER BY node\_data\_field\_best\_answer\_p\_field\_best\_answer\_p\_value DESC, votingapi\_cache\_node\_points\_vote\_sum\_value DESC, node\_created DESC LIMIT 0, 10 in D:\xampp\htdocs\drupal\sites\all\modules\views\includes\view.inc on line 771.

# Answer
You *should* override the view and change the sort. I have never seen a module that attempted to alter a view defined by another module.
> 1 votes

---
Tags: views, entities
---


# Question
Title: FAPI 'radios' don't respect '#default_value'?
I noticed that the 'comment settings' radio buttons ('#type' =\> 'radios') were not respecting their default value settings in my content types.

I have several module created custom content types, as well as the normal 'Page' and 'Book' content types in this D6 installation, and all of my custom content type's node forms are appearing with apparently random values for their default values.

Repeated loads of the same node form shows different default values for 'comment settings' every time. Looking at the $form arrays for my content types and comparing them against the $form array for a Page content type I only saw one difference: the use of the '#parent' element; I added to my logic (as shown below) but it makes no difference.

I noticed this while trying to create a 'radios' form element for a non-node creation form. Here's some logic I'm using that *should* give me a consistent default value, but does not:

```
$form['radios-test'] =
    array( '#type'          => 'radios',
           '#parents'       => array('radios-test'),
           '#title'         => '',
           '#default_value' => 0,
           '#options'       => array(t('first'), t('second'), t('third')),
           '#description'   => 'explainer text goes here',
         );

```

What am I missing here?

# Answer
> 3 votes
Your code works fine at my end, I always get "first" selected on repeated page refresh. Can you copy paste your actual code that is showing different value for comment settings? Maybe something else is interfering. Can you paste your code at one of the pastebins - http://pastebin.com/ ?

Below is a screenshot at my end.

---
Tags: 7, forms
---


title: What are the available image sliders?

text:
# Question
Title: What are the available image sliders?
I want to know what sliders are available for Drupal 7, and which ones can be used in blocks.

# Answer
> 9 votes
See handbook page Comparison of Rotator / Slider modules.

---
Tags: 7, media, javascript
---


# Question
Title: How do I Print/Display Site information Form
I'm trying to print the Site Information Form, and a series of other forms in the near future, inside a lightbox using a snippet of code I found similar to the following.

global $user; module\_load\_include('inc', 'user', 'user.pages'); print user\_edit($user);

This, along with some other code not mentioned, will display the user account form. But I'd like to know how do I print the Site Info Form, and any other form I may wish to display in the future? What process or methods can I use to find out what I need to do?

I hope I'm not being too vague. Any pseduo-code, suggestions or even a hint would be greatly appreciated.

Thanks.

# Answer
> 2 votes
```
<?php print drupal_get_form('system_site_information_settings'); ?>

```

You can output any form in Drupal using drupal\_get\_form once you know it's form\_id (which is the function name that returns the form array)

# Answer
> 0 votes
You might wanna look at the answer provided at - Theming the node edit forms to open them within Lightbox \- You can use popups module to display and work with any form in a lightbox like popup which u can theme.

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


# Question
Title: Is there a way to exclude the addthis module's output in the $content variable?
The `$content` variable in my `node.tpl.php` file outputs some CCK field content, the content body, five star content, and the add this content. I don't want it to show `add this content`. Is there a way to override the `$content` variable to make it not show `add this content`? I can't do this by editing the addthis module's settings, because I invoked the `add this` in another place.

# Answer
You can unset or alter items in `$node->content` by implementing hook\_nodeapi() and using the 'alter' `$op`.
> 2 votes

# Answer
I'm not sure what you mean by:

> I invoked the "add this" in another place

You may want to have a look at implementing one of the following hooks, to remove it from the `$content` variable:
> 0 votes

---
Tags: 7, theming
---


# Question
Title: Single document, multiple filetypes for download: how to manage?
I want to upload/attach several documents to a book node. Each document will be offered in a number of file formats, for example:

* Report2010.pdf
* Report2010.rtf
* Report2010.doc
* Agreement11.pdf
* Agreement11.rtf
* Agreement11.doc

Given this, in order to:

1. Offer a sensible upload interface (like FileField) that allows an unlimited number of files to be uploaded.
2. Present these files for download, for example:

**Is there a robust way to relate the different file formats for each document to each other?** By robust, I mean something that (for example) doesn't rely on the user naming the files in a particular way for it to work.

# Answer
> 0 votes
The Fieldgroup module seems to do almost everything I need: for each document, I create a group which has a filefield for each file type (PDF, DOC, RTF). It doesn't solve the requirement to allow unlimited files, but the workaround would be to create a number of groups that would reasonably cater for most scenarios.

# Answer
> 0 votes
node-\[type\].tpl.php

```
$fields = array('field_reports', 'field_agreements'); // you should to create 2 fields for different filenames
$items = array();
foreach($fields AS $field){
  $exts = array();
  foreach($node->{$field} AS $file){
    // delete real extension from file name
    $filename = explode('.', $file['filename']);
    $ext = array_pop($filename);
    $exts[$ext] = l($ext, $file['filepath']);
    $filename = implode('.', $filename);
  }
  ksort($exts);
  $items[] = t('!filename - download as: !links', array('!filename' => $filename, '!links' => implode(', ', $exts)));
}
print theme_item_list($items);

```

Hovewer, this code must be in template.php in phptemplate\_preprocess\_node function.

# Answer
> 0 votes
You can use

http://drupal.org/project/mimedetect
to ensure the files have the correct mime type, and then

http://drupal.org/project/filefield\_paths
http://drupal.org/project/file\_aliases
http://drupal.org/project/token

to rename them based on file values

# Answer
> 0 votes
You should make a custom CCK formatter (start with filfield\_formatter.inc as example) to output the files the way you want without hacking up your template files.

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


# Question
Title: Is there a way to assign categories before the articles are added via the Aggregator module?
I'm interested to aggregate posts with the built-in Aggregator module.

My problem is that it's not possible to assign a category at the same time. Users have to later find the post and manually set the category.

Is there a way to to assign categories when the post is created?

# Answer
The aggregator is for importing feeds from other sites, but it sounds more like you're trying to create new feeds on your site from your content. For that use, you could use Views.
> 3 votes

---
Tags: 7, feeds
---


title: Extending a CCK field formatter

text:
# Question
Title: Extending a CCK field formatter
I've created a custom formatter (display) for filefield but I'd like to add a settings page per field for width and height.

Currently my code only consists of the bare minimum to get the formatter to work (which it does). However I'm currently hardcoding width and height at the hook\_theme() level.

I've not found any examples of setting pages for formatters only for custom fields. I suspect that it's not possible to do this for a formatter and I'd have to define my own field rather than formatter. I could create a global admin page and loop through all fields and set the settings as a variable but that might become an issue when upgrading it to 7.

Any feedback or ideas would be great.

# Answer
> 1 votes
D7 has this baked into the field formatters. You could look at how that is done and emulate it. But I suspect that would be quite a lot of work. How far off is D7 for you? It could be worth waiting till then to allow field settings.

# Answer
> 0 votes
The way imagecache handles it is that you define certain presets through separate configuration and each preset generates a new formatter option.

---
Tags: 6, entities
---


title: Options for "create and reference"

text:
# Question
Title: Options for "create and reference"
In a screencast based on Drupal 6, I spotted (~3:45) that several fields had an additional "create and reference" icon that would pop a secondary dialog, for in-place creation of non-existent nodes, which would then be added as reference. This appears to be missing from Drupal 7 Reference module, which is now responsible for fields of that type, and I can't seem to find any evidence it's going to be put back.

My homework:
I dug up an old groups.drupal thread where eventually someone posted a round-up of many options last year, but most of those now range from inactive to abandoned. A few have issue threads full of people asking about a Drupal 7 upgrade, with absolute silence from the maintainers. From that list, two actually show Drupal 7 work:

1. Node Reference Create: Seems to only do the barest minimum: create a node with a title of what you input in the textarea. To provide values for any other fields, you need to make your way over to that node's individual edit screen. This isn't enough for my needs.
2. Corresponding node references: I'm actually just not sure why this is even on the list. I've installed it, poked around, and can't actually find this feature implemented. Am I just missing it?

I'm also aware of Relation, which seems intended to supersede just about every other reference-ish module and I presume will do this. But it doesn't even have any released code at the moment, and this research is for something I'm working on right now, timeline of probably a couple months tops.

Are there any *currently* viable options for accomplishing this? I'm willing to guinea pig anything at least in beta status. Or do I need to give serious consideration to doing this in Drupal 6 instead?

# Answer
> 1 votes
If you are using the overlay module in Drupal 7. Create the main node but use the Node Reference URL widget on the referencing nodes. This will put links on every node view page that behave similar to the Relationships module. If you add Field Collections module to group all the fields, you can get edit in place with overlay popups on the node.

The workflow would be like this. 1. Create a node. 2. The node form only asks for the title of the node. 3. Return to the node with several different parts, each getting their own popup form or if JavaScript is enabled a return destination back to the node after creating or editing.

# Answer
> 0 votes
It doesn't have a Drupal 7 release, so far, but the Node Relationships module to is the module for this feature, on Drupal 6.

> The Node Relationships module provides methods to complete two way relationships between content types enhancing the features of node reference fields.
>
> Almost all the settings to administer the features of this module can be located at Administer -\> Content management -\> Content types -\> \[type\] -\> Relationships.

# Answer
> 0 votes
While waiting for a solution to mature, I've just been adding field help descriptions to nodereferences such as 'Choose a foo or add a new foo.'

---
Tags: 7, nodes
---


# Question
Title: Configuring Drupal 6.20 to display a different icon in a specific region on a specific group of pages
I've added a block called 'Course Information', configured the block to display on a particular group of pages (courses/full-time/\*). This works fine, but I don't know to configure Drupal to display a different icon for each of the pages.

At present, the block contains:

```
<img alt="An icon symbol" src="/sites/default/files/images/icon-1.png" />

```

This will display the same image on each page that the block is used. How would I go about having a dynamic filename inserted, like icon-2.png, icon-3.png, icon-n.png?

# Answer
> 4 votes
If this is being displayed on nodes you can add an imagefield to the content type and set its display settings to excluded. Then make a views block that displays the image field, using a default argument of the current node.

# Answer
> 0 votes
You can use PHP-code inside your block, and use the arg() function to solve it like

```
 print '<img alt="An icon symbol" src="/sites/default/files/images/icon-' . arg(2) . '.png" />'

```

This depends on the * behind full-time. It would be better to use an extra function with a mapping (\* =\> int), and validation inside your theme or a module.

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


# Question
Title: Views - currently logged in user problem
There's a taxonomy list labeled `games-list` that's used in both the content type named `game` and user field `subscribed`. Each `game` has exactly one of the terms from `games-list` selected, but a user can select an unlimited amount of items within `subscribed`.

To be clear, both the user field `subscribed` and the content type field `game` are a term reference field that's linked to `games-list`.

My goal is to create a view that shows a list of content from `game` that is unique to each user, and that only shows the values of `game` that has been selected by the user from `subscribed`.

Whenever I try to filter by "currently logged in user," it only shows content that was authored by that user. Specifically, how do I configure the view to show only content that the user wants, regardless of who authored that content?

# Answer
> 4 votes
I figured it out.

The key was to create a "user" view from the beginning, and not a "content" view. Then, the view provided me with all the necessary relationships/filters that I could use. I got this idea from Views - Filtering nodes by current user profile field.

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


title: Turn numerical filter into ON/OFF

text:
# Question
Title: Turn numerical filter into ON/OFF
I'm using uc\_best\_sellers to count the number of times a product has been sold.

The module provides a numeric views filter like this:

I'd like to have a view like this:

A product would be a best seller if it was sold more than 50 times (in my case).

What would I need to achieve this filtering style?

# Answer
Instead of using exposed filters for this, I think it will be easier to make separate views displays with overridden filters. Then either use quicktabs to display the different filter options, or make each one a page display with a path and output the links to the filter displays in the headers.
> 6 votes

---
Tags: views, 6
---


title: Block template suggestions

text:
# Question
Title: Block template suggestions
Is there a way to use a custom template for each block by title? For example, if I named my block "test1", and it is in the region "left1", I want to use the following template suggestions:

* block-left1-test1.tpl.php
* block-left1.tpl.php
* block-test1.tpl.php

Is there a list of template suggestions for blocks?

# Answer
> 6 votes
The Drupal theming system has a concept called "template suggestions". When a theme hook is invoked, Drupal checks if the theme hook is implemented as a template or as a function. In case of a template, All preprocess functions for that theme hook are invoked. This means that every module or template can add its own data to the variables that will be made available to the template. Those variables are passed around as a large array, `$variables`. This array can contain a list of template suggestions as a nested array called `$variables['template_files']`. Drupal will later reverse that list and use the first existing template it can find. See the documentation on drupal.org for more details.

Now what you can do is:

1. Add a function to your theme's template.php named `[themename]_preprocess_[themehook]` (eg. `function mytheme_preprocess_block(&$variables) {}` )
2. In that function, construct the desired template name suggestions
3. Add those suggestions to the `$variables['template_files']` array

By the way, if I'm not mistaken you cannot use the region name in the template suggestion, because at the time the block is rendered, it is not yet known in which region the output will be shown.

PS 1: It helps if you tell us which Drupal version you're using.

PS 2: I'm voting for this question to be moved to https://drupal.stackexchange.com/

# Answer
> 3 votes
The template suggestion patterns for blocks (and the rest of core) can be found at http://drupal.org/node/1089656. Instead of using the block's title, you use the block's id, such as block--block--1.tpl.php would be for the block that block module defined (user defined) with an id of 1 (you can find the id and module in the url when you edit a block).

You can also use region names, but there's no need to use both the id and the region name since a block can only go into one region.

# Answer
> 1 votes
I'm not sure if it would do exactly what you're looking for, but the Block Theme module sounds close. A similar module worth looking into is Skinr.

---
Tags: blocks, theming
---


# Question
Title: How to use Google and Ubuntu fonts on Zen theme
How can I use Ubuntu font and Google fonts on Zen theme?

# Answer
You can also try Google Fonts.

> This module enables you to add Google Fonts to your site using the Google Font API.
>
> ### Benefits of the Google Font API
>
> * A choice of high quality open source fonts.
> * No Javascript needed, pure CSS!
> * Works in most browsers.
> * Extremely easy to use.
> 4 votes

# Answer
Just do it as you would normally:

* For Google Web Fonts copy the `<link>` to your html.tpl.php, above `<?php print $styles; ?>`
* For Ubuntu or any other font just use `@font-face`

Then just apply the font normally in your CSS.
> 2 votes

---
Tags: 7, theming
---


title: Taxonomy terms follow/unfollow module

text:
# Question
Title: Taxonomy terms follow/unfollow module
Is there any module or options to allow site users to follow or unfollow the taxonomy terms?Basing on the following terms, I have to send a notification if any new post has been created on those particular terms.

# Answer
I think that this module will do the trick: Subscriptions.
> 5 votes

# Answer
Notifications or Subscriptions are the best options.

> This is a complete Subscriptions/Notifications Framework aiming at extendability and scalability. It allows any number of plug-ins defining new event types or subscription types or a different user interface.

> This module enables users to subscribe to be notified of changes to nodes or taxonomies, such as new comments in specific forums, or additions to some category of blog. Once enabled, all nodes will have an additional link that allows the user to change their subscriptions. Users have tab on their user screen to manage their own subscriptions.
> 2 votes

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


title: Theming user-profile

text:
# Question
Title: Theming user-profile
I am on Drupal 7. Hi, I have installed the Devel module and I am using it to help me theme the user-profile.tpl.php. I want to show the e-mail information only when the user looking into the user info page is the own user.

I am checking the currently logged in user with $user-\>uid.

Now I want to get the uid corresponding to the current user page to evaluate if they are the same so that I can print the e-mail. When I go to the Devel interface, it shows me the information I need on the Load area, when expanding the stdClass information.

How can I use these attributes on the stdClass? I was expecting to do something more or less like $somethinghere-\>uid to grab the current page user uid, but my trial-and-error process isn't working, I have tried everything... Thanks.

# Answer
> 2 votes
You should be able to get the account of the current page via

```
$account = menu_get_object('user');

```

and then check

```
if ($account->uid == $user->uid)

```

menu\_get\_object will grab the loaded object based on the url

---
Tags: 7, theming
---


# Question
Title: Embed some user profile fields in a block form
I've added some fields to user profile.
None of these fields are displayed on registration form, but I want user can edit them quickly when he is logged.
I want to embed some fields in a static content and display them to the user: how can I manage this? Can I create a php page or is it better using hook\_form?

# Answer
This should give you a start. Probably it is not the most elegant solution, but after 5 minutes of hacking, this is what I got. It works, and updates the profile fields (alone).

```
  function custom_block_info() {
     $blocks['user_profile'] = array(
       'info' => t('User profile edit'),
       'cache' => DRUPAL_NO_CACHE,
     );

     return $blocks;
    }

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

      switch($delta) {
        case 'user_profile':
          $block['subject'] = t('Fill your profile');
          $block['content'] = drupal_get_form('custom_profile_form');
          break;
      }

      return $block;
    }

    function custom_profile_form($form, &$form_state) {
      global $user;

      $form_state['user'] = $user;
      $form['#user'] = $user;
      $form['#user_category'] = 'account';
      $form['actions']['submit'] = array(
        '#type' => 'submit',
        '#weight' => 100,
        '#value' => t('Save'),
      );

      $form['#action'] = url('user/' . $user->uid . '/edit');
      // $form['#validate'][] = 'user_profile_form_validate';
      $form['#submit'][] = 'user_profile_form_submit';
      field_attach_form('user',$user,$form,$form_state);

      return $form;
    }

```
> 2 votes

---
Tags: 7, entities
---


# Question
Title: Use Drupal as a 'cloud system' frontend, what is your opinion?
I'm working on a small project where I need implement some kind of cloud architecture.

I'd like to deploy multiple Drupal installs among multiple servers; one would act as a domain controller and other as nodes. It should be simple to scale; adding nodes to the cluster would be as simple as cloning a node install and changing it's parameters (such as IP address and name). The new node will then announce itself to the controller which would update its nodes-list records.

I also like to be able to manage users in a centralized way; I would add users to the controller and assign them one or many nodes; once created it would sync to the target node(s) (e.g. create the user in the unix list as well as in drupal install on the target node).

Finally, once logged in the controller, the user would be able to do various operations such as:

* download/upload files to nodes (on which he's granted to)
* execute predefined shell commands such as starting/stopping services (probably as a module that would do all that stuff)

I hear that Drupal 7 has now some interesting file management modules in core; can they help in my case? Also, what would be the best communication protocol for accessing the different nodes from the controller?

Is it possible to have a kind of RPC call to a module (on target node) from the controller and get the result back ?

Any thoughts or starting points?

# Answer
> 4 votes
You might want to look at Aegir.
It will let you manage multiple Drupal sites across multiple servers; you can add new servers via the Aegir master controller and once the servers are known to the controller you can create complex Drupal installs via the UI (Aegir master) with db on one server and code on other, mix and match, etc.

One of the cool stuff is that Aegir can also take a drush make file and assemble a Drupal install for you; it supports Drupal distributions which let you not only install Drupal, but also Open Atrium, Pressflow, Open Publish, etc.

If I were you I would definitely look at Aegir even if it doesn't take care of all my needs as it will be the only logical place to start extending.

For an introduction see An introduction to the Aegir Hosting system.

There are so many Aegir videos online; these are some of my favorites:

If you like looking at code, here is the code for provisioning system which does all the magic: http://git.aegirproject.org/?p=provision.git;a=summary.

---
Tags: 7
---


# Question
Title: Display a Views slideshow only if more than one image
I have a content type with an image field that allows multiple values. I have a View that displays the images using Views Slideshow.

If there is only one image added to a node, I just want to display it as a static image. If multiple images have been added, I want to display the slideshow View.

I'm using a Panels Page override for this content type, so I can use a visibility rule for the Views slideshow pane (i.e. only display if number of images \> 1). But I'm not sure how to check the image field to see if there is more than one image for the current node?

Am using Drupal 7.

# Answer
I think you'd have to do some custom coding to get that result. To simplify, you'd have to make a separate field for the single image option.
> 1 votes

---
Tags: views, panels, media
---


title: How do I disable comment auto approval?

text:
# Question
Title: How do I disable comment auto approval?
I have comments that are being auto approved in Drupal and I'd like to disable that. I want to approve comments before they are published.

# Answer
If a comment is 'auto approved' as you call it, depends on the user's permissions. To change it, log in as administrator, go to `/admin/user/permissions#module-comment` and make sure that the 'post comments without approval' permission is not set for roles that are not allowed to post comments without approval.
> 17 votes

# Answer
In Drupal 7 authenticated (logged in) users have the 'Skip comment approval' property set by default. This can be changed at `/admin/people/permissions/list#module-comment` to put the comments in an approval queue, before they are published.
> 4 votes

---
Tags: comments
---


title: post comments with approval on forum

text:
# Question
Title: post comments with approval on forum
i use advanced forum. in permission page and comment module permission i **dont** set post comments without approval for authenticated user but when authenticated user send post on forum it immediately appear in forum without admin approval. but if this user add comment for a post it will add to approval list. why?

**edit**: there is my mistake. when i dont set post comments without approval for authenticated user it works correctly (and user cant post **comments**) however authenticated user can create **forum topic** without approval.? how to handle this?

# Answer
> 4 votes
Have in mind that a post is a node, so it doesn't behave such as comments and so, it doesn't fall into the same logic. If you want moderation for posts, you should do something else, maybe playing with rules (and or views) to establish a moderation panel/system.

---
Tags: users, nodes
---


# Question
Title: Starting batch operations from hook_node_update()
When importing content using Feeds using an importer associated with a node type, the mapping can be configured to assign taxonomy terms from the *Feed Node* to the imported *Feed Items*. On a project, we need to extend this feature by also updating all the already imported *Feed Items* when a *Feed Node* is updated.

This can be done using `hook_node_update($node)`. But since a single *Feed Node* can have a lot of *Feed Items*, they cannot be all updated in a single HTTP request otherwise we may encounter a timeout. The obvious way to avoid timeouts, is to use the Batch operations API.

Most of the time, `hook_node_update()` implementations will be executed because `node_save` has been called from a form submit handler, therefore, most of the time, there is no need to call batch\_process from a `hook_node_update()` since it will be called automatically at the end of the form processing. Calling `batch_progress` from `hook_node_update()` may also produce unexpected result since it will prevent other implementation of the same hook or others hooks to be executed.

But what about the times when the `hook_node_update()` implementations are not executed from a form submit handler. For instance, when `node_save` is called from an implementation of `hook_cron`? Is there a way to detect these cases to either run all the update at once or delay them to a dedicated queue?

# Answer
> 1 votes
As pointed in kiamlaluno's answer, there is no execution context information passed to `hook_node_update()` implementations. So we ended up using `debug_backtrace()` to look up for the currently processed form (if any). If a form is processed, `drupal_process_form()` will handle batch processing for us. If not, we can't safely start a progressive processing of the batch. But we can run the whole batch in a single pass. This can lead to timeout and should really be replaced. Either by delaying operations execution (queued operations) or by starting progressive processing of the batch after all update hook have been run (but how ?).

```
function _MODULE_get_currently_processed_form() {
  $backtrace = debug_backtrace();
  while ($frame = next($backtrace)) {
    if (isset($frame['function']) && $frame['function'] == 'drupal_process_form') {
      return array(
        'form_id' => $frame['args'][0],
        'form' => &$frame['args'][1],
        'form_state' => &$frame['args'][2],
      );
    }
  }
  return FALSE;
}

function MODULE_node_update($node) {
  if (some_condition_on($node)) {
    $batch = array(
      'operations' => array(
        // ...
      ),
    );
    batch_set($batch);
    $currently_processed_form = _MODULE_get_currently_processed_form();
    if (!$currently_processed_form) {
      // We are not currently processing a form, the batch processing won't be
      // automatically started. But we cannot start processing it because it
      // will end the request and prevent any other post node update code to
      // run. So we process the batch in a single pass and hope for the best.
      // FIXME: Start progressive processing of the batch after node update
      // processing (using hook_exit?) or use other delayed execution (using
      // queued operation?)
      $batch =& batch_get();
      $batch['progressive'] = FALSE;
      batch_process();
    }
  }
}

```

# Answer
> 0 votes
In short, it is not possible to know which function invoked a hook implementation; a hook doesn't get an argument that, for example, is `TRUE` when the hook is called from a form submission handler and `FALSE` when the hook invocation is caused from another hook implementation.

Generally, it is better to start batch operations from a menu callback, not from a function that is invoked, for example, during cron tasks, where Drupal is not outputting a page to a browser. In fact, to avoid PHP timeouts, Drupal causes the browser to invoke the batch menu callback every X seconds; if it is not involved a browser (as it happens with cron tasks executed from a cron utility), then the batch operations don't work, or work as a normal function call that could cause PHP timeouts.
This rules out the possibility to use batch operation in your case.

If you really needs to use batch operations, then you should do what done by Drupal core code. When the module needs to use batch operations, it reports that in a hook\_requirements() implementation which gives to the user the link of a page that starts the batch operations. Alternatively, a similar warning message can be placed in an administrative settings page; also in this case, the user will start the batch operations clicking on a link provided in the message.

What I reported before about batch operations is still valid: batch operations rely on the browser. If there are connection problems with the server, or the browser crashes, the batch operations will be interrupted; that is what also happens if the computer running the browser freezes, or it switches off/resets for any cause.
Batch operations should be used for relatively long operations, but not operations that last 20-30 or more minutes.

---
Tags: 7, batch-operations, nodes
---


title: Hook module and Drop table

text:
# Question
Title: Hook module and Drop table
I would know if it's possible to drop a database table created by a module.
I could see the hook "uninstall" and "disabled" but nothing works.

Can you help me please?

# Answer
> 4 votes
It could sound a stupid question, but have you enabled your module? Have you launched the uninstall procedure?

---
Tags: 7, hooks, database
---


# Question
Title: Override nodereference_autocomplete functionality
I would like to edit the functionality contained in nodereference\_autocomplete() so that it will only return a subset of all nodes. What would be the best way to override this default functionality?

# Answer
> 2 votes
This isn't exactly the same question, but I think this answer is just as valid.

> If I understand you right, you can use a View as the source for the nodereference widget, and give it appropriate filters to only show nodes of a certain type authored by the current user. Or have I got the wrong end of the stick?!

# Answer
> 0 votes
An autocomplete function is, in Drupal 6, registered as menu callback. For example, this is the code used by user.module to register the function that autocompletes the usernames.

```
function user_menu() {
  $items['user/autocomplete'] = array(
    'title' => 'User autocomplete',
    'page callback' => 'user_autocomplete',
    'access callback' => 'user_access',
    'access arguments' => array('access user profiles'),
    'type' => MENU_CALLBACK,
    'file' => 'user.pages.inc',
  );

  // …
}

```

If you want to alter the autocomplete function defined from a module, you just implement hook\_menu\_alter() to alter the menu callback definition that uses the autocomplete function as menu callback.

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


# Question
Title: Is safe adding uid=0 in users table just to use $_SESSION?
I read many articles about adding it, but I'm not encouraged to use it yet. People says that Drupal doesn't add this user because MySQL Auto-increment starts at 1. So, about adding uid=0, is it a good practice? Is it widely used? What possible problems could I have with it? Thanks. :)

# Answer
Drupal *does* come with a row with uid=0 by default.

Some backup tools (notoriously some versions of PHPMyAdmin) are unable to deal with that, so you will lose this row when restoring from backup.

The easiest way to get back the missing row is to issue this query (for example in PHPMyAdmin):

```
UPDATE users SET uid = uid - uid WHERE name = ''

```
> 5 votes

---
Tags: 7, database
---


title: Custom logo for each organic group

text:
# Question
Title: Custom logo for each organic group
I want to add a logo (CCK image field) to the group nodes and show it when users visit that group.
Is there any module for that?

# Answer
> 3 votes
I write this module to render custom logo for each Organic Group:

```
function og_logo_block($op = 'list', $delta = 0, $edit = array()) {
    if ($op == "list") {
        $block = array();
        $block[0]["info"] = t('OG Logo Block');
        return $block;
    } else if ($op == 'view') {
        global $theme;
        global $node;
        $block['subject'] = '';
        $settings = theme_get_settings($theme);
        if (($node = og_get_group_context()) && node_access('view', $node)) {
            $block['content'] = l('<img alt="' . $node->title . '" title="' . $node->title . '" src="' . base_path() . $node->field_logo[0]['filepath'] . '" />', "node/$node->nid", array('html'=>true));
        } else if ($settings['default_logo']) {
            $block['content'] = '<img src="' . base_path() . 'sites/all/themes/' . $theme . '/logo.png" alt="this is logo" />';
        } else {
            $block['content'] = '<img src="' . base_path() . $settings['logo_path'] . '" alt="this is logo" />';
        }
    }
    return $block;
}

```

# Answer
> 1 votes
Spaces module could do this.

# Answer
> 0 votes
There is no such module as such, but I did it earlier some time back. You will have to attach the logo to the node on node load.

I generally did it from the theme level, following these steps:

* check if page is a group page
* if it is a group page, then replace the default logo with group logo contained in the node as `$node->group_logo`

# Answer
> 0 votes
Just add a regular image field using CCK or, under Drupal 7 and higher, the image field implemented by the Fields module that comes with the Drupal core modules.

# Answer
> 0 votes
I don't use OG so I can't explain in detail however the strategy would be to create a template.php file in the theme folder. In that file create a template preproses function that adds a class to the OG node title with some markup. The class should be prefaced with logo- and then some PHP code to add a unique identifier for the node. Because there are certain rules for characters to use in a class name, it's important to pass the string through some code that will clean it up. Then in the CSS file use the class to add a background image to the element. Since we are on the subject of OpenAtrium, this is how they add all the icons to menu items.

It's entirely possible that using the Zen theme or using something like the Context module that the particular OG as a unique body class. For example, on groups.drupal.org the Location and Mapping group has og-context-303 added to every node within that group. Then the solution is to add a CSS selector like `body.og-context-303 h1.title {[image type stuff here], background:url(images/map-icon.png)}`. If there are only ten groups then there are only ten lines of CSS to add.

---
Tags: 7, organic-groups
---


title: Using a custom template in a theme

text:
# Question
Title: Using a custom template in a theme
I have created the custom template page-org.tpl.page in the Zen theme, and I want to include this custom template file in the menu calling; when the user clicks on the Org link it should use the template file page-org.tpl.page.
How can I do that?

# Answer
> 1 votes
Output your $vars in the theme so you can see your candidate templates.

EDIT: I thought you were looking for a content type solution when I first read this :)

**Here's a gotcha:** you have to have master templates before you can have ones within it. For example content-field-field\_my\_content.tpl.php will not work until content-field.tpl.php is in place in the theme.

You may need to place some PHP in your template.php within preprocess\_page()

`if(!arg(2)) $variables['template_files'][] = 'page-node_'.$variables['node']->type;`

(The arg2 check helps make sure this doesn't happen on edit pages.)

Lastly, you can also accomplish this with Context Layout.

# Answer
> 0 votes
The page template must be named: page-node-XX.tpl.php.

Replace XX by the node id of the page.

# Answer
> 0 votes
As reported in the source code of template\_preprocess\_page():

```
// Build a list of suggested template files in order of specificity. One
// suggestion is made for every element of the current path, though
// numeric elements are not carried to subsequent suggestions. For example,
// http://www.example.com/node/1/edit would result in the following
// suggestions:
//
// page-node-edit.tpl.php
// page-node-1.tpl.php
// page-node.tpl.php
// page.tpl.php

```

Similar comment is contained in the code source of theme\_get\_suggestions(), which is the function called from `template_preprocess_page()` in Drupal 7:

```
//One suggestion is made for every element of the current path,
// though numeric elements are not carried to subsequent suggestions. For
// example, for $base='page', http://www.example.com/node/1/edit would result
// in the following suggestions and body classes:
//
// page__node              page-node
// page__node__%           page-node-%
// page__node__1           page-node-1
// page__node__edit        page-node-edit

```

Supposing that the link takes to http://example.com/links/org, then the template file for that page should be page-links-org.tpl.php or page-org.tpl.php for Drupal 6, and page--links--org.tpl.php or page--org.tpl.php for Drupal 7.

---
Tags: theming
---


# Question
Title: D7 views 3, display content based on path
I have a block that displays results of the nodes i have created but i have those nodes on a specific path, anyway to put this short im trying to make a block from views that displays content based on the url it is on.

For example, if i am on page green, it displays all content from the path green/whatever or if im on red it displays content from red/whatever, im trying to achive this without making a bunch of blocks is there another module or something for this?

Any help is greatly appreciated.

# Answer
Please watch Learn Views with NodeOne, part 19: Contextual filters with paths.
> 1 votes

---
Tags: 7, views, nodes, path-aliases
---


# Question
Title: What is the picture field in the node object?
`print_r($node)` outputs:

```
stdClass Object
(
    [nid] => 4
    [type] => grouptype
    [language] => fa
    [uid] => 1
    ....
    [title] => sample group
    ....
    [name] => roshd
    [picture] =>
    ....
)

```

What is picture and how can I upload a picture into this field?

# Answer
This is the profile picture of the author of that node. You can upload that in your edit profile form and you can display it using `theme('user_picture', $node);`.

If you want to be able to attach images to nodes, have a look at CCK and ImageField..
> 1 votes

---
Tags: 7, organic-groups
---


# Question
Title: How do I create a catalogue list that links through to my individual product nodes?
I have taken Ryan Szrama's advice from a question I asked on how to display products and have now got that working. I have also built a catalogue list of all my products using views. I now need to link the two up, so that if a user views the catalogue they can click through from there to the appropriate individual product node. How do I do this, or am I missing something?

To be specific: I have a view called 'catalogue' that is a list of books using a table, and I have a view 'book' that is an unformatted list that contains more detail on each book (like cover image, author etc). This view returns all books initially. I want the title in the list to link through to the book view and filter that view using ISBN (SKU) for an individual book. I can create the link, but I am not sure how to correctly format it. Currently the link looks like this: /book?isbn=123456789 (I have also tried /book?sku=123456789). This link just returns a full unfiltered list of the view.

# Answer
Now, I'm not using D7 yet, but Views has settings to turn fields within a node (your product nodes) into links to the originating node. Just go to your View that is your grid of products, check out the individual Fields you use, in their settings some of them (if not all of them) should have an option to turn the field into a link back to the original node.
> 2 votes

---
Tags: views, commerce
---


# Question
Title: Custom block that's always the first thing in a region?
I'm trying to create a region for my Drupal 7 theme that will be clickable drop-down to allow the user to log in/out, access their profile page and a few of other things. The best analogy I can come up with is that I'm trying to create something similar to the sort of drop-down that you see on sites like Twitter. (It's not *exactly* the same as what I'm trying to build, but close enough to demonstrate my point.)

Now, neither styling the region nor implementing a show/hide behavior in jQuery is difficult. The key here is to add a bit of custom HTML to the region that will wrap *outside* the blocks, but *inside* the region itself.

The output should look something like this:

```
<div class="region region-name"> <!-- region -->
    <!-- custom HTML "wrapper" -->
    <p><a href="link-to-activate-dropdown">Click here</a></p>
    <div id="wrapper">

        < blocks go here >

    </div> <!-- /custom HTML "wrapper" -->
</div> <!-- /region -->

```

It's also important to make sure users can't move or delete this special stuff, so I *think* this should probably go in template.php, but since I'm a Drupal theming newbie, I'm not sure.

Anyone have an idea how to do this?

# Answer
After a little digging, I found out that Drupal 7 includes support for a new template called `region.tpl.php`. I created one and here's what it looks like:

```
<?php if ($content): ?>
  <?php if ($region == 'popdown'): ?>
  <div class="<?php print $classes; ?>">
    <a href="link-to-activate" id="popdown-link">Click</a>
    <div id="popdown-wrapper">
      <?php print $content; ?>
    </div>
    <script type="text/javascript">
    jQuery('#popdown-link').click(function(e) {
      e.preventDefault();
      jQuery('#popdown-wrapper').toggle();
    });
    </script>
  </div>
  <?php else: ?>
  <div class="<?php print $classes; ?>">
    <?php print $content; ?>
  </div>
  <?php endif; ?>
<?php endif; ?>

```

It's not terribly elegant, but it seems to work with no errors. Now I can focus on cleaning it up and getting the logic out of the `region.tpl.php` (i.e., moving the inner if/else into `template.php` and the jQuery into `script.js`.)
> 0 votes

# Answer
Your "custom HTML wrapper" is only useful for the Javascript, so you are looking at this the wrong way: the HTML generated by Drupal should not contain it, and it should be the job of the Javascript to transform the markup of the region to fit its use.

You probably want something like this:

```
$('<your selector>').each(function() {
  // Wrap all the content of the region inside a wrapper.
  $(this).wrapInner('<div class="my-custom-wrapper" />');

  // Create a link and insert it into the region.
  var link = $('<p><a href="link-to-activate-dropdown">' + Drupal.t('Click here') + '</a></p>');
  link.prependTo($(this)).click(function() {
    // Your custom logic.
  });
}

```
> 2 votes

# Answer
I suppose that you have to edit your block.tpl.php like in Drupal 6 ? Add a class to the link and insert a javascript in your theme with a jquery function who toggle the content. Also, don't use the #id 'wrapper', you cannot have more than one id the same in the html, you should use classes.
> 0 votes

---
Tags: 7, blocks, theming
---


title: Templating a form

text:
# Question
Title: Templating a form
I'd like to change the template of a form that I created via a module but I do not know what I'm doing exactly as I have snippets of "information." For information, this form is in 'node /add/page' or 'node/add/article'.

# Answer
Thank you for your help. I managed to find what I wanted.

I used this:

```
$ form ['takealook'] = array (
     '# type' => 'fieldset',
     '# title' => t ('Take a look settings'),
     '# description' => t ('Determines if users Cdn The Access limited to a page. '),
     '# collapsible' => TRUE,
     '# collapsed' => TRUE,
     '# group' => 'additional_settings'
     '# access' => user_access ('takealook_administer')
     '# Attached' => array (
       'js' => array (drupal_get_path ('module', 'takealook') '. / takealook.js')
     )
     '# attributes' => array ('class' => array ('takealook-settings-form')),
   );

```

This code is to create groups with tabs or add to existing group "additional\_settings"
> 2 votes

# Answer
Try using the Theme Developer module to find which function or template file is outputting the form you're interested in theming. Theme Developer will also tell you what "suggestions" you can use to override the output. Check out the Theme Developer screencast for an introduction on how to use the module.
> 3 votes

---
Tags: 7, theming
---


# Question
Title: User relationship one way relation block and unblock option
Im using user relationship module for twitter like one way relationship ,

But i find any option to block the user from following me and in future.

Only remove option is there to remove and once removed, the user again start following me.

Any option to block the user from following me?

Thanks, Edie :)

# Answer
> 2 votes
This feature does not currently exist, you can not implement it without hacking the module.

There are feature requests open for this, I suggest have a look at these:

http://drupal.org/node/203364

---
Tags: 7, users
---


title: PayPal handling with Simple Payments?

text:
# Question
Title: PayPal handling with Simple Payments?
I'm using Simple Payments to handle PayPal processing in a module I'm building (See previous question).

The first part is fine -- it sends data to PayPal okay, but now that users can pay, I need to write the post-transaction handling code (which will ultimately store that the transaction succeeded in the database.). I'm supposed to use hook\_simple\_payment\_process, but there's very little documentation. In its entirety:

```
/**
 * Passes a completed payment to the module that created it for processing.
 *
 * @param $payment
 *   A payment to be processed.
 *
 * @return
 *   TRUE if the payment was successfully processed.
 */
function hook_simple_payment_process($payment) {
}

```

What am I supposed to do with this...?

Thanks!

# Answer
You need to process the payment. In your case you could mark that the invoice has been paid, maybe in storm or a custom table. `$payment` should hold all the info about the payment that you need. I guess some of the info depends on your module as well.

Anyways when you have processed the payment you should return TRUE which will make the simple payment module mark that payment as being processed. I imagine that there is an interface that will allow you to see if a payment hasn't been processed, which would happen if an error occurred while processing.
> 1 votes

---
Tags: hooks, payment-gateways
---


# Question
Title: Attach different CSS styles on a node basing on publishing date or other PHP properties
I want to attach a different CSS style to a node, basing on the node publishing date or some PHP properties.
What would be the best way to do this?

# Answer
> 5 votes
You are asking the wrong question. The question you should have asked is "how do I add a class on a node depending on some properties?". Using different set of CSS files to control styling a an element is just a no-no.

The answer to the correct question depends on whether you are targeting Drupal 6 or Drupal 7:

* On Drupal 6, you will generally have to implement the logic your own node template;
* On Drupal 7 (or on Drupal 6 if you are using an intelligent base theme like Zen), you would implement a `hook_preprocess_node()` in your theme and add classes to the `'classes_array'` variable

# Answer
> 1 votes
Create a module, then in the

```
hook_init()

```

do your php calculations and include css with

```
drupal_add_css()

```

and js with

```
drupal_add_js().

```

---
Tags: nodes, theming
---