title: Localization - Hello World Example

text:
# Question
Title: Localization - Hello World Example
I am extremely tired right now and don't have time to read through verbose drupal 7 documentation. Can someone just show me a quick Hello World example that will do the following in drupal 7?

I have a template file `/sites/all/themes/mytheme/page.tpl.php` and in it I have

```
<?php echo "Hello World"; ?>

```

When a person comes to the page in English, it should show "Hello world". When the person comes to the page in French, it should show "Bonjour tout le monde". How do I augment the command echo "Hello World" to do such a thing? If language files are needed, show me how to structure them.

Thanks

# Answer
> 4 votes
Instead of "Hello World", use `t("Hello World")`.

Using the Localization client module, you can add the translation of that string in any language you want.

> This module helps you fix translations on your site as you see the issues. Just by navigating around your pages, you'll be able to fix translations and fill in missing ones using the on-page translation editor. At the same time, if configured properly, the module also submits your translations back to the community, to localize.drupal.org or any other localization server.

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


# Question
Title: Views Arguments formatted nicely for the title
I know that you can get the arguments in the view's title and format it so that it makes sense so that an argument like "search-for-something" can be output as "Search For Something".

I have an argument passed like "argument-here" and I need to search in the database for that exact phrase.

The problem is that in order to get it to format nicely in the title as "Argument Here", this also removes the dash in the SQL query - resulting in nothing for my view to return.

Is there a way that I can format the result for the title without messing up the actual argument for the SQL query?

# Answer
Restore your view so that the query works. Then, make sure the PHP Filter module is enabled and that you have permissions to use it.

In the view, add this header:

```
<?php
$view = views_get_current_view();
$my_title = ucwords(str_replace("-", " ", $view->args[0]));
drupal_set_title($my_title);
?>

```

Make sure the input format for the header is PHP.

The view's preview will show the wrong title. That's ok. When you navigate to the page, you'll see that the title is as you want it.
> 1 votes

---
Tags: views, 6
---


# Question
Title: How to change the label of username field on all forms/pages that it occurs?
The following snippet changes the label of the username field on the user registration form from 'username' to 'nick-name' (when inserted into the template.php of the theme:

```
function my_theme_form_user_register_form_alter(&$form, &$form_state, $form_id) {

    $form['account']['name']['#title'] = t('nick-name');

}

```

To be consistent I'd like to change the label everywhere that it occurs in the system, such as the user settings form... how do I do that!

# Answer
Add the following code at the bottom of the settings.php file:

```
 $conf['locale_custom_strings_en'][''] = array(
   'username'      => 'nick-name',
 );

```

As alternative, you can use the String Overrides module.

> Provides a quick and easy way to replace any text on the site.
>
> ### Features
>
> * Easily replace anything that's passed through `t()`
> * Locale support, allowing you to override strings in any language
> * Ability to import/export \*.po files, for easy migration from the Locale module
> * Note that this is not a replacement to Locale as having thousands of overrides can cause more pain then benefit. Use this only if you need a few easy text changes.
> 3 votes

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


# Question
Title: $form_state for an autocomplete callback
I'm trying to get the value of `$form_state` for my autocomplete textfield.

Basically, I have a search textfield and checkboxes to restrict the autocomplete. What would be the best way of passing the checkbox values to the autocomplete?

# Answer
> 2 votes
The autocomplete callback just gets the string that needs to be auto-completed.
In your case, the only solution I can think of is that the checkboxes use an AJAX callback that is used to set a value the autocomplete function can then access.

---
Tags: 6, forms, ajax
---


# Question
Title: Add cck field as scoring factor to drupal standard search
So, by default there are four scoring factors in drupal:

* relevance of keyword
* recency
* number of comments
* number of page views

I'd like to be able, to control relevance of specific cck-fields. In my case, i've got a cck field (computed field), where all relevant search-data is getting summed up.

I'd like to be able to give this special field a higher relevancy to the search results than anything else.

Is there a possibility to do this?

# Answer
Implement hook\_update\_index in a way that calls search\_index. The source code of `search_index` tells you how the `$text` argument is analyzed. From a quick look at the source, I would wrap the field content in `<h1>` tags. Not that the string only applies to searching, not to rendering. So it does not need to represent the actual structure of the node.
> 1 votes

---
Tags: 6, search
---


# Question
Title: drupal_mail() and names with apostrophes
When using drupal\_mail to send an email, I get errors when display names (not emails) contain apostrophes in the "To" field.

For example, referring to drupal\_mail() documentation, email addresses like "`Another User <anotheruser@example.com>`" are valid. "`Another User <anotheruser@example.com>`" validates perfectly, but "`Another O'Neil <anotheroneil@example.com>`" fails.

Do I need to change the last name to ONeil instead of O'Neil, or can escape it somehow?
I have also tried "`"Another O'Neil" <anotheroneil@example.com>`" without success.

* Setup: Ubuntu 11.04 LTS
* Drupal Version: 7.x
* Mail Service: Amazon SES
* Additional Mail Modules: "HTML Mail" and "Mail System"

# Answer
I assume a few things:

* You have no exotic mail transport installed, having Drupal fallback to phps' mail()
* You deliver the mail trough a unix system. Windows deals differently with mail.

Digging into RFC2822 you will find about escaping " and some other characters.

The solution then presents itself as

```
$to = "\"Another O'Neil\" <anotheroneil@example.com>";
drupal_mail('contact', 'page_mail', $to, language_default(), $values, $from);

print $to; #=> "Another O'Neil" <anotheroneil@example.com>

```
> 2 votes

---
Tags: 7, emails
---


title: Linking to other nodes

text:
# Question
Title: Linking to other nodes
I'm looking to add a field to a content type that lists nodes. Basically, I need that users are able to choose the node they want to link to, and then (in the template) output the link to that node.

This seems like a basic thing to do; I'm using Drupal 7 but can't for the life of me work out what I'm missing.

# Answer
> 4 votes
In order to use the "node reference" field in Drupal 7, you need the References module.

# Answer
> 0 votes
You should use a 'node reference' field for this.

---
Tags: 7, nodes, uri
---


# Question
Title: How to define my own block regions for original, custom front page layout?
I want to define my own block regions for the front page

I want to have a grid of blocks, each block containing a list of recent media (pictures, youtube, audio) with a certain tag. See example wireframe as ascii art below

A rule with the blocks is that if an item has already appeared in one block, then it doesn't appear in the others (media items can have multiple tags obviously).

Questions after the drawing.

```
+-----------------------------------+
! main menu                         !
+-----------------------------------+
! rolling display                   !
!                                   !
!                                   !
+-----------+-----------+-----------+
! tag a     ! tag b     ! tag c     !
! heading   ! heading   ! heading   !
+-----------+-----------+-----------+
! list      ! list      ! list      !
! of media  ! of media  ! of media  !
! with tag a! with tag a! with tag c!
! & thumb   ! & thumb   ! & thumb   !
! nail for  ! nail for  !nail for   !
! each item ! each item ! each item !
+-----------+-----------+-----------+
! tag d     ! tag e     ! tag f     !
! heading   ! heading   ! heading   !
+-----------+-----------+-----------+
! list      ! list      ! list      !
! of media  ! of media  ! of media  !
! with tag d! with tag e! with tag f!
! & thumb   ! & thumb   ! & thumb   !
! nail for  ! nail for  !nail for   !
! each item ! each item ! each item !
+-----------+-----------+-----------+
! tag g     ! tag h     ! tag i     !
! heading   ! heading   ! heading   !
+-----------+-----------+-----------+
! list      ! list      ! list      !
! of media  ! of media  ! of media  !
! with tag g! with tag h! with tag i!
! & thumb   ! & thumb   ! & thumb   !
! nail for  ! nail for  !nail for   !
! each item ! each item ! each item !
+-----------+-----------+-----------+

```

Please outline specifically how I would go about doing this. I'm looking for a fairly definitive answer - i.e. something that won't break something else, and is robust in itself.

Specific questions:

1. Would I use PHPTemplate and if so how? Would I use this to declare the regions, and how?
2. What would the roles of Panels, Views and Blocks be in creating this layout?
3. Can I create the layout in panels without writing any PHP code?
4. Presumably the Views module would provide the content within the blocks.
5. How do I tell Views and Blocks where to put the content, i.e. in a particular block?

# Answer
> 1 votes
1. If you just need it on your front page, doing it in page template is wrong.
2. You can do in in Panel - create new panel for logged and not logged users; use there blocks; and views' display 'panel pane' for using views which need argument from context.
3. Yes you can
4. It can, but sending view argument this way is really painful. I recommend use panels panes.
5. You set it in panel.

---
Tags: 7, views, theming, blocks, panels
---


title: Is check_plain() enough?

text:
# Question
Title: Is check_plain() enough?
Is check\_plain() enough for re-displaying the text entered by users in the browser, or should I still filter with filter\_xss()?

# Answer
I imagine the question is about using `check_plain(filter_xss($string))`, or `filter_xss(check_plain($string))`.

`check_plain()` and `filter_xss()` have two different, and in contrast, purposes:

* `check_plain()` encodes special characters in a plain-text string that is then displayed as HTML.
* `filter_xss()` filters an HTML string to prevent cross-site-scripting (XSS) vulnerabilities. In particular its purpose is:

+ Removing characters and constructs that can trick browsers
    + Making sure all HTML entities are well-formed
    + Making sure all HTML tags and attributes are well-formed
    + Making sure no HTML tags contain URLs with a disallowed protocol (e.g. javascript:)

If you use `check_plain()`, the string passed to the function is supposed to be used as plain text; in such case, `filter_xss()` is not necessary. If you use `filter_xss()`, then the string passed to the function is supposed to be HTML, and `check_plain()` is not necessary.

If the question is about using `check_plain()` and `filter_xss()` on different parts of the same string then, as greggles pointed out in his comment, you can use (for example) `check_plain()` on the content of tag attributes, and `filter_xss()` on the entire HTML tag.
> 26 votes

---
Tags: security
---


# Question
Title: How to show a View field depending on roles?
I have a view, and I added 2 fields: "title" and "edit link".
Now I just want to show the "edit link" link if the visitor is a registered user, and has the "administrators" role.

How can I accomplish it?

# Answer
Check the permissions for the role of "administrators" (D7: admin/people/permissions, D6: admin/user/permissions). If the user has permission to edit the node, the edit link will be visible, if not, the edit link will not be shown. Views takes into account a user's (role's) permissions.

