title: Add CSS class to fields

text:
# Question
Title: Add CSS class to fields
I have the following snippet.

```
function <themename>_preprocess_node(&$vars) {
  if ($vars['teaser'] && !$vars['is_front']) {
    $vars['theme_hook_suggestions'][] = 'node__teaser';
  }
  elseif ($vars['teaser'] && $vars['is_front']) {
    $vars['theme_hook_suggestions'][] = 'node__teaser__front';
  }

  if (!$vars['teaser'] && count($vars['field_related']) > 2) {
    $vars['theme_hook_suggestions'][] = 'node__alt';
    foreach (element_children($vars['content']['field_related']) as $k) {
      $vars['content']['field_related'][$k]['#attributes']['class'][] = 'grid_1';
    }
  }
}

```

Basically, I have this field\_related in my node that holds from 0 to 3 values. If it holds more than 2 values, I change the template suggestion (node\__alt) and I'd like to attach a class (grid\_1) to each of the values. I've spent the last 4 hours researching but nothing got me even near to where I want to go.

Do you have any idea?

**EDIT** In the template file I did like this:

```
<aside id="related">
  <?php foreach(element_children($content['field_related']) as $k) : ?>
    <div class="grid_1">
      <?php echo render($content['field_related'][$k]) ?>
    </div>
  <?php endforeach ?>
</aside>

```

It works, but it is far from being clean.

# Answer
> 1 votes
Make a copy of your\_drupal\_site/modules/field/theme/field.tpl.php in your theme directory and name it field--field\_related.tpl.php In this file You can attach the class (grid\_1) to each field as follows:

```
<?php foreach ($items as $delta => $item) : ?>
<div class="grid_1"><?php print render($item); ?></div>
 <?php endforeach; ?>

```

All the available variables are listed in the comments of this file so you will be able to customize as you like.

On any given node you can check how many fields have been created and theme according to that. You can change the above code to count how many fields are there on any node, the revised code is as follows:

```
<?php foreach ($items as $delta => $item) : ?>
    <?php
    if (count($items) > 2) {
        print '<div class="grid_1">' . render($item) . '</div>';
    } else {
        print '<div class="two_or_less">' . render($item) . '</div>';
    }
    ?>
<?php endforeach; ?>

```

This will add class "grid\_1" to any node with 3 or more fields of field\_related and add class "two\_or\_less" to the nodes with 1 and two fields.

---
Tags: 7, entities, theming
---


title: Update site from core dev to stable

text:
# Question
Title: Update site from core dev to stable
Using advice from Drush: Update core from stable to dev I ran `drush up drupal-7.x` in order to switch from 7.7 to 7.x-dev.

However I'm now in the position whereby I want to move the project back to 7.8, however I don't seem to be able to figure out how to do this. I've tried:

```
drush up drupal-7.8

```

Which produces:

```
 Name         Installed version  Proposed version  Status
 Drupal core  7.x-dev            7.x-dev           Specified version available

```

So it appears to understand I'm asking for a new version, but following this through just updates the site to the latest 7.x-dev.

# Answer
You could hack the includes/bootstrap.inc file The very first line of code will be something like:

```
define('VERSION', '7.11-dev');

```

Set it to 7.7, and drush should accept that 7.8 is a never release. I know that hacking core is strongly discouraged, but since the upgrade itself will remove the hack, I think it's more than ok.
> 2 votes

# Answer
You probably need to upgrade to a version of Drush that is at least 7.x-4.5 so that you don't run into Specifying the version to update a module doesn't work in d7.
> 0 votes

# Answer
Long story short, it doesn't look like you can. I think the basic reasoning is that dev is *generally* always going to be newer that the latest stable release and that would be a Drupal downgrade, which is not possible through Drush.

Basically, if you want to do it...you'll have to do it manually :(.

See here.
> 0 votes

---
Tags: 7, drush, updating
---


# Question
Title: Check to see if content exists; if not, create it
I have two node types that are related by a node reference. Essentially, content type A is a container, and content type B is an item. For illustration sake, I'll call content A Box and content B Item. the Item has a number of taxonomy terms that are shared with Box. Again for illustration sake lets call them color and size. What I'm trying to do is set up a rule that does the following:

* On Creation of an Item ( actually before the content is save) check to see if there is a Box that shares both the color and the size of the item.
* If one exists, assign the new item to that box (via node reference).
* If one does not exist create the box, then assign the new item to that box.

I'm new to the Rules module, and although it seems really powerful, I'm just not sure that this particular use case is possible. The part that I'm most unsure about is how to check if the box with certain terms exists.

# Answer
> 0 votes
I think doing this with Rules alone, will work if you have a very limited set of nodes. Once you pass 100 or so, then the overhead of all the object wrappers will soon force you to give PHP gigabytes of RAM instead of megabytes, and then set your servers CPU aflame.

I belive an approach that integrates Rules with Views bulk operations however, could do this neatly for you. I have not attemped anything similar myself, but a VBO should be able to query the database for the node, and then if it exists, return it to Rules.

The code approach would be to implement hook\_node\_presave, query the database with an EntityFieldQuery for a Box node with the right terms, and assign the reference.

---
Tags: taxonomy-terms, rules, entities, nodes
---


# Question
Title: Relative and broken image with simplenews and mime mail
I have a content type with an image field. When I send a test mail with the simplenews module I get an image with an absolute path in email and see the image, but when I send it with cron I get a broken image because image url is relative. How can I solve this problem?

I am using simple news 6.x-1.3.

# Answer
How are you calling cron?

You need to make sure that the base\_url is set.

E.g., when calling cron with drush, you *need* to provide the `--uri http://example.org` parameter.
> 2 votes

---
Tags: 6, emails
---


title: Tokens in Views don't seem to work

text:
# Question
Title: Tokens in Views don't seem to work
I added a new view (block) with **FIELDS** type. I added "Content: Comment count" to see the comments number, and in "Rewrite results" I clicked to "Output this field as a link", and added the token "\[comment\_count\] == Content: Comment count" as link.
This link doesn't work.

When I add a different token, such as "\[body\] == Content: Body" or "\[title\] == Content: Title," the links still don't work.

Am I doing anything wrong?

# Answer
> 2 votes
I wanted to do the same thing. I had a view of blog posts and at the bottom of the post I wanted to put a link that had a comment count that was a hyperlink (as I've seen this done on many other blogs). The way I did it was like this:

Originally my view was set up to just display the full nodes. I clicked to edit the view and went to Page Details-\>FORMAT-\>Show and changed the setting from "Content" to "Fields".

Added the following fields:

```
Content: Title
Content: Body
Content: Path
Content: Comment count

```

The key and answer to this post is: Even though I don't want to display the path on my view I need to add it as a field so that I can later use it when building the link for the comment count. Also I believe the order of the paths is important, so the path field must come before the comment count field. For the `Content: Path` field I checked the "Exclude from display" check box. This hides the path from showing up in the view. Next under "REWRITE RESULTS", I checked "Use absolute link (begins with "http://")". This is necessary for a proper URL when using the path as token below.

For the `Content: Comment count` field, under "REWRITE RESULTS" I checked "Output this field as a link" and in the "Link path" box I put `[path]`.

---
Tags: 7, views, tokens
---


# Question
Title: How can I restore author and post information for nodes?
When I create a content type, I disabled showing "author name" and "posting date"; then, I created nearly 100 nodes from that content type.

Now I want to show the posting date in the node content.

When I edit the node, and enable the posting dates to be shown, everything is OK; when I edit the content type, and enable the posting date, I can't see it in node page.

It is hard to edit all nodes to show the posting date. Is there a better way?

# Answer
> 1 votes
Regarding both date and author info: If you are not comfortable updating the Post date directly in the database, then I suggest you take a look at Views bulk operations, which is capable of performing mass manipulation of your sites content.

If the data doesn't show up as expected, it's always a good idea to switch to stark, to see if it's a theme issue.

---
Tags: nodes
---


# Question
Title: How do you strip HTML from the node summary that appears on taxonomy node listing pages?
I've tried using hook\_preprocess\_node() inside of a if statement for arg(0) == 'taxonomy', but changes to the node aren't carried through to display.

What is the best way to make the teasers appear in plain text (stripped HTML) when listing in the taxonomy node listing page?

# Answer
> 6 votes
Within `node--taxonomy.tpl.php`, you could isolate the field data for your teaser or any field, depending on how you have that template set up, and apply the php `strip_tags` to that field data.

For example:

```
$teaser = render($content['body'][0]);
$textteaser = strip_tags($teaser);

```

This video is a great starting point for learning about the theming templates if that is new: Theming Fields and Nodes with Templates

---

One other idea is to isolate the div that wraps each teaser (if possible) and use jQuery to transform the content using the relevant CSS selector using `.text()` method.

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


title: Clickable Images fields

text:
# Question
Title: Clickable Images fields
When creating new content types, I know I can have an image field, but how do I associate a URL with an image so that when you click on the image, it goes to that node or location? Is the only way to get into the code and surround the img tag with an href tag?

# Answer
Welcome to Stack Exchange doug! :)

This is what I believe to be the most popular solution. It's good because it's fairly easy to set up, yet very flexible. You will need the Views module.

1. Add a textfield to the same bundle (content type) as the one holding your images.
2. Create a View
3. Add your link field to the field list, and check "Exclude from display".
4. Add your image field to the field list, scroll down to rewrite results, check "Output this field as a link", and add the link "token", in the "Link path" field. The list of available tokens are listed further down under "Replacement patterns". .
5. Save the View, and add it where you want. :)

If you want to know more about Views, you can see a video tutorial series here.
> 4 votes

---
Tags: media, uri
---


# Question
Title: Do features uninstall variables when a module is uninstalled?
I have created a module using The Features module. The module exports some variables using the Strongarm module.

If a person installs the module and then uninstalls it, will those variables be removed?

# Answer
> 7 votes
No, it does not. Features do not implement an uninstall hook, and as such don't get a chance to clean up after themselves.

---
Tags: 7, features
---


# Question
Title: How do I automatically add links on the right sidebar in drupal 7?
Let's say I have a few articles about weight training. How do I populate the right sidebar blocks with related links to current article?

# Answer
> 2 votes
I've just implemented related content using views following this tutorial. If you prefer using a module you got even more choices.

---
Tags: views, blocks
---


title: Drupal 7.9 and flexible images

text:
# Question
Title: Drupal 7.9 and flexible images
Drupal 7.9 re-introduces height and width attributes to images - I understand this helps improve front-end performance, but it's giving me problems while using flexible images in the vein of responsive web design.

This is the same issue as whitefleaCH mentioned on this post: How can I prevent height/width attributes on images run through the theme system?

Using max-width in CSS still scales images, however the height remains as what was defined in the markup. Does anyone know how to either correct this in CSS or remove the height/width attributes from images all together?

