# Question
Title: Set default value with PHP on a node field.
I'm using Drupal 7 and have created a content type called abc. In abc there is a field called seller. When a logged in user creates a new piece of abc content, the value of the seller field would be the name of the person who is logged in.

So what I want is a default value for the seller field for a small piece of PHP code. But I am not able to find the place to enter this PHP. In Drupal 6 there is text area for the php code to enter, how can this be done with Drupal 7.

# Answer
I don't know if there is an UI for it, but fields allows either an array as allowed values or an callback.

This means that you most likely will need to create a function in a module instead of hardcoding the php which then would be saved in the database. IMO this is a good thing.

In your field config array you want something like this:

```
....
'settings' => array(
    'allowed_values' => array(),
    'allowed_values_function' => 'callback_function',
),
...

```

If you are new to this, take a look at `field_create_field` and `field_update_field`.
> 2 votes

# Answer
I'm using User reference field to properly describe content made by few authors. It can be multi value, node author is only one out of the box. So if You have big article performed by few people user reference field is reasonable solution.

---

Sometimes User reference field is also needed, when you have real author of content and operator (person, who is posting content) and you need to know, who posted and when. If author is always operator, there is no need to use user reference field, because reference is already within Drupal core author stored.
> 1 votes

# Answer
If the content of this Field is the same as the Author of the Node, there is no need to make a seperate field.

Instead, you should add the already available Node:Author field to your View.
> 0 votes

---
Tags: 7, entities
---


title: How to add custom css file by code?

text:
# Question
Title: How to add custom css file by code?
Well I know that I have to use `drupal_add_css` like described here.

But that doesn't work and I don't understand why.

I tried to use this hooks: function hook\_init, hook\_views\_pre\_render, hook\_preprocess\_html and hook\_preprocess\_page.

I tried in that hooks this code:

```
$css=drupal_add_css(drupal_get_path('module', 'mymodule') . '/style.css');
$variables['styles'] = drupal_get_css($css);

```

or:

```
drupal_add_css(drupal_get_path('module', 'mymodule') . '/style.css');
$variables['styles'] = drupal_get_css();

```

or also just the first line.

also:

```
drupal_add_css("/".drupal_get_path('module', 'mymodule') . '/style.css');

```

or that:

```
drupal_add_css(drupal_get_path('module', 'mymodule') . '/style.css',
               array('group' => CSS_DEFAULT, 'every_page' => TRUE));

```

Here is my style.css:

```
#logo {
    display:none;
}

```

That should hide the logo on success. What is wrong with my tries?

# Answer
> 2 votes
in `hook_init`, removing the first slash should solve the problem. If not, check for permissions.

```
drupal_add_css("/".drupal_get_path('module', 'mymodule') . '/style.css');

```

Should be

```
drupal_add_css(drupal_get_path('module', 'mymodule') . '/style.css');

```

---
Tags: 7, theming
---


# Question
Title: Drupal Commerce default amount before adding a product
I want that the Drupal Commerce module checkout by default starts with one specific product , whether you choose another product or not.

Is this possible to achieve this by building a rule? Which rule do I need to build?

# Answer
> 1 votes
You can do this, but I doubt that this is possible with rules.

What you want is a custom checkout flow. Either this can be done by altering the checkout flow provided by Commerce, or disable it completely and write your own.

Either way you will need to write your own code to create this custom checkout experience, and this is beyond what Rules is capable of.

---
Tags: hooks, rules, commerce
---


title: how to set administrator menu

text:
# Question
Title: how to set administrator menu
i want to set

```
Site building
Site data management
Site configuration
Site users management
Store administration
Reports

```

as menus as admin login, else it show other menu bar.

```
Home
Search
Mark List
Contact
Help

```

so can any one suggest how will I achieve this.
cheers.
Sanjay Dev

# Answer
> 2 votes
Sounds like you are using Drupal 6. The Admin menu module provides a nice menu on top of the page for all admin items the user has access to.

Screen shot of admin menu http://drupal.org/files/images/Administration-menu.preview.png

---
Tags: navigation, routes
---


# Question
Title: Custom user profile fields, not editable by user
I've created some custom user profile fields but I don't want to let the user change those fields when he is editing his profile. These fields should only be changed by the site admin.

How can I do that? Thanks

# Answer
> 9 votes
You could try looking at the Field Permissions module. Simply don't allow editing of your specific fields for the role that the registering/registered user has.

---
Tags: 7, entities, users
---


title: Using a variable inside a print

text:
# Question
Title: Using a variable inside a print
I have the following code:

```
print $node->field_carousel_1[0]['filepath'];

```

What I would like to do is changing the 1, and use a variable instead.

Do you have any idea how I would be able to do this?

What I am aiming for is using a variable to create a looping function to print "field\_carousel\_1," "field\_carousel\_2," "field\_carousel\_3," etc.

# Answer
You can just change the 1 to your particular variable in the loop.

Example:

```
foreach ($values as $k => $v) {
  print $node->field_carousel_ . $v . [0]['filepath'];
}

```

That should output the values you need.
> 1 votes

---
Tags: theming
---


title: Adding jQuery Timeline to Drupal

text:
# Question
Title: Adding jQuery Timeline to Drupal
I have found this awesome jQuery Timelinr that I have customized for my Drupal site but am now at a loss at how to insert it. It is only going to be on one page. Does it need to be in a block? Do I have to make a custom module? Any assistance would be greatly appreciated!

# Answer
There are many ways to do it. Easy one is to add it on your theme's .info file: `scripts[] = js/your_jquery_plugin.js` But then its everywhere.

You can add it in a block. Check that your text-filter is set to PHP (May need to be active in the modules: PHP filter). Then add drupal\_add\_js()
> 1 votes

# Answer
If it's only o one page you can also create a plane new page set the text filter to PHP and add the drupal\_add\_js() code.

See here for some hints about integrating custom jQuery code into Drupal.
> 1 votes

# Answer
Did you resolve it meanwhile? If not, I suppose it is because of jquery-version conflicts. The Drupal built-in version is NOT new enough for this script; even the jQuery Update module does not bring the newest version. I had the same problem when trying to implement another jQuery script. I resolved it by removing the built-in jQuery and adding the new one. I did that in the page template. I know, it is not recommended.
> 1 votes

---
Tags: 7, javascript
---


# Question
Title: Hide formatting options from a CCK field in Drupal 6
I have a custom module in which I am using hook\_form\_alter to remove the formatting options/help text for the body and comment fields:-

```
function mymodule_form_alter(&$form, &$form_state, $form_id) {
// We don't want the format options displaying
if (isset($form['body_field']['format'])) {
    $form['body_field']['format']['#access'] = false;
}
if (isset($form['comment_filter']['format'])) {
    $form['comment_filter']['format']['#access'] = false;
}
}

```

This works fine. However, I also need to remove the same formatting options/help from a CCK field. I've tried to use the same technique but can't isolate where in $form the formatting options are being included. Is it not possible to removed them using the same method as above?

We want to remove this information as it is not relevant to the user as the WYSIWYG editor provides them with all the tools they need and nothing more. We don't want to hide these with CSS, they need removing from the output.

# Answer
> 1 votes
Found that this can be handled in the theme's template.php file:-

```
function phptemplate_filter_tips_more_info() {
return '';
}
function phptemplate_filter_tips($tips, $long = FALSE, $extra = '') {
return '';
}

```

Which then overrides all filter tips from forms.

---
Tags: entities, 6, input-formats
---


# Question
Title: Enable all languages for multilingual site
I notice I can add languages one by one on this page mysite.com/admin/config/regional/language/add

Is there an easy way for adding all languages? Maybe there is a command with drush?

# Answer
No - there is no drush command for this and you would want to do this one by one because you're going to need to upload your specific po translation files from Drupal.org (one reason its not practical to make this an option with the base install for n languages)
> 2 votes

---
Tags: i18n-l10n
---


title: Consolidating site CSS sheets

text:
# Question
Title: Consolidating site CSS sheets
As I'm moving on to the markup/stylesheet work on my site, I noticed that there are quite a bunch of CSS references to modules. Not only does it clutter the page markup, but it also refers to core Drupal modules, such as `/modules/field/theme/field.css`.

Since I have to override some of the style definitions (clear problematic floats, narrow a context, and some such), at the same time a question raises in my head - how do you guys approach those stylesheets: do you paste all the definitions in your theme css and remove unneeded css stylesheet links - or rather: - leave the stuff in place and override all problematic style definitions in your theme css?

How do you approach module-related stylesheets, such as Display Suite layouts?

I would like to avoid redundancy where possible, but only when the effort is justifiable. Any insights?