D7 Example: Say you are creating a list of Stories. If the administrators role has the permission "Story: Edit any content", the user will be able to see the "Edit" link for that node in the listing, while if the role only has the permission "Story: Edit own content" the "Edit" link will only be shown if the current user created the Story.
> 3 votes

---
Tags: views, entities, users
---


# Question
Title: Programatic output of views block breaks jquery
I am using the following code to load a views slideshow block:

```
  <?php
            $view       =   'pagetopimage';
            $block_id   =   'block_1';
            $args       =   array(32);
            print views_embed_view( $view, $block_id, $args );
        ?>

```

The block is produced just fine but the javascript that makes the slideshow work is abscent.

**Can you enlighten me about a way to programmatically load the block whilst maintaining the javascript functionality, please?**

# Answer
I would assume you are just missing the jQuery Cycle plugin. You might try adding

```
drupal_add_js(drupal_get_path('module', 'views_slideshow') . '/js/jquery.cycle.all.min.js');
drupal_add_js(drupal_get_path('module', 'views_slideshow') . '/contrib/views_slideshow_singleframe/views_slideshow.js');

```

before outputting the view and see if that works.
> 1 votes

---
Tags: views, javascript
---


title: How to set up a Weekly Digest

text:
# Question
Title: How to set up a Weekly Digest
I need to set up a weekly email digest of all content from a few particular content types (latest news, latest tech articles etc.) for all users in a particular group.

I have Simplenews installed and it looks like the Simplenews Digest module is not updated. Is there anything else that offers the feature I am looking for?

# Answer
You can make an RSS feed of the digest and then use Mailchimp to make a newsletter of that RSS feed. This has to be setup one time and the rest is automated. Mailchimp module synchronizes Drupal user groups with the mailing lists and groups.
> 3 votes

---
Tags: emails
---


# Question
Title: Anyone have any luck exposing Ubercart's "enter your VAT" part of the form?
I am using http://drupal.org/project/uc\_vat and http://drupal.org/project/uc\_vat\_number and am able to enter different VAT rates, but a the moment it seems that it simply applies whatever is the last item in the list as VAT. I need to find where in the interface (I may be being blind as well as ignorant) it will allow me to enable the part of the form where the user can select that they have a VAT number to enter to avoid paying VAT. I am pretty sure it is part of the interface, I just don't know where to find it.

If I find it, I will post and/or close the question. Many thanks for any and all support!

# Answer
This module is dependant on the billable address module being enabled. I did not need the billable module and thus is did not show (javascript dependancy).
> 1 votes

---
Tags: ubercart
---


# Question
Title: Using Drupal's database for Apache authentication
I have static content outside of Drupal that I need to password protect using the users's existing credentials in Drupal. I found an apache module that lets you use MySQL for Apache authentication:

http://sourceforge.net/projects/modauthmysql/

Unfortunately, this doesn't support sha-2 (sha512) that Drupal 7 uses.

Does anyone know of any alternative ways to do this? I'd like to avoid wrapping all this content in PHP because it's generated (and regularly updated) by a tool, has any number of relative links and folders and such, and the only way I can think of handling that with PHP outside of modifying the files is to use mod\_rewrite to route all the requests for html files through some sort of front controller that is a Drupal module (or a bootstrapped Drupal).

# Answer
Even if you manage to find an apache module that has sha-2 implemented, you still need to fetch and integrate the salt. **The solution will have to include Drupal somehow, since Drupal is the only one who really knows how to authenticate against its database**.

I am not aware of any maintained module that does what you want, but it would be really easy to implement in a module.

Pseudocode that illustrates how simple this is in Drupal:

```
/**
 * Implements hook_menu().
 */
function mystatic_menu() {
  $items['mystatic'] = array(
    'title' => 'Blogs',
    'page callback' => 'mystatic_serve',
    'access arguments' => array('access content'), # Or check against other permissions.
    'type' => MENU_CALLBACK,
  );
  return $items;
}

function mystatic_serve($filename = '') {
  if (empty($filename)) {
   return _mystatic_directory_index(); #String will be printed as $content inside Drupals page.tpl.php template.
  }
  elseif(_mystatic_is_valid_file($filename)) {
    print _mystatic_serve_file($filename);
    drupal_exit(); #String will be sent to user without going trough Drupals theme layer.
  }
  else {
    drupal_not_found();
  }
  return $html;
}

```

The function `_mystatic_directory_index()` would generate a list of files, or the index of the static system. To be served inside Drupals theme when people access */mystatic*.