# Answer
Check out `theme_image()`:

```
foreach (array('width', 'height', 'alt', 'title') as $key) {
  if (isset($variables[$key])) {
    $attributes[$key] = $variables[$key];
  }
}
return '<img' . drupal_attributes($attributes) . ' />';

```

So you need to clean width and height as top level keys but also from the attributes array:

```
function mymodule_preprocess_image(&$variables) {
  unset(
    $variables['width'],
    $variables['height'],
    $variables['attributes']['width'],
    $variables['attributes']['height']
  );
}

```

And yes, in Drupal 7, Variable process functions can now be used for all theming hooks. Don't forget to clear your cache so the new preprocess function is picked up.
> 6 votes

# Answer
You might be interested in checking out the Adaptive Image module:

> The Adaptive image module provides device-appropriate versions of images from your fields. You can activate adaptive images by adding an adaptive effect to any of your image styles.
> 2 votes

# Answer
```
function YOUR_THEMENAME_image($vars) {
  $attributes = $vars['attributes'];
  $attributes['src'] = file_create_url($vars['path']);

  // remove width and height attributes
  foreach (array('alt', 'title') as $key) {
    if (isset($vars[$key])) {
      $attributes[$key] = $vars[$key];
    }
  }
  return '<img' . drupal_attributes($attributes) . ' />';
}

```
> 2 votes

# Answer
In CSS overriding the currently defined height by setting height to 'auto' should do the trick.
> 1 votes

---
Tags: media
---


# Question
Title: How do I insert HTML just before the body closing tag?
I am looking for the best way to insert arbitrary HTML content into a page before the closing body tag, similar to the way `drupal_add_js()` adds JavaScript to the bottom of a page.

I am coming from a Wordpress background, and in Wordpress this could be accomplished by using the `wp_footer()` hook.

I have looked into using `hook_page_alter()`, but I was wondering if this was the correct way to do this or if there is a better way of accomplishing this task.

# Answer
> 23 votes
The equivalent of hook\_footer() that was used in Drupal 6 is to implement hook\_page\_build(), and alter the content of `$page['page_bottom']`, using code similar to the following one:

```
function mymodule_page_build(&$page) {
  $page['page_bottom']['devel'] = array(
    '#weight' => 25,
    '#markup' => '<div style="clear:both;">' . devel_query_table() . '</div>',
  );
}

```

The content of `$page['page_bottom']` is output from html.tpl.php, using the following code:

```
  <?php print $page_top; ?>
  <?php print $page; ?>
  <?php print $page_bottom; ?>
</body>
</html>

```

The value of `$page_bottom` is initialized from template\_process\_html() using the following code:

```
  // Render page_top and page_bottom into top level variables.
  $variables['page_top'] = drupal_render($variables['page']['page_top']);
  $variables['page_bottom'] = drupal_render($variables['page']['page_bottom']);
  // Place the rendered HTML for the page body into a top level variable.
  $variables['page'] = $variables['page']['#children'];
  $variables['page_bottom'] .= drupal_get_js('footer');

```

The difference between hook\_page\_alter() and `hook_page_build()` is that `hook_page_alter()` is executed after `hook_page_build()` and should be used to alter, or remove content added by another module, while `hook_page_build()` should be used to add new content to the page.

---
Tags: 7, hooks
---


# Question
Title: Optionally add image/icon after node title based on boolean content type field?
Using Drupal 7.10 with a Zen sub-theme. I have a custom content type, say Product. The products have titles such as "Wrench", "Hammer", "TV". I want to designate certain products as being a recommended product by having a little star icon appear inline after the title.

So for example:

```
Wrench
Hammer *
TV
Scooter
Piano *

```

Whether the star appears or not should be based on a boolean field I added to the product content type. I want the star to appear when viewing the node directly or when the node appears as part of a list in a view.

My thought was to put an if statement in the node template for my content type, e.g. node--product.tpl.php. However, what has me stuck is that in Zen it appears, if you are viewing a node as a page then the title is rendered in the page template, and if you're not viewing the node as a page then the title is rendered in the node template. I'm not sure how to reconcile this. Furthermore, I'm not sure if my field variable would even be available directly from the page template.

**UPDATE**

It appears I can successfully create a boolean preprocess variable in the function `mytheme_preprocess_page` whose value is based on field from the node:

```
function mytheme_preprocess_page(&$variables, $hook) {

  //$variables['sample_variable'] = t('Lorem ipsum.');

  if (isset($variables['node'])
      && $variables['node']->type == 'mycontent_type') {

    if($variables['node']->field_is_recommended
       && $variables['node']->field_is_recommended[LANGUAGE_NONE][0]['value'] == 1) {
      $variables['is_recommended'] = TRUE;
    }
    else {
      $variables['is_recommended'] = FALSE;
    }

  }
}

```

So now that I know this is possible, what's the best way for me to do this?

# Answer
While this can be on in the page preprocess, and the node template, and probably several other places as well, I would discourage that. It is putting to much logic in the theme, that doesn't belong there. The main advantage of my solution is that the field can look right regardless of where you display it. On a page, in a block, in the header, or essentially anywhere that properly integrates with the Field API.

My solution is as follows

Add a text field, with the boolean Yes/No options

Implement two hooks, hook\_field\_formatter\_info() and hook\_field\_formatter\_view()

```
function product_field_formatter_info() {
  return array(
    'product_star' => array(
    'label' => t('Recommended product'),
    'field types' => array('text'),
  );
}

function project_field_formatter_view($entity_type, $entity, $field, $instance, $langcode, $items, $display) {
  if ($field['type'] == 'text' && $display['type'] == 'product_star') {
    return array(0 => array('#markup' => '<img src="star.png">'));
  }
}

```

**Clear the cache**

Go to the fields display settings, and set it to "Recommended product"

Profit!
> 3 votes

---
Tags: 7, theming, entities
---


# Question
Title: How can I ensure that every page within my drupal 6 site loads a specific Javascript file?
I want to include the sites/all/themes/fusion/mapsindeed/js/css3-mediaqueries.js file so that mediaqueries will work within Internet Explorer 8 and below, like it already does for other web browsers.

How can I do it?

# Answer
Add the URL of the JavaScript file as `scripts[]` to the theme's info file.
> 3 votes

---
Tags: 6, theming
---


# Question
Title: What are search_index & search_dataset tables for, can I clean them?
I am trying to dump sql from local dev site to production server, I found that search\_index & search\_dataset these two tables are big, made the sql file really big.

I am guessing these two tables are about storing search indexes which I can always to re-index from scratch later. Correct me if wrong.

So **is it OK/safe to delete all the records of them**? then export the database, import to my server. By doing this I can reduce the file size of dump file.

Thanks!

# Answer
These tables are used by the site's search function, as provided by the core's Search module. They're built from your site's content, and the descriptions in code in `search_schema()` say:

* **search\_dataset** \- "Stores items that will be searched"
* **search\_index** \- "Stores the search index, associating words, items and scores"

Though you can ignore/truncate the contents of these tables to keep your database dumps smaller, they will be recreated during cron runs as your site's content is re-indexed. Beware that rebuild times can be a lengthy if your site has a lot of content.

I've always found the Backup and Migrate module to be much handier than command-line MySQL as tables and/or their contents can be ignored, plus do scheduled dumps and have various export/import profiles.
> 10 votes

---
Tags: database, importing-exporting
---


# Question
Title: Display a menu on all pages except a specific page type
In my site, I have a menu that should be displayed on all pages, except on pages of a certain type.

In "admin -\> structure -\> blocks" I can set the visibility parameters of this menu to "pages of a certain type", and check all page types except the one I dont want. This has 2 problems :

1) whenever I add a new page type, I need to update this menu visibility (minor problem)

2) the menu will not be visible except on pages. For example, on the contact page, there is no menu.

What should be the right way to do that ?

# Answer
I suggest using the context module for better and more advanced handling of blocks.

Alternatively, you could use pathauto to create a unique url for that content type (like mysite.com/type/content ) and set the block to show up everywhere, excluding 'type/\*'. If you do this, make sure to rebuild your urls.
> 1 votes

# Answer
If you use aliases for the content type using 'pathauto' module you can select types by their path. Then you would set the block as follows: Select the "configure" option for the specific block select the pages tab select the radio button "All pages except those listed".

List the pages to omit similar to this:

```
contentType1/*
contenttype2/* ( one type per line)

```
> 1 votes

---
Tags: routes
---


# Question
Title: Node reference field options supplied by Views 3 work in preview, not in content
I am trying to associate a node with a product type in Drupal Commerce. It is like choosing a t-shirt color, but instead they are choosing a node they published as a product attribute.
I'm using Views to filter for only nodes published by current user, then I click the check box "Enable this field to function as an attribute field on Add to Cart forms" while editing this field type.

When I view this product display, the node reference selection box is there, but there are no selections aside from "-none-".

I have flushed the cache, multiple times; I run the cron tasks. I've done everything I thought I could do.

What am I missing?

# Answer
I faced this problem. After some hours of googling, I found the solution in these issue reports.

What you basically need to do is to install the development snapshot (7.x-1.x-dev, 25 Dec 2011) of Drupal Commerce. The patch has already been committed there.
> 0 votes

---
Tags: views, nodes, commerce
---


title: Custom field placement

text:
# Question
Title: Custom field placement
I have a custom field that is an unordered list that I want to be placed under a static title and to the left of an advertisement. I only want this to show on article pages, but right now I can't seem to figure out how to place the custom field where I want it to be placed. I know a module is required, but what I am asking is if anyone can give me the correct hooks or whatever to retrieve the custom field information, so I can place it where needed.

# Answer
Copy node.tpl.php of your theme and name it node--article.tpl.php. In this file create the html structure you like. In this file you have access to the individual fields.

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

```

will print out content of your custom field. Wrap this filed with html id or class and style it with css. (I am assuming you are working with a non core theme)
> 4 votes

# Answer
I'm a big proponent (and co-maintainer) of the Panels module, which gives you a UI where you can arrange your fields. It takes work to learn how to use it, but it's well worth it in my opinion. :)
> 2 votes

---
Tags: entities, hooks
---


# Question
Title: Change the error message "An illegal choice has been detected. Please contact the site administrator."
When a user submits a content that has a taxonomy selection field and *NOT* make a selection, then the referenced error appears.

Now, I know exactly when, how and where the message appears, is there any way to change it so that it's actually useful for the user (i.e. "You did not select a category."), and not merely a cryptic error message that could potentially freak the user out?

# Answer
> 1 votes
I would add custom validation to the node, so that you can control the error message that get's output. There's an excellent example of that in this question. A potential problem with this is that you *may* now get both error messages. I don't immediately have a suggestion for how to deal with that.

# Answer
> 6 votes
This is to add onto Letharion's answer. Using the same principle, we can also check for error messages to replace in the validator.

```
function MY_MODULE_form_validate($form, &$form_state){
    $errors = drupal_get_messages(); // (dpm()'s has to go AFTER this line--they get cleared)
    foreach ($errors as $type => $id) {
        foreach ($id as $message){
            // Loop through individual messages, looking for ones to remove or replace
            if (test_for_invalid_error($message)===FALSE){
                drupal_set_message($message,$type);
            } elseif (test_for_invalid_error($message)!==TRUE){
                drupal_set_message(test_for_invalid_error($message), $type);
            }
        }
    }
}