# Answer
> 4 votes
Drupal will aggregate all of your style sheets into one when you enable it at admin/config/development/performance (Don't set it during development).

If you feel there is too many redundant stylesheets, you can use a module like Omega Tools which allows you to completely disable stylesheets provided by modules (even core).

---
Tags: 7, theming
---


# Question
Title: Nodes being imported from the Feed module not being published
I have finally accomplished the communication between my 2 websites through the Feed module. I am exporting xml and I am using the XPath XML Parser to receive the nodes. The problem that I have now is that it is only updating nodes that have been previously imported through the feed, even though some of that content was already on the other website. The ones that are being imported are left with the Unpublished status, even though they were initially published on the website that exported them. How can I change this?

# Answer
I know this might sound way too easy but have you been into the content type you are importing to and made sure that it is set to default published? Unless you tell the imported nodes otherwise, they will use the default for the content type. If you are using the published status from the xml as the published status for the imported nodes, then thats another matter.
> 2 votes

---
Tags: feeds
---


# Question
Title: Change the formatting of a label in Drupal 7
When viewing the teaser for a node, all labels are output as uppercase. I want them titleized (meaning the first letter of every word is capitalized). What's the best way to go about doing this? Currently there is no CSS effecting the label field, so I know Drupal is just outputting all capitals.

I don't know why Drupal is rendering the label text in all capitals, so I was looking for a theme preprocessor function in the Drupal 7 API that could maybe dig into the label data and then change it to all lowercase from there, but I couldn't find anything concrete. I could then apply CSS to format the label how I want. However, until I know HOW Drupal renders the labels I can't apply any CSS that will have the desired effect.

EDIT: I changed the title from "Change label in teaser output to lowercase" to "Change the formatting of a label in Drupal 7" as I think that the question can be answered in a less specific sense, and I may have found the reason my labels are turning up in all caps.

# Answer
> 1 votes
This is likely controlled by CSS, you can change it by adding a rule to your CSS file similar to this:

```
.node-teaser label{text-transform:capitalize}

```

You might need to target the particular element a bit more precisely so have a look with Firebug to see what rule is setting the `text-transform` on the labels currently.

# Answer
> 3 votes
Something is odd about this as you say your labels are in lower case but they are being rendered in all caps. I would view it with Firebug / Chrome Web Inspector to make sure there is not a higher level selector in your CSS that's transforming it to all caps in which case you would have a tough time going back to title case if your selector does not override the one thats making it all caps.

*At any rate you can't transform all caps back to titlecase* but you could with jQuery:

https://stackoverflow.com/questions/3471157/css-text-transform-capitalize-on-all-caps

Also see this for reference, http://www.w3.org/TR/CSS21/text.html#propdef-text-transform

```
"capitalize
Puts the first character of each word in uppercase; other characters are unaffected."

```

But before you go an add some JQuery, I would take a serious look at your CSS with Firebug to make absolute sure that something is not transforming it to all caps in the first place.

# Answer
> 2 votes
Okay, since this code was inherited I began to suspect that the previous dev had done some fishy things, which he in fact did. Here is the code I found in the ridiculously huge template.php file.

```
function ccom_field($variables) {
  $output = '';

  // Render the label, if it's not hidden.
  if (!$variables['label_hidden']) {
    $output .= '<div class="field-label"' . $variables['title_attributes'] . '>' . strtoupper($variables['label']) . '</div>'; //<-- HERE the colon
  }

  // Render the items.
  $output .= '<div class="field-items"' . $variables['content_attributes'] . '>';
  foreach ($variables['items'] as $delta => $item) {
    $classes = 'field-item ' . ($delta % 2 ? 'odd' : 'even');
    $output .= '<div class="' . $classes . '"' . $variables['item_attributes'][$delta] . '>' . drupal_render($item) . '</div>';
  }
  $output .= '</div>';

  // Render the top-level DIV.
  $output = '<div class="' . $variables['classes'] . '"' . $variables['attributes'] . '>' . $output . '</div>';

  return $output;
}

```

Notice the line that has the `strtoupper` call... That was the issue. I removed that and everything is now how it should be.

There's been a couple of other methods mentioned here for altering the data stored in the label variable during the rendering process. They all would be effective, including the method I just posted. The method I posted has the added effect of allowing you to change the structure of the field as it is rendered in your theme. For the sake of rewarding other's efforts in answering this ridiculous question, I'll find the next closest answer and set it as the accepted answer.

# Answer
> 1 votes
First of all you need to establish what html is wrapping your labels, you can use firebug or just look for them in the source html.

For instance I find the labels on a site I happen to be working on are wrapped in `<h3 class="field-label">`, so some css like `.field-label { text-transform: lowercase; text-transform: capitalize;}` in your theme's stylesheet should do the trick.

# Answer
> 0 votes
Seeing as this is a style issue you could do this using the text-transform property in CSS:-

```
text-transform: capitalize;

```

Really, your labels you've defined in Drupal shouldn't all be in uppercase. It would be better to use `text-transform: uppercase;` for your form labels if that is what you are aiming for. Style should be kept separate from content.

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


# Question
Title: Tutorial for creating website using existing MySQL db?
I'm an experienced web developer, but I'm new to Drupal.

I have an existing MySQL database and I would like to build a website around it, with one page for each record in the main table. That would mean a few thousand pages for the site right from the start.

Are there any good tutorials that explain how to do this in Drupal?

# Answer
> 4 votes
It's not too hard. Assuming Drupal 7 and a one-time import:

1. Create a new content type in Drupal with the fields you want
2. Export a CSV file of your records with a header row from your legacy database with the fields you want.
3. Use Feeds to import the csv file. You will setup a mapping between the csv fields and your content types fields (from within the Drupal UI). This is pretty straightforward and the feeds module guides you through it.
4. Feeds will create one node per record (line) in your csv file.

Now if you will continue to use your existing database and want to import new records as they are added, I believe Feeds has some support for this but I haven't personally used it.

# Answer
> 0 votes
You might find the Feeds Module useful. Here is the link to the tutorials.

# Answer
> 0 votes
Another approach is to wrap views around your table(s). You can have a look at the maillog module for an example. The module integrates its maillogs with views.

Once you have the integration, views gives you a very powerfull query and report generator.

---
Tags: database, migrations
---


title: Get more details about log messages

text:
# Question
Title: Get more details about log messages
I'm getting a lot of "Missing text format: 1." errors in my log. It seems to point to a bug where text formats used to get referenced by number in D6 (\['format'\] = '1') but now are referenced by a name in D7 (\['format'\] = 'plain\_text').

How would I find where does bugs are?

Or a more general question: how can I get more details about error messages in the Drupal log?

# Answer
> 2 votes
Guess log means watchdog here. Generally, you only have what the developer passed to the watchdog.

You can try to parse the code for (a part) of the error message. There's a good chance that this points you to the code sending the watchdog, which in turn gives you more information about the problem.

---
Tags: 7
---


# Question
Title: What options do I have for changing CSS depending upon context?
I would like to change CSS for different site areas and page layouts depending upon contextual information such as the user role or the type of content being displayed. The types of changes would include font, color, and background options. I can think of several ways to approach this, but could really benefit from the experiences of others.

Some options:

* Use Views or panels to identify context and then associate styles with them. This is limited because some of the elements are not directly associated with content, such as menu background, colors, etc.
* Create a custom module to identify the user, content type or other context criteria and then modify the render array. This sounds feasible, but the render array is pretty cryptic, and I'm not clear on what needs to change. IF you've tried this, what have you done.
* Create custom code in a theme to identify the context and then assign div class values to isolate the affected sections.

If you have tried this or other options, what did you do and how effective was it?

# Answer
> 1 votes
We have been using the theme key module to switch between different styles and (sub-) themes for different situations.

---
Tags: theming, 7
---


# Question
Title: Drupal override search form: how to debug hook failure?
In the past I've always been able to override the theme form using the method mentioned http://drupal.org/node/154137.

```
function YOURTHEME_form_alter(&$form, &$form_state, $form_id) {
    if ($form_id == 'search_block_form') {
        $form['search_block_form']['#title'] = t('Search');
    }
}

```

However, this doesn't appear to be recognised in the template.php of my latest theme. It hasn't been an issue in the past - what is the best way to debug why the hook doesn't appear to be activated?

# Answer
* Clear cache.
* Place some debugging code to see if the hook and then if statement is called.
* Inspect the form variable, does it look correct?
> 1 votes

---
Tags: hooks, theming, search
---


title: Custom module with its own menu block

text:
# Question
Title: Custom module with its own menu block
I am trying to create a module that supplies a custom menu block, that changes based on what organic group you are looking at. I'm confused by the documentation, so I thought I'd ask here. I saw an answer for Drupal 7, but I'm using Drupal 6.

og\_menu doesn't work for me because I don't want group admins to change it. I just want the default to be dynamic based on some logic of my own.

Specifically, should I supply a custom block from my module? If so, how do I render the list of links I create, or should be supplying a custom menu? What hook do I use?

# Answer
Sounds like you'd really want to supply a hook\_block, whose $content will call a custom PHP function that will construct your array of links to other organic groups, based on your criteria.
> 0 votes

---
Tags: routes
---


# Question
Title: How can I link Fields in a View to the entity it belongs to?
How can I link Fields in a view to the entity it belongs to, along the lines of 'Node: Link' or 'Link this field to its node' in Views D7? Do I have to define anything special to give me a field in Views Field to pick from to enable this?

Also, instead of just link to the defaultUri, how could I use a pathauto aliased path if it exists instead of the entity uri?

# Answer
> 3 votes
The link to node or link to user option you see on some properties in views are special. The reason the possibility is there, is because Views has added the option and functionality in a special handler.

Things are not that easy with fields since they can be attached to anything, which makes it much more complex (compared to nid, uid, title and username). You could probably do this with some code, but usually it's much easier to use the **rewrite result** option, and select **output as link** and type in the link with tokens: `node/[nid]`. I'm not sure, but I believe the Views will run the link through `l` or `url` enabling path auto.

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


# Question
Title: Help implementing Supersized.js in Drupal 7
I am trying to add Supersized.js into my Drupal 7 site. I have updated Drupal to use the latest version of jQuery, I added scripts\[\] = js/supersized.3.1.3.min.js to my .info file, and in my html.tpl.php file i added:

```
<script type="text/javascript">

        (function($){
            alert('test');
            $.supersized({
            alert('test2');
                //Functionality
                slideshow               :   1,      //Slideshow on/off
                autoplay                :   1,      //Slideshow starts playing automatically
                start_slide             :   1,      //Start slide (0 is random)
                random                  :   0,      //Randomize slide order (Ignores start slide)
                slide_interval          :   3000,   //Length between transitions
                transition              :   1,      //0-None, 1-Fade, 2-Slide Top, 3-Slide Right, 4-Slide Bottom, 5-Slide Left, 6-Carousel Right, 7-Carousel Left
                transition_speed        :   500,    //Speed of transition
                new_window              :   1,      //Image links open in new window/tab
                pause_hover             :   0,      //Pause slideshow on hover
                keyboard_nav            :   1,      //Keyboard navigation on/off
                performance             :   1,      //0-Normal, 1-Hybrid speed/quality, 2-Optimizes image quality, 3-Optimizes transition speed // (Only works for Firefox/IE, not Webkit)
                image_protect           :   1,      //Disables image dragging and right click with Javascript
                image_path              :   'img/', //Default image path

                //Size & Position
                min_width               :   0,      //Min width allowed (in pixels)
                min_height              :   0,      //Min height allowed (in pixels)
                vertical_center         :   1,      //Vertically center background
                horizontal_center       :   1,      //Horizontally center background
                fit_portrait            :   1,      //Portrait images will not exceed browser height
                fit_landscape           :   0,      //Landscape images will not exceed browser width

                //Components
                navigation              :   1,      //Slideshow controls on/off
                thumbnail_navigation    :   1,      //Thumbnail navigation
                slide_counter           :   1,      //Display slide numbers
                slide_captions          :   1,      //Slide caption (Pull from "title" in slides array)
                slides                  :   [       //Slideshow Images
                                                    {image : 'http://buildinternet.s3.amazonaws.com/projects/supersized/3.1/slides/quietchaos-kitty.jpg', title : 'Quiet Chaos by Kitty Gallannaugh', url : 'http://www.nonsensesociety.com/2010/12/kitty-gallannaugh/'},
                                                    {image : 'http://buildinternet.s3.amazonaws.com/projects/supersized/3.1/slides/wanderers-kitty.jpg', title : 'Wanderers by Kitty Gallannaugh', url : 'http://www.nonsensesociety.com/2010/12/kitty-gallannaugh/'},
                                                    {image : 'http://buildinternet.s3.amazonaws.com/projects/supersized/3.1/slides/apple-kitty.jpg', title : 'Applewood by Kitty Gallannaugh', url : 'http://www.nonsensesociety.com/2010/12/kitty-gallannaugh/'}
                                            ]

            });

        })(jQuery);

    </script>

```

I am stuck here. I am not very experienced with Drupal, Javascript, or jQuery.

Edited to include Bob's change to the wrapper.

# Answer
There are a few issues here.

1. It's not in Drupal best practices to add a script to html.tpl.php
2. That being said, there are two ways to do it. **(a)** You can add it to your theme's .info file and call a .js file script from there (i.e. "scripts.js") in your theme folder, ideally in a "js" or "scripts" sub-folder if you need this site-wide **(b)** If you don't need it site-wide or you can call it with drupal\_add\_js in your theme's template.php file to target only specific pages / paths
3. The way Javascript gets called has changed in Drupal 7

The main new thing is to include something like:

```
(function ($) {
//needed for drupal 7
Drupal.behaviors.myTheme = {
attach: function(context, settings) {
// end drupal 7 syntax

```

... at the top of your script.

so a clean version should work like so:

```
(function ($) {

//needed for drupal 7
Drupal.behaviors.myTheme = {
attach: function(context, settings) {
// end dtupal 7 syntax

            $.supersized({

                //Functionality
                slideshow               :   1,      //Slideshow on/off
                autoplay                :   1,      //Slideshow starts playing automatically
                start_slide             :   1,      //Start slide (0 is random)
                random                  :   0,      //Randomize slide order (Ignores start slide)
                slide_interval          :   3000,   //Length between transitions
                transition              :   1,      //0-None, 1-Fade, 2-Slide Top, 3-Slide Right, 4-Slide Bottom, 5-Slide Left, 6-Carousel Right, 7-Carousel Left
                transition_speed        :   500,    //Speed of transition
                new_window              :   1,      //Image links open in new window/tab
                pause_hover             :   0,      //Pause slideshow on hover
                keyboard_nav            :   1,      //Keyboard navigation on/off
                performance             :   1,      //0-Normal, 1-Hybrid speed/quality, 2-Optimizes image quality, 3-Optimizes transition speed // (Only works for Firefox/IE, not Webkit)
                image_protect           :   1,      //Disables image dragging and right click with Javascript
                image_path              :   'img/', //Default image path

                //Size & Position
                min_width               :   0,      //Min width allowed (in pixels)
                min_height              :   0,      //Min height allowed (in pixels)
                vertical_center         :   1,      //Vertically center background
                horizontal_center       :   1,      //Horizontally center background
                fit_portrait            :   1,      //Portrait images will not exceed browser height
                fit_landscape           :   0,      //Landscape images will not exceed browser width

                //Components
                navigation              :   1,      //Slideshow controls on/off
                thumbnail_navigation    :   1,      //Thumbnail navigation
                slide_counter           :   1,      //Display slide numbers
                slide_captions          :   1,      //Slide caption (Pull from "title" in slides array)
                slides                  :   [       //Slideshow Images
                                                    {image : 'http://buildinternet.s3.amazonaws.com/projects/supersized/3.1/slides/quietchaos-kitty.jpg', title : 'Quiet Chaos by Kitty Gallannaugh', url : 'http://www.nonsensesociety.com/2010/12/kitty-gallannaugh/'},
                                                    {image : 'http://buildinternet.s3.amazonaws.com/projects/supersized/3.1/slides/wanderers-kitty.jpg', title : 'Wanderers by Kitty Gallannaugh', url : 'http://www.nonsensesociety.com/2010/12/kitty-gallannaugh/'},
                                                    {image : 'http://buildinternet.s3.amazonaws.com/projects/supersized/3.1/slides/apple-kitty.jpg', title : 'Applewood by Kitty Gallannaugh', url : 'http://www.nonsensesociety.com/2010/12/kitty-gallannaugh/'}
                                            ]

            });

//ending drupal 7 specific calls / syntax
}};
}) (jQuery);

```
> 2 votes

# Answer
Have you verified through viewing the page source in your browser that the script is being loaded correctly? If it isn't you can investigate into where the file is located on your server versus where your info file is pointing to.

If it IS loading correctly I imagine it's something client side. If it's just going on your front page, or a particular page you could use something like front--page.tpl.php/node--.tpl.php/etc and put your code there.

If it's client side it might also make good sense to create/find a working copy that uses just HTML, and transfer your code piece by piece from there, that way you can at least have a working copy to verify against.

This would require some troubleshooting, and a general working knowledge of JavaScript, but I will say I had similar issues getting a jQuery image gallery up on my own site, and worked it out after some trial and error.

**edit**

I just noticed in your code the wrapper is:

```
(function($){
    //code
}(jQuery));

```

You should change that to:

```
(function($){
  // code
})(jQuery);

```

Sorry I didn't notice before, but this is probably why the alerts aren't working.
> 1 votes

# Answer
Have you included all the CSS and JavaScript files that come with supersized.js?

Looking at the code, it seems you have an `alert('test2');` inside the supersized call. That should be removed; also, in the supersized call you have a option called "image\_path" that doesn't seem to be an available option for the supersized plugin. Try removing that.

I would also update the plugin to the current release, which is 3.2.6.
> 1 votes

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


# Question
Title: Is there a module that saves Twitter posts in a custom table?
I need to save Twitter posts in Drupal 7, but I don't want to create a node for each tweet.

Is there a module that can save them in a custom table?

Thanks.

# Answer
> 2 votes
Try the feeds module and data module

```
http://drupal.org/project/feeds
http://drupal.org/project/data

```

and import the rss of your twitter feed or search into the feed than save it as a simple database record with the data module.

---
Tags: 7, social-network
---


# Question
Title: How can I set a variable in the body of a node?
In Drupal 7 I've created a node of type basic page. Then in Body field I've inserted some markup mixed with php code. Then this was saved in PHP text format. In the above mentioned markup I have variable I'd like to output to html. I tried some preprocess functions but that didn't give me any result. How can I set the variable?

# Answer
> 1 votes
take a look at What is best method for token replacement within node content?

If you are feeling lack of available tokens, you can extend it with tokens hooks.

---
Tags: 7, theming
---


# Question
Title: Can the core Profile module (it is deprecated) be used? And how will I upgrade?
The profile core module is being deprecated in D7. It exists and operates in D7, but is hidden and can only be enabled with drush or a custom module. Drupal.org recommends that users now use Profile2, a custom module, but my attempts to do so have met with WSOD on several attempts. In fact, after enabling the module, it will crash the site if you try to disable it. The problem links to a core issue, but even with the recommended patch, Profile2 still has other problems I have not been able to correct yet.

In the meantime, I enabled Profile, and it has desirable features I would like to implement. My concern is that whatever I do may be lost in the future. Since I cannot load Profile2, I do not know if it builds on Profile or I will have to reconstruct everything later.

# Answer
> 1 votes
First of all, it's important to understand something MotoTribe has already mentioned. The most important functionality of "Profile" is now in for Drupal 7 new "users are entities" concept. Since this allows you extend users with fields, the profile module was considered redundant.

If I recall correctly, the main reason for it remaining in Core, was as a transition path from D6 Profile. In D8 I don't believe Profile will exist at all, and since it's already deprecated, I very much doubt there will be an upgrade path from D7 profile.

If we instead follow the trail of issues that follow from yours on the Profile2 queue, we find a Core issue, which is so far advanced that it has been applied to D8, and applies cleanly against D7 with full test coverage. I would apply that D7 patch, and try with Profile2 again.

---
Tags: 7, users
---


# Question
Title: Adding items to another Modules Admin form
I have a module that I need to add a few items to, I was told that using hook\_form\_alter was the best way to do this, but have been completely unable to get anything to work. Maybe some one could help me out on it a bit....

The PURPOSE of this enhancement is to add text and links to a login modal, but that's unimportant at the minute.

The code that I have in my module atm is just to show the form I'm trying to alter

```
<?php
/**
 * Implements hook_menu_alter().
 */

function [modulename]_enhancements_menu_alter(&$items) {
  $form['modal_window'] = array(
    '#type' => 'fieldset',
    '#title' => t('Modal text and links'),
    '#collapsible' => TRUE,
    '#collapsed' => 0,
    '#weight' => -399,
  );

    $form['modal_window']['login'] = array(
      '#type' => 'text_format',
      '#format' => 'plain_text',
      '#title' => t('Login text'),
      '#default_value' => variable_get('[modulename]_login_text', '[Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis a arcu et sem pharetra consectetur. Proin eget lectus neque, quis suscipit lectus. Nullam dictum, massa at sodales porttitor, mi nisi fermentum magna, eu suscipit dui. ]'),
    );

    $form['modal_window']['registration'] = array(
      '#type' => 'text_format',
      '#format' => 'plain_text',
      '#title' => t('Registration text'),
      '#default_value' => variable_get('[modulename]_registration_text', '[Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis a arcu et sem pharetra consectetur. Proin eget lectus neque, quis suscipit lectus. Nullam dictum, massa at sodales porttitor, mi nisi fermentum magna, eu suscipit dui.]'),
    );
}
?>

The module has something like this going on with it
<?php
/**
 * Implements hook_menu().
 */
function [modulename]_menu() {
  $items['admin/config/services/[modulename]'] = array(
    'type' => MENU_NORMAL_ITEM,
    'title' => '[modulename] Settings',
    'access arguments' => array('administer [modulename]'),
    'page callback' => 'drupal_get_form',
    'page arguments' => array('[modulename]_admin_form'),
    'description' => '[modulename] Configuration.',
    'file' => '[modulename].admin.inc',
  );
?>

and here's the [modulename].admin.inc
<?php
/**
 * Form builder for the [modulename] administration form.
 */
function [modulename]_admin_form($form, &$form_state) {
  global $user, $base_path;
  include_once DRUPAL_ROOT . '/' . 'modules/user/user.pages.inc';
  module_load_include('inc', '[modulename]');
  $capabilities = [modulename]_get_capabilities();
  $form = array();

   $form['[modulename]_debug'] = array(
    '#type' => 'checkbox',
    '#title' => t('[modulename] debuging'),
    '#description' => t('Write errors to watchdog'),
    '#default_value'=> variable_get('[modulename]_debug', 0),
    '#collapsible' => TRUE,
    '#collapsed' => TRUE,
    '#weight' => -401,
  );
?>

```

# Answer
> 1 votes
For the sake of clarity, let's say that your custom module is named CUSTOMMODULE, and the one you want to alter is ALTERTHIS.

You can use `hook_form_FORM_ID_alter()` like this:

```
/**
 * Implements hook_form_FORM_ID_alter() for ALTERTHIS_admin_form().
 */
function CUSTOMMODULE_form_ALTERTHIS_admin_form_alter(&$form, &$form_state, $form_id) {
  // Alter the $form here.
}

```

---
Tags: routes, hooks, theming
---


# Question
Title: How do I distinguish menu items without children and display different content in panels or views?
I have a taxonomy based menu (3 tiers) that displays a specific content type. Content items are always tagged at the lowest level child (\*) so when the menu items are selected a range of content is displayed.

```
top-level | mid-level1 | child1*
          |            | child2*
          |
          | mid-level2 - child3*
          |
          | child4*

```

When the parent levels are selected, I would like a summary page for the parent to show. I am using views and panels and getting the lowest level children to show is easily accomplished, but how do I set a filter or context to determine if the view is not at the lowest level?

Panels exposes a context that selects content with a parent (or not) so I can easily identify the top level menu selections, but the bottom children can occur at either level two or three and there is no context for 'has children'.

What can I use as a context to select the parents and which hook to use?

# Answer
> 1 votes
This is an excellent example of a custom Ctools plugin. In this case, our plugin type is "Access". The below is copied from "term\_has\_parent", and adopted to search for the reverse. It could probably be improved with some more robust error checking.

In Panels, you will get a new "Selection Rule", so that you can distinguish between terms that have children, from those that don't.

```
<?php
/**
 * Plugins are described by creating a $plugin array which will be used
 * by the system that includes this file.
 */
$plugin = array(
  'title' => t("Taxonomy: term has child(ren)"),
  'description' => t('Control access if a term has children.'),
  'callback' => 'term_has_child_ctools_access_check',
  'default' => array('negate' => 0),
  'summary' => 'term_has_child_ctools_access_summary',
  'required context' => new ctools_context_required(t('Term'), array('taxonomy_term', 'terms')),
);

/**
 * Check for access.
 */
function term_has_child_ctools_access_check($conf, $context) {
  $children = db_select('taxonomy_term_hierarchy', 't')
    ->fields('t')
    ->condition('parent', $context->data->tid)
    ->range(0, 1)
    ->execute()
    ->fetchAssoc();

  return count($children) > 1;
}

/**
 * Provide a summary description based upon the checked terms.
 */
function term_has_child_ctools_access_summary($conf, $context) {
  return 'Returns true if the current term has children';
}

```

If you don't know how to use a custom Ctools plugin, I suggest that is the topic of another question.

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


# Question
Title: Can I use the function menu_tree() in Drupal 7 to customize a menu and add CSS classes?
Can I use the function `menu_tree()` in Drupal 7 to customize a menu and add CSS classes? I've tried to customize a main\_menu by adding CSS classes: Is it the right way?

# Answer
The easiest way to add custom classes to menu items in Drupal 7 is the Menu Attributes module.

If you really want to do this programmatically, then you can override the theme\_menu\_link() function in your theme's template.php file. Be sure to read the drupal.org documentation on Overriding Themable Output.
> 2 votes

---
Tags: theming, routes
---


# Question
Title: Display all tokens programmatically? Trying to debug token
I'm trying to debug creating a token. How to programmatically create a custom token in a module shows me how to create them.

Is there a way to display all available tokens? I'm trying to test if my module actually created that token.

# Answer
> 4 votes
There's a function in the token module called `token_get_list()` which is:

> A helper function that retrieves all currently exposed tokens, and merges them recursively.

It invokes `hook_token_list()` for all modules so should give you every single token defined in the site.

---
Tags: 6, tokens
---


# Question
Title: Translating "Content: Link" in a Drupal 7 View
I am working on my first Drupal 7 site that has internationalization. My site is in both English and Spanish. Generally I am pretty happy with the way it's going so far. The basis of my translation is using the *Entity Translation Module* and it works great, Views are translated seamlessly.

However, I have run into a snag, When I create a View and add "`Content: Link`" as a field, essentially a "read more..." link to the node, I am finding no way to translate the "Read more..." text that I enter into the "`Text to display`" textbox. My guess is because it's not actual content in the node that's been translated. I've looked around here, on drupal.org and my google-foo is failing me too. Just looking for some suggestions on how to do this.

# Answer
I ~~won't~~ didn't put this as an answer as it may not be exactly what you want, the Translation Table module will let you set translations for arbitrary strings in the system.

Since Views is almost definitely going to pass the 'Read more...' string through the t() function that module will make your translation work for as many languages as you like across the site
> 2 votes

---
Tags: 7, views, i18n-l10n
---


# Question
Title: How to disable persistent database connections for Drupal 7 / PostgreSQL
I have a Drupal 7.2 + CentOS 5.6/64 bit + PHP 5.3 + PostgreSQL 8.4.8 (servicing unix domain sockets only) web site which often goes down on peak times because of too many postmaster processes started.

On the advice from PostgreSQL mailing list I have installed pgbouncer at "port" 6432 with the following config:

```
[databases]
pref = host=/tmp user=pref password=XXX dbname=pref

[pgbouncer]
logfile = /var/log/pgbouncer.log
pidfile = /var/run/pgbouncer/pgbouncer.pid
listen_port = 6432
unix_socket_dir = /tmp
auth_type = md5
auth_file = /var/lib/pgsql/data/global/pg_auth
pool_mode = transaction
server_check_delay = 10
max_client_conn = 200
default_pool_size = 16
log_connections = 0
log_disconnections = 0
log_pooler_errors = 1

```

And forced Drupal 7.2 to use it by changing sites/default/settings.php to:

```
$databases = array (
  'default' =>
  array (
    'default' =>
    array (
      'database' => 'pref',
      'username' => 'pref',
      'password' => 'XXX',
      'host' => '/tmp',
      'port' => '6432',
      'driver' => 'pgsql',
      'prefix' => 'drupal_',
    ),
  ),
);

```

Here an excerpt from /var/log/pgbouncer.log during peak times:

```
2011-06-20 17:32:48.591 23883 LOG File descriptor limit: 1024 (H:1024), max_client_conn: 200, max fds possible: 230
2011-06-20 17:32:48.591 23883 LOG File descriptor limit: 1024 (H:1024), max_client_conn: 200, max fds possible: 230
2011-06-20 17:32:48.592 23886 LOG listening on unix:/tmp/.s.PGSQL.6432
2011-06-20 17:33:48.593 23886 LOG Stats: 36 req/s, in 3346 b/s, out 57238 b/s,query 74605 us
2011-06-20 17:34:48.593 23886 LOG Stats: 43 req/s, in 3167 b/s, out 54435 b/s,query 68969 us
2011-06-20 17:35:48.593 23886 LOG Stats: 25 req/s, in 3391 b/s, out 42060 b/s,query 95764 us
2011-06-20 17:36:48.593 23886 LOG Stats: 25 req/s, in 3370 b/s, out 103636 b/s,query 72986 us

```

Also I've been advised to disable persistent database connections and have done it for my own PHP scripts.

But I don't know how to do it for Drupal, what would be the best spot for that?

Thank you! Alex

# Answer
> 2 votes
Drupal does not use persistent connections. See https://drupal.org/node/1079892. You may need to lower the number of web server processes (e.g. Apache MaxClients).

# Answer
> 1 votes
Persistent connections are not be the only issue for pgBouncer transactional mode. You need to make sure that Drupal doesn't use `SET`/`RESET`, `WITH HOLD CURSOR`, etc.

Actually, I see that Drupal issues `SET NAMES 'UTF8'`, but maybe this is superfluous (so it doesn't break pooling).

---
Tags: 7, database
---


# Question
Title: Changing Allowed HTML tags: @tags for help text input field
I want to display a simple table under a form field as part of the help text for that field (file field to be exact). Am I being totally mental or is there really no easy way of changing the allowed html tags for this text area? At the moment I have displayed:

`Instructions to present to the user below this field on the editing form.
Allowed HTML tags: a b big code del em i ins pre q small span strong sub sup tt ol ul li p br img`

If there is no easy way, what is the next easiest way of doing it?

UPDATE:

Clive came up with a great way of doing it below with a custom module. You can also add to this using ctools to make the help text collapsible as follows:

```
// Implement hook_field_widget_form_alter()
function MYMODULE_field_widget_form_alter(&$element, &$form_state, &$context) {
  // If some condition is matched based on the element provided...
  if (isset($element[0]) && $element[0]['#field_name'] == 'field_test') {
    // Alter the description using your more permissive set of tags
    $reworked = filter_xss($context['instance']['description'], _MYMODULE_field_filter_xss_allowed_tags());
    $element[0]['#description'] = theme('ctools_collapsible', array('handle' => 'Help text', 'content' => $reworked, 'collapsed' => TRUE));
  }
}

// Provide a more permissive set of tags to be used with filter_xss()
function _MYMODULE_field_filter_xss_allowed_tags() {
  // Merge the new set of allowed tags with the less permissive defaults
  $new_tags = array('table', 'thead', 'tbody', 'tfoot', 'tr', 'th', 'td');
  return array_merge(_field_filter_xss_allowed_tags(), $new_tags);
}

```

# Answer
There isn't an easy way to do it really, the list of allowed tags is hard coded into the `_field_filter_xss_allowed_tags()` function.

This is in turn called by `field_filter_xss()`, not when the data is saved to the database but rather when it's displayed in `field_default_form()`.

Fortunately there is a way but it'll take a small custom module to do it. You're basically looking to implement a form alter hook for the field's widget form and set the element's description to use `filter_xss()` with a more permissive set of tags.

Something along these lines:

```
// Implement hook_field_widget_form_alter()
function MYMODULE_field_widget_form_alter(&$element, &$form_state, &$context) {
  // If some condition is matched based on the element provided...
  if (isset($element[0]) && $element[0]['#field_name'] == 'field_test') {
    // Alter the description using your more permissive set of tags
    $element[0]['#description'] = filter_xss($context['instance']['description'], _MYMODULE_field_filter_xss_allowed_tags());
  }
}

// Provide a more permissive set of tags to be used with filter_xss()
function _MYMODULE_field_filter_xss_allowed_tags() {
  // Merge the new set of allowed tags with the less permissive defaults
  $new_tags = array('table', 'thead', 'tbody', 'tfoot', 'tr', 'th', 'td');
  return array_merge(_field_filter_xss_allowed_tags(), $new_tags);
}

```

That's based on the premise that you only want to allow the new tags for an element called `field_test`, obviously if you want to do the same for other fields you'll need to change it to match a different condition. I advise using the excellent `dpm()` function included in the `Devel module` to inspect object in your form alter function.

I've just tested the above and it works (I now have a table where my file field description would normally be), it feels a bit like a hack even though it technically sticks to the rules but hopefully it'll get you on the way.
> 7 votes

# Answer
In case you are using D6, you can navigate to /admin/settings/filter. There you need to click the "configure" option of "Filtered HTML". Then click on the configure tab. you will be presented with a text box labeled "Allowed HTML tags". Enter the html tags that you need to use there.

In case of D7 go to admin/config/content/formats/filtered\_html. Under Filter Settings, click on "Limit allowed HTML tags" tab. Enter the HTML tags you want to use in the text box.
> 2 votes

---
Tags: theming, input-formats
---


# Question
Title: Can't save settings after copying site to new server
I just recently copied a Drupal 7 site from one server to another, everything looks like it works fine except that I cannot save any settings.

Here are some other symptoms:

* I can't disable or enable modules
* Overlay doesn't work
* Once I log out, I can't log back in
* When trying to log back in with the wrong criteria, I don't get a message about the user/pass being wrong
* admin\_toolbar doesn't work (except immediately after clearing cache via drush)
* Status report doesn't show anything being wrong

I've got varnish running on the server and I'm not quite sure if that would have anything to do with it.

# Answer
> 17 votes
I had to enable Mod Rewrite.
`sudo a2enmod rewrite`
If you're having this issue, also check that your .htaccess files copied over to the new server (I've wasted countless hours chasing this).

---
Tags: 7
---


# Question
Title: User submitted content in drupal (Drupal Noobie)
First off, I would like to state that I am a total noobie when it comes to Drupal and do not have a great deal of experience with web development in general. On the other hand I have a good deal of experience programming in general and will not shy away from some serious PHP hacking.

I am trying to create a webpage that will allow users to submit project files (which will be .zip files) which need to be extracted, then analyzed, then stored.

I would like to have a main ladding page that will allow user to navigate to different types of projects or allow them to follow a link to submit their own project.

So far I have not been able to find many good resources that talk about challenges associated with user generated content. Can anyone suggest any books, videos, tutorials, really anything that would help me get started on this specific topic? I own the book Drupal 7 module development, which was a decent starting point but doesn't really offer much information about my specific problem.

Also, any modules that might be helpful for this task?

EDIT:

So far I have been able to create a new content type which can be added using add content and then will show up in one of the main tabs on my basic page. So far I only allow the user to add screenshots and a title, one big thing I am wondering if how would I handle anything more complex? So far I have created everything by using the GUI interface under structure-\>content types but I see no way that I could call some php code after the user has uploaded the project to unzip their project and do whatever else I need to do. Am I going about this wrong?

# Answer
> 1 votes
"Drupal7 Development", Apress publishing is a very good book covering the full range of coding issues when working with Drupal including issues such as how to create, search and modify content nodes, user info, taxonomies, fields, comments, and etc. It will also give you a good look under the hood at how Drupal works. This site is always good for specific answers, as is the IRC for Drupal which as some real experts online at #Drupal-Support.

As for user-generated content, I have not seen a great deal published. My first priority would be KISS! If there is a way to screw it up, they will. You will, of course, want to sort and store the information they submit in fields. You will arrange your submission forms to make it clear to the user how the info should be split up. All content is stored in the database and the Views module is an UI for the database query engine. Design your database relationships for the data first. You will use the form API to generate the input from the users. It provides a system for creating forms, validating input and plugging it automatically into the database.

Another consideration should be the styling of the materials for rendering on the site. The first rule here should be don't get fancy. Drupal provides a plain text widget, but you can also add WSYWIG editors. BUEditor (see the module on the Drupal site) allows you to create custom buttons so you could create, for example, a button called Headline to provide HTML codes, or table formats or lists etc...

I would also recommend looking into Panels and Panels Everywhere. The Drupal theming process is fairly complex and the various third party themes can make styling your content a nightmare. Panels w/ Page Manager provides an excellent method for creating complex formats and making your CSS easy to manage. You may want to look at the book Drupal Building Blocks, which does a great job of explaining how to go about creating a site using Views and Panels.

Workbench is another module you should look at. It will help you monitor what is going on with your sites content so you can do things like edit the project info before it is published.

There's more, but this is a start.

# Answer
> 1 votes
Have you taken a look at Open Atrium? It is not a Drupal module, rather a Drupal distribution pre-configured with a set of modules to help you manage projects. It includes functionality to upload files into projects, allows users to create new projects, etc.

Open Atrium has been around for a few years now, and it is pretty stable. Since it is Drupal (and hence, GPL'd), if the features that it brings does not satisfy your needs, as always, you can create your own modules to extend the existing functionality, or as a minimum, you could use Open Atrium to provide you ideas on how you might structure your project, which modules might help you out, etc.

There's also Storm, but it is currently available only for Drupal 6.x, and it's 7.x version is still not stable.

# Answer
> 1 votes
You could always use the rules module to perform a task when the node is saved. Rules has the ability to let you do some pretty nifty complex things without having much knowledge of the drupal hook system or drupal's underlying workings

---
Tags: files
---


# Question
Title: How can i add a block below the Main Menu?
I asked for a second horizontal menu here. But i couldn't manage to success so i'm changing my question a bit.

I want to add a block below the "Main Menu". I will put a table into that new block, which will be looked like a horizontal menu.

In my default case "Main Menu block" is disabled. But i can see the Main Menu horizontally. I ccan't understand how it can be seen :) When i enable "Main Menu block" from "admin/structure/block" that block becomes visible where i set its position, but it sorts Main Menu Items vertically. Also horizontal Main Menu still appears. (That case is also occurs for "User Menu". Its block is disabled. When i enable its block it comes with a vertical menu)

What's the position of the "below of the horizontal Main Menu" in Bartik theme? I created new block and put it to highlighted, help, featured regions. Help and highlighted regions doesn't cover all horizontal part. Featured tooks three times more place than the block.

So i couldn't find a way to put my new block just below the Main Menu.. I would be happy if you can help. Thank you.

# Answer
The main menu that you can see in the theme is ***not*** in a block. It's printed at a certain spot within your page.tpl.php page in the bartik theme. Check it out (make a copy first) and mess about to see the results.
If you want to add a new block to a region that doesn't already have a block check out this post http://drupal.org/node/1088718 as it details how to do so.
Your other question had to do with why the menu renders vertically instead of horizontally like the main menu, it's all due to the css styling. Chances are that the menu is in an unordered list ``

`` and that the list items (menu links) have been set to `display:inline` or `float:left`.
I hope I was of some help
> 2 votes

# Answer
The basic Drupal menu is pretty ... well, basic. Try installing a menu module such as superfish. The user interface allows you to do a lot more out of the box. Much of the appearance for menu items is accomplished through css and html. In Bartik that appearance information is being addressed in the Bartik .css files and displayed through the template files such as page.tpl.php also found in the sites/all/themes/bartik directory. The template file is arranging the content in the regions and the css file should hold codes for the menu that are specific to the region it is in.

Modifying the appearance of the menu is going to involve learning how to perform these changes in the appropriate files. Modules such as superfish will make the basics a bit simpler, but in either case, once you get the basics correct for your needs, , you will want to do more to refine it and that will mean learning more about how this all works.
> 1 votes

---
Tags: theming, routes, blocks
---


# Question
Title: Best Way to share content across a UK and USA website
I am creating a website that will have a US and UK section and we are going to separate the two via the addresses ....com/uk and ....com/us.

Some of the content will be the same and some of it will differ. The menu structure will also differ.

The site is relatively small and about half of the content will be shared between the two and half of it will be unique.

We have had had a look at the language/internationalisation modules and they seem a little bit overkill for our needs.

It seems that the best way to achieve this for the shared content is to have a "Shared Page" content type that is never seen, but then a View that accepts a contextual filter in the url (the title) which displays the body of the node at both uk/title and us/title.

However I read somewhere that it is not a good idea to use views to display only a single node and that they should be used only for lists etc.

Is this the case? If so what method should I use if I want to display a single node at two locations?

# Answer
> 3 votes
We have successfully done this with a multi site installation and the domain module.

# Answer
> 0 votes
I use Views every now and then to pull out just a single piece of content (node), and I've suffered no ill effects from it. If the Views solution that you describe is enough for you, then I would go for it.

Some will probably tell you that you this is "bad for performance", but doubt that can be backup up with numbers. I have seen situations where such usage becomes *part* of a performance problem, but that was the front page of a site, with a 3x3 grid of such Views, and they could have been cached better.

---
Tags: views
---


title: D7 CCK default values and PHP input

text:
# Question
Title: D7 CCK default values and PHP input
what happened the ability to add PHP to the default value of a CCK field? Also, is it possible to set a CCK field to 'greyed out' or disabled by default? I don't need users editing this ref # field but I need admins to search it.

# Answer
Drupal 7 is a lot different than Drupal 6 in many ways. What used to be called CCK, now called "fields in core" or "fields" is also different. Not all of the features that was in CCK is available in Drupal 7 fields, some are, but contrib modules is needed.

Regarding using PHP default values, I don't know of a module that does this. It's possible with `hook_form_alter` in a custom module, but this might not be what you are looking for.

I don't know of any way to gray out fields when editing an entity, other than again using `hook_form_alter`. The field permissions module might be able to help you, to deny users the ability to edit the field. It would then disappear entirely, but that could be a possible solution.
> 1 votes

---
Tags: 7, entities
---


# Question
Title: Any way to add something similar to Olark or Zopim
Olark and Zopim are live chat services. Is there any module to add this feature to a Drupal site? I took a look to 'chat room' module but it is not what I need.

# Answer
I don't know of a free Drupal service to do this.
Olark has a Drupal guide to get it working on your site. There is also the Olark Chat module. I know that VPS.NET and Lullabot are both using Olark.
> 2 votes

# Answer
Many of us are looking for a reliable livechat for Drupal. There is no secret how to choose one of them.

First of all take a look at this list and find the solution for yourself. Then, find reviews of choosen chat and make a correct decision.
> 0 votes

---
Tags: 7
---


# Question
Title: How do I transfer nodes categorized with one taxonomy term to another?
Im on d7. I have a lot of nodes on my site that are all categorized with one of eight terms of my "category" vocabulary. I have been doing a theme redesign that calls for me to make a new taxonomy vocabulary that these node will be categorized in called "sections". I need a way to make all current nodes with "categories/term-1" to also have "sections/term-1", "categories/term-2" to have "sections/term-2", and so on. I was thinking I could do this with rules, but that would be a per node basis and I need this to update ALL current nodes. Any suggestions? Thanks.

# Answer
> 0 votes
You can use hook\_update\_N() to update multiple nodes at once with a single run of update.php. Inside it you can load all the nodes that you need to modify using node\_load(), and after you are done changing the taxonomies programatically, call node\_save().

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


# Question
Title: Rendering a content type with Views, in Drupal 7
I have 3 content types and I'd like to render two of them using Views. But there is not option when I can mark this 2 types. I can mark "show all," "show first type," or "show second type," but I can't choose 2 of 3 types.

How can I do it?

# Answer
> 7 votes
To create a list of two content types in Views you can't set it directly in the 'wizard'. For now just select 'All', at the bottom click 'Continue & Edit'. To only show two content types go down to 'Filter Criteria' and click 'Add'. Find 'Content: Type' in the list and check it, then click 'Add and configure filter criteria'. This will allow you to select the content types you'd like to show. Finally click 'Apply'.

---
Tags: views, nodes
---


# Question
Title: Module for sidebar menu which appears in open atrium
I wanted to know if any modules already exists for creating side bar menu which appears in open atrium. So that it expands only when required.

/\** Update \**/

Please see the image below. I am talking of the LHS black sidebar.

# Answer
> 3 votes
That's the admin module.

# Answer
> 3 votes
I think you're looking for the Admin module.

---
Tags: 7, distributions
---


# Question
Title: Send POST data to payment gateway on form submit
I am running drupal 6 and currently working on payment gateway integration module. I have a basic form in my module which will collect billing information from the user. In the form submit handler, I need to create certain parameters and send the post data to the payment gateway URL. How do I handle this? Any help is appreciated.

# Answer
> 1 votes
Check drupal\_http\_request().

> Performs an HTTP request.
>
> This is a flexible and powerful HTTP client implementation. Correctly handles GET, POST, PUT or any other HTTP requests. Handles redirects.

# Answer
> 0 votes
You can use CURL. CURL stands for client URL library. It allows you to communicate with any webservice (and much more). It can handle SSL/HTTPS and all the other stuff you might need.

---
Tags: 6, redirection, forms, payment-gateways
---


title: How to use views achieve this

text:
# Question
Title: How to use views achieve this
I've two nodes Person and Mission. A Mission can contain many Person's. Now if I'm browsing Person node, then in right side bar block I want to show all Mission's associated with this Person.

Example:

Mission1 contains ( 1 field containing multiple values):

* Person-A
* Person-B

Now if I go and view Person-A then in a block I should see Mission1 as it is associated with it.

# Answer
You can use a CCK "node-reference" field. This way you can "link" one mission page on all person pages. After you did this you can easily make a view that gets all persons that are in the mission node...

Maybe you can take a look at: http://drupal.org/project/Relation
> 3 votes

---
Tags: views, 6
---


title: Attaching Entities to other Entities

text:
# Question
Title: Attaching Entities to other Entities
I have two custom entities in a D7 site. One is 'additional' data on an entity, and I want to attach that data to the main entity every time it is loaded.

Within Entity/Entity API, how can I do that correctly? attachLoad sounded correct but seems to be Field related, all my data are not fields (yet).

# Answer
Solved: I began using the Field Collection module to facilitate this.
> 1 votes

# Answer
I've seen modules use attach load as well, which is what you need to get it on the actual entity.

It also depends on your data structure if the base entity has a reference to the additional data entity, you could simply use the entity wrapper along with entity properties. You wouldn't actually have the data on the entity, but have it accessible via the wrapper. The advantage is that you only run extra queries (loading the entity) as required.

In code you would then do

```
 $entity = load_entity_function($foo);
 $enity_wrapper = entity_metadata_wrapper('entity_type', $entity);
 $additional = $enity_wrapper->addition->value();
 $additional_id = $enity_wrapper->addition->id->value();

```

In order to have the wrapper do this, you tell it about the additional entity in a hook:

```
/**
 * Implements hook_entity_property_info().
 */
function module_entity_property_info() {
  $info = array();

  $properties = array();
  $properties['additional'] = array(
    'label' => t('Label'),
    'type' => 'entity_type',
    'description' => t('description.'),
    'getter callback' => 'function_get_entity_id',
    'setter callback' => 'function_set_entity_id',
    'clear' => array('id_of_additional'),
    'schema field' => 'schema_of_additional',
  );

  $info['base_entity']['properties'] = $properties;

  return $info;
}

```

You need a function that will get or set the id from the entity. Depending on your naming convention entity modules come with some that you can use.
> 2 votes

# Answer
I'm not familiar with the inner workings of this, but if you don't get other good answer, here is a patch that does something similar to what you ask. It loads the media edit form on the node edit for to which the media element is attached.

This is "edit", and your usecase sounds like "view", but hopefully it can help you get started.
> 1 votes

---
Tags: 7, entities
---


# Question
Title: Is there an opposite / reverse of entity_uri()?
I understand that entity\_uri() generates a uri for a profied entity

http://api.drupal.org/api/drupal/includes--common.inc/function/entity\_uri

However, is it possible to go the other way? is there a function in drupal to pass a system uri and see if it's an entity? and then return the entity object?

# Answer
I'm afraid there's nothing (existing at least) that will do that, the URI function is provided by the module implementing the entity (in `hook_entity_info()`) and the method within that function is completely transparent to Drupal...the core entity module doesn't give modules the chance to implement a function that reverses the process, nor does it store *how* the conversion was made.

Because of this I don't think a fully generic function is possible, however you could do it on a type-by-type basis:

```
$uri = entity_uri('node', $entity);
if (preg_match('/node\/([0-9+])/', $uri, $matches)) {
  $entity2 = entity_load('node', array($matches[1]));
}

```

You could then extract that logic to build a slightly more generic function based on the known attributes of your Drupal installation...it's not a pretty way to do it though, I'd love to hear a different solution to this.
> 2 votes

---
Tags: 7, uri, entities
---


title: Theming Drupal fatal error messages

text:
# Question
Title: Theming Drupal fatal error messages
Whenever Drupal encounters an unrecoverable error, it displays an error message.

Is there a way I can provide a template for this page?

# Answer
> 4 votes
The closest thing you come by is the `maintenance-page.tpl.php`, It doesn't cover all cases, but if things go wrong but not that wrong that Drupal can't post a page, it uses `maintenance-page.tpl.php` to display the error(s).

The error itself is displayed using `drupal_set_message`

---
Tags: theming
---


# Question
Title: Combining 2 Queries to pull titles of 2 related content types from the node table
Time to put our database hats on! We have a complex database call that responds to an AJAX request. We've omitted most of the code to just include the portion that is giving us trouble. We are working in Drupal 7.

```
  $products = "field_data_field_product_ref"; // table that contains the info about the product
  $productref = "field_product_ref_target_id"; //

  // The following query prints the Title of our Object and the ID of the product it references

  $query = db_query ("Select n.nid AS nid, n.title AS title, p.$productref AS productid
  FROM {node} n
  INNER JOIN {$products} p ON p.entity_id = n.nid");

foreach ($query as $row) {
  print 'Swatch Title: '.$row->title.'<br>';
  print 'Product ID: '.$row->productid.'<br><br>';

}

```

**This outputs:**
Swatch Title: Saddle Brown
Product ID: 19
Swatch Title: Sandalwood
Product ID: 20
Swatch Title: Saratoga
Product ID: 22

**However, we want to also return the actual title of the product being referenced not its Product ID. A separate query can do this:**

```
    $query = db_query ("Select n.nid AS pnid, n.title AS ptitle, p.entity_id AS productentityid
      FROM {node} n
      INNER JOIN {$products} p ON p.$productref = n.nid");

    foreach ($query as $row) {
      print 'Product Title: '.$row->ptitle.'<br>';
      print 'Swatch ID: '.$row->productentityid.'<br><br>';

    }

```

**Our second query's output:**
Product Title: Slab
Swatch ID: 265
Product Title: Stone
Swatch ID: 184
Product Title: Brick
Swatch ID: 185

**We would like the results to be:**

Swatch Title: Saddle Brown
Product Title: Slab
Swatch Title: Sandalwood
Product Title: Stone
Swatch Title: Saratoga
Product Title: Brick

**Can anyone clear up how to combine the 2 queries to get the intended output?**

# Answer
> 3 votes
I think you just want to join the node table in to your query again and grab the title that way:

```
$query = db_query("
  SELECT n.nid AS pnid, n.title AS ptitle, n2.title as swatch_title
    FROM {node} n
    INNER JOIN {$products} p ON p.$productref = n.nid
    INNER JOIN {node} n2 ON n2.nid = p.$productref"
);

```

# Answer
> 3 votes
```
$query = db_query ("SELECT np.title AS product_title, ns.title AS swatch_title
                    FROM {node} np
                    INNER JOIN {$products} p ON p.entity_id = pn.nid
                    INNER JOIN {node} ns ON p.$productref = ns.nid");

```

Should work. Hard to tell since you use variables inside your SQL not defined in your code sample. But basically just join the products table and then back to the node table.

---
Tags: nodes, database, entities
---


# Question
Title: Display one recent comment in node teaser?
Trying to find the easiest way to include the first most recent comment in my view that is using the 'teaser' mode. I am using the rate module to display number of votes in the view as well which doesn't have a 'field' to add so that is why I need to use teaser mode instead of fields mode. Thanks

# Answer
> 4 votes
Add Views, Token, and Viewfield modules.

Make a new view. The first page gives you most of it: Show comments, newest first. Make a page, limit the number to 1. Continue & Edit, and set the contextual filter to `Content: Nid`. Be sure and save it. :-)

Edit your content type. Add a new field, of type Views. Set the default view to be the 'recent comment' one you just made. Under 'Default Values,' have it always use the default view, and have `[node:id]` as an argument. Save that.

Now you can manage the display of this field in the 'manage display' tab, and place it in the 'teaser' view.

You might find that showing the whole comment under the teaser looks wrong, so then it's time to go back to the view and tweak it so it uses fields instead of the whole comment.

HTH.

---
Tags: views, nodes
---


title: Menu secondary tabs

text:
# Question
Title: Menu secondary tabs
How do I create secondary local tasks with hook\_menu in Drupal 7?

For instance, if I wanted to add a new tab to a node, that presented multiple tasks beneath it?

* View
* Edit
* Update
    + Price
    + Photo
    + Person

# Answer
> 7 votes
You should use a combination of the `MENU_LOCAL_TASK` and `MENU_DEFAULT_LOCAL_TASK` types:

```
 $items['node/%node/update'] = array(
   'title' => 'Update',
   'page callback' => 'price_callback_function',
   'access arguments' => array('access args'),
   'type' => MENU_LOCAL_TASK // This adds the 'Update' tab to the node path
 );

 $items['node/%node/update/price'] = array(
   'title' => 'Price',
   'type' => MENU_DEFAULT_LOCAL_TASK,
   'weight' => -10
 );

 $items['node/%node/update/photo'] = array(
   'title' => 'Photo',
   'page callback' => 'callback_function',
   'access arguments' => array('access args'),
   'type' => MENU_LOCAL_TASK // This adds another tab under 'Update'
 );

// etc...

```

You can control the order of the tab using the `weight` key in your menu item.

Don't forget to clear Drupal's cache once you add this to `hook_menu()`

---
Tags: 7, routes
---


# Question
Title: Redirecting user after login when using the ip_login module
I'm trying to show a different frontpage to users of a specific role, using the Front Page module (version 6.x-2.0-rc1) in alias mode. This works fine for users that are already logged in, but the problematic point now is that I'm also using the IP Login module (version 6.x-1.2) to log in certain users based on their IP address. This login seems to work differently from the usual login via the `/user` page.

Those users that are logged in via IP, they first get the normal frontpage that anonymous users get, they are not redirected automatically to the special frontpage I defined using the Frontpage module. If they reload the frontpage they are already logged in now and they see the special frontpage as intended.

The usual ways of using the Rules module or the Login Redirect module to redirect the users after they login just don't work, the users are not getting redirected when they are logged in via IP address.

Any ideas on how I could work around this problem, so that users logged in via IP see the special, redirected frontpage directly after openening the page?

# Answer
> 1 votes
As mentioned by charan in a comment, this works in version 6.x-2.0-rc1 of the IP Login module.

# Answer
> 0 votes
I had similar issues when using the Secure Pages module. I tried the Login redirect module, without success; I have finally found the Login/Logout Destinations module which worked perfectly (and still does).

> This module adds the destination back to the current page with JavaScript and checks to make sure the user has access before trying to have the user stay there on logout.

---
Tags: 6, redirection
---


# Question
Title: Css from zenbased theme not getting processed
I have something weird going on. My font-style of my zen-based custom theme is arial, verdana, sans-serif but what's showing is a serif font type.

I checked all the following:

* CSS compression turned off.
* flushed caches
* Activated a different theme and set it as default, then changed some css and it worked so now I know it has to do with the zenbased custom theme.
* Went into the file manager of my host's cpanel directly and made changes to my stylesheets directly to see if changes would make any effect on the site but no success.
* The site is run on hostgator
* checked to see if stylesheets are mentioned in the info file in a proper fashion

# Answer
> 1 votes
This is a good checklist for resolving css bugs - I would suggest two more that I've used when stuck on css bugs that may help you resolve this quicker next time.

* Check the element in firebug or developer tools to confirm whether the CSS file you think should be loaded actually is and what css styles are actually being applied to it. In this case, you could have determined that the file was loaded but the styles weren't so you could isolate your debugging to the syntax of the statement.
* Try using an external validator on your css file, like:

http://jigsaw.w3.org/css-validator/

Most of the feedback from this will be noise but it may highlight syntax errors in your file.

---
Tags: 6, theming
---


# Question
Title: views - group by first letter of results
As the title describes, I am trying to group the results of a view by their first letter. Googling revealed a way for me that half does the trick : display title twice, exclude from display, limit to 1(st) character, group by that. Clever I must admit but i need to reveal a grouping field even if there are no results in it such as:

```
A
  Alpha
  Anekin

B
  Bravo
  Borvo
C

D
  Delta
  Dooku

```

Any thoughts on how to go about doing that?

# Answer
It was really frustrating but in the end I figured it out:

In the views row output style tpl file:

```
<?php print $wrapper_prefix; ?>
  <?php if (!empty($title)) : ?>
    <h3><?php print $title; ?></h3>
  <?php endif; ?>

<?php $letters = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z');
foreach ($letters as $letter):?>
<div class="letter family">
  <div class="letter-header"><?php print $letter;?></div>
<?php print $list_type_prefix;  ?>
  <?php foreach ($rows as $id => $row):?>
    <?php $rest = substr($view->result[$id]->node_title,0,1);?>
  <?php if ($rest == $letter):?>
        <li class="<?php print $classes_array[$id]; ?>"><?php print $row; ?></li>
      <?php endif;?>
  <?php endforeach; ?>
<?php print $list_type_suffix; ?>
</div>
<?php endforeach;?>
<?php print $wrapper_suffix; ?>

```

This works for me since that view ouputs all it's results so I can safely assume $view-\>result will have the same elements in it as $rows. $rows afaik is the output of the current page. I am not sure if $view-\>result behaves in the same way.
> 1 votes

# Answer
A simple solution would be to add a field that only had the first letter and group by that.

Views also supports doing glossary, which is a but different, but allows you to group by the first letter and count the number of results and show fx

A(2) B(2) C(0), as an exposed filter, this is done through contexts in views 3.
> 4 votes

# Answer
Take a look at this article in Drupal.org. Hope it'll be useful for you, at least it helped me.

http://drupal.org/node/1078962
> 0 votes

# Answer
We actually added code in the "Header" portion of our view (select input method to PHP code). Here's our php code that does what you're looking for (and it doesn't require a separate template file).

```
<?php
  $letters = array(
    'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','y','z'
  );
?>
<h2>Browse by Last Name</h2>
<ul>
  <li style="display:inline; padding-right:8px;">
    <a href="/Full_time_Faculty_Listing" >All</a>
  </li>
  <?php for ($i=0; $i<count($letters); $i++): ?>
    <li style="display:inline; padding-right:8px;">
      <a href="/Full_time_Faculty_Listing/<?php print $letters[$i];?>"><?php print strtoupper($letters[$i]);?></a>
    </li>
  <?php endfor; ?>
</ul>

```
> -1 votes

---
Tags: views
---


# Question
Title: How to load modal form on page load using ctools?
I have an issue to show modal form on page load. This form will have 3 steps to submit. I've found CTools will suit the best. I'm newbie in drupal, that's why I've looked all tutorials ctools. Every example article tells how to show modal form by clicking on link. But I can't find any examples, how to load my modal form not clicking on link. I want to call it through AJAX after the page loads, but I don't know how.

Please, give me some advices.

# Answer
This post I wrote a while back deals with CTools AJAX events at any time. It involves writing your own Javascript handler and executing it on page load.

```
    Drupal.CTools.AJAX.refreshElements = function() {
  var url = '/mymodule/ajax/refresh-elements';

  try {
    $.ajax({
      type: "POST",
      url: url,
      data: { 'js': 1, 'ctools_ajax': 1},
      global: true,
      success: Drupal.CTools.AJAX.respond,
      error: function(xhr) {
        Drupal.CTools.AJAX.handleErrors(xhr, url);
      },
      complete: function() {
      },
      dataType: 'json'
    });
  }
  catch (err) {
    alert('An error occurred while attempting to process ' + url);
    return false;
  }

  return false;
};
$(document).ready(Drupal.CTools.AJAX.refreshElements);

```

Set the URL to the callback URL of your module. The last line tells the ajax to happen on page load but this could be replaced to happen in response to the exact event you need it to.
> 5 votes

# Answer
This article by zroger may be a little old about this exact subject, have you taken a look to it?
> 1 votes

---
Tags: forms, ajax, chaos-tool-suite
---


# Question
Title: How do I customize the comment reply link?
I'm trying to customize the comment reply link to direct the user to the comment submission form on the same page. I've tried:

```
<?php
$content['links']['#links']['comment-reply']['href'] = '#edit-comment-body-und-0-value';
?>

```

in my comment.tpl.php, but no luck. Also I need to add a JavaScript `onclick` to make the comment body in focus and add the user name of the user being replied to.

What should I do?

# Answer
> 4 votes
Have a look at the code of the AJAX comments module. It does simmilar things. There's a good chance that you can learn from theire code.

---
Tags: 7, comments, navigation
---


title: Notify user checkbox

text:
# Question
Title: Notify user checkbox
I'm looking for a bit of code, or module that would insert the following behavior into my user registration flow that exists as a php file. Use case as follows:

1. User registers for a free trial
2. User checks a box that says "Send an email reminder to \[WILL AUTOMATICALLY INSERT USER EMAIL\].com 3 days before I am charged.

User checks box. The back-end functionality might need to be manual for now. All I want to do is add the box, text, and have it pull the email address token automatically.

# Answer
You can add as many field you like to the user object using Fields. Just tell your field to be visible on the main user panel.

Once this is working, implement hook\_cron and send your mails using drupal\_mail().
> 2 votes

---
Tags: users
---


# Question
Title: What are some drawbacks/benefits of using ctools?
What is the purpose of ctools?

Are there any drawbacks in using ctools for one's programming needs?
Also, what are some benefits to using ctools? From the project page it seems to just be a large collection of random tools.

# Answer
> 0 votes
Discovered the best place to learn this is actually from a lecture from drupalcamp austin in 2010 by Erik Summerfield.

http://vimeo.com/17957123

That's just a start. Otherwise going through example ctools integrated modules has helped as well. The fact is (at this moment) documented use case examples are limited.

---
Tags: 7, chaos-tool-suite
---


# Question
Title: Ubercart - hook for modifying the order review page
What's the ubercart hook for modifying the table when visiting: /?q=user/%/order/%

I'm looking to remove columns in the orders node.

# Answer
> 0 votes
Documentation is lacking. This is the only documentation i could find and it's here: http://www.ubercart.org/docs/api

but not exactly what i want.

---
Tags: ubercart
---


# Question
Title: How to use taxonomy fields with Views and avoid duplicates?
I have content type 'sports venue' which is related to taxonomy vocabulary 'activity'. So a simple View of venues and activities might look like this:

* Park : football, hockey, running
* Pool: swimming, diving
* Stadium : athletics, running

I add an image field to the taxonomy terms to show an icon for each activity. Then I want the same View as above, but showing the activity icon instead of the term name.

In the View I add a relationship to the taxonomy vocabulary and add the taxonomy icon field.

Now the View has duplicates; 3 entries for park, 2 entries for pool etc. I only want a simple list as above.

Sometimes I can get close by using grouping and aggregation settings, but it gets quite messy. Am I missing something obvious here?

Note: This comment from Merlinofchaos is relevant, but refers to D6. Now that we can add fields to taxonomy terms in D7 core, I wonder if there are more options?

# Answer
> 1 votes
I don't know if this will help, but it seems similar. (Drupal is still pretty confusing to me, so I am sorry if this is not helpful.)

I eliminated duplicate rows in my view by changing the filter criteria. I could filter with two different criteria and get the same view, but one view had duplicates and one didn't.

The filter criterion that gave me duplicates was "Content: Producer\_category (taxonomy vocabulary 5)." Producer\_category is the name of a field. With this filter, if the content had multiple terms of the vocabulary applied, it appeared multiple times.

The filter that worked was "Content: has taxonomy term". After choosing this, I was prompted to select a vocabulary, and then to select term(s). I used the dropdown to display the terms. Also, Since I only selected one term for my display, i did NOT check "reduce duplicates", but I guess if you choose multiple terms you should.

Also, FYI, I was getting multiple errors when using Views since updating to Drupal 7, and I figure I probably did something wrong in the update process; all my Fields disappeared, among other things. So I ended up re-building the View from scratch. It seems like there are a bunch of new settings and options, and my view had some old, obsolete settings, and it just seemed better to start over and eliminate any hidden errors.

Good luck.

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


# Question
Title: Why is drupal_json_output only returning page HTML?
I'm trying to get drupal to return some rendered views content that I request through ajax, but all it seems to want to output is what looks like a rendered page. What am I doing wrong here?

// This is logging a ton of page HTML

```
jQuery(function($) {
    $.ajax({
        url: 'fetch/explore/' . category,
        success: function(data) {
            console.log(data);
        }
    });
});

```

// This is from my custom module

```
function wdfm_menu() {
    $items['fetch/explore/%'] = array(
    'page callback' => 'fetch_explore_content',
    'type' => MENU_CALLBACK,
    'access arguments' => array('access content'),
        'page arguments' => array(2)
  );
    return $items;
}

```

// Nothing is showing up in my log from this so I'm unsure it's even being called.

```
function fetch_explore_content($category) {
    watchdog('blargh', 'something');
    $data = array();
    $data['test'] = 'test';

  drupal_json_output($data);
    exit;
}

```

# Answer
You have an error in your Javascript, you're trying to use PHP syntax to concatenate the URL (the `.` symbol). As it is you JS shouldn't be running at all which is why the callback isn't being called. Your module code looks fine. Just change your JS to this:

```
jQuery(function($) {
  $.ajax({
    url: 'fetch/explore/' + category, // + instead of .
    success: function(data) {
        console.log(data);
    }
  });
});

```

Just to clarify, if the ajax call is going through despite the syntax problem the HTML response you're getting might be a 404/403/500 error page caused by the wrong URL being called.
> 7 votes

---
Tags: 7, ajax
---


# Question
Title: Province/State list does not update when Country changes when set to "Dropdown" (Location Module)
The Location module is exhibiting a weird bug. When setting a location (Country & Province/State), if I use autocomplete for the Province field, it will only suggest provinces in the selected country.

However, when I change it to a Dropdown, the Province/State field does *not* change, despite the AJAX refresh clearly working (the Province/State field fades in and out, so the AJAX callback is clearly working).

I've used the Webkit Inspector to check the page and there's no JS errors and there is an AJAX callback (however, since I don't have a base reference from a functional site, I'm not sure what data payload I should be expecting to see in the callback).

EDIT: I figured out a solution, but Drupal Answers won't let me answer my own question for another 6 hours. For the sake of anyone else who may be running into the same issue, I've uploaded the code + explanation in a pastie.

EDIT: Nevermind, that didn't entirely work... Will update once I find a working solution.

# Answer
> 2 votes
A friend of mine worked on that issue a while ago, this was the link to the issue. He is now using the Address Field module. I'm personally using address field as well, the country - province/state selections work well in that module.

---
Tags: 7, location
---


# Question
Title: Drupal 7, displaying an image to search results
I have a content type called "people". When a search is made and one of the search results is of "people" type, I want to display two fields of the "people" type; an image called "photo", and a text filed called "email".

Under "Manage Display" of the "people" content type, I selected custom display types and selected "Search Result" box. After saving, I selected the new "Search result" button and hid all other fields except "photo" and "email". I then customized the photo to have image style of "thumbnail".

I saved, cleared the cache, and reindexed the site. The search results are correct but no images are shown. I am very new to Drupal; all the help I could find is for Drupal 6 and by reading the comments people say that the solutions shown do not work for Drupal 7.

# Answer
> 4 votes
This is a core issue. See http://drupal.org/node/1166114.

Workaround is to add this to your theme's template.php. Also copy search-result.tpl.php from the core search module into your theme folder and clear cache.

```
function YOURTHEME_preprocess_search_result(&$variables) {
  $result = $variables['result'];
  if (isset($result['node'])) {
    $variables['snippet'] = $result['node']->rendered;
  }
}

```

The rendered node will pick up the Manage Display settings.

# Answer
> 1 votes
You have to isolate the issue first. Open up Firebug or your browser's developer tools and see if HTML is being output for the image. Maybe the path to the image is wrong in the search results for one reason or another. Also, ensure that you selected the proper formatter over at Manage Display (e.g. a formatter that works in another view mode).

Finally, check which template file is being used to output search results. Maybe this is getting in the way.

---
Tags: nodes, search
---


# Question
Title: How to suppress output of <p> tags in a views2 field output?
I've determined that I have an extra blank line above/below a field as output by views2. The generated html code examination shows a set of paragraph tags enclosing the field. I can find nowhere within this view to suppress that output. Is there a way either within views2 or via some css attribute?

# Answer
> 2 votes
You could go through the effort of overriding the template for that field, or you could just target the p tag with css and set the margins to 0px.

Views adds pretty granular classes to every field and row to make it easy to target.

---
Tags: views, theming
---


# Question
Title: How to hide webform label from email only?
I'm currently using the Webform module to build a warranty support form for Drupal 7.

Here is a screen shot of the webform:

Below is the email output I receive when the form is submitted:

> James Blunte.g. Joe Smith (jamesblunt@123.com) has submitted a warranty request.
>
> Order Number: 39840e.g. 1248

I've used the right label to show examples of what to enter in the field on the webform. My question is how do I hide the label from showing on the email template? As you can see the label follows right after the value.

Here is a screenshot of my 'Edit Components' page:

I can see how it's useful for the label to appear, but in my case I don't need it in the email.

Thanks for your time!

# Answer
It would take quite a bit to edit the email templates. The truth is that this is design behavior, because labels

The better way to do what you want is to put that text in the help/description field of the component and then style it with CSS. That text is not included in the email.
> 1 votes

---
Tags: 7, theming, webforms, emails
---


title: Taxonomy from URL

text:
# Question
Title: Taxonomy from URL
I want to show a views-block on a taxonomy page.

There are two taxonomy vocabularies.

Collections: bronze, silver, gold & Sizes: small, medium, large

So I have url's like this: collections/bronze/small

So what I want to do: show articles that have a taxonomy term "collection" set to "bronze" and size set to "small".

I found similar problems, but I can't get it to work :(

Same issue, but didn't work out for me:

Edit: Hmm, it works when I enter "bronze" into "Preview with contextual filters:", but when I try it on the taxonomy page nothing is shown. My path looks like this: http://localhost/drupalwebsite/?q=collections/bronze

Overview of my view settings:

Fields: Title CK field: Image

Contextual filter: Collections taxonomy term

When value NOT available: Provide default value -\> Raw value from URL -\> 2th component.

When value IS available: Specify validation criteria -\> Validator: Taxonomy -\> Type: Term name conv. to ID -\> Transform dashes to spaces

The taxonomy "sizes" isn't included yet in my view!

# Answer
> 0 votes
Enabling the "taxonomy term" view and changing the settings is a way to solve this problem.

If you want to show the "taxonomy description" on your view you can use this method: http://www.pridedesign.ie/content/drupal-taxonomy-description-view

In Drupal 7 use the taxonomy\_term\_load() function instead of the taxonomy\_get\_term() function.

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


title: Intelligently altering URL's

text:
# Question
Title: Intelligently altering URL's
I have a dilemma.

For my articles content type, i'm wondering how to alter a url automatically if i need to replace the hyperlink of my image thumbnails residing on my site to link to my other site which is my data repository on another server. Apart from doing it manually, i would like to know if i could automate this and create a script to do it, but i'm also not sure where to put it.

regards, V

# Answer
> 2 votes
I believe one of the better solutions to this would involve an extension to Storage API. You can't do it out of the box since it your own server, instead of say S3, but it seems like the best fit. When I saw a demo presentation by the maintainer, he showed how one could split thumbnails storage to a low-redundancy system from base image storage, which was stored more safely.

---
Tags: hooks, uri
---


title: How to catch duplicate comments

text:
# Question
Title: How to catch duplicate comments
In my sites comments are moderated so (anonymous) visitors sometimes get confused and try to resubmit it. It happenens within say 5 minutes only.

What is the best way to catch and reject duplicate comments by the same user?

One way is to look for same body text from same session within say 5 minutes and reject it.

# Answer
I'm not aware of any module that would provide this particular functionality. First of all, I would reduce the risk for confusion. An example is: Store a CID in the users $\_SESSION, and theme the comment form with "You have X comments awaiting moderation."

You could also add a custom validation function to the comment form with a hook\_form\_ID\_alter, and simply deny comments that fall within your stated condition, "Same body text within 5 minutes from same session", or so.

I would definitely focus on the first one though. No matter what type of validation criteria you add, there will always be edge cases where there is a good reason for posting something that your will then reject. This will of-course be a tradeoff between how large a risk you are willing to take rejecting valid input, and the effor required to "un-confuse" users.
> 1 votes

---
Tags: 6, comments
---