The function `_mystatic_is_valid_file()` would sanitize the filename (to avoid serving e.g. `../../etc/password`. There are many tutorials out there for this. It would obviously also check if the file $filename actually exits. Will be served if people open urls such as */mystatic/example.html*. Note that */mystatic/somedir/example.html* will not work; Drupal splits on `/` and passes that as separate arguments.

The function `_mystatic_serve_file()` would simply read `$filename` from the disk and stream (print) it to the user.
> 1 votes

# Answer
I did in the past use the export\_user\_db module, but it is similarly lacking in D7 support.

I am now using modauthmysql quite successfully with D6; I also have an auxiliary module that I can publish to do single-sign-on between Drupal and Apache-authenticated sections of the website.

You are correct that the lack of a Drupal-7-compatible password hash is a limitation, but I don't think this would be too hard to add. Contact me on d.o if you would like to collaborate.

http://drupal.org/user/438598

If you really only need to serve static content, serving it from Drupal per the other answer is easier and better.
> 2 votes

---
Tags: database
---


title: Export blocks to production site

text:
# Question
Title: Export blocks to production site
> **Possible Duplicate:**
> Quickest way to reimport menus and blocks (D7)

**I need a way to easily transfer the block configuration from my staging site over to the live site.**

I've been working on implementing a new theme for my client and showing them my progress using a staging site, which is basically a clone of the live site. The staging site's blocks configuration is completely different from the live site.

I've heard about the Features module, but unless i'm mistaken, it doesn't work with Blocks. Maybe I need to use Chaos Tools?

I'm just trying to avoid having to manually place each block in its correct position when it's time to go live, which would be very time consuming. Using exportable blocks sounds like a good idea, but I am unsure if it is a safe procedure.

# Answer
> 1 votes
Yo will need to use the Features Extra module. It currently supports: vocabularies; nodequeues (definitions); block settings; **custom blocks** (boxes).

---
Tags: 6, theming, blocks, staging
---


# Question
Title: Problem with migration from Apache to IIS
I run a website with Drupal in Linux/Cpanel/Apache/MySql and it worked perfect.
I want to put this site in Windows/plesk/IIS/MySql. I backed up and restore database in the new host and copied Drupal files.

My website run in new host with some problem.

1. I can't see administrative page; this page is white.
2. My links don't work with clean URLs and I should add (?q=) to links.
3. My images with ImageCache are not shown. The URLs for images are not correct and have a space.

# Answer
> 6 votes
You need to translate the Apache server's rewrite rules into their IIS equivalents, in the root web.config.

For reference, see what is reported in the Windows Download Instructions.

> **IIS7: Create/modify web.config file.** Drupal distributions come with .htaccess files for \*nix use; IIS7 users should convert this file to a web.config file for their site. If you have used the IIS Manager to create a new site, a basic web.config file will exist in your site's root directory.

# Answer
> 0 votes
1. It can be solved by cleaning all cache tables using something like phpMyAdmin.
2. See the other answer; just use the web.config file that comes with Drupal.
3. It will be solved if point #2 is solved, and the right permissions are set.

# Answer
> 0 votes
Running D6 on an IIS machine is a little more difficult. You require a IIS module that allows for rewrite rules, there a quite a few, some free others are a paid solution. There will be quite a few quirks to work out. But that should get you started.

---
Tags: 6, migrations, iis
---


# Question
Title: How can I embed an Editor just like those in StackExchange Q&A in Drupal 7?
I am new to Drupal.

I want to embed an editor in my content, body nodes so that I can do different editing when I add a new content. (i.e., bold , hyperlink, list) etc.

Is it possible to do that? Any module is available?

# Answer
Yes, there are quite a few. One of the most popular editor modules is WYSIWYG which allows you to choose which JavaScript library you want to use, or there are more specific modules such as the CKEditor module
> 2 votes

---
Tags: 7, nodes
---


# Question
Title: How to loop through a taxonomy vocabulary to find the top category in a nested tree?
What I have so far is this

```
$term=therm_id_that_I_already_have;

$parent = db_result(db_query("SELECT h.parent FROM {term_data} d INNER JOIN {term_hierarchy} h ON d.tid = h.tid WHERE d.tid = $term"));
$term = $parent;

$th=taxonomy_get_term($term);

```

probably I need a while of something...

# Answer
> 2 votes
I would recommend using taxonomy\_get\_parents\_all(). If you have a vocabylary that looks like:

* Vocabulary
    + Child 1 (tid=1)
        - Child 1.1 (tid=3)
    + Child 2 (tid=2)

Then you can do:

```
<?php
$parents = taxonomy_get_parents_all(3);
$top_category = array_pop($parents);

```

Will give you the term for tid 1.

---
Tags: taxonomy-terms, database
---


# Question
Title: Create RSS feed for content type = news?
I created a content type called news items in drupal 7. How do I tell D7 to create an RSS feed of ONLY news items?

When I go to /rss.xml, it displays all content types, which is too much. I only need news items.

# Answer
> 14 votes
You can use the Views module to create feeds. Simply add a new display of type "Feed" and customize the view to contain only the content you want. Be sure to choose a path for your feed so that it can be accessed.

To add a "Feed" display:

Go to your views administration and select the view you want to edit. Towards the top of the page you will see the "**Displays**" heading with an "+ Add" button. Click that and select "Feed" (See image below). You will then have a Feed display that is using the Default Display's settings.

---
Tags: 7, feeds
---


# Question
Title: How can I change the Apache Solr search URL?
How can I change the default Apache Solr URL path from "search/apachesolr\_search/term" to something else?

# Answer
> 3 votes
The way I've typically done this is to implement hook\_menu\_alter(). You can then customize the url in the exact way you choose:

```
/**
 * Implements hook_menu_alter().
 */
function example_menu_alter(&$menu) {
  // Ensure Apache Solr is the default and that the menu item exists.
  if (variable_get('apachesolr_search_make_default', 0) && isset($menu['search/apachesolr/%menu_tail'])) {
    $menu['search/%menu_tail'] = $menu['search/apachesolr/%menu_tail'];
    unset($menu['search/apachesolr/%menu_tail']);
  }
}

```

# Answer
> 4 votes
This should work if you place it in settings.php:

```
function custom_url_rewrite_outbound(&$path, &$options, $original_path) {
  // Filter to get only the apache solr links with filters so it doesn't launch it for every link of our website
  if ($path == 'search/apachesolr_search/' && strpos($options['query'], 'filters') !== FALSE) {
    $new_path = $path.'?'.urldecode($options['query']);
    // See if we have a url_alias for our new path
    $sql = 'SELECT dst FROM {url_alias} WHERE src="%s"';
    $row = db_result(db_query($sql, $new_path));
    // If there is a dst url_alia, we change the path to it and erase the query
    if ($row) {
      $path = $row;
      $options['query'] = '';
    }
  }
}

function custom_url_rewrite_inbound(&$result, $path, $path_language) {
  // See if we have a url_alias for our new path
  $sql = 'SELECT src FROM {url_alias} WHERE dst="%s"';
  $row = db_result(db_query($sql, $path));
  if ($row) {
    // We found a source path
    $parts = preg_split('/[\?\&]/', $row);
    if (count($parts) > 1) {
      $result = array_shift($parts);
      // That's important because on my website, it doesn't work with the / at the end of result
      if ($result[strlen($result) - 1] == '/') {
        $result = substr($result, 0, strlen($result) - 1);
      }
      // Create the $_GET with the filter
      foreach ($parts as $part) {
        list($key, $value) = explode('=', $part);
        $_GET[$key] = $value;
        // Add this because the pager use the $_REQUEST variable to be set
        $_REQUEST[$key] = $value;
      }
    }
  }
}

```

And then when you create a menu entry, you put the link to apache solr : search/apachesolr\_search/?filters=tid:13

And create a url alias for search/apachesolr\_search/?filters=tid:13 like products/tv.html

Found via: http://drupal.org/node/783836#comment-4136475

# Answer
> 4 votes
It is non-trivial to change the search path if you are only using the apachesolr search module. Since it depends on the core search module, the path is nearly hard-coded. It depends on search/{module}/%menu\_tail. If you look at search\_view(), the callback for the search module, you'll find that it calls search\_get\_keys(), which expects the search keys to be in a particular part of the path. The apachesolr search module also uses this function to get keys, so implementing a simple hook\_menu\_alter() won't work on its own.

As mentioned in another answer here, if you are able to run Views 3.x, then your best bet is to use the apachesolr views module. With this module, you can easily define any number of custom paths for search results.

If you can't run 3.x, then you'll need to use a combination of form alter (specifically, search\_form) and custom menu callbacks to successfully change the default search path.

# Answer
> 3 votes
You could use solr views for your site search.

1. Create a solr view.
2. Add a page display with the path you want
3. Add search text as a filter.
4. Exposed form in block
5. Put the block where you want your search box to go.

# Answer
> 2 votes
Check out Adding custom search paths with hook\_menu by the guys at Evolving Web. It talks about how they wrote a custom module to create friendly URLs for their Solr searches. You'll probably need to tweak it a bit, but it's a good starting point.

# Answer
> 1 votes
What about creating a new menu callback like the following to make apachesolr return results at that path?

```
$menu['search']['page callback'] = 'apachesolr_search_view';

```

# Answer
> 1 votes
Or you can just modify a contributed module that does this: Apache Solr Custom Path.

# Answer
> 0 votes
If you just want to change search/apachesolr\_search/ to something else, for example 'inventory', you can try Global redirect module.

The trick is to create 2 aliases - one for search/apachesolr\_search/ (for faceted items) and another one without trailing slash (for the main search page). Global redirect might refuse to create 2 aliases for the same destination, but you can insert it into the db directly.

---
Tags: 7, search
---


# Question
Title: Automatically adding paid membership products based on field values with Ubercart and Content Profile
I'm in the early stages of building a client site that is heavily centred around paid membership. Depending on a fairly complex set of rules, members will join the site and be charged different amounts for their annual membership based on fields they fill in on the signup form.

I am using Ubercart and Content Field Profile to create a custom membership form. The membership boils down to having 1-many products added during the sign up, based on the values entered in the form.

Is there a way I can do this without coding it all myself using submit or validate hooks and uc\_add\_product or similar?

# Answer
Thanks to wizonesolutions and a bit of googling, I came up with a very simple solution using a custom module.

I've now moved to Drupal 7. Using a combination of Logintoboggan, Rules, and Entity Fields, I can set up complex conditions for membership using the admin interface rather than code. More importantly, this means my clients will be able to do the same.

Ubercart Rules is fantastically useful, but doesn't have support for adding products to a user's cart out of the box. This was easily fixed with a small custom module which added the action. Below is the code from that module:

```
<?php

/**
 * @file
 * This file contains the Rules hooks and functions necessary to enable adding
 * products to carts from Rule actions.
 */

/**
 * Implements hook_rules_action_info().
 */
function mycustommodule_rules_action_info() {

  $actions['mycustommodule_add_product'] = array(
    'label' => t('Add a product to the cart'),
    'group' => t('MyCustomModule Order'),
    'base' => 'mycustommodule_add_product_to_cart',
    'parameter' => array(
      'product' => array(
        'type' => 'text',
        'label' => t('Product'),
        'restriction' => 'input',
        'options list' => 'mycustommodule_product_list_options',
      ),
      'quantity' => array(
        'type' => 'text',
        'label' => t('Quantity'),
      ),
    ),
  );

  return $actions;
}

/* * ****************************************************************************
 * Condition Callbacks and Forms                                              *
 * **************************************************************************** */

/**
 * Return a list of product nodes, keyed to their nid.
 */
function mycustommodule_product_list_options() {
  // Get a list of all products
  $query = db_select('node', 'n')
    ->fields('n', array('nid', 'title'))
    ->orderBy('title');
  $query->join('uc_products', 'p', 'n.vid = p.vid');

  $result = $query->execute();

  foreach($result as $row) {
    $return[$row->nid] = $row->title;
  }

  return $return;

}

/**
 * Add a product to the user's cart, based on the rule.
 *
 * @param int $product
 *   nid of the product to add
 * @param nid $quantity
 *  quanity of product to add
 */
function mycustommodule_add_product_to_cart($product, $quantity = 1) {
  uc_cart_add_item($product, $quantity);
}

```

I hope someone finds this useful.
> 1 votes

# Answer
I would look into Rules (may require some patches and the Ubercart Rules module, as I don't know if it can add products to the cart by default).

That said, a Google search (which I'm sure you've also done) doesn't hint at much. If you have time, I would suggest doing it the way you're planning (validate and submit hooks and uc\_add\_item). It will work well. Then contribute back what you've done either to an existing, similar module or as a new uc\_ module.

Before doing so, you could ask in #drupal or, more specifically, #drupal-ubercart on IRC.
> 1 votes

# Answer
We are having actually the same problem that we cant add automatically a product to cart with a rules. (annual membership) Unfortunatlky we are using commerce and we are asking ourself what param to change in your code for using it with commerce instead of UC. Do you have an idea or some key for us?

thank you very much. sebastien L.
> 0 votes

---
Tags: 6, ubercart, users
---


title: Menu Management

text:
# Question
Title: Menu Management
I am trying to make menu management easy for my clients in Drupal 7.

1. How can I make it so that clients can move links on the menu but cannot delete the top level menu? For example, if the top level menu item is "Products", how can I make it so that the clients cannot delete the menu item "Products" (and even the node itself) but they can reorder the children?
2. Let's say I have a main menu item called "Products" and under it I have "Phones". How can I make it so that if a node "Phones" has children under it on the menu, that it can not be deleted. Because right now, if the client deletes "Phones", all of its menu children are automatically moved up to the same level that the other product categories were on i.e. "Televisions", "Computers", etc.

# Answer
> 1 votes
If using Drupal 6 is a possibility, these 2 modules would help:

Menu Parent

Menu Admin per Menu

# Answer
> 0 votes
From what little I know, I think this is tricky to do in Drupal 7. It does look like there is some work going on with the workbench access module to allow better integration for menus: http://drupal.org/node/1101638.

Some other things to explore might be the book module (comes with drupal core), or even fudging with different content types (maybe make one for "landing pages" which the editor cannot delete, and one for "sub-page" which they can delete... I have never tried this though). Also potentially organic groups with organic groups menu (this, as a lot of modules is in dev, and I'm not sure how well it works).

Let us know if you come to a solution, I would be interested in knowing as well.

---
Tags: 7, routes
---


title: Locations using GMAP

text:
# Question
Title: Locations using GMAP
A client has asked us to look at extracting information from an MS Access DB to designate where his products have most recently been delivered.

The end result is to output a variety of maps based on the last known delivery date, from which we can then specify what colour to designate each location marker on the map, based on the date they were last delivered to.

The other variable would be locations that they know are always stocked (regulars).

We can format the data from MS Access either at the point of origin, from our server or in Drupal. This DB will not change in its structure for a long time I expect, so we're happy treating this as a data 'Stub' to work with.

What we've also established is that the frequency of this data update isn't too critical, but since we're going to link our VPS to their system and then into Drupal, we think that regular updates (e.g. on each cron run) would be a good thing to offer.

Can anyone point us in the right direction for how to achieve this?

Its right on the cusp of our knowledge and we're a little bewildered by what approach to take.

Thanks!

# Answer
It's not totally clear what you're asking, but here's a stab:

1. It doesn't sound like the data will be updated frequently enough to justify processing it on every cron run - you mentioned recent deliveries... what do you mean by *recent*? In the last hour? Last day? 30 days? Find the right balance based on the freshness of the data itself, and only update what's new, especially if you're doing it on every cron run.
2. Get the data out of Access in a reasonably ready-to-consume format - don't expose the ugliness of your Access data structures to Drupal. This could mean setting up a custom view in Access to summarize and reformat the data you need for Drupal.
3. Setup a scheduled export from Access.
4. Use Drupal Feeds to import/update the data from Access into Drupal, either on demand or periodically.

HTH.
> 2 votes

---
Tags: 7, google-maps
---


title: Field language - Multi language

text:
# Question
Title: Field language - Multi language
I have a node in Dutch and I want to get the field in this language. When I do:

```
$node->field_name[$node->language][0]['value'];

```

I get the error:

```
Undefined index: nl

```

So I try:

```
$node->field_name[$node->language]['nl']['value'];

```

But that doesn't work. What am I doing wrong?

Edit:

I already figured it out:

> $language = field\_language('node', $node, 'field\_yourfield');

This gave me the language of the field and it was 'und' and not 'nl' as I thought it would be. The language of the node can be different then of the field. Learnt a lot about i18 & Drupal :)

# Answer
> 1 votes
I use a function from this blog post to retrieve the fields value, it's quite handy as it allows you to parse the different values of the field (also it handles `value` or `nid`).
Drupal 7 tip : Get field values from entity objects like nodes, users, taxonomy...

Regarding the `und`, I'm not very sure why is this happening, I saw this issue: Field display languages are cached before locale has changed field language, but I have to wrap my head against this.

---
Tags: entities, i18n-l10n
---


# Question
Title: How do I show the site-wide contact form on a page in Drupal 7?
I have seen other posts about this, but none specifically for Drupal 7, and I can't get it to work. I am trying to get the default contact form to show up below the main content of a page, perhaps in a block.

Do you have any suggestions?

# Answer
> 6 votes
You could create a custom block in a module and embed the form there. Something like this (I haven't tested this code!):

```
/**
 * Implements hook_block_info().
 *
 * This hook declares what blocks are provided by the module.
 */
function MODULENAME_block_info() {

  $blocks['contact_block_form'] = array(
    'info' => t('Contact Form'),
    );

  return $blocks;
}

/**
 * Implements hook_block_view().
 *
 * This hook generates the contents of the blocks themselves.
 */
function MODULENAME_block_view($delta = '') {
  //The $delta parameter tells us which block is being requested.
  switch ($delta) {
        case 'contact_block_form':
      $block['subject'] = t('Contact Us');
      // Load contact pages inc as the form definition sits there.
          module_load_include('inc', 'contact', 'contact.pages');
      $block['content'] = drupal_get_form('contact_site_form');
    break;
  }
  return $block;
}

```

Hope this helps

---
Tags: forms
---


title: Adding custom vars with a block

text:
# Question
Title: Adding custom vars with a block
I want to use the title of the block as a hyperlink (or maybe adding an image) and I do not know how can I do this.

I've been looking to block.tpl.php. I know I can modify the template the way I want.

Maybe the way to do it is defining custom variables, such as `$block->mycustom`.

If the variable is defined there is a link, if not, nothing. The problem with this approach is that I don't know where this variable should be defined.

Is that correct, or am I totally mistaken?

I am interested in an answer for Drupal 7.

# Answer
> 1 votes
You could add a theme preprocess function for blocks to add some logic pushing variables into your block template. You can then check against those variables to output the title as a link etc.

```
THEMENAME_preprocess_block(&$vars) {
 //logic here to add variables
}

```

---
Tags: blocks
---


title: Is Drupal Commons right for me?

text:
# Question
Title: Is Drupal Commons right for me?
I'm reading a lot, searching, asking questions. Measuring thrice before cutting once.

Now it seems to be a straight choice between a pre-built Drupal Commons and roll-your-own based on core-Drupal plus some modules. I absolutely require a wiki, which doesn’t seem to be in the standard distro, no easily addable as a single module.

I won’t mention standard stuff like forums, but will say that I want a “social networking site” for ex-pat foreign workers in another country.

It would be nice to have some form of Goups of fiends & colleagues and to provide sharing permissions at that level of granularity (e.g, world read, group right/ group read only, etc); joint calendars, access to blogs, maybe chat rooms or even one form per Group; maybe a photo album, although I suppose they can just refer to their Flikr.

Maybe profiles with some extra stuff like IM, phone #, etc, where the user can control who gets to read it.

(Plus anything more that you can suggest for such a community, of course)

It looks to me like I would be best to start with Drupal Commons – do you agree?

The only thing is that when I go to download it, it says 6.x-2.0 tar.gz (17.4 MB) 2011-Aug-26 Version 2.0 is a major upgrade Which seems to imply that it is based on Drupal 6, not Drupal 7. Is that correct? Is it a show-stopper for me? Or can I just install it and upgrade everything?

Sorry if I don’t sound too knowledgeable; I am still not a Drupal user, just a dabbler on my local PC.

Thanks in advance for any help.

# Answer
> 1 votes
I would recommend starting with Drupal Commons as a base. It comes with a lot of prebuilt configuration that's very nice, like the fb-style walls for groups and for users. You get all the standard things you mentioned except for forums, but that comes with Drupal core, or you could go for a more advanced solution. You can disable any features you don't want in a per group basis. Commons already comes with a nodes as profiles solutions, so you just need to add the fields you want to the profile node. For chats you will also need an additional module, there are several, maybe this will help get started.

To answer your question more directly, yes Drupal Commons is right for you. It will save you a lot of configuration time, and you can see some best practices in configuration from what they did. Remember to back up your db often and don't be afraid to modify everything to suit your needs, you will learn a lot that way. As long as you have a a backup you can always revert.

---
Tags: 7
---


# Question
Title: how to unpublish a comment rather than deleting it
I like to use "threaded style" comments. However the problem with them is that when a users deletes their own comments all the "replies" to those comments are deleted as well.

Is there a way to "unpublish" those comments instead of deleting them?

# Answer
> 2 votes
To unpublish a comment, click on the link to edit it. In the page that appears, you will see an "Administration" section that is a a collapsed field set; select the "Non published" checkbox, and the comment will be unpublished.

If you unpublish a comment, the child comments will still be published; you need to unpublish each of them.

# Answer
> 1 votes
I think by unpublishing the comment you will get the same result. Replies not appearing.

You could use the flag module to provide a 'delete link' flag and then remove the default delete link. You could then at the template level detect whether the comment author has decided they want to delete the comment (i.e. flagged it) and show a message such as "Author removed comment" etc. That way they would still appear in a threaded list.

# Answer
> 1 votes
With http://drupal.org/project/hidden\_comment you can hide a comment without having to give the "administer comment" permission to a role. Even more, you can allow a role to hide comments in their posts.

---
Tags: 7, comments
---


# Question
Title: how to show views for particular language
I have simple problem - there is a view that is aggregating some info and it has a link in the main menu. I'm also using i18n and would like to have that particular view only in one language, but it looks like that it's impossible to make it - I can't find any option how to make the view just in one language - the main menu item appears in both languages and I can't figure out how to disable it. I'm using D7 and newest Views.

# Answer
> 1 votes
Have you tried to use filters? When you create your view, you add a new filter and select "Node translation" from the "Groupes" list and the check "Node translation: Language" and click "Add". Then you can chose language(s) on which you want the view to show

---
Tags: views, routes, i18n-l10n
---


title: Best way to go about my news menu item

text:
# Question
Title: Best way to go about my news menu item
Drupal newb here.

I'm trying to rebuild an existing site into the drupal architecture. For the sake of context, it is a site for a non-profit organisation that wants to make insights in a certain field of scientific research accessible to the general public. Because the organisation is not large I would like to keep the current structure of the site. Now, my first problem is with creation of a menu item for news item. Clicking on that item is supposed to display news items. That's all I want for now.

What I've been trying to figure out reading pfds, surfing the web, watching videos about menu creation and taxonomy et.. for a little more than a DAY now, what is the best way plant this in Drupal (7.7 by the way)?

**1.** \- Create content type called "news item"
\- Create a node using the basic page content type and give as title "News" enter "Latest news" in the body field
\- Go to admin\>structure \> Menu and create a menu item and assign as path www.domain/news/news item \- Each time a news item would be created, the author could then choose "News" as parent menu item.

This approach is obviously ignoring taxonomy. But how does one apply taxonomy to this anyway? As I understand, you can't create a vocabulary and then assign a menu item to that vocabulary name itself, simply because there doesn't seem to be a node that represents a vocabulary name. Correct me if I'm wrong(I kind of hope I'm wrong here).

Of course, You could create a vocabulary called "News" but and then one level below "News" would have to be something like types of news as terms and then use those terms as nodes that I can assign menu items to. The problem is the types of news would be already too granular for the site that I want to rebuild with Drupal. I just want to have a content type newsitems to be children of of a menu item in my main menu called "news".

**2.** Just create a "content" taxonomy and have terms like News, and About, media, bios as terms (and thus menu items) and branch off from there.

This approach also seems besides the point of what taxonomy is trying to accomplish. The uberparent of any vocabulary is "content" for each and every site on the web anyway and doesn't describe anything at all, so what would be the use making a vocabulary out of it then? But then again, does it have to describe anything just as long is works and would it be a relatively decent "creative" solution?

# Answer
> 0 votes
I wanted an automatic way for content to be listed like a "menu". So I created the content type "page". Any time someone post a page I know this is a primary piece of content. So now on the sidebar I list out the pages A-Z. I'm using organic groups, so each page is posted to a group and those pages are only listed on that group, but you could do something similar with taxonomy.

Just my two cents to get around this problem.

# Answer
> 0 votes
Ok, I kind of found my way through it eventually. Still pretty amazing the amount of possibilities. Makes me dizzy.

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


# Question
Title: How can authors choose a different display name?
I am looking to add to the create user feature to allow or display a drop down and or a text field that would allow the user to create a custom display name to associate with the post he or she would be creating.

# Answer
> 3 votes
While this doesn't allow for someone to choose their name per post, it does allow for someone to have a username and a "realname" http://drupal.org/project/realname

You could also just add a text field to nodes where they can fill out any name they want. Then plug that field into your theme instead of the username.

# Answer
> 1 votes
I don't know of any module etc. that would create this functionality.

This doesn't mean that it can't be done.

One way of doing this, would be to add a field on nodes, where the user could enter the author name. If present, you could then change the default author name with the value entered by the user.

---
Tags: 7, theming
---


title: Adding Custom JS to CKEditor

text:
# Question
Title: Adding Custom JS to CKEditor
I'm looking for a way to add custom JS to the CKEditor instance that is being created by the WYSIWYG module.

I posted a feature request on the WYSIWYG module's issue que, but sun suggested I post here as well. http://drupal.org/node/1126656

If you're wondering about why I want to add custom JS, the reason is so that I can adjust WYSIWYG input to more accurately reflect the WYSIWYG output.

# Answer
> 1 votes
You can edit/add CKEditor settings by implementing hook\_wysiwyg\_editor\_settings\_alter(), see Allow configuration of advanced editor settings - comment #52 and later comments for examples.

If you want your own script to run after CKEditor has loaded, maybe How to attach Javascript to a form so that it loads AFTER CKEditor can help you.

---
Tags: 7
---


# Question
Title: Looking for most reliable and compatible (with other Drupal modules) multiple photo uploader and gallery system in Drupal 6 and Drupal 7?
DrupalGardens hosted (Drupal 7) sites use a fantastically easy multiple photo uploader - i.e. one can select multiple image files from an Explorer Browser box (or other OS equivalent) using CTRL, SHIFT and upload them all at once into a gallery.

Question 1) What modules is this based on, so that I can export and deploy a site outside of DrupalGardens?

More importantly:

Question 2) If I was building a Drupal 7 site from scratch with my own hosting, what modules would I need to achieve this?