function test_for_invalid_error($message){
    if (strpos($message, 'An illegal choice has been detected. Please contact the site administrator.') !== false) {
        return t('Please select a category!');
    }
    return FALSE;
}

```

This will not only add your own custom error, but replace the "An illegal choice" error. Isn't it neat? Yay!

# Answer
> 1 votes
The module String Overrides will be yours best solution , just change the string for what ever you like.

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


# Question
Title: How to change a term URI based on content type
I have 2 content types (photos, videos) and both have a term reference to a "topic" taxonomy. The topic terms are showing on the node display pages and I would like to link to "/photo/%" for photos and "/video/%" for videos instead of the default "/taxonomy/term/%".

How can I do that?

# Answer
> 2 votes
This problem is Hard if implemented the way suggested in the question. It becomes easy with pathauto if you use two separate vocabularies: video\_topic and photo\_topic. Then, video\_topic could have pathauto paths that start with video/% and photos can have paths that begin with photo/%.

Consider: if you use a single vocabulary, then clicking on the link video/% would show both videos and photos. Same with photo/%. If this is what you want, then perhaps the path you should use should be topic/% instead of video/% and photo/%. If you *do* want the results to be shown separately, then separate vocabularies are definitely the way to go.

If you want to keep your video/% and photo/% vocabularies in sync, then you could add a video topic in code every time a photo topic was clicked, and visa-versa. It's important to consider how you want your system to behave, though, as that will drive the solution and implementation that you'll want to choose.

# Answer
> 4 votes
My answer is going to use two modules, that are **tools**, not solutions. You will get the flexibility to do most anything you want with the paths, at the cost of needing to understand how the modules work. I will provide an outline of the required configuration below, there are useful videos here, and I will try to update the answer if you get stuck anywhere specific.

1. Install and enable the Page Manager, as well as Panels
2. Go to admin/structure/pages/add, and add a Page, with the path video/%video\_term
3. On the next page, click "Change", and pick "Taxonomy term: ID", then pick ID, or Name, as it suites you.
4. Pick any layout, and just move on until you can click "Finish" to end the wizard. Now fill your layout with whatever content you wish.
5. Repeat steps 1-4 for your "photo" page.

Since Drupal doesn't allow you to use a variable at the first level, you can't do /%content\_type/%term, so instead we create two pages. Personally, I would opt to do something like /products/%content\_type/%term, as a single page will lower your maintenance burden down the road. That however, will require understand "Variants", to accommodate two pages in one. The videos will explain that.

# Answer
> 1 votes
I'm pretty sure you can set this up using Pathauto. I know for a fact that you can set custom taxonomy paths. I just did for my Drupal Commerce Site.

http://drupal.org/project/pathauto

Just make sure that when you set a pattern, it doesn't overlap with a pattern you have set for another content type.

# Answer
> 1 votes
In Drupal 6, I've done this with the pathauto module, and a quick look at the Drupal 7 code suggests it works there as well. In D6, you go to `admin/build/path/pathauto` and select `Taxonomy term paths` and change it to whatever you want so something similar should work in D7.

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


# Question
Title: Omega theme node template renders outside any regions
The node template should render within the content region or at least should be replaced by the node template. But I am finding that it is not rendering within any regions, but it does rend within the content zone.

Now to be fair, Omega works correctly on a different site that I am working on. Just not here. At first I thought it was the sub-theme that was jacked. But I created a brand new empty one and it had the same problem. I also tried using the Omega base theme as the theme and had the same problem. So now I am at a loss as to what is causing this.

On my other site I tried to add the Delta module to see if that affected it, but no dice. So either another module is breaking it or something else is wrong in the config.

Do you have any idea?

# Answer
> 1 votes
I had the same issue. It turned out I had the "main content" block visibility settings set to "Only the listed pages," but I had no pages listed in the box below.

So, (of course) it did not render.

# Answer
> 0 votes
Ok, so it turns out I was ignorant of a new feature in Drupal 7. Apparently you have to specify where the main content will go in blocks or context. If you don't then it will just put it where it can best find a place.

---
Tags: 7, theming
---


title: Return themed node via AJAX / AHAH

text:
# Question
Title: Return themed node via AJAX / AHAH
Is there a way to get a fully themed node given the node id or path alias so that I can render it via AJAX / AHAH?

# Answer
Create a menu hook with the path `"[themed_node/%node]"`.

Within the function returning the the output for the menu hook use

```
return theme_node($node);

```

And then make an ajax call to "themed\_node/nodeid" whenever you need the themed node.

Hope that should work.
> 2 votes

---
Tags: 7, nodes, ajax
---


title: References versus Entity Reference

text:
# Question
Title: References versus Entity Reference
This question has been asked before, but a while ago, looking for a fresh opinion. Many more people seem to be using references (perhaps because it's a port from Drupal 6) but the functionality of entity reference seems pretty good. Opinions? Thoughts?

# Answer
I think the only way you will find out is through testing this for yourself. I speak from experience in using Entity Reference currently in a project with success. It comes down to your needs. For example I needed a way to reference commerce products - which are not node entities - so the references module is useless. Entity reference was perfect for this case and would work with any other entity type.

With the massive change in drupal `7.x` moving from a common mindset of "everything can be a node" `7.x` core has emphasized and shown us the benefits of "everything can be an entity". With the success of entities you can pretty much guarantee that entity reference has a strong future in `d7.x`

I am not sure if there is any advantage in using references since Entity Reference does all that references does, while being much more powerful.

From the project page;

> "Note : \- As the past couple months showed, the current maintainers are not up to the task. This module accepts new maintainers. \- References will most probably be deprecated in the near future in favor of Entity Reference, which should probably be considered first on fresh `D7` projects."

I think this says it all.

* For the extended future developers should look into Relation which is expected to replace entity reference.
> 21 votes

# Answer
As the Reference module site says the future for it is not very promising and it will probably be deprecated in favor of entity reference, so there may not be much to discuss :)
> 2 votes

---
Tags: 7, entities
---


# Question
Title: How to get the calculated sell price for the current user?
Is there a simple way to get the calculated sell price for the current user?

I try to get it from an implementation of hook\_field\_formatter\_view.

Context: I use multiple rules to alter the base price. Work find but I want to alter the displayed price on product page. Sadly, from my hook implementation, the only price I get is the base price.

# Answer
> 3 votes
Find the tips: Add this to the array return by my\_price\_formatters\_field\_formatter\_info() :

```
'settings' => array(
    'calculation' => TRUE,
  ),

```

Like this:

```
/**
 * Implements hook_field_formatter_info().
 */
function my_price_formatters_field_formatter_info() {
    return array(
    'commerce_price_for_me' => array(
      'label' => 'Price my way',
      'field types' => array('commerce_price'),
      'settings' => array(
        'calculation' => TRUE,
      ),
    ),
  );
}

```

Then add this function:

```
/**
 * Implements hook_field_formatter_settings_form().
 */
function my_price_formatters_field_formatter_settings_form($field, $instance, $view_mode, $form, &$form_state) {
  $display = $instance['display'][$view_mode];
  $settings = $display['settings'];
  $element = array();

  switch($display['type']) {
    case 'commerce_price_for_me':
      $element['calculation'] = array(
        '#type' => 'checkbox',
        '#value' => TRUE,
        '#title' => t('Show calculated price'),
        '#default_value' => empty($settings['calculation']) ? 'TRUE' : $settings['calculation'],
      );
      break;
  }
  return $element;
}

```

And this one too:

```
/**
 * Implements hook_field_formatter_settings_summary().
 */
function my_price_formatters_field_formatter_settings_summary($field, $instance, $view_mode) {
  $display = $instance['display'][$view_mode];
  $settings = $display['settings'];
  $summary = array();

  switch ($display['type']) {
    case 'commerce_price_for_me':
      if ($settings['calculation'] == TRUE){
        $summary[] = 'Show calculated price.';
      } else {
        $summary[] = 'Show base price.';
      }
    break;
  }
  return implode('<br />', $summary);
}

```

Then amount (in $items or $entity) will be the calculated price.

And that's all folks.

---
Tags: 7, rules, commerce
---


# Question
Title: Using a file extension (.htm) in Views contextual filter path
When I add a file extension after the contextual filter in my view's path it no longer works. The path with wildcard is: "*section/%.htm*"; can this be done or do I have to write some custom PHP to trim the URL of the file extension?

Please note that this is a legacy site which is rolling out section changes in phases, so there can be absolutely no URL changes while we convert the site to Drupal.

# Answer
Why not use the redirect module (or just plain ol' .htaccess 301 redirects) to redirect `/section/file.html` to `/section/file` ?

I understand the client doesn't want URLs to change, but doing a proper 301 redirect would preserve any SEO rankings they are trying to retain.
> 1 votes

# Answer
Drupal does not contain static content, it stores all content in a database which gives it great flexibility in how it assembles your content. You do not call static pages, although it is possible to add each static page in your current site into a Drupal page. The power of Drupal is in the flexibility with which you can assemble content.

The proper format for URLs for views would be `section/%/whatever-you-choose`. The "%" serves as a wildcard and the third position might define variations that might define various subsections of the section/% content, depending upon how you define various page variations within the view definition.

A view path is not intercepting the URL request. What you are doing with the path is assigning a name for the view. Other content on the site should have different names/paths. When you use a '%' in a path you are actually assigning many possible names to that view and the view varies the content for each value used in the wildcard according to the contextual filter definition you provide.

Before beginning work on a Drupal conversion you may want to do view some tutorials etc. There is fairly comprehensive coverage at Lullabot.com, buildamodle.com, or Lynda.com that will give you a broader perspective in short order. Armed with a fuller perspective of what is possible, you may find yourself rethinking how you want to stage a conversion.
> 0 votes

---
Tags: 7, views, uri
---


# Question
Title: How to add Google adsense Adlinks at the middle of the post
Hello I need to put adsense adlinks at the middle of the content or between paragraphs but I am not getting any modules to do that.Currently i use Content Injector to display image ads at top and bottom of the post.

# Answer
2 Methods:

1. Create two body fields, display adsense between the output of the two.
2. Output the block for the adsense code (I assume it is in a block) via PHP in your body.

`<?php
$block = module_invoke('block', 'block_view', 26);
print render($block);
?>`
> 1 votes

---
Tags: 7, advertising
---


# Question
Title: Programmatically override permissions in Drupal 6
I'd like to know if there's any way to programmatically override Drupal's permissions defined in admin/user/permission.

What I've managed so far is to block a user's certain action. However, if a user is not permitted to perform an action (eg. "create custom\_type content") and my module's access callback for this action returns `TRUE` the result is a white page. No PHP error, warning, or log entry. If `FALSE` is returned, I get an access denied page, as expected.

The method I used to implement custom permission is through `hook_menu_alter()`. Specifically, something like this (a common one for Drupal 6):

```
function mymodule_menu_alter(&$items) {
  $old_access_callback = $items['node/%node']['access callback'];
  $old_access_callback_add_customContent = $items['node/add/custom_type']['access callback'];

  $items['node/%node']['access callback'] = '_custom_node_access';
  $items['node/%node']['access arguments'] = array(1, $old_access_callback);

  $items['node/add/customContent']['access callback'] = '_custom_node_access';
  $items['node/add/customContent']['access arguments'] = array(1, $old_access_callback_add_customContent);
}