Question 3) If I was building a Drupal 6 site from scratch with my own hosting, what modules would I need to achieve this?

I wish to stay with Drupal 7 in my consideration as to which version to use. But if Drupal 6 has more rich functionality then I may use that.

# Answer
They use Media Library on Drupal garden but this is only for D7 and it's still in dev. You can also try Cincopa which is really interesting, it's for D6 but they are developping a D7 version
> 3 votes

---
Tags: 7, media, files
---


title: Custom Public form for content type

text:
# Question
Title: Custom Public form for content type
How can I create a form for a specific content type so that it can be accessed publicly, I mean by user that has no administrative rights but on this content type only? I specificly need to hide all options like publication options, menu options etc from the basic form.

Thanks

# Answer
> 1 votes
Theming the default "node/add/content-type-name" content type form will allow you to achieve what you need as these forms are publicly available to users with permission. If the user has permission to create that content type, he will be able to access the page, so either create a link to the page (node/add/content-type-name) or use the default Navigation Menu link "Create Content" to take the user to the node/add page. Take a look at Theme a CCK Input Form for CCK2 & CCK3 to learn more about theming content type forms.

To remove the configuration fieldsets such as Menu Settings, Publishing Options, Revision Information, etc you really just need to change the permissions for the role. For example, remove "administer nodes", "administer menu", "administer comments", etc.