function _custom_node_access($node, $old_access_callback = "node_access"){
  //check if user has permission to view the node object
  //or add new content and return TRUE or FALSE
}

```

Note that with 'node/%node' item, everything works as expected. When `_custom_node_access()` returns `TRUE` for a user that have no permissions to perform the certain action (add), I get a WSD. One way I found to avoid this behavior is to return my calculated `result && user_access("create custom_type content")` so that I can, at least, get an access denied page. Do you have any suggestion for this behavior?

Finally, `_custom_node_access()` seems to run more than one time every time the '/node/add/customContent' path is visited. Is there any particular reason for this?

*It's been only few months since I started using Drupal so it's very likely that I'm missing something about permission...*

# Answer
There is a way to override programmatically drupal's permissions defined in `admin/user/permission`. Example:

```
<?php

function set_permission($rid, $permission) {
  $result = db_result(db_query("SELECT perm FROM {permission} WHERE rid = %d", $rid));
  if (is_array($result)) {
    $permissions = array_flip(explode(', ', $result));
  } else {
    $permissions = array();
  }
  $permissions[$permission] = true;
  db_query("DELETE FROM {permission} WHERE rid = %d", $rid);
  db_query(
    "INSERT INTO {permission} (rid, perm) VALUES (%d, '%s')",
    $rid,
    join(', ', array_keys($permissions))
  );
}

function unset_permission($rid, $permission) {
  $result = db_result(db_query("SELECT perm FROM {permission} WHERE rid = %d", $rid));
  if (is_array($result)) {
    $permissions = array_flip(explode(', ', $result));
  } else {
    $permissions = array();
  }
  unset($permissions[$permission]);
  db_query("DELETE FROM {permission} WHERE rid = %d", $rid);
  db_query(
    "INSERT INTO permission (rid, perm) VALUES (%d, '%s')",
    $rid,
    join(', ', array_keys($permissions))
  );
}

```
> 3 votes

# Answer
See the drupal doc how to resolve a white screen of death problem.
> 0 votes

---
Tags: users
---


# Question
Title: Within my themes page.tpl.php file it has a reference to a lot of variables like $head and $local_styles. What file are they stored in?
Within my themes page.tpl.php file it has a reference to a lot of variables like $head and $local\_styles. What file are this variables stored at so that I can looked at what each of these variables represent? John

# Answer
> 3 votes
The values are not stored at all. Instead they are generated dynamically at run time and feed into the template. The list of variables is just there so you will know which variables exactly are available in any particular template.

If you want to examine their content, you can add

```
drupal_set_message(print_r($variable, TRUE));

```

to the template, and simply load the page. If you install the Devel module, you can get much easier to read output like this:

```
dpm($variable);

```

I frequently use dpm in my everyday work when debugging or building new code.

# Answer
> 1 votes
The variables are driven by the templating engine. Check out the Drupal API on page.tpl.php for details of what each variable does.

---
Tags: 7
---


# Question
Title: Drupal Views: Get all of x categorised by y
Is this possible?

I have products and each product has a list of associated downloads. I would like to output all downloads (an index of downloads if you like) but split by headings of each product.

Product A
• Download A
• Download B
• Download C

Product B
• Download D
• Download E
• Download F

Can I get this through Drupal Views?

**Update:**

Just to give anyone seeking the same solution a helping hand... In views Advanced turn Use Aggregation on.

Add the fields you would like to use.
The aggregation settings automatically pop up after adding a field. For Associated Product, I chose Group By.

Then in the Format (HTML List) settings, choose group by Associated Product.

# Answer
> 1 votes
I haven't learned how this works myself yet, so I can't give you an exact answer, but here's a video tutorial on Using aggregation in Views, which should answer this for you.

---
Tags: views
---


title: How to query for parent theme(s)?

text:
# Question
Title: How to query for parent theme(s)?
Drupal lets you sub-theme a theme, basically like inheritance. How can I print out a list of all themes that a drupal site is 'using'. For example: actual theme -\> parent theme 1 -\> base theme

# Answer
This is how Display Suite does it:

```
// Get layouts defined in the default theme and base theme (if applicable).
$theme = variable_get('theme_default');
$themes = list_themes();

$base_theme = array();
$ancestor = $theme;
while ($ancestor && isset($themes[$ancestor]->base_theme)) {
  $ancestor = $themes[$ancestor]->base_theme;
  $base_theme[] = $themes[$ancestor];
}

```
> 3 votes

# Answer
Install Devel and devel\_themer modules. Go to the page you want to see where the output is coming from. Check the box at lower left corner which devel\_themer creates. Click on the element, it will display which template was used and what are other alternatives. It aslo tell you which theme\_function was used you can copy that function in you theme's template.php file name it as yourtheme\_function and customize it. (Remember to enable the devel\_themer module only when you are looking for templates or theme functions. It adds lots and lots of spans to html of the site)
> 0 votes

---
Tags: theming
---


title: What could be causing this ajax error?

text:
# Question
Title: What could be causing this ajax error?
I am getting an Ajax error when attempting to open a panel definition variant "summary" tab. Sometimes ajax is working and sometimes it is failing. This same question was asked twice several hours ago but one version was closed without an answer and the other was deleted. Does anyone have any suggestions about how to investigate or solve this?

Edit: The error is generated in panels on only some of the vertical option tabs such as summary and general, but not on the context, layout and content pages.

```
An AJAX HTTP error occurred.
HTTP Result Code: 200
Debugging information follows.
Path: /admin/structure/pages/ajax/operation/node_view/handlers/node_view_panel_context/settings
StatusText: OK
ResponseText: [{"command":"settings","settings":{"basePath":"\/","pathPrefix":"","ajaxPageState":{"theme":"seven","theme_token":"pfhU4ZtN-CjUT9YtHcYnH7OvO_Rbbb45p-GczYg97v8","css":[],"js":{"misc\/textarea.js":1}},"nice_menus_options":{"delay":"800","speed":"slow"},"admin_menu":{"destination":"destination=admin\/structure\/pages\/ajax\/operation\/node_view\/handlers\/node_view_panel_context\/settings","hash":"2dd7a85b62aff52c002ef6882d5ec80b","basePath":"\/admin_menu","replacements":{".admin-menu-users a":"0 \/ 1"},"margin_top":1,"position_fixed":1,"toolbar":{"activeTrail":"\/admin\/structure"}},"CToolsModal":{"loadingText":"Loading...","closeText":"Close Window","closeImage":"\u003cimg typeof=\"foaf:Image\" src=\"http:\/\/CR-Hub:8082\/sites\/all\/modules\/ctools\/images\/icon-close-window.png\" alt=\"Close window\" title=\"Close window\" \/\u003e","throbber":"\u003cimg typeof=\"foaf:Image\" src=\"http:\/\/CR-Hub:8082\/sites\/all\/modules\/ctools\/images\/throbber.gif\" alt=\"Loading\" title=\"Loading...\" \/\u003e"}},"merge":true},{"command":"insert","method":"prepend","selector":"head","data":"\u003cscript type=\"text\/javascript\" src=\"http:\/\/CR-Hub:8082\/misc\/textarea.js?v=7.10\"\u003e\u003c\/script\u003e\n","settings":null},{"command":"insert","method":"replaceWith","selector":"#page-manager-edit","data":"\u003cdiv id=\"page-manager-edit\"\u003e\n    \u003cdiv class=\"page-manager-wrapper\"\u003e\n          \u003cdiv class=\"primary-actions clearfix actions\"\u003e\n        \u003cul class=\"page-manager-operations Array\"\u003e\u003cli class=\"operations-actions operation-first not-changed not-active\"\u003e\u003ca href=\"\/admin\/structure\/pages\/nojs\/operation\/node_view\/actions\/disable\" id=\"page-manager-operation-disable\" class=\"page-manager-operation\" title=\"De-activate this page. The data will remain but the page will not be in use on your system.\"\u003eDisable\u003c\/a\u003e\u003c\/li\u003e\u003cli class=\"operations-actions not-changed not-active\"\u003e\u003ca href=\"\/admin\/structure\/pages\/nojs\/operation\/node_view\/actions\/add\" id=\"page-manager-operation-add\" class=\"page-manager-operation\" title=\"Add a new variant to this page.\"\u003eAdd variant\u003c\/a\u003e\u003c\/li\u003e\u003cli class=\"operations-actions not-changed not-active\"\u003e\u003ca href=\"\/admin\/structure\/pages\/nojs\/operation\/node_view\/actions\/import\" id=\"page-manager-operation-import\" class=\"page-manager-operation use-ajax\" title=\"Add a new variant to this page from code exported from another page.\"\u003eImport variant\u003c\/a\u003e\u003c\/li\u003e\u003cli class=\"operations-actions operation-last not-changed not-active\"\u003e\u003ca href=\"\/admin\/structure\/pages\/nojs\/operation\/node_view\/actions\/rearrange\" id=\"page-manager-operation-rearrange\" class=\"page-manager-operation\" title=\"Change the priority of the variants to ensure that the right one gets selected.\"\u003eReorder variants\u003c\/a\u003e\u003c\/li\u003e\u003c\/ul\u003e      \u003c\/div\u003e\n        \u003cdiv class=\"page-manager-tabs clearfix\"\u003e\n      \u003cdiv class=\"page-manager-edit-operations\"\u003e\n        \u003cdiv class=\"inside\"\u003e\n          \u003cul class=\"page-manager-operations Array\"\u003e\u003cli class=\"operations-main operation-first not-changed not-active\"\u003e\u003ca href=\"\/admin\/structure\/pages\/edit\/node_view\" id=\"page-manager-operation-summary\" class=\"page-manager-operation\" title=\"Get a summary of the information about this page.\"\u003eSummary\u003c\/a\u003e\u003c\/li\u003e\u003cli class=\"operations-main operation-last not-changed active-group\"\u003e\u003cdiv class=\"page-manager-group-title\"\u003eVariants\u003c\/div\u003e\u003cul class=\"page-manager-operations Array\"\u003e\u003cli class=\"operations-handlers operation-first not-changed active-group\"\u003e\u003cdiv class=\"ctools-collapsible-container\"\u003e\u003cdiv class=\"ctools-collapsible-handle\"\u003e\u003cdiv class=\"page-manager-group-title\"\u003eMaterial Articles\u003c\/div\u003e\u003c\/div\u003e\u003cdiv class=\"ctools-collapsible-content\"\u003e\u003cul class=\"page-manager-operations Array\"\u003e\u003cli class=\"operations-handlers-node_view_panel_context operation-first not-changed not-active\"\u003e\u003ca href=\"\/admin\/structure\/pages\/nojs\/operation\/node_view\/handlers\/node_view_panel_context\/summary\" id=\"page-manager-operation-summary\" class=\"page-manager-operation use-ajax\" title=\"Get a summary of the information about this variant.\"\u003eSummary\u003c\/a\u003e\u003c\/li\u003e\u003cli class=\"operations-handlers-node_view_panel_context not-changed active\"\u003e\u003ca href=\"\/admin\/structure\/pages\/nojs\/operation\/node_view\/handlers\/node_view_panel_context\/settings\" id=\"page-manager-operation-settings\" class=\"page-manager-operation use-ajax\" title=\"Change general settings about this variant.\"\u003eGeneral\u003c\/a\u003e\u003c\/li\u003e\u003cli class=\"operations-handlers-node_view_panel_context not-changed not-active\"\u003e\u003ca href=\"\/admin\/structure\/pages\/nojs\/operation\/node_view\/handlers\/node_view_panel_context\/criteria\" id=\"page-manager-operation-criteria\" class=\"page-manager-operation\" title=\"Control the criteria used to decide whether or not this variant is used.\"\u003eSelection rules\u003c\/a\u003e\u003c\/li\u003e\u003cli class=\"operations-handlers-node_view_panel_context not-changed not-active\"\u003e\u003ca href=\"\/admin\/structure\/pages\/nojs\/operation\/node_view\/handlers\/node_view_panel_context\/context\" id=\"page-manager-operation-context\" class=\"page-manager-operation\" title=\"Add additional context objects to this variant that can be used by the content.\"\u003eContexts\u003c\/a\u003e\u003c\/li\u003e\u003cli class=\"operations-handlers-node_view_panel_context not-changed not-active\"\u003e\u003ca href=\"\/admin\/structure\/pages\/nojs\/operation\/node_view\/handlers\/node_view_panel_context\/layout\" id=\"page-manager-operation-layout\" class=\"page-manager-operation\" title=\"Change the layout of this panel.\"\u003eLayout\u003c\/a\u003e\u003c\/li\u003e\u003cli class=\"operations-handlers-node_view_panel_context not-changed not-active\"\u003e\u003ca href=\"\/admin\/structure\/pages\/nojs\/operation\/node_view\/handlers\/node_view_panel_context\/content\" id=\"page-manager-operation-content\" class=\"page-manager-operation\" title=\"Add content items and change their location with a drag and drop interface.\"\u003eContent\u003c\/a\u003e\u003c\/li\u003e\u003cli class=\"operations-handlers-node_view_panel_context operation-last not-changed not-active\"\u003e\u003ca href=\"\/admin\/structure\/pages\/nojs\/operation\/node_view\/handlers\/node_view_panel_context\/preview\" id=\"page-manager-operation-preview\" class=\"page-manager-operation\" title=\"Get a preview of what this variant will look like.\"\u003ePreview\u003c\/a\u003e\u003c\/li\u003e\u003c\/ul\u003e\u003c\/div\u003e\u003c\/div\u003e\u003c\/li\u003e\u003cli class=\"operations-handlers not-changed not-active\"\u003e\u003cdiv class=\"ctools-collapsible-container ctools-collapsed\"\u003e\u003cdiv class=\"ctools-collapsible-handle\"\u003e\u003cdiv class=\"page-manager-group-title\"\u003eStory authors\u003c\/div\u003e\u003c\/div\u003e\u003cdiv class=\"ctools-collapsible-content\"\u003e\u003cul class=\"page-manager-operations Array\"\u003e\u003cli class=\"operations-handlers-node_view_story_author_redirect operation-first not-changed not-active\"\u003e\u003ca href=\"\/admin\/structure\/pages\/nojs\/operation\/node_view\/handlers\/node_view_story_author_redirect\/summary\" id=\"page-manager-operation-summary\" class=\"page-manager-operation use-ajax\" title=\"Get a summary of the information about this variant.\"\u003eSummary\u003c\/a\u003e\u003c\/li\u003e\u003cli class=\"operations-handlers-node_view_story_author_redirect not-changed not-active\"\u003e\u003ca href=\"\/admin\/structure\/pages\/nojs\/operation\/node_view\/handlers\/node_view_story_author_redirect\/settings\" id=\"page-manager-operation-settings\" class=\"page-manager-operation use-ajax\" title=\"Change general settings about this variant.\"\u003eSettings\u003c\/a\u003e\u003c\/li\u003e\u003cli class=\"operations-handlers-node_view_story_author_redirect not-changed not-active\"\u003e\u003ca href=\"\/admin\/structure\/pages\/nojs\/operation\/node_view\/handlers\/node_view_story_author_redirect\/criteria\" id=\"page-manager-operation-criteria\" class=\"page-manager-operation\" title=\"Control the criteria used to decide whether or not this variant is used.\"\u003eSelection rules\u003c\/a\u003e\u003c\/li\u003e\u003cli class=\"operations-handlers-node_view_story_author_redirect not-changed not-active\"\u003e\u003ca href=\"\/admin\/structure\/pages\/nojs\/operation\/node_view\/handlers\/node_view_story_author_redirect\/context\" id=\"page-manager-operation-context\" class=\"page-manager-operation\" title=\"Add additional context objects to this variant that can be used by the content.\"\u003eContexts\u003c\/a\u003e\u003c\/li\u003e\u003cli class=\"operations-handlers-node_view_story_author_redirect operation-last not-changed not-active\"\u003e\u003ca href=\"\/admin\/structure\/pages\/nojs\/operation\/node_view\/handlers\/node_view_story_author_redirect\/preview\" id=\"page-manager-operation-preview\" class=\"page-manager-operation\" title=\"Get a preview of what this variant will look like.\"\u003ePreview\u003c\/a\u003e\u003c\/li\u003e\u003c\/ul\u003e\u003c\/div\u003e\u003c\/div\u003e\u003c\/li\u003e\u003cli class=\"operations-handlers operation-last not-changed not-active\"\u003e\u003cdiv class=\"ctools-collapsible-container ctools-collapsed\"\u003e\u003cdiv class=\"ctools-collapsible-handle\"\u003e\u003cdiv class

```

# Answer
I found the problem. When the module Drupal for Firebug is disabled, the ajax error disappears. I will report it to them.
> 2 votes

# Answer
Not sure if it's just a limitation of the StackEx message area or what, but your ResponseText is not valid JSON (not terminated) -- even taking into account that it turns invisible after "data": in this web page.

Other than that, I can't tell much without a live example.
> 1 votes

---
Tags: 7, ajax
---


title: Drupal 7.8 customising user.module

text:
# Question
Title: Drupal 7.8 customising user.module
I am going to build a site using Drupal 7.8. I have some knowledge in PHP, but it is my first time I use Drupal, so I would like to ask your help regarding some basic functional questions I have

1. I want to have 2 tabbed blocks in my first page. One for "log in" and another for "sign up". To create this blocks: For "log in" block it s easy: I will use the out of the box functionality as is (removing create new and request password). For "sign up" block I would like to remove and add some fields. Is there any way to find inside user.module the fields used for "username","password","email" etc. and try to use them in my own module? What are the minimum requirements to use these fields? In other words, if I find the name of these fields, can I use only the names on my module, or I have to override a form/function that maybe contains these fields?
2. I want to use these fields, but finally for the submission in the database I 'd like to use the default submit functionality. How that could be done? 3.And one last and very newbie question! Forms are implemented using functions or can be stand alone? So to use an existing form, I have to find in which function it s declared or I have to override only that form? I know that these are basic questions I should already know but after searching in google, I didn't manage to find a clear solution that works. Could you please help?

# Answer
> 1 votes
You can also use fields to add additional fields to a user or user the profile2 module. There's a good chance, that you don't even have to code a line ;-).

If you need: You can change any form in Drupal with hook\_form\_alter. This way you can add more functionality to the sign up form.

# Answer
> 0 votes
The builder function for the user registration form is user\_register\_form(), whose essential code is the following one:

```
  $form['#user'] = drupal_anonymous_user();
  $form['#user_category'] = 'register';

  $form['#attached']['library'][] = array('system', 'jquery.cookie');
  $form['#attributes']['class'][] = 'user-info-from-cookie';

  // Start with the default user account fields.
  user_account_form($form, $form_state);

  // Attach field widgets, and hide the ones where the 'user_register_form'
  // setting is not on.
  field_attach_form('user', $form['#user'], $form, $form_state);
  foreach (field_info_instances('user', 'user') as $field_name => $instance) {
    if (empty($instance['settings']['user_register_form'])) {
      $form[$field_name]['#access'] = FALSE;
    }
  }

```

The most important part of user\_account\_form() is the following one:

```
  // Only show name field on registration form or user can change own username.
  $form['account']['name'] = array(
    '#type' => 'textfield',
    '#title' => t('Username'),
    '#maxlength' => USERNAME_MAX_LENGTH,
    '#description' => t('Spaces are allowed; punctuation is not allowed except for periods, hyphens, apostrophes, and underscores.'),
    '#required' => TRUE,
    '#attributes' => array('class' => array('username')),
    '#default_value' => (!$register ? $account->name : ''),
    '#access' => ($register || ($user->uid == $account->uid && user_access('change own username')) || $admin),
    '#weight' => -10,
  );

  $form['account']['mail'] = array(
    '#type' => 'textfield',
    '#title' => t('E-mail address'),
    '#maxlength' => EMAIL_MAX_LENGTH,
    '#description' => t('A valid e-mail address. All e-mails from the system will be sent to this address. The e-mail address is not made public and will only be used if you wish to receive a new password or wish to receive certain news or notifications by e-mail.'),
    '#required' => TRUE,
    '#default_value' => (!$register ? $account->mail : ''),
  );

  // Display password field only for existing users or when user is allowed to
  // assign a password during registration.
  if (!$register) {
    $form['account']['pass'] = array(
      '#type' => 'password_confirm',
      '#size' => 25,
      '#description' => t('To change the current user password, enter the new password in both fields.'),
    );

```

`$register` is set by `user_account_form()` using the following code:

```
$account = $form['#user'];
$register = ($form['#user']->uid > 0 ? FALSE : TRUE);

```

If you just need to show those three fields, then it is sufficient that you call `user_account_form()`, setting `$form` with the first two lines I reported for `user_register_form()`.

```
  $form['#user'] = drupal_anonymous_user();
  $form['#user_category'] = 'register';

```

`user_account_form()` has its own validation handler (user\_account\_form\_validate()); you don't need to write code for validating the input given from the user.

To re-use a field created from a function, you need to call that function. In the case of `$form['account']['name']`, if I use the following code in my form build, I would not obtain anything: the field will not be created, nor would I get the field defined by that form builder simply for the fact I am using the same string that function uses.

```
$form['account']['name'] = array();

```

---
Tags: forms
---


# Question
Title: Show newest nodes for each taxonomy term in Views
A block with taxonomy terms and an overview of the newest nodes for each taxonomy term. Every news sites uses this idea.

Business: Article 1, Article 2 Technology: Article 1, Article 2 Sports: Article 1, Article 2

Only article 1 for every node has a teaser and picture...

Any idea how to do this with just one view? You can make a view for each term, but I don't like that idea...

# Answer
I was trying to achieve a similar thing. I've managed to create a view that gets one article for each taxonomy term using 'Taxonomy term: Representative node' under 'Advanced \> Relationship'.

There is also 'Content: Taxonomy terms on node' there which might be more what you're looking for.

Once you've got the relationship you can pull out fields and base filter criteria on that relationship. My view only returns 1 content type for instance.

Make sure your view is on Taxonomy not Content.
> 9 votes

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


title: Add custom node content to cache

text:
# Question
Title: Add custom node content to cache
I have added a few custom nodes to my website via the admin CMS. I wanted to know if I would have to explicitly add them to cache or if the nose\_save or one of the internal drupal methods would add it to cache? I am using memcache for my caching purposes.

# Answer
Generally, Drupal caches pages for *anonymous* users. This is true for all nodes. You can turn this, together with some other caching settings, on and off at admin/config/development/performance

If memcache handles the data that otherwise goes into cache\_page, then you will benefit from memcache in returning nodes.
> 2 votes

---
Tags: nodes, caching
---


# Question
Title: How to apply an image style to an image field within a node template
I have a view where I can't use fields (the reason is complicated but I have to list the content as full content). I'm trying to figure out how to use differnt image styles from withing the node template. For instance, I have two image styles one that is 120 x 120 and one that is 360 x 360. I want to make the node template behave so that the first row displays the 360 x 360 and the subsequent rows display 120 x 120, but I can't figure out how to apply the image style to the field within the node template.

# Answer
I found this code somewhere as well and it seems to work within the template file.

```
 print theme('image_style', array( 'path' =>  $field_my_image[0]['uri'], 'style_name' => 'square_550'));

```

where the field\_my\_image is the name of your field .... I suppose it does the same as the above code.
> 3 votes

# Answer
You could use image\_style\_url($style, $uri);

```
foreach($node->imagefield[LANGUAGE_NONE] as $image) {
  echo '<img src = "' . image_style_url('style-name', $image['uri']) . '">';
}

```
> 1 votes

---
Tags: views, nodes, theming, media
---


# Question
Title: Correct Syntax for $conf to populate Varnish Control Terminal
This may be more a php question, but pertains to Drupal, so here goes: I'm trying to configure Varnish Control Terminal to use multiple hosts using `settings.php`. I have:

```
$conf['varnish_control_terminal'] = array ('11.22.33.44:6082','22.33.44.55:6082');

```

but I keep getting this error (1 set for each host in the array) at http://localhost/admin/config/development/varnish:

```
Warning: explode() expects parameter 2 to be string, array given in _varnish_terminal_run() (line 192 of /app/aegir/platforms/cms-1.0/sites/all/modules/contrib/varnish/varnish.module).
Warning: Invalid argument supplied for foreach() in _varnish_terminal_run() (line 196 of /app/aegir/platforms/cms-1.0/sites/all/modules/contrib/varnish/varnish.module).

```

I've also tried these (one by one):

```
$conf['varnish_control_terminal'] = array ('11.22.33.44:6082 22.33.44.55:6082');
$conf['varnish_control_terminal'] = array (11.22.33.44:6082 22.33.44.55:6082);
$conf['varnish_control_terminal'] = array ('11.22.33.44:6082');

```

with the same result. I think my `array` syntax is incorrect, but I am not sure what the correct syntax would is ... any ideas ... ? I looked at php's array documentation as well.

**EDIT**: This also causes the varnish status at http://localhost/admin/reports/varnish to go blank, so I am not sure if Varnish caching for Drupal is functioning properly or not at all.

Many thanks!

PS: I also posted a note in the Varnish project's issue queue on Nov 30th and haven't heard anything.

# Answer
So, turns out, the list of hosts is not an array; this works:

```
$conf['varnish_control_terminal'] = '11.22.33.44:6082 22.33.44.55:6082';

```

Hopefully, it helps someone else.
> 0 votes

---
Tags: caching, configuration, proxies
---


title: drupal_add_js(), script not executed

text:
# Question
Title: drupal_add_js(), script not executed
I try to include a simple script (below) and cant get it to work.

```
(function ($) {
  Drupal.behaviors.myModuleBehavior = function (context) {
    alert('say something pretty please');
  }
})(jQuery);

```

The script is added within a hook\_form\_alter function

```
drupal_add_js(drupal_get_path('module', 'my_module') . '/js/my_module_form.js', 'file');

```

Up to here, no issues. I see the script is added to the long line of js:extends with the correct path. Thus I would expect to receive an alert... but nothing happens.

As I've run out of things to check for and consulted docs, google and this site, only to find that the code should work, is anyone able to point out what might be wrong here?

# Answer
> 3 votes
I believe the `= function (context)` bit needs to include the `attach`:

```
(function ($) {
  Drupal.behaviors.myModule = {
    attach: function (context, settings) {
      alert('say something pretty please');
    }
  };
})(jQuery);

```

---
Tags: 7, javascript
---


# Question
Title: Use Subdomains as variable with Domain Access
I'm new to Domain Access module. It seems it is built to allow you to run different sites off the same database. I'm looking for something more simple than that.

I want to the subdomain title to be included in the site name. I want a content type to be assigned to different subdomains and for that content to be the only content of it's type visible on the same subdomain.

Aside from that, everything else on the site should remain the same. Theme, users, layout, etc.

How can I best do this with DA module? Is it possible to use the domain as a variable (for use in views, panel's context and a token for the site name)?

# Answer
I did this by installing Domain Access module. When skimming Domain Access module's documentation before, it seemed extremely complicated. However, the documentation is geared towards you learning all about how it works. The actual steps to install are more than a regular module, but not too complicated.

It allows me to restrict content to a specific domain and to have different site names for each domain.
> 1 votes

# Answer
Edit: I see the 7.x version of Subdomain does not yet support Content type domains.

If you use Domain Access, you can manually create all the required subdomains and you can define a site name for each (I believe this requires the included submodules Domain Configuration and Domain Settings). You can set a default front page for each domain you create (such as a Views page). If you want to filter by content type, you will have to configure a view for each subdomain. It may be better, however, to use the DA module's model of content affiliation, that is, when you create a node you can assign it to a specific (sub)domain. If you want to restrict on which domains nodes are viewable, you will have to do this anyway, so the differentiation by content types might not be necessary (depending on your needs).

If you do need different content types for each subdomain and you can't trust your users to choose the right domain content affiliation, you can use Domain Content Types to restrict which content type can be used for each domain, e.g. the 'News' content type is configured for use only on the domain news.example.com.

---

It seems the Subdomain module will do exactly what you want:

> Content type subdomains: e.g. "News" content at http://news.example.com

This is also a much more light-weight solution than Domain Access - always a good thing.
> 0 votes

---
Tags: 7, domain-access
---


title: Taxonomy vocabulary

text:
# Question
Title: Taxonomy vocabulary
I created a taxonomy vocabulary that groups all blogs with the specified taxonomy term. I mapped a menu link to this taxonomy term. When this menu link is accessed, I see all the blogs listed, but at the top of the page I see the vocabulary term shown in bold. I do not want this term on the page. How do I hide the term? Thanks.

# Answer
I found the solution, it was actually very simple. I logged in as the user that created the vocabulary and the vocabulary-URL mapping, clicked on the menu link that linked to the taxonomy vocabulary page, the page loads with view & edit tabs, clicking edit will let you change the title of the page.
> 1 votes

# Answer
You could try tracking down from which theme function or template file it is coming from and removing it there. The Devel and Theme developer modules can probably help you with that. Hiding it via CSS may be acceptable as well since it's only a small piece of html code.
> 1 votes

# Answer
Edit the content type \> Manage Display \> Hide the term reference.
> 0 votes

# Answer
I'm not immediately sure why the term is displayed as it is, but what I always do myself, is use Panels to override the taxonomy display. Panels being a complicated tool, one could think it's a bit overkill to use for something as simple as removing this little piece of text; but the extra control you get this way is well worth learning. Here are videos demonstrating the use of the Page managar and Panels.
> 0 votes

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


title: Premium Responsive Drupal 6 themes?

text:
# Question
Title: Premium Responsive Drupal 6 themes?
Where can I find Premium Responsive Drupal 6 themes?

(CSS defined in such a way that the same stylesheet is used on mobile and desktop)

It must be Drupal 6 because I am using it with drupal-cod.

# Answer
> 0 votes
Update 1: As pointed out by the OP, Jeff Burnz doesn't only sell his time as a consultant, but actually has a site, AdaptiveThemes.com, where he sells his "adaptive"-themes, but those are D7 only.

Unfortunately I'm not aware of any company advertising such themes yet. One of the first I would except to see this from is http://fusiondrupalthemes.com/, but nothing there yet.

If you are looking for something more unique, I believe the Drupal 8 Design Initiative owner, Jeff Burnz, sells his time to make themes, and is the author of a number of responsive themes already. Sky, Corolla and the base theme Adaptive theme, which you may want to look into, given the lack of an actual answer to your question.

---
Tags: theming
---


# Question
Title: Context Node Add Form and Wrong Button Position
I created a context node add form and added it to the panel page.
The form is displayed in the page but, "Save" button is wrongly positioned.

Another form also has the button wrongly at the top instead of bottom.
I updated the button's weight from my custom code to move the button underneath of the form, but it doesn't work.
I used CCK fields in my form.
I'm looking for a fix.

# Answer
Have you tried adding the submit button separately from the contact form?

If you are using an override to the node add/edit form in panels, try this:

**1.** Click on the little gear of your region to add content

**2.** Select Node form submit buttons which is under the "Form" heading

**3.** Position the form submit buttons where you want.

We had a similar problem on a Drupal 6 installation, and I think it may work on Drupal 7 as well.

Hope this helps
> 1 votes

---
Tags: 7, forms, panels
---


# Question
Title: Bypass publish approval on content creation for a certain role
I have a content type *"place"* which can be created by any registered user but needs to be published by a *"site editor"* role. I also have a *"place editor"* role which will have his *"place"* content published as soon as it is created, not needing an approval.

There are other content types such as *"event"*, which will have their own editors, so that a *"place editor"* will have to have his *"event"* content published by a site editor, but his *"place"* content will be published right away.

Can you name a module for this? I am using drupal 7

# Answer
You could user Rules to publish or unpublish content based on a role or any other condition.
> 1 votes

# Answer
This sounds like you might need a module to moderate content (especially if the content may be changed after publishing and these changes need to get approved again before being published).

In Drupal 6, you might want to try content\_moderation or revisioning.

In Drupal 7, workbench\_moderation would be my first choice.
> 1 votes

---
Tags: users
---


# Question
Title: How to integrate custom code into a "Features" feature
My specific problem: In a Feature, I have a View. I want to use this View on several different sites. The View has a nid-argument, which validates Node:type == \[node\_type\_1\]. When the Feature get's exported, it outputs the filter settings like this:

```
'node_type_1' => 'node_type_1',
'node_type_2' => 0,
'node_type_3' => 0,

```

Problems ensue when the feature is used on site number 2, which, with exception of \[node\_type\_1\], has an entirely different list of content types. Thus the list becomes

```
'node_type_1' => 'node_type_1',
'node_type_4' => 0,
'node_type_5' => 0,

```

And suddently, I have an override, with a diff like:

```
< 'node_type_2' => 0,
< 'node_type_3' => 0,
> 'node_type_4' => 0,
> 'node_type_5' => 0,

```

Some background: At some point, I listened to an interview with a Features maintainer, who mentioned something interesting. It is both possible, and supported, to add custom code into features. I hope that can provide me with more dynamic means of handling this particular part of my problem.

My question is deliberately stated such that I hope someone can provide an answer to my specific problem, as well as similar problems, from other modules. I can easily imagine a similar problem showing up in many different situations. However, if it turns out that no-one can solve the problem in a general fashion, yet can solve this specific problem, I will re-phrase the question title to reflect that better.

# Answer
> 1 votes
You have a few options, to create generic Views.

* One way of dealing with this, would be to add code to the views definition. This would work out fine, but the problem is that the code would be removed when you update the feature - not good.
* Another option would be to exclude the view from the feature entirely. This would work out fine, but in case you have other views in your feature you will get into trouble - no good.
* My way of solving this problem: `hook_views_default_alter`. This is specific to views, but I believe a similar tactic would be needed for other components exported in features. The hook will allow you to alter the default which will make it possible to alter the view definition and make it fit into the current site. This also works great for views defined by other modules that you want to alter by code.

None of these, however, will fix the problem that features will adapt it's feature to the site it belongs to. That is, no matter how you alter the view, Features will still detect that the current definition (the file) if different from what it would look it if it were to be re-exported to code again. There isn't much you can do about this (without changing features), but I believe this is a needed to make features work like it should. What you are able to do, is to negate the changes that could be made, or to simply choose not to alter the file and let your `hook_alter` handle it instead to keep the code the same.

I can understand that none of these solutions aren't 100% what you are after. But if you want to have a generic view and you don't want to have features telling you that the view is different from what it would have created, the only solution is to not use features.

If this is a problem you should consider if you actually need features (Views can by itself export and revert views. The only thing missing is drush integration.

# Answer
> 1 votes
I think I've been at your spot before with a single D6 codebase running on different sites and using Features for managing exportables such as Views.

In our example we had site sections running off taxonomies and firing off contexts (which got exported via Features). The problem was that although the name of most of our taxonomy terms was the same across sites, their tids changed, and there where exceptions as well, resulting in the problem you expose above.

Our solution was to go directly into the Feature and substitute the hard-coded, instance-specific variables with our own dynamic code. So we had a custom function in a custom module that would determine the contents of a particular variable in the exported feature. Then after exporting the feature initially, we would go into the array that we wanted to modify, and substitute it with a call to our dynamic function. When reverting features on each individual site the dynamic value would take the place of the hard-coded value. The only drawback to this solution is that you need to copy/paste the call to your custom function every time you recreate the feature. But overall the solution was straightforward, easy to implement, and reliable.

---
Tags: views, 6, features
---


# Question
Title: In Drupal 7, do database queries need to be enclosed by double quotes?
I am migrating custom modules from Drupal 6 to 7. Since the database API changed it's quite a lot to do. During this I stumbled upon a problem regarding quotes. I am used to enclose strings in PHP with single quotes, so in Drupal 6 I wrote

`$q = 'SELECT * FROM {node} WHERE type = "page"';`

However, without any pattern (as far as I could detect) some of these queries fail in Drupal 7. When changing the above line to

`$q = "SELECT * FROM {node} WHERE type = 'page'";`

it suddenly works. But I couldn't find any information if this quoting style is required by the new DAL. Anybody got further information on that or can confirm my observation?

# Answer
Some SQL database engines are not supporting double quotes inside the query, that's why it didn't work out for you. Read more here: db\_query#comment-11959.
> 6 votes

---
Tags: 7, database
---


title: Pass arguments using hook_menu

text:
# Question
Title: Pass arguments using hook_menu
I would build a confirmation screen. So I initialized the path in the `hook_menu` as it should be but for some reason, the argument `$node` isn't send with the function... What am I doing wrong?

This is my `hook_menu`:

```
$items['node/%/revisions/%/offline'] = array(
      'title' => 'Offline,
      'description' => 'Confirm the action "Fiche offline".',
      'page callback' => 'drupal_get_form',
      'page arguments' => array('_mymodule_confirm_offline'),
      'type' => MENU_LOCAL_TASK,
      'weight' => -4,
    );
    return $items;

```

And this is my function:

```
function _redactie_omgeving_confirm_offline($form, $form_state, $node) {
    $question = t('Take fiche offline. ');

    return confirm_form($form,
                    $question,
                    'node/7', t('You\'re about to depublish this fiche. <br />Are you sure you want to depublish this fiche?'),
                    t('Yes'), t('Cancel'));
}

```

But the `$node`-variable in my function stays empty... What do I have to do to fill in this variable?

# Answer
> 13 votes
Your page callback is `drupal_get_form`, and your page argument is `_mymodule_confirm_offline`, so the call Drupal makes is `drupal_get_form('_mymodule_confirm_offline');`, which doesn't at all seem to be what you want to do.

What you need is a custom callback instead.

In hook\_menu:

```
'page callback' => '_confirmation_form_page',
'page arguments' => array(1, 3),

```

And then

```
function _confirmation_form_page($node) {
  $question = t('Take fiche offline. ');

  return confirm_form($form, $question, 'node/' . $node->nid, t('You\'re about to depublish this fiche. <br />Are you sure you want to depublish this fiche?'), t('Yes'), t('Cancel'));
}

```

In order to "auto-load" an object from the url, it needs to be *named*, otherwise Drupal can't know how to perform the load. On a url like "node/%nid", the argument is named "nid". In reality the argument would usually be called %node, but I wanted to distinguish the parts. Drupal will then look for a function called load\_nid, pass the number from the URL in, and this function is responsible for returning the fully loaded object. Core has a "load\_node" function, so arguments named %node will be auto-loaded without further effort from your part.

To add autoloading into your callback then, you need

`$items['node/%node/revisions/%/offline'] = array(`

However, this will still only give you the right node, not the right revision. node\_load() supports a second argument, `$vid`, that we need to use to get the right revision. Telling Drupal to pass on extra arguments is used with the `load arguments` key, and we need to use the fourth argument from the url `node/%node/revision/%/offline` for this.

So in conclusion, the hook\_menu implementation becomes:

```
$items['node/%node/revisions/%/offline'] = array(
  'title' => 'Offline',
  'description' => 'Confirm the action "Fiche offline".',
  'page callback' => '_confirmation_form_page',
  'page arguments' => array(1),
  'load arguments' => array(3),
);
return $items;

```

# Answer
> 0 votes
hook\_menu does not get $node object as parameter. Node in 'node/%/revisions/%/offline' is just a path it is not any node.

---
Tags: 7, routes
---


# Question
Title: Why isn't my Sub Theme's CSS file showing up?
I created a sub theme which is intended to just have a few color changes and background image changes.

The Base theme is called `limon`. The sub theme is `limon_orange`. In the sub theme, i have a unique style sheet that I want to use to override the base theme styles via cascade. In the limon\_orange.info file I have this line:

`stylesheets[all][] = orange.css`

The sub theme works, but orange.css is never used. What am I missing? Why is orange.css not loading?

# Answer
> 2 votes
Any change in .info does not take effect only by clearing cache. Remember to clear the theme registry. You can do this by just going to the admin/appearance and saving it.

# Answer
> 0 votes
First, I assume that you do not need a relative path for the stylesheet and Drupal can find the file.

There is a strong chance that your css is being read but is overridden by other style elements. If you use firebug you can see which css files and style inputs are controlling the display. Quite often you might have an element such as a paragraph, header, or link that is attached to several classes. CSS uses a scoring system to determine what style will prevail. The css hierarchy is scored with css info in a 'style' definition highest:

```
style="" -       1000 points
#Wrapper #ID {} - 200 points
#ID .class {} -   110
div#id {} -       101
#id -             100
p.class class {}   21
p.class {} -       11
div p {} -          2
p -                 1

```

*(p represents any html type such as h1, a, etc.)*

---
Tags: 7, theming, .info
---


title: Limit one user per IP in Drupal 6.22

text:
# Question
Title: Limit one user per IP in Drupal 6.22
Recently I found that multiple accounts are being created in my Drupal 6.22 website by someone from a particular IP. Is someone aware of any modules to limit the user to create only one account per ip?
Thanks.

# Answer
If it seems spammy, then maybe use Drupal to block the IP address (settings.php or admin) but if it's only a few and they look okay and genuine it could be users from the same college or company behind a proxy server.

If it you still want to block someone you could add an additional validate function to the user registration form and include an IP check in there.
> 2 votes

---
Tags: 7, users
---


# Question
Title: Paypal payments pro integration with drupal 6
I have a drupal 6 website which has the following workflow:

* User logs into site.
* User creates content through a custom module that I built.
* This content is not a content-type, its custom content.
* The user saves this content type, but cannot yet publish it.
* User then hits publish.
* He is asked how long he wants to publish the content for.
* User selects from 15 days, 1 month, 2 months etc.
* Depending on his selection he is provided a price for publishing the content for the interval.
* If the user pays the amount shown, his content is published.
* For each content page that he wishes to publish he will be provided the same options of selecting the interval and paying the price for the same.

**I have three questions about this:**

**1:** Are there any existing modules that would let me achieve this? (I did search and couldn't find any. My initial instinct was of-course ubercart, ecommerce etc... but I can't figure out how I would implement this specific workflow in any of these.)

**2:** If there aren't any existing modules for this, how would I integrate Paypal payments pro in my custom module? I can't find a straightforward tutorial anywhere.

**3:** Is it possible to use the payment backends of any other modules. I know ubecart provides a bunch of different payment methods. Is it possible to use these modules without ubercart and call them in a custom module?

# Answer
> 1 votes
For a quick win on this on Drupal 6 I would use Ubercart, it ships with paypal pro integration. And http://drupal.org/project/scheduler

It uses conditional actions to assign roles, give access to file downloads etc. A simple, if perhaps slightly inelegant way would be to pass the node ID of the unpublished content to a product as an free value attribute, then upon successful purchase use conditional actions to publish it, setting an expiry date time on the object properties scheduler uses before saving the node. You should not give users permissions to use scheduler, and I'm assuming you have cron up and running.

Sounds bodgy, but you could get it up and running very fast like that. Check if you like it and still have time to look at other solutions if not.

Commerce module might also be good but haven't used it on d6

---
Tags: commerce, payment-gateways
---


title: How *.drupal.org single sign-on works

text:
# Question
Title: How *.drupal.org single sign-on works
I believe there are many ways to achieve single sign-on within drupal. I would like to know the approach that \*.drupal.org sites have been using. If I visit any drupalconf sites http://chicago2011.drupal.org/user or http://london2011.drupal.org/user it authenticates me with the user credentials given in drupal.org site. I would appreciate if anyone can point me to the modules or handbook pages on achieving this. Thanks in advance.

# Answer
You might have a look at Bakery Single Sign-On System.

It mentions "This module started at the 2009 Drupal.org redesign sprint in San Francisco as a way to manage single sign-ons across \*.drupal.org infrastructure."

For more details about how it work, you can see this article that has great explanation: Single Sign-on across Sub-Domains in Drupal with No Extra Modules.
> 11 votes

# Answer
Drupal.org uses Bakery Single Sign-on System.

The following one is the description that will be added to the INSTALL.txt file of the project:

> Bakery provides single sign-on between Drupal sites on the same domain using a shared cookie. When a user authenticates on a site they are sent a cookie by Drupal, containing a unique identifier for that user. Sub-sequent requests by that user will contain the identifier, allowing Drupal to recognize that the request is coming from a specific user, an authenticated user.
> This process is handled by Drupal core. Bakery augments the login process and sends an additional cookie (referred internally to as the CHOCOLATECHIP cookie). Should the user now visit a sub-site (on the same domain) their browser will send this Bakery-created cookie. On the sub-site Bakery will recognize the cookie and if it is valid will authenticate the user (via Drupal core's processes). The user is now authenticated on both sites while only have to log on to one.
> 1 votes

# Answer
This is a writeup of how Bakery works, and thus SSO on drupal.org.
> 1 votes

---
Tags: 7, users, multi-sites
---


title: Does anyone knows a good menu module?

text:
# Question
Title: Does anyone knows a good menu module?
I'm looking for a menu module which would show a menu tree like:

```
Menu level 1 (Container)
    |-------Menu level 2
    |-------Menu level 2
    |-------Menu level 2
    |-------Menu level 2
    |-------Menu level 2
Menu level 1 (container)
    |-------Menu level 2
    |-------Menu level 2
Menu level 1
Menu level 1 (container)
    |-------Menu level 2
    |-------Menu level 2
    |-------Menu level 2
Menu level 1

```

It'd be the best if it would be dynamic, but that doesn't really a must. So anyone knows a Drupal 7 module which is capable of doing this?

# Answer
> 2 votes
UPDATE: This answer is no longer valid due to the module not being maintained. Please refer to other menu modules.

DHTML Menu may be an solution. It's still in beta for Drupal 7 though.

> DHTML Menu uses Javascript to reduce the number of page loads when using nested menus; this is particularly useful with Drupal's administration system.
>
> Ordinarily in Drupal, in order to see the sub-items in a menu, you need to click the link of this item and wait for a full page load. After enabling DHTML Menu, clicking a menu link once will expand it to reveal its sub-items without reloading the page. A double-click on the item will load the page normally. Additionally, a cookie stores which menus are open and which are closed, so that the state of the menus remain consistent as you navigate around the site.

# Answer
> 4 votes
Superfish is pretty configurable. You can use classic drop downs or try a mega menu

# Answer
> 2 votes
Take a look at the Special menu items module. It will let you define a menu item as `<nolink>` so that it can just serve as a parent item. I have used this on a few projects, and it works mostly well. Just keep in mind that you will need to do a decent amount of CSS work, though, since many themes/modules assume that menu entries are also links. Nothing earth shattering though, just a little annoying.

# Answer
> 1 votes
For your situation i would use superfish.

But to answer your first question (the title of your post):

There's actually a Drupal.org page of contributed menu modules:

> * Jump
> * Superfish
> * Menu block
> * Menu minipanels
> * Nice Menus
> * Nice Primary Menus
> * Site Menu: Site map and sidebar menu
> * Submenu Tree

**Comprehensive Listing on Drupal.org**

Also, if you're hungry for more comprehensive list of contributed menu modules; you're able to search by the category, "menu," in Drupal.org. It provides an extensive listing of 631 modules though.

---
Tags: 7, routes
---


title: Modify Commerce Product before saving

text:
# Question
Title: Modify Commerce Product before saving
How do I modify a commerce product before saving or alter the validation?

Specific use case: SKU field of commerce product is required but I want users to be able to leave this blank and have a SKU field auto generated and filled into the field automatically before saving the product.

# Answer
Sounds like you want auto sku check out some wonderful code already done http://drupal.org/project/commerce\_autosku

Some details from the module's project page:

> Commerce AutoSKU allows administrators to generate SKU's for Drupal Commerce products automatically. Using tokens, the SKU can be generated based on the value of arbitrary product fields such as title, author, or any custom fields you have added. Additional sitewide tokens are available when the Token module is enabled.
> 1 votes

# Answer
If you want to alter the validation you can use hook\_form\_alter to add/alter the validation handlers used for the form.

To change the product you can use one of the entity hooks: `hook_entity_insert` is probably the one you want to use, but there also is one for update, presave and delete, and they also exist in a variant specific for commerce products: `hook_commerce_product_insert`
> 1 votes

---
Tags: hooks, commerce
---


# Question
Title: Form behavior when form creation data changes
I've a form which shown from values in the database.

Now next day user fills it in and submits it. But the underlying data has already changed in the database.

I can see that in the validation handler form\_state contains data from the form prepared after it is submitted but which contains updated values from other users, while the data submitted by the user is based on 1 day old data and he/she is not aware of changed data.

How does Drupal form behave in the scenario?

For example:

1. I load a form and I see one row of data
2. Another user comes and adds a new row of data
3. I submit 1 row of data I see after checking on the checkbox
4. FAPI now rebuilds the form but it now finds two rows instead of one
5. In validation handler it sees two rows of data(but I submitted seeing single row)

→ Assume each row is 1 checkbox + textfield

Now I want to give error and ask the user to reload the form and submit again

# Answer
If you include a function `myform_validate`, you can test the value in the $formstate array against a query for the current value in the database. IF they do not match, return false and the original form will be redisplayed. This is explained in greater detail in the documentation for the form api
> 0 votes

---
Tags: forms
---


# Question
Title: Best place to add to Drupal.settings from a theme
I am working on a theme for a client, and have run into an instance where I would like to add to `Drupal.settings` via drupal\_add\_js() from the theme.

In this particular case, it is really most appropriate to do it from the theme itself and not a module hook, as the setting is related to the theme itself.

Doing it from template\_preprocess(), or one of its relatives, is too late because `$vars["scripts"]` has already been built. I suppose I could do something like the following code, but this doesn't seem right.

```
$settings = array(
  "bar" => "bar",
);

drupal_add_js(array("foo" => $settings), "setting");

$vars["scripts"] = drupal_get_js();

```

Is doing it from hook\_theme() really the only option, or is the above approach kosher?

# Answer
I have seen that pattern multiple times before, and it seems to be a standard practice.
> 4 votes

# Answer
Just for the record I had a similar problem today and solved it using hook\_preprocess\_hook() to intercept my theme function, no messy `$vars['scripts']` exists yet
> 1 votes

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


# Question
Title: Best place to include javascript in a field formatter?
I've created a custom field formatter using hook\_field\_formatter\_info() and implemented it using hook\_field\_formatter\_view().

My formatter requires additional javascript though and at the moment I'm including it in hook\_field\_formatter\_view() but I have a feeling there's gotta be a better place to do this.

However there is no hook\_field\_formatter\_preprocess() (there is a formatter\_prepare\_view() though but it doesnt't seem right)

Any ideas?

# Answer
Adding the JavaScript in hook\_field\_formatter\_view() works just fine. Just also be sure to use #attached and not drupal\_add\_js() since that way your file is included in the render cache.

```
function mymodule_field_formatter_view($entity_type, $entity, $field, $instance, $langcode, $items, $display) {
  $element = array();
  $settings = $display['settings'];

  foreach ($items as $delta => $item) {
    $element[$delta] = // Blah blah blah add output for each $items in $element as a render array.
  }

  // Add the JavaScript file.
  $element['#attached']['js'][] = drupal_get_path('module', 'mymodule') . '/mymodule.field.js;

  return $element;
}

```
> 4 votes

---
Tags: 7, javascript, entities
---


# Question
Title: Determine the row number of an unformatted row in views
I'm using the Views module with the unformatted style with full content, and I'm using node.tpl.php to style the row. I'm looking for a way to determine what row it is (e.g. I want to style the first row different than the subsequent rows).

Is there any variable that is available to the template? Is this something I would have to add into the template.php (via a pre-process function, or something of that nature)?

# Answer
> 1 votes
Views already wraps each row in all sorts of CSS classes, like views-row, views-row-#, views-row-first, views-row-last, etc, so if all you want to do is STYLE things differently, you can use these classes. Now, if you want to re-arrange the CONTENT of your node, that's a whole 'nother story...

# Answer
> 0 votes
So using css is by far the easiest way, however if really need to customize it, you can make two views, one for the top row (set the page limit to one) and one for all others (set the offset to 1). You can then use a different style for each. You can also use Views Split Node which essentually does the same thing.

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