---
Tags: forms
---


# Question
Title: How to create a node programmatically in Drupal 7?
I know you can create nodes programmatically by creating a node object and then firing node\_save() but I don't actually want to store the node in the database.

Is there a way to create nodes of a specific content type in code that show up in the Find Content screens and work with views etc, but are not physically stored in the database.

The reason I ask is that I have a view that lists a series of nodes of a specific content type, but I want to create a custom node in that list that uses PHP to set the content dynamically but if I fire node\_save() will it node get stored in the database every time the module is executed.

I'm also using node reference to link to these nodes so my programatic node will need to work with node reference too.

# Answer
> 4 votes
**You're trying to do a lot there.**

You can do most of what you want without having a node in the database. I think node reference is a sticking point.

Views can be used with a number of back ends, you can get it to point to a different database or index your data with solr and use solr views to search and access your content, there is an issue with using completely external content but you can get round that. Sparql views can allow you to get data from a triple store.

You can populate a node object with fields and use theme node to display it without using node save.

A common pattern is to create stub nodes, which contain only a reference to an external resource and use nodeapi hooks to load the data when the node is viewed. This is often less work and would allow you to use the standard search and node reference functionality.

Without knowing quite why you don't want to save the nodes, it is difficult to make a concrete suggestion.

# Answer
> 3 votes
This link might help:

http://timonweb.com/how-programmatically-create-nodes-comments-and-taxonomies-drupal-7

# Answer
> 2 votes
Node reference works by saving the id of the node that you want to reference. For a node to have a nid, it needs to be saved to the database.

Views works by querying your database. While it is possible to let views use different things to fetch data other than SQL/database it's the only thing I know off that is well supported. I don't believe you can use more than one engine to fetch data, which means that in order for views to get your dynamically created node, you will need save it in the database.

Have you thought about saving a list of the nodes you create instead and update them if needed, instead of create new nodes every time?

---
Tags: 7, nodes
---


# Question
Title: Empty cart functionality with a link, (no form) in Ubercart
I'm trying to make a link (not a form submit) to empty the cart; my link would be /cart/empty.

I can't find where to make a case or something for the URL to work.
I know I have to use `uc_cart_empty(uc_cart_get_id())` to empty the cart.

# Answer
Check Cart Links API page: http://www.ubercart.org/node/1427

So, you have to enable Cart links module (included in Ubercart) and your link will be:

```
http://example.com/cart/add/e

```

Ubercart wil ask for confirmation for this action. If you don't want this confirmation I think you will have to write your own empty cart routine:

Define in your own module hook\_menu an entry for your desired path. Then, assign as callback a function of your own. Inside that function, call `uc_cart_empty(uc_cart_get_id());`

For example:

```
  function mymodule_menu() {
    $items['your/path'] = array(
      'page callback' => 'mymodule_empty_cart',
    );
    return $items;
  }

  function mymodule_empty_cart() {
    uc_cart_empty(uc_cart_get_id());
    return 'Your cart has been emptied.';
  }

```

Note that have to provide a message to show the user.

If you want to use the link with AJAX (so no page reload is done) you will need to something like this:

```
 function mymodule_menu() {
    $items['your/path'] = array(
      'page callback' => 'mymodule_empty_cart',
      'type'          => MENU_CALLBACK
    );
    return $items;
  }

  function mymodule_empty_cart() {
    uc_cart_empty(uc_cart_get_id());
    print 'done';
  }

```

You will have to add the jQuery code to do the AJAX call. The print statement is sent back to user's browser but it will not be shown (at least if you do not show it to the user in your jQuery code).

For both examples you may adjust the other menu options (access restrictions, for example). Check hook\_module documentation: http://api.drupal.org/api/drupal/modules--system--system.api.php/function/hook\_menu/8
> 4 votes

---
Tags: forms, ubercart, navigation
---


# Question
Title: Display a node counter, by specific content type?
How can I display a counter e.g. Total News: 999, Total Blog posts: 123, etc. ? (looking for d6 solution actually)

# Answer
Use the Count Nodes module.

> The Count Nodes Module counts total number of nodes created(published and unpublished both) in each content type. It provide a total number of blocks equals to the total number of content types created such that administrator can use one block for each content type.
> 2 votes

---
Tags: 6, nodes
---


title: Create nodetype with cck fields

text:
# Question
Title: Create nodetype with cck fields
Any clues or examples how to programmatically create node types with cck fields in Drupal 6? I would like to create a content type with has a cck file field in it. The Example module has an example of creating a node type but it does not utilize existing cck fields.

# Answer
This blog post explains one way to do this: http://www.openbandlabs.com/blog/2009/06/programmatic-cck-content-type-creation
> 1 votes

# Answer
You can use Features module.

This module allow to export not only a content type, but a lot of other configurations.

In your case just define your content type, and then go to Features admin pages, click the 'Create new feature' link, fill the form and select Content Type on the select widget and then tic your content type in the contetn types that is shown on the right. Then just click export. This gives you a zip file with a autogenerated module with your content type. Just install in your site as a normal module, go to the Features admin page (you need Features to enable it) and enable that module/feature.

Benefits of using this method is you can update your content type. Just edit your content type in tyour first site, generate your module again (click regenerate) and deploy in your second site. Then go to Features admin pages and you will see your module/feature mark as 'Overriden'. Just use the revert function to update (revert your content type to what is in the module code).

Features is a powerfull module, but use with caution: if you put many things inside a feature (content types, menu, permissions, etc) you may have some conflicts later (may be not, but is better to start using it with small features).
> 0 votes

---
Tags: nodes, entities
---


# Question
Title: Is there a way to pass many arguments and not have an ugly url?
I'm writing a module that displays graphs based on a selection of arguments (an array with items to display, a daterange and some other stuff). This results in a long and ugly url.

Is there a way to get the arguments to the page with the graphs without putting everything in the url for that page? I'm looking for something that can keep temporary variables with a short reference that I can pass in the url, but haven't been able to find anything.

I'm using Drupal 7.

# Answer
The solution turned out to be a simple one: put the urls with an index in the session, pass the index as an argument to the next page and once there lookup the url again in the session.
> 0 votes

# Answer
You could use form submission or cookies to store values, but neither of these are a particularity good ideas.

I would recommend (if you don't like the URL showing) using AJAX to retrieve/update the graph. You still have the ugly url but you hide it inside the ajax request.

So your module displays

/mypath

but the request could be

/mymodule/displaygraph/x/as/32432/s///
> 1 votes

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


title: Why is jQuery .focus not firing?

text:
# Question
Title: Why is jQuery .focus not firing?
In the code below, the first `alert()` fires, but the second one never fires when I click the textfield assigned with the 'clear' class.

Does anyone have a clue why this happens?

```
(function ($){

   alert('TEST 1');
   var clearMePrevious = '';

   // Clear input on focus.
   (function ($)('.clear').focus(function() {
     alert('TEST 2');
     /*
      if ($(this).val() == $(this).attr('title')) {
        clearMePrevious = $(this).val();
        $(this).val('');
      }
      */
    }(jQuery));

}(jQuery));

```

The problem is just in the inner code, as `$document.ready()` fires the `TEST 1` alert.

I have tried different variations of `(function ($){});` and `function (jQuery){});`.

# Answer
Your formatting made me twitch, so I fixed it up for you.

Drupal JS Coding Standards

Also you weren't using a behavior, so I fixed that too:

Javascript in D7

```
(function ($) {
  Drupal.behaviors.textFieldClearer = {
    attach: function (context, settings) {
      var clearMePrevious = '';

      // clear input on focus
      $('.clear').focus(function() {
        if($(this).val() == $(this).attr('title')) {
          clearMePrevious = $(this).val();
          $(this).val('');
        }
      });

      // if field is empty afterward, add text again
      $('.clear').blur(function() {
        if($(this).val() == '') {
          $(this).val(clearMePrevious);
        }
      });
    }
  };
}(jQuery));

```
> 2 votes

# Answer
It turns out I misunderstood the documentation: `$` is accessible inside a `(function ($){}` block. The trick is that you really need to add the `$(document).ready()` call to have the selectors accessible after the page loads.

```
(function ($) {
  $(document).ready(function() {
    var clearMePrevious = '';

    // clear input on focus
    $('.clear').focus(function()
    {
        if($(this).val()==$(this).attr('title'))
        {
            clearMePrevious = $(this).val();
            $(this).val('');
        }
    });
    // if field is empty afterward, add text again
    $('.clear').blur(function()
    {
        if($(this).val()=='')
        {
            $(this).val(clearMePrevious);
        }
    });
  });
})(jQuery);

```
> 1 votes

---
Tags: javascript
---


# Question
Title: JQuery Causes Seemingly Endless Loop and page load times of 1 minute + - "Warning: reference to undefined property D.cache[a][d]"
The rendering of my pages on my website have slowed down drastically. When I turn on the error console I get the image below that shows the error:

```
Warning: reference to undefined property D.cache[a][d]

```

You can see a screenshot below:

These warnings continue until the browser memory becomes bloated, the browser locks up, or the page simply takes over a minute to load!

I am at a loss for how to debug this issue b/c when I open the file cited in the warning, it is the long minified jquery script.

How can I go about fixing this issue?

# Answer
This is obviously not a problem in Drupal core. This mean the the issue is in one of three places:

* The theme
* Custom module (developed by you)
* Contrib module from Drupal.org

I can think of two approaches to go about and fix this.

**Debugging**

Replace the minified JS file(s) with non minified versions and start debugging.

**Experiment**

Try disabling modules/theme at turn until the problem disappears and try to pin point the part in the module/theme that causes the problem and from there try to find a solution.

Personally I would go for the experiment route, as this is often the fastest way to gain initial results.
> 2 votes

# Answer
The error comes from misc/jquery.js, and happens even when going through the installation procedure. So nope, it doesn't come from contrib, theme or custom module, but from core itself.

After looking further into things, it seems to be JQuery-specific. I replaced the jquery.js file with the most recent, minified version. Problem still arised. Then with the most recent development (so not minified) version. Problem still exist. Then did the same thing with jquery.form.js. Still no solution.

Now, though, if I look at the errors it gives me (only on pages with JS, like the modules page, or the progress bar during installation), I get explanations like this for the errors:

```
Jquery.js, ln. 2525:
anonymous function does not always return a value
return;

Jquery.js, ln. 443:
anonymous function does not always return a value
else return;

Jquery.js, ln. 444:
anonymous function does not always return a value
},

```

So the endless errors seem to come from Jquery itself. Not sure how to fix this (besides the obvious fixing every line it reports), but will look further into this.

**Edit:** Ok, like any good IDE where you can turn off warnings and show only errors (which isn't to say you got to ignore warnings. They're there for a reason), you can turn them off in Firefox too.

In the URL bar, type in about:config. In the filter field, type in javascript. One of the options shown, should be something like javascript.options.strict. Set it to FALSE and you're done. The endless list of warnings is gone. Let's just hope the Jquery folks'll fix it someday.
> 0 votes

# Answer
Turn off strict mode in your browser.
> 0 votes

---
Tags: caching, javascript
---


title: Drupal Caching strategies

text:
# Question
Title: Drupal Caching strategies
I read this interesting article on Drupal caching, but I'm not sure which caching method I should be using.

My code is implementing a menu callback, and returning a renderable array.
What is the difference between method #1 and method #2?

**Please see the question embedded as a comment in method#2**

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

// Method #2.
function my_module_menucallback() {
  // ** Do the calculations and population of $render_array that would occur here
  // get called repeatedly if this method of caching is used??? **

  $render_array ['my_content'] = array(
    '#cache' => array(
      'cid' => 'my_module_data',
      'bin' => 'cache',
      'expire' => time() + 360,
      ),
    // Other element properties go here...
    );
  return $render_array;
}

```

Please ignore the time specified, as this is just sample code.

# Answer
So I tested and there is a significant difference between the two that I failed to understand originally. Calculations **not** surrounded with ...

```
$render_array = &drupal_static(__FUNCTION__);
  if (!isset($my_data)) {
    if ($cache = cache_get('my_module_data')) {
      $render_array = $cache->data;
    }
    else {
      // Do your expensive calculations here
      cache_set('my_module_data', $render_array, 'cache');
    }
  }

```

...are executed **every time** the menu callback function is called (every time user visits that page).

Method #2 caches only the final, rendered output. So if your calculations/processing in the method has changed the output value and you've cached the rendered output, you will not see the updated value until the cache is cleared.
> 1 votes

# Answer
I think, but I'm not sure (we shall do some benchmark for it), that the second method is a little bit slower than the first one.

With the first method, you call directly the lower functions to set the cache and get the cache. With the second method, according to the documentation and code, severals checks are done before calling `cache_set()` and `cache_get()`. In the other hand, you already rendered the code.

I think the use of one or another method depends on what you need, raw data or directly rendered code.
> 0 votes

---
Tags: 7, caching
---


title: Add image field programatically in D7

text:
# Question
Title: Add image field programatically in D7
I'm moving a bunch of info from an xml feed into drupal nodes. I'm a little hung up on adding the image. I'm using php `copy()` to copy the image from a url to my drupal directory. From here, I'm not sure how to insert the field info into the node in such a way that an fid and all of the required data is generated. What is the preferred way to do this?

# Answer
> 1 votes
OK, what I came up with here:

```
function save_my_image($uri) {
  //copy file into drupal files directory
  $contents = file_get_contents($uri);
  //then save into drupal's file system
  $file = file_save_data($contents);
  return $file;
}

```

`file_save_data()` (http://api.drupal.org/api/drupal/includes--file.inc/function/file\_save\_data/8) will handle creating an fid for the file and keeping track of it generally.. then simply add the fid to the node in question and you should be golden.

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


# Question
Title: hook_block_view called multiple times per request
I am creating a module for Drupal 7 that implements the hook\_block\_view. I make a call to watchdog in the hook method and I noticed (while debugging) that the the watchdog method is firing three times per page refresh. Is this normal, or is it something I should be worried about. Since each call to the method makes a database query it seems that this could result in a performance hit.

# Answer
> 5 votes
It gets called everytime the block is rendered. Truthfully, that is a bit wasteful since the params it is passed are the same. Still, in the normal block system, each block only loads once (i.e. it can only be in one region). This makes the logic forgivable, but yeah, it should be cached. You can of course cache it yourself in your hook\_block\_view implementation.

Disclaimer: I am drunk.

---
Tags: 7, blocks, hooks
---


# Question
Title: Region with block shows up in admin preview, but not on site
I'm new to drupal and a bit confused by this. Using the standard Bartik theme (Drupal install 7.8) I see a search bar on the sidebar. Checking the Structure \> Block it shows that the search is included in the Bartik theme on the sidebar. The preview while an admin shows the search.

However, as soon as I log out the entire sidebar\_first region does not show. Just the content area.

EDIT: When adding a login box to the sidebar it does appear, however, the searchbar, and navigation do not. There are NO RESTRICTIONS applied.

EDIT2: View the screenshots below to see my settings.

Normal User sees:

Admin User sees:

Current settings for navigation block:

# Answer
You've to allow anonymous use to access the search form, to add this permission, you've to go People \> Permission and search "Search" and check the box "Search content".
> 1 votes

---
Tags: blocks, theming
---


# Question
Title: Make some text of the calendar module multilingual?
I instaled and got running fine the 'calendar' module. I just need to make some texts multilingual.

This module generate a view which shows a monthly calendar, then you can change to weekly canlendar, day calendar and so on.

To switch between this display this module show some links above the calendar. The text for these link are what I need to make multinlingual (see picture 1)

These links are taken from the name of the display of the view (see picture 2)

How can I accomplish this. Thanks

# Answer
> 0 votes
The calender links are defined in the calendar/theme/theme.inc in the function `function template_preprocess_calendar_main(&$vars)` here you can see that the `$calendar_links` use the function `date_t()` as found in the date\_api.module and can be translated. In other words, if i am correct, you can translate this through the translate interface, as found on admin/build/translate.

---
Tags: views, i18n-l10n, datetime
---


# Question
Title: How to create block with custom embed code in D7?
I am trying to create a custom block with the following embed code in D7:

```
<form style="border:1px solid #ccc;padding:3px;text-align:center;"     action="http://tinyletter.com/pumpbeat" method="post" target="popupwindow" onsubmit="window.open('http://tinyletter.com/pumpbeat', 'popupwindow', 'scrollbars=yes,width=800,height=600');return true">
  <p>Enter your email address:</p>
  <p><input type="text" style="width:140px" name="emailaddress"/></p>
  <input type="hidden" value="1" name="embed"/>
  <input type="submit" value="Subscribe" />
  <p><a href="http://tinyletter.com">A TinyLetter Email Newsletter</a></p>
</form>

```

In D7 I go to Structure \> Blocks \> Add block, then paste the embed code into the Body field, and choose PhP code as the text format (I have also tried plain text and full html, without success).

However, rather than displaying the desired widget the new block displays the embed code above.

Please note that I also have the WYSIWYG module installed (with CK editor).

I would really appreciate any help in solving this problem. Thanks!

# Answer
WYSIWYG editor sees this code as a normal text.You should copy this text in source(There is a source or html button in WYSIWYG toolbar) or disable rich text box and then copy it to your text area.

Also you should use drupal form api to insert forms to your pages.
> 3 votes

---
Tags: 7, blocks
---


# Question
Title: Using drupal to run a download website with about 10K files
I want to run a website which has more than 10000 files available for download.Is sites/default/files a good place to store the files? I see some websites store their files in someting like server1.example.com/file1.zip or drupal.org uses ftp for project files.

Which one should I use?

# Answer
It depends on how do you want to manage/upload your files. You can put your files in sites/default/files but create a new vhost (with or without the same web server with your primary site) at files.example.com to give access to this folder. Also, it depends on whether you want access control to your files. If you don't want public access to those files, you should use the vhost, but use something like X-Sendfile header to reduce server load.
> 1 votes

---
Tags: 7, files
---


# Question
Title: Proper with "Executing Custom PHP Code" Action
I am trying to add an action that "Executes Custom PHP Code". I click Add a new action to the rule I have created and I choose "Execute Custom PHP Code" from the drop down the loading spinner appears for a couple of seconds and then disappear. The only thing I can do is click Continue which does nothing.

Then when i navigate to another page I receive the follow error

> Value field is required.
>
> The integrity check failed with the following error message: "Missing configuration for parameter code."

Has anybody got any idea why this is coming up.

It sounds like a box is supposed to appear but it doesn't.

As far as I can see I have all the right modules installed. (PHP filter, Rules, Rules Scheduler, Rules UI, Trigger).

Oh I am using Drupal 7.7 (I am planning on upgrading to 7.8 later today)

Thanks

Conor

# Answer
> 1 votes
Okay I solved it, It turned out to be very simple. *Facepalm*

I had misconfigured nodejs which was causing a javascript error. Which meant the textbox which should've appeared didn't.

I reconfigured nodejs and it worked fine :)

---
Tags: 7, rules, actions
---


# Question
Title: Rendering a simple PHP array into an HTML table
I am trying to render a simple PHP array witch isn't a drupal render array, basicly it s something like this:

```
array(
  array(
    'Some Index:',
    ' Some value',
  ),
  array(
    'Some Index:',
    'Some value',
  )
);

```

I would like to render it as an HTML table, is there any out of the box API to do that ?

Thank all for the help,

Cheers

# Answer
Assume you have code similar to this:

```
$table_data = array(
  array( 'Some Index', 'Some value'),
  array( 'Some Index', 'Some value'),
);

```

In this case, just call `theme('table', array('header' => array(), 'rows' => $table_data));`.

This will call `theme_table()`, unless your theme overrides that particular theming function. Any override, however, should expect the array to be structured in the same way as described for `theme_table()`, so look there about the specifics. In particular, you might want to replace `'Some Index'` with `array('data' => 'Some Index', 'header' => TRUE)` to indicate that this cell is a table header cell.
> 5 votes

---
Tags: 7, theming
---


# Question
Title: Link To Already Defined Path In Menu Using hook_menu()
I'm sure this is an obvious answer but I seem to be missing something important.

How can I add a link to a menu **using hook\_menu()** to an already defined path?

I'm trying to add a direct link to a node/add page that already exists.

I need to use hook\_menu() instead of the control panel.

# Answer
You can best use hook\_menu\_alter(), which should be used when "Additional items may be added, or existing items altered."

In *custom\_node\_add.module* :

```
function custom_node_add_menu_alter(&$items) {
  if (aray_key_exists) { //some sanity checking;
    $items['node/add']['page callback'] = 'custom_node_add_page'
  }
}

function custom_node_add_page() {
  return t("Hello World! This is content on my node/add page");
}

```
> 2 votes

# Answer
I really should have spent more time searching. The following works beautifully in `hook_menu();`

```
$items['customeurltocreate/nodetype'] = array(
        'title' => 'Create Node Type',
        'page callback' => '_menu_create_node_type',
        'type' => MENU_NORMAL_ITEM,
    );

function _menu_create_node_type() {
    module_load_include('inc', 'node', 'node.pages');
    return node_add('node_type');
}

```
> 0 votes

---
Tags: 7, routes
---


title: Instant Search for Drupal 7

text:
# Question
Title: Instant Search for Drupal 7
Are there any 'instant search' modules (similar to Google's instant search) available for Drupal 7?

I found the Drupal 6 modules listed below, but neither of them seems to be available for Drupal 7, yet.

# Answer
> 2 votes
You should use the Finder module; I haven't used the D7 version yet, but the Drupal 6 version worked well for my needs.

---
Tags: 7, search
---


# Question
Title: Theme Drupal Form API checkboxes as a grid
I have a custom form that displays a form element of about 2 dozen checkboxes. I would like to output them 3 per row, in a table if possible. How can I go about doing that?

```
$form['preference'] = array(
    '#type' => 'checkboxes',
      '#default_value' => 1373,
    '#required' => TRUE,
    '#title' => 'Choose all that apply',
    '#options' => $preference_options,
    '#prefix' => '<div id="preference-options">',
    '#suffix' => '</div>',
  );

```

# Answer
> 8 votes
First, define a custom theme function with hook\_theme() and assign it to the form element with #theme.

In that theme function, you can use expand\_checkboxes to convert it into an array of separate checkbox elements. Then, re-structure it into an array with 3 elements each, render the checkboxes and pass it to theme\_table().

Something like this, all untested.

```
function theme_yourmodule_preference($element) {
  $elements = element_children(expand_checkboxes($element));

  $rows = array();
  for ($i = 0; $i < count($elements); $i += 3) {
    $row = array(drupal_render($elements[$i]));
    // The following two might not always exist, check first.
    if (isset($elements[$i + 1]) {
      $row[] = drupal_render($elements[$i + 1]);
    }
    if (isset($elements[$i + 2]) {
      $row[] = drupal_render($elements[$i + 2]);
    }
    $rows[] = $row;
  }
  return theme('table', array(), $rows);
}

```

# Answer
> 4 votes
I adapted Berdir's solution for display in columns and Drupal 7. Thought I'd share it.

```
function yourmodule_theme() {
  return array
      (
      'form_yourmodule_form' => array
          (
          'render element' => 'form'
      ),
  );
}

function theme_form_yourmodule_form($variables) {

  $form = $variables['form'];

  $element = $form['checkboxelement'];
  unset($form['checkboxelement']);

  $elements = element_children(form_process_checkboxes($element));

  $colnr = 3;   // set nr of columns here

  $itemCount = count($elements);
  $rowCount = $itemCount / $colnr;
  if (!is_int($rowCount))
    $rowCount = round((($itemCount / $colnr) + 0.5), 0, PHP_ROUND_HALF_UP);
  $rows = array();
  for ($i = 0; $i < $rowCount; $i++) {
    $row = array();
    for ($col = 0; $col < $colnr; $col++) {
      if (isset($elements[$i + $rowCount * $col]))
        $row[] = drupal_render($element[$elements[$i + $rowCount * $col]]);
    }
    $rows[] = $row;
  }

  $variable = array(
      'header' => array(),
      'rows' => $rows,
      'attributes' => array('class' => 'checkbox_columns'),
      'caption' => NULL,
      'colgroups' => NULL,
      'sticky' => NULL,
      'empty' => NULL,
  );

  $output = theme_table($variable);

  $output .= drupal_render_children($form);

  return $output;
}

```

I found an even easier solution: there is a module for this! Multi-column checkboxes radios

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


# Question
Title: How can i programmatically trigger a Lightbox window using Drupal
I'm creating a new module for a Drupal 7 site, and I was wondering if it is possible, using Drupal's AJAX functionality, to trigger a Lightbox window programmatically with PHP.

I have looked into the `ajax_command_invoke()` function, but unfortunately it doesn't seem to do what I need.

Edit: I would either like to run a custom function which would trigger the lightbox via `$('#id').ceebox().trigger('click');` or using another way to programmatically achieve this. (This is an example I have taken off from a non-Drupal project.)

# Answer
> 2 votes
I achieved this by using `ajax_command_invoke(NULL, 'nameOfCustomFunction', array('select'));` with the following JavaScript code:

```
(function($) {
  $.fn.nameOfCustomFunction = function(data) {
    alert(data);
  };
});

```

---
Tags: ajax, javascript
---


# Question
Title: How to override page.tpl.php with view's template file
I am using D7 and view3 (beta). I created a view named employee with a template for the field first\_image, **views-view-field--employee--page--field-first\_image.tpl.php**. When I rescan the theme information, this template became bold. It worked fine (When clicking the image, a slim box will show).

But I inserted this view in a basic page using insert view2.x dev module with tag **\[view:employee\]**. But this time my template file doesn't show and seems to be broken. How can I solve this?

# Answer
First you define a specific display in your template: views-view-field--employee--**page**--field-first\_image.tpl.php.

Then you don't specify a display in your insert tag, making it fallback to *default*.

To fix your problem you need to either strip the display part of your template name or specify a display in your tag, like \[view:employee=page\].

I would probably go for the first solution, so your theming targets all possible displays of that view, but how you do it really depends on your implementation.
> 3 votes

---
Tags: views, theming
---


# Question
Title: On Feed API, what does the setting "Delete news items older than:" mean?
Using FeedAPI on a site I just started working on (but getting ready to get rid of it), and I don't understand this setting:

"Delete news items older than:"

Does that mean "delete unpublished items after a set time"? Or "delete published items we've turned into posts after a set time"? Or just "ignore items coming in from a given feed if they're older than this?"

Or something else altogether?

# Answer
This setting does two things:

1) When reading from a feed, ignore items older than this setting.

2) On cron, delete *all* node feed items older than this setting.
> 0 votes

---
Tags: feeds
---


# Question
Title: How to customize the admin toolbar in Drupal 7?
I'm trying to customize the administration toolbar in Drupal 7 but I don't know how to do it. I'd like to add custom links (e.g node/add/\[content-type\]) and links that are only available for specific users.

\[Edit\] Finally, I used admin\_menu module and I added a menu item with a custom module using hook\_admin\_menu\_output\_alter

# Answer
> 0 votes
Use the shortcut module that's in core, that's what it's for. The Toolbar wasn't designed to add custom links because the shortcut bar was (from what I understand). Ironically the Drupal 6 backport module of the module does have this feature.

# Answer
> 1 votes
Take a look at the Quickbar module.This is a simple administration toolbar. It allows you to take any menu and assign it to a role. This menu will be displayed at the top of your page as an administration toolbar.

You could also look at the Manager module. It includes the Manager's Bar. An admin-bar designed for users that aren't familiar with Drupal. It is like the default "Navigation" menu, when we cut off everything that doesn't matter to this users, and it looks like some known admin-bar-modules, like Admin Menu, but a lot more simple.

---
Tags: 7, theming
---


# Question
Title: Resource for understanding Drupal Core functions?
I'm looking for something to help me understand drupal core and its functions. I've gotten a hang of writing modules, and I've found plenty of resources, such as books and blog posts. But I'm still stumbling when I find I'm needing to manipulate basic core functions such as creating nodes or manipulating users.

Of course, there is the documentation of each function, but it doesn't tell you much beyond what that function does.

For instance, I wanted to create some nodes automatically in my module. I know about `node_save`, but I didn't know what fields I had to set in order for my new node to be saved properly. The documentation says that `node_save` saves a node to the database -- so it doesn't tell you anything more than what the function name already says. My node creation in my module is not working. Then I hear somewhere along the about about `node_save_prepare` for creating new nodes -- maybe I need to do that? But its documentation says that it prepares a node for editing. So I look in my module dev resources, and they talk about the various hooks... which assume some basic understanding of core functionality. So after some more hacking and trial and error, I get my nodes created... with the title only. Do I set the body with `$node->body = "blah"` or `$node->body[0]['und']['value'] = "blah"` (and what is all that stuff, anyway)?

Of course I can source dive, but that doesn't really tell you any more about the right way to do things. So I'm looking for something comprehensive about "how do to things". Does there presently exist such a resource?

One book I have read is Pro Drupal 7 Development, and while it's a great resource for understanding hooks, it doesn't go into core functions in a comprehensive, foundational way.

**Please note:** It's okay to answer "No such single comprehensive resource exists" or "You'll have to piece it together from multiple sources." If that's the reality of the situation, I want to know that rather than continuing my holy grail quest. I'm not looking to be pointed to more piecemeal resources. I'm asking if there's one comprehensive one for understanding core api functions.

# Answer
The Examples module is a good way to see "how to do things". Another useful tool is grep - you can download all of contrib, and search for examples where other developers have implemented the hook or function that interests you. You can "upgrade" to `ack` for more powerful searching. The book "Pro Drupal Development" used to be a good resource, but sadly the 7.x edition is rubbish.
> 1 votes

# Answer
I would highly recommend two books.

Pro Drupal Development is a must have, though the D7 version isn't as good as the previous versions.

Drupal 7 Module Development is also a good reference.

The other thing you can do is find modules that you are familiar with (ie, those that you have been using) that do similar tasks and look at the source code. drush hooks can also be enlightening.
> 0 votes

---
Tags: 7
---


title: HTML in Menu title

text:
# Question
Title: HTML in Menu title
I want to be able to add HTML tags in the Menu title - line breaks, italics, etc. I've gotten as far as needing a custom function in my template.php file. Something about "theme\_menu\_link?"

# Answer
> 1 votes
If I understand well your question, I guess that you can use Jquery. You can manipulate the html outside the text that you want. See this functions (with examples) to manipulate your html http://api.jquery.com/category/manipulation/

# Answer
> 0 votes
This is a potential security risk, so be sure to only let trusted users have permissions to do this. You can use the Menu HTML module. HTH

---
Tags: routes
---


title: Using a CDN for jQuery and jQuery UI

text:
# Question
Title: Using a CDN for jQuery and jQuery UI
For my Drupal 6 site, I'd like to get the latest jQuery and jQuery UI from Google CDN. Although this seems like something that many people would want to do, it seems that it isn't so easy.

The Advanced CSS/JS Aggregation module seems promising, but after installing it and trying to use the Google CDN in the standard way, for example using `drupal_set_html_head()` to add the following lines in `<head>`, those files aren't available.

```
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.14/jquery-ui.min.js"></script>

```

How can I get the latest jQuery and jQuery UI from a CDN like Google CDN?

# Answer
> 2 votes
Drupal 6 ships with jQuery 1.2.3 and the jQuery Update module can push it to 1.3.2. You are trying to use a much more recent version of jQuery than Drupal 6 can handle. Drupal uses a lot of jQuery in its workings, so it isn't straightforward to put a new version on top.

Otherwise, those files are available in https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.14/jquery-ui.min.js.

# Answer
> 0 votes
You can use the lastest version of JQuery and JQuery UI in Drupal 6 by using jQuery.noConflict(). This will allow you to have both multiple versions of the library for specific needs.

See the Drupal documentation here:

Using Newer Versions of jQuery with Drupal 6

---
Tags: javascript, cdn
---


title: In hook_boot jQuery is undefined

text:
# Question
Title: In hook_boot jQuery is undefined
I am doing some processing in `hook_boot` since I need that code to run on every page, irrespective of whether or not they are cached.

As a result, jQuery is undefined when I add inline JavaScript to the page.

```
function hook_boot() {
  drupal_add_js("jQuery('document').ready(function() { //do });");
}

```

The idea is that we will potentially load a lightbox on every page after processing in `hook_boot`.

The only way I can see round this is using `variable_set` and then retrieving that in another hook (e.g `hook_node_*`). However, that might not be sufficient since we need it to run on *every* page.

How would you get round this?

# Answer
> 1 votes
If you add the JavaScript in hook\_init, then it will be there the next time the page is served from the cache.

And if the page is served from the cache, then calling drupal\_add\_js in hook\_boot will not add JavaScript to the page, because the page is not assembled from calling the page callback, but is served from the cache.

Use hook\_init instead of hook\_boot.

# Answer
> 1 votes
I would write a menu hook that replies with "yes, run a function" or "no, don't run a function" (eg, your conditional logic's answer) and is called on every page via ajax. You don't have to worry about expiring your caches that way.

# Answer
> 1 votes
You can't have it both ways - if you use the page cache than you lose the ability to deliver a unique response tailored to each visitor.

The answer is usually to serve the same script to all anonymous users, and move the conditional logic into the script itself. If you are switching based on some user action or input, you can store the user data in a cookie or localstorage.

---
Tags: 7, hooks, javascript
---


# Question
Title: How do I display a Taxonomy Term Description to a view in D7?
I would also like to know how to display a custom field that you add to taxonomy terms.... D7

# Answer
You will have to add a *relationship* to include the term data for the content(?) you are listing – then the term description will be available as regular View fields.

You can check out Learn Views with NodeOne, part 11: Relationships for a quick video on managing relationships.

Good luck!
> 5 votes

---
Tags: taxonomy-terms
---


# Question
Title: Altering ImageField Widget with FUpload enabled
I need to alter the ImageField Widget so that I can add some fields other than the Description, Alt and Title fields. I'm able to do this when I select the file field widget type as Image Uplaod, but when I select the FUpload widget type, the changes don't take effect. Here's the code I'm using:

```
function bridge_widgets_imagefield_extended_widget($element, $extra_values) {
  // If you need the field or widget to conditionally add a FAPI field, use these.
  $field = content_fields($element['#field_name'], $element['#type_name']);
  $widget = $field['widget'];

   if( $element['#type_name'] == 'property_gallery'  ){
  global $user;
  user_load($user);
  return array(
    //This will Replace the Textfield with dropdown select for the description
    'revise' => array(
      '#type' => 'checkbox',
      '#title' => t('Revise This Description'),
       '#default_value' => isset($extra_values['revise']) ? $extra_values['revise'] : 0,
         '#attributes'=>array('class' => 'revise-check')
       ),
    'revisedby' => array(
      '#type' => 'textfield',
      '#maxlength' => 64,
      '#title' => t('Revsied By'),
     '#default_value' => ($extra_values['revise']==0) ?  NULL : $extra_values['revisedby'] ,
       ),
       'revisedon' => array(
      '#type' => 'date',
      '#title' => t('Date'),
     '#default_value' => ($extra_values['revise']==0) ?  NULL : $extra_values['revisedon'] ,

       ),

  );
  }
}

```

# Answer
> 0 votes
I guess it is the line

```
$element['#type_name'] == 'property_gallery'

```

that makes your changes have/not have effect.

I would actually suggest writing a new widget alltogether, instead of altering the existing one(s). It isn't that difficult, but I don't know of any good tutorial for it online – there is a good chapter about it in the book "Drupal 7 Module Development" though, which helped me a lot.

If you find a good online tutorial, please post the link!

---
Tags: entities, media
---


# Question
Title: How to make a blog tab in every user profile
I have enabled the Blog module in order to have a blog for every user. Now I want to create a tab in each user profile that it links to that user's blog.

Is it possible? How can I do this?

# Answer
You can also do this by either using the Views module or the Page manager module, without any custom coding:

* With the Views module, you could create a list of all blog posts by a user, and display that as a tab on the user's page. However, it would not be *the same* list as the one the Blog module creates (though it could look the same). A guide for using Views can be found here: http://nodeone.se/blogg/learn-views-with-nodeone-part-1-overview – in particular check out episode 21 for this use case.
* With the Page manager module, you could create a tab that redirects to the blog list page for that user. However, the visitor would end up on the blog list page – which *does not* have tabs for returning to the previous page. See Learn Page manager! for an introduction to this module.

In general, I would recommend that you build your own blog using custom content types and the Views module – it will give you more flexibility in the long run.

Good luck!
> 0 votes

# Answer
Using a custom module, you can implement `hook_menu()` in the following way:

```
function mymodule_menu() {
  $items['user/%user/blog'] = array(
    'title' => 'My blog',
    'page callback' => 'blog_page_user',
    'page arguments' => array(1),
    'access callback' => 'blog_page_user_access',
    'access arguments' => array(1),
    'file path' => drupal_get_path('module', 'blog'),
    'file' => 'blog.pages.inc',
  );

  return $items;
}

```

The "file path" property is used because the module that defines the menu is not the one containing the "blog.pages.inc" file.

If you have few experience on how to create a Drupal module, you should start looking at:
> 1 votes

---
Tags: users, nodes
---


title: Drupal ignores check_markup()

text:
# Question
Title: Drupal ignores check_markup()
It seems like Drupal is ignoring `check_markup()`. What is wrong with the code below?

```
print check_markup($node->body, 'microblog', TRUE);

```

Site's default input format filter is = 'Filtered HTML'. All users have access to the 'microblog' filter, but I see my 'microblog' filter is kind of not working, and it uses filtered HTML.

What am I doing wrong?

# Answer
In Drupal 6, the second argument of `check_markup()` is the value of the "format" field in the "filter\_formats" table; it is a serial field, which means it can contain only numbers.

The documentation for the function doesn't specify what you should pass; it uses a phrase that could be misunderstood, but it doesn't talk of format name.

> `$format` The format of the text to be filtered. Specify `FILTER_FORMAT_DEFAULT` for the default format.

Looking at how the function is called in node\_prepare(), I noticed the code that calls the function is the following one:

```
  if ($teaser == FALSE) {
    $node->body = check_markup($node->body, $node->format, FALSE);
  }

```

The content of `$node->format` is always a number, in Drupal 6.

In a standard installation of Drupal 6, without any extra modules installed, these are the values for the format ID to pass to `check_markup()`:

```
Format ID     Input format
---------------------------
1             Filtered HTML
2             Full HTML
3             PHP code

```

To get the format ID knowing the name (e.g. "Filtered HTML"), you should use code similar to the following one:

```
$format_id = db_result(db_query("SELECT format FROM {filter_formats} WHERE name = '%s'", $format_name));

```

The format ID required from the function is different from a filter ID: An input format is a set of input filters that are used together to filter out or change what entered from users. What the modules implement are input filters.
> 6 votes

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