title: Tracking down pesky PHP 5.3 errors

text:
# Question
Title: Tracking down pesky PHP 5.3 errors
We have a site that is throwing errors when uploading files to a simple "Page" node. I've done a lot of work trying to track down the actual source of the error, and I posted a half dozen messages to various likely threads at drupal.org.

The errors we get on file attach/upload:

> warning: Parameter 2 to wysiwyg\_form\_alter() expected to be a reference, value given in /var/www/drupal/includes/common.inc on line 2892.
>
> warning: Parameter 2 to simple\_access\_form\_alter() expected to be a reference, value given in /var/www/drupal/includes/common.inc on line 2892.

I understand about passing by reference versus value. I understand about fixing the problem in the offending module by using the two calls to `drupal_alter()`, as described on http://drupal.org/node/930992#comment-4066840, but so far I have not been able to find what module is making the call incorrectly.

I tried installing and enabling the same set of modules on a test site but cannot reproduce these errors.

It's hard to post a bug report when you don't know the offending module.

See also http://drupal.org/node/1200970#comment-5463436.

# Answer
> 1 votes
Assuming you do not have a debugger going (getting XDebug to run for your local development environment is probably the single most useful thing you can do the entire year), you could use debug\_backtrace() at the place of the error (i.e. in the two form alter functions) to find out what is calling them. If you shoot its output into watchdog(), hopefully you can cross reference the time of the error with a particular invocation of these functions. Do be aware that these are form alter hooks, which get called for each and every form Drupal is building (and you might be surprised there can actually be several forms on a single page; just think of search and login forms). I.e. not every call will be the offending one.

# Answer
> 0 votes
The errors reported are for functions contained, respectively, in the Wysiwyg module and the Simple Access module. `wysiwyg_form_alter()` is the implementation of hook\_form\_alter() done from the first module, and `simple_access_form_alter()` is the implementation of the same hook done from the second module.

The function names of function implemented from a module are generally prefixed by the short name of the module. In the case of hook implementations, the list of the hooks used by Drupal is listed under Hooks (Drupal 7) and Hooks (Drupal 6); that helps because the hook name is the second part of the hook implementation.

For example, `wysiwyg_form_alter()` could be the function implemented by a module using "wysiwyg\_form" as short name, but looking at the installed modules, you will see that you don't have any "wysiwyg\_form.module" file; instead, you have a "wysiwyg.module" file that is generally inside a "wysiwyg" directory.

---
Tags: debugging
---


# Question
Title: New User Registration take long time (more than 60 seconds)
New user registration take too much time in my drupal 6 website. When we perform **Add user** in administrator section, it is working normally, within one or two second we can add users. But when we are trying to **Create new account**, it takes long time.

I have enabled CCK, Content Profile,Token,CAPTCHA,Views Modules.

How does debug it ?.

# Answer
You can install the devel module and see which part of Drupal that slows things down. You could start out by taking a look at the queries that are run.
> 4 votes

# Answer
You can always try to debug the code to see where in the code Drupal gets slow. Here is a great tutorial how to track the slow parts down.

An other thing you should test is give a normal user the privilege to create users (`Administer users`). See if it works as slow as `Create new account`. What actions are done when creating the new account by the way?
> 1 votes

---
Tags: 6, users
---


# Question
Title: How do I add a link to the category in menu?
Now this might be a dumb question, but it's not obvious. Seriously. I have a menu with node/ID links as paths, but I also need one link to the category in the menu. I know that pasting in absolute urls or slugs is not a good idea. But how do I do it otherwise?

# Answer
Have you tried a root link, one beginning with a slash? such as /taxonomy/term/34
> 1 votes

# Answer
You can pass in absolute's. Is the Category a taxonomy? If so you could just link to the taxonomy page. Want a more custom view, use Views with an arguement.
> 0 votes

---
Tags: taxonomy-terms, routes, navigation
---


# Question
Title: Create a new page of particular content type and make it home page during drupal installation
I am building a installation profile. I want to create a page of particular content type and make it as front page during drupal installation. How do i do this?

# Answer
> 1 votes
You should do it in the same way as in common module. Your code will be in files `YOURPROFILE.install` and `YOURPROFILE.profile`.
You can see, for example, how new content type “Article” created in Standard profile. To set front page programmatically you can easily call `variable_set('site_frontpage', $path);`

If I needed to create this functionality, I would create a content type, a view and a Feature with my content type and view. Then I would add Views, Features and my Feature module in dependencies. So I wouldn't write any PHP code in my profile except maybe setting front page.

Other way is to create your own module with your own `hook_menu()`, page callback and all the staff you need. Then again you should add this module in profile dependencies.
Modules from dependencies can be placed in profile folder or downloaded manually to `sites/all` folder.
Of course, you can add all the code from such module to `YOURPROFILE.profile` and it will work, but I think it can be difficult for support.

Reading:

1. How to Write a Drupal 7 Installation Profile
2. Drush Make theory for happy profile development

---
Tags: 7, distributions
---


# Question
Title: translate interface search exact keyword
Is there a way in drupal 7 translate interface to search for exact keyword? The problem is that when I search for keyword 'no' it gives me 19 pages of results.

# Answer
> 2 votes
No, there isn't any way to do that through admin interface. The string search is based on the LIKE condition which includes hardcoded placeholders (%) to search for all strings containing your provided string.

Only way for you is to directly tamper with the database or go through all 19 result pages. Alternatively, you could change the code temporary. For that you have to open locale.inc and go to `function _locale_translate_seek()` in line 1833. Depending on your search (all, untranslated, translated) you have to look for

`->condition('s.source', '%' . db_like($query['string']) . '%', 'LIKE');`

and change it to

`->condition('s.source', db_like($query['string']), 'LIKE');`.

Your search should then only result in exact strings.

---
Tags: search, i18n-l10n
---


# Question
Title: Drupal 7: fetchField(0) giving me half of the records!
I am trying to get all the records from one table. I get from the count 18 record, but the actual given lines are 9.

```
$name = 'admin';
$result = db_query("SELECT name FROM {users} WHERE name <> :name", array(':name' => $name));
$rownum = $result->rowCount();
print "This is the total number: ";
print $rownum;
print "<BR>";
foreach ($result as $record) {
  $value = $result->fetchField(0);
  print $value;
print '<br>';
}

```

Results:

> This is the total number: 18 user1 user2 user3 user4 user5 user6 user7 user8 user9

Do you think is my loop?

# Answer
> 2 votes
Yes, the loop iterates through `result`, but additionally you do that kind of again in your line `$value = $result->fetchField(0);`.

This should be changed to `$value = $record->name;`.

---
Tags: database
---


# Question
Title: Multiple node references using url-widget
I am trying to set up a structure of three content types where two references to one or more parents.

* The main content type is assignment
* The second is assignment\_image that references the assignment content-type, this I have solved using the node references url widget.
* The third is assignment\_vote. This content-type needs to reference both the assignment and the assignment\_image.

I can't figure out how to use the node reference url widget to reference two values. I don't want the user to be able to change these values so the autocomplete/selectboxes are not viable options.

I have thought about doing this using hidden-fields and jQuery but I really would like to be able to use existing modules/code.

Does anyone have any ideas?

# Answer
You can put in the number of values that goes into the reference field, i.e. number of references to other nodes, as part of the content type definition (manage fields). That is at least the case Node Reference. You can also select which content types that can be selected. So pick the content types you need and select how many that the users should be able to pick.
> 1 votes

---
Tags: nodes
---


# Question
Title: Every five seconds without refresh the new web page
How can I on a drupal site do a partial refresh of a page's content with AJAX every 5 second?

# Answer
Well it totally depends on what you want to refresh. I think what you are probably after though is Block Refresh which will allow you to refresh blocks every x seconds.
> 1 votes

# Answer
You could use jQuery's .load function to request the page and just return a part of it. See 'Loading Page Fragments' here: http://api.jquery.com/load/

You can specify a div id to be pulled and just replace that div on your current page. Run that using a setTimeout every 5000 milliseconds and you're there.

Not really a Drupal based solution. But should work.
> 0 votes

---
Tags: 7, ajax, javascript
---


title: Solving drush error

text:
# Question
Title: Solving drush error
I am trying to use drush with an installation profile nodetream. But i get error like

```
Drush Error:

    C:\wamp\www\drupal9\profiles\nodestream>drush make --no-core --contrib-destinati
    on=. nodestream.make
    The drush command 'make nodestream.make' could not be found.             [error]

    Drush was not able to start (bootstrap) the Drupal database.             [error]

    Hint: This error often occurs when Drush is trying to bootstrap a
    site that has not been installed or does not have a configured
    database.

    Drush was attempting to connect to :
      Drupal version    : 7.10
      Site URI          : http://default
      Default theme     : garland
      Administration theme: garland
      PHP configuration : C:\Program Files\Propeople\Drush\Php\php.ini
      Drush version     : 5.0-dev
      Drush configuration:
      Drush alias files :
      Drupal root       : C:/wamp/www/drupal9
      Site path         : sites/default
      Modules path      : sites/all/modules
      Themes path       : sites/all/themes
      File directory path: sites/default/files
      %paths            : Array

    You can select another site with a working database setup by
    specifying the URI to use with the --uri parameter on the command
    line or $options['uri'] in your drushrc.php file.

    C:\wamp\www\drupal9\profiles\nodestream>drush make --no-core --contrib-destinati
    on=. nodestream.make
    The drush command 'make nodestream.make' could not be found.             [error]

    Drush was not able to start (bootstrap) the Drupal database.             [error]

    Hint: This error often occurs when Drush is trying to bootstrap a
    site that has not been installed or does not have a configured
    database.

    Drush was attempting to connect to :
      Drupal version    : 7.10
      Site URI          : http://default
      Default theme     : garland
      Administration theme: garland
      PHP configuration : C:\Program Files\Propeople\Drush\Php\php.ini
      Drush version     : 5.0-dev
      Drush configuration:
      Drush alias files :
      Drupal root       : C:/wamp/www/drupal9
      Site path         : sites/default
      Modules path      : sites/all/modules
      Themes path       : sites/all/themes
      File directory path: sites/default/files
      %paths            : Array

    You can select another site with a working database setup by
    specifying the URI to use with the --uri parameter on the command
    line or $options['uri'] in your drushrc.php file.

```

/\** Update \**/ I have put the drush\_make folder under drush/commands folder also

# Answer
> 1 votes
Since you are using Windows, presumably you are already using Drush-5; Drush-4 does not support Windows. Drush make is included in Drush-5, but unfortunately, Drush make is not supported on Windows either.

Try setting up VirtualBox, a free virtual machine solution, and install Drupal and Drush under ubuntu.

# Answer
> 2 votes
Drush Make is now in Drush (see issue), so you shouldn't need to have `drush make` anywhere. Try running your command with the `--debug` flag and see what the output is?

---
Tags: 7, drush
---


# Question
Title: Does the Search API module integrate with the standard search?
I have Profile2 installed and want to be able to search on Profile2 fields that I have created. Does the Search API module integrate into the default Drupal search, which would therefore when configured, find Profile2 field values and the associated user?

If not, is there another approach I can use to include the Profile2 fields into Drupal standard search?

# Answer
> 5 votes
Search API and core search do not integrate. Just use Search API and scrap core search (Core Search does not work on Profiles as entities See http://drupal.org/node/1369544). The Search API can search on an entity known to Drupal. Profile2 creates profiles as entities. Therefore Search API can search Profiles. When adding a new index to Search API, just choose "Profile" or "Profile Types" under "Item Type".

---
Tags: 7, search
---


# Question
Title: What's the proper (seo safe) way to blackout a site (e.g. for SOPA)?
I want to safely blackout my Drupal site to raise the awareness of SOPA. What's the SEO friendly way to do that?

I'm thinking of putting my site into maintenance mode and just changing the maintenance message.

# Answer
I found this post on the Drupal Google+ page. It says:

> Black out your #Drupal site against #SOPA on Wednesday. Drupal's maintenance mode is 503 status so it won't hurt your SEO.
> 8 votes

# Answer
You can use the SOPA Blackout Module, which will make your site look like the image below. It will also add a 503 header to preserve SE ranking.
> 5 votes

---
Tags: 7
---


# Question
Title: Can regions be printed within a node template?
Can regions be printed within a node template, or are regions strictly confined to page templates?

# Answer
> 48 votes
You can print regions inside any template, but they aren't available out of the box in the `node.tpl.php` template. To make them available, you'll create a new variable for use in your `node.tpl.php` template that'll contain all the region content.

Creating new template variables is done by using a preprocess function. In your theme's `template.php` file, create a function that looks like this:

```
function mytheme_preprocess_node(&$variables) {
}

```

Replacing `mytheme` with your theme's short name. Now, in order for Drupal to recognize this new preprocess function, you need to rebuild your site's theme registry. This is as straightforward as going to *Configuration**Development**Performance* and pressing the "Clear all caches" button at the top.

Now, the way preprocess functions work is that `$variables` contains an array that corresponds to your template's available variables. For example, in `node.tpl.php`, `$submitted` contains the author byline. In the preprocess function above, it's found in `$variables['submitted']`.

To mimick what you have in `page.tpl.php`, where you have an array called `$page` that contains all the regions, you'd want to populate `$variables['page']`.

The problem is that `$page` in `node.tpl.php` is already populated with a true/false value that lets you know whether you're looking at the node by itself or in a listing.

So to avoid that name collision, populate `$region` instead:

```
function mytheme_preprocess_node(&$variables) {

  // Get a list of all the regions for this theme
  foreach (system_region_list($GLOBALS['theme']) as $region_key => $region_name) {

    // Get the content for each region and add it to the $region variable
    if ($blocks = block_get_blocks_by_region($region_key)) {
      $variables['region'][$region_key] = $blocks;
    }
    else {
      $variables['region'][$region_key] = array();
    }
  }
}

```

Then, in your theme's `node.tpl.php` template, you can render any region by doing the following:

```
<?php print render($region['sidebar_first']); ?>

```

Where `sidebar_first` is the name of the region you want to render.

---
Tags: theming
---


# Question
Title: How can I stop a specific page in the Omega Responsive theme from being responsive
I need to stop a specific page from resizing and display the styles specified in the normal stylesheet. I have an iframe that is a set width and height and will not display properly when viewed on smaller screen sizes. Is this possible?

# Answer
You can use the Context and Delta modules. Delta was developed by the Omega developers and Context+Delta is part of the Omega philosophy.

Use Delta to create a variation on the original theme that does not respond to theme width. Uncheck "Enable the responsive grid" setting in the theme, for instance. Then use Context to enable your Delta'd theme variation to trigger only on a certain path, in your case the page with the iframe.
> 3 votes

# Answer
Unless someone can come up with a better option, I think you have two options.

One is to override the rules from the media queries in your `global.css` with a more specific one. Pages should have a unique-enough class on them, eg `body.page-the-name-of-the-page` or `body.page-node-123`.

This is a really ugly solution, though. Essentially, you would need to replicate one of the normal or wide sheets (eg, alpha-default-normal-16.css) in your `global.css` and prepend each and every selector with the body class.

The other option would be to implement a hook\_css\_alter, check the page you are on, and remove the sheets you don't want.

Of the two, I would see if the `hook_css_alter` works in your situation.
> 0 votes

---
Tags: theming
---


title: Switch between databases

text:
# Question
Title: Switch between databases
I was wondering if it is possible to switch between different databases on one Drupal installation.

I have a different DB which another application uses it. Both DB are on the same server (localhost) and I was wondering if it is possible to temporarily connect to that DB in order to READ and WRITE data from/to it, using Drupal.

# Answer
> 2 votes
You can, of course, use the database API that comes with PHP.

To use Drupal's database API, configure your databases as described in *How to connect to multiple databases within Drupal* and use db\_set\_active() to switch between databases.

---
Tags: database
---


title: D7 RSS Feeds - Omitting Content Fields

text:
# Question
Title: D7 RSS Feeds - Omitting Content Fields
I created a view with an RSS feed on my D7 site. From the XML feed I'd like to remove the author who created the node displayed in my view and the creation date. I've searched everywhere and tried everything, but I can't seem to remove these two fields from my feed.

I only have permissions to work in views so if you have a solution using Views 3 I'd be most appreciative.

Thank you!

# Answer
You can specify under "Manage Display" how the content you want to feed will look in the "RSS" (or any other) viewmode. By default, you only have the body (or any additional fields) available. To have more control over what's displayed in which viewmode, you can use the Display Suite module. This module allows you (among many other features) to use another layout for this content. By enabling a layout on the viewmode you like, you also get additional fields like for example the Author and the Post date which you then can enable or disable.
> 1 votes

---
Tags: feeds, views
---


# Question
Title: Add a content type as a select list when creating a new user
I have a content type called Location.

Each user needs a location assigned to them.

How do I go about attaching the Location to the user?

Basically I need to add a dropdown of locations that I can select from for each user I create/edit.

# Answer
> 3 votes
If you use/add the Content Profile module, you can use it to create a profile for each user. In that profile content, you can have a field that is a node reference back to the Location type you mention.

> This module builds user profiles as content (aka nodes), which opens the opportunity to use all the powerful modules for content for user profiles too, e.g. the Content Construction Kit (CCK). It's intended to be simple and useful, but extensible by further modules.
>
> Content profiles can be restricted to certain roles; the module also supports separate content profiles for different roles.

# Answer
> 1 votes
Use the Content Profile module.

> This module builds user profiles as content (aka nodes), which opens the opportunity to use all the powerful modules for content for user profiles too, e.g. the Content Construction Kit (CCK). It's intended to be simple and useful, but extensible by further modules.
>
> Content profiles can be restricted to certain roles; the module also supports separate content profiles for different roles.
>
> Content profile is the successor of the Drupal 5 Node Profile and Bio modules. The intention is to have a common "profiles-as-nodes" base module upon which further extension modules can rely.

---
Tags: 6, users
---


title: Using Drupal as client of a web service

text:
# Question
Title: Using Drupal as client of a web service
I need to use Drupal as client for a web service, for extracting data and showing it in a view or as content. (The format use is JSON or REST.)

I use a Web Service Client module in Drupal 7, and the Services module in Drupal 6, but I don't know how to use them. I read the documentation but I don't get any result.

Can anyone help on this issue, or tell me how to use these modules? Is there any other module for this purpose?

---

A possible solution: I find a module called XML VIEWS but this module convert only XML files.

Now, I programing in this module for convert the JSON to XML.

In this files: `xml_views_plugin_query_xml.inc`

In this function: *Execute*

Anyone have another solution?

# Answer
Drupal has specific functions that can help with communicating with a web service, and handling JSON input.
Drupal 7 has the following functions:

With those functions you can write your own custom module to make requests to a site implementing a web service.

If there are some restrictions about the number of requests that can be done to the web server, you can use the Drupal functions to cache the result obtained from the web server:

To notice that Drupal supports more than one cache bin, and modules can use their own cache bins, when necessary.
Drupal supports also cache items that are automatically removed at the successive cache swipe (see the description for the CACHE\_TEMPORARY constant). Implementing hook\_flush\_caches(), the modules allow to the administrator users to clean the cache used by the module when the "Clear" button on the "Performance" page is clicked, or any times a module calls drupal\_flush\_all\_caches().

In Drupal 7, cache data for frequently used data are associated with a static variable handled with drupal\_static(). When the data is really frequently used when outputting the same page, code similar to the following one is used:

```
  // Use the advanced drupal_static() pattern, since this is called very often.
  static $drupal_static_fast;
  if (!isset($drupal_static_fast)) {
    $drupal_static_fast['implementations'] = &drupal_static(__FUNCTION__);
  }
  $implementations = &$drupal_static_fast['implementations'];

  // …

  // Fetch implementations from cache.
  if (empty($implementations)) {
    $implementations = cache_get('module_implements', 'cache_bootstrap');
    if ($implementations === FALSE) {
      $implementations = array();
    }
    else {
      $implementations = $implementations->data;
    }
  }

```

The code is part of module\_implements().
> 9 votes

# Answer
Every time I have needed to consume a webservice, I have just created a PHP class based around file\_get\_contents or curl in conjunction with json\_decode or simplexml\_load\_string.

The class then gets accessed in a module via a getter function that uses drupal\_static, or the `$static` pattern for Drupal 6.

I then use this inside my custom blocks, menu callbacks, etc, as needed.

EDIT

@kiamlaluno's answer is correct and demonstrates a way to do this all through the Drupal API. The primary reason I don't do this is that I prefer to abstract the webservice class in a way that allows me to use it in other applications. There are advantages and disadvantages to this, so weigh your options.
> 2 votes

---
Tags: 7, services
---


title: Replacing menu items with images

text:
# Question
Title: Replacing menu items with images
I'm looking for a way to display a menu items as images (with rollover) rather than the usual text links. I found the module Menu Icons, but as the name implies, it's designed to place the icon next to the link. Does anyone have a technique for doing this? Perhaps I have to create some sort of custom block or panel, but I thought maybe there was an easier way.

# Answer
You can use the **Menu Icons** module to implement the functionality you are looking for - I've done this multiple times.

You simply need to customize the menu\_icons\_css\_item.tpl.php file so that the image is displayed using the CSS image replacement technique rather than positioning the image as an icon-like background. For roll-over functionality, each image you upload with the image icon module would need to include the static and roll-over versions of the menu image.

Here is sample content of a menu\_icon\_css\_item.tpl.php file I've used before. This is for Drupal 6, so some of the syntax may need to be updated if you are using Drupal 7.

```
<?php
$base_url = $_SERVER['DOCUMENT_ROOT'];
$image_info = getimagesize($base_url.$path);
$width = $image_info[0];
$height = $image_info[1]/2;
?>

ul.links li.menu-<?php print $mlid ?> a {
  background-image: url(<?php print $path ?>);
  background-repeat: no-repeat;
  background-position: 0 0;
  height:<?php print $height?>px;
  text-align: left;
  text-indent: -9999px;
  width: <?php print $width?>px;
}

ul.links li.menu-<?php print $mlid ?> a:hover {
  background-position: 0 <?php print $height?>px;
}

```

After you've created a customer menu\_icons\_css\_item.tpl.php file in your theme, you will need to delete the CSS file that the Menu Icons module previously generated, so that it will generate a new file using this template. It should be in your sites/default/files folder.

Of course, if you do not need to allow site admins to update menu item images via the Drupal UI, you could just implement the CSS image replacement technique within your theme, without needing a helper module like Menu Icons.
> 7 votes

---
Tags: routes, media, theming, navigation
---


# Question
Title: Adding attribute class in table row not working
If I add any other attribute like class2 then it works but 'class' is not working. If you see below, there is a line: `'class' =>'hellodssdddsdsdsds'`. What I want is that this class should be added in tr like: `<tr class="hellodssdddsdsdsds" >...</tr>;`

If I use class2 instead of class in in below code it works and the table row now correctly contains attribute class2: `<tr class2="hellodssdddsdsdsds">...<tr>` but not when adding class word. How to add a class as per the `theme_table()` api function?

```
$donation_records = & $form['show_donation']['donation_records'];

if(user_access(AnuDonationUtilities::APPROVE_DONATION_DETAILS or user_access(AnuDonationUtilities::ENTER_DONATION_DETAILS)))
{
foreach(element_children($donation_records) as $key)
{
    if( ctype_digit("$key"))
    {
        $state_mask = $donation_records[$key]['hidden_current_state_mask']['#value'];

        $class_attrib = "";

        if($state_mask & AnuDonationSingleRecordState::IS_CANCELLED)
        {
            $class_attrib .= " an-dr-cancelled ";
        }
        if($state_mask & AnuDonationSingleRecordState::IS_VERIFIED)
        {
            $class_attrib .= " an-dr-isverified ";
        }
        if($state_mask & AnuDonationSingleRecordState::NEEDS_VERIFICATION)
        {
            $class_attrib .= " an-dr-needs-verification ";
        }

        $class_attrib = "an-dr-needs-verification";

        $row = array(
            'data' => array(
            array( 'data' => drupal_render($donation_records[$key]["sno"]) ),
            array( 'data' => drupal_render($donation_records[$key]["op"]) ),
            array( 'data' => drupal_render($donation_records[$key]["cancel"]) ),
            array( 'data' => drupal_render($donation_records[$key]["verify"]) ),
            array( 'data' => drupal_render($donation_records[$key]["donation_amount"]) ),
            array( 'data' => drupal_render($donation_records[$key]["donated_by"]) ),
            array( 'data' => drupal_render($donation_records[$key]["donated_by_uid"]) ),
            array( 'data' => drupal_render($donation_records[$key]["donation_details"]) ),
            array( 'data' => drupal_render($donation_records[$key]["comments"]) ),
            array( 'data' => drupal_render($donation_records[$key]["donor_comments"]) ),
            array( 'data' => drupal_render($donation_records[$key]["payment_medium"]) ),
            array( 'data' => drupal_render($donation_records[$key]["create_date"]) ),
            array( 'data' => drupal_render($donation_records[$key]["created_by"]) ),
            ),
            'class' =>'hellodssdddsdsdsds',
        );

        if($state_mask != 0)
        {
            $row['class'] = array($class_attrib);
        }

       $rows[] = $row;
    }
}
    $header = array(
    t('Sno'),
    t('Op'),
    t('Cancel(ed)'),
    t('Verify'),
    t('Donation Amount'),
    t('Donated By'),
    t('Donor Username'),
    t('Donation Details'),
    t('Comments'),
    t('Donor Comments'),
    t('Payment Method'),
    t('Dated'),
    t('Updated By'),
  );

 $output = '<fieldset><legend>'.t('Donation Contribution Details').theme('table', $header, $rows);

 //Now format the table to add new records

 $rows = array();

 foreach(element_children($form['add_new_records']) as $key)
 {
     if( ctype_digit("$key"))
    {
        $row = array(

            array( 'data' => drupal_render($form['add_new_records'][$key]["sno"]) ),
            array( 'data' => drupal_render($form['add_new_records'][$key]["donation_amount"]) ),
            array( 'data' => drupal_render($form['add_new_records'][$key]["donated_by"]) ),
            array( 'data' =>drupal_render ($form['add_new_records'][$key]["donated_by_uid"]) ),
            array( 'data' => drupal_render($form['add_new_records'][$key]["donation_details"]) ),
            array( 'data' => drupal_render($form['add_new_records'][$key]["comments"]) ),
            array( 'data' => drupal_render($form['add_new_records'][$key]["donor_comments"]) ),
            array( 'data' => drupal_render($form['add_new_records'][$key]["payment_medium"]) ),
        );

       $rows[] = $row;
    }

 }

 $header = array(
    t('Sno'),
    t('Donation Amount'),
    t('Donated By'),
    t('Donor Username'),
    t('Donation Details'),
    t('Comments'),
    t('Donor Comments'),
    t('Payment Method'),
  );

 $output .= '<fieldset><legend>'.t('Enter Donation Details').theme('table', $header, $rows);

 $output .= drupal_render($form);

 return $output;
}//if

```

# Answer
> 1 votes
The 'class' element in a render array should be an array, not a string. So your code:

```
'class' =>'hellodssdddsdsdsds',

```

should be:

```
'class' => array('hellodssdddsdsdsds'),

```

When you define a new element in the array, 'class2', there is nothing dictating what type of variable this new element should be, so it works without any problems.

---
Tags: 6, theming
---


# Question
Title: need popup display of term definition in page contents
I have glossary terms in site as glossary type content. Client now wants to have each instance of each term linked to the term explanation, to popup when user hovers over term.

Suggestions? Modules? Magic?

# Answer
Check out the Popups API (Ajax Dialogs) module.
> 1 votes

---
Tags: navigation
---


# Question
Title: How do I find the Delta of a CCK Multivalue Field
I have two unlimited multi-value cck fields in one content type: `field_before` and `field_after` . In my custom node template file, I need to match up the deltas of each before and after value so I can display my content like this:

```
Before 0
After 0
------
Before 1
After 1
------
Before 2
After 2

```

So how do I get this output in my node.tpl file?

# Answer
> 1 votes
I would suggest putting this in a node-TYPE.tpl.php instead of node.tpl.php unless this is your only content type, but anyway, here is a quick start to accomplishing what you asked for using a simple *for* loop:

```
<?php $max = max(count($node->field_before), count($node->field_after)); ?>
<?php for ($i = 0; $i < $max; $i++): ?>
  <div class='before'>Before <?php print !empty($node->field_before[$i]) ? $node->field_before[$i]['view'] : ''; ?></div>
  <div class='after'>After <?php print !empty($node->field_after[$i]) ? $node->field_after[$i]['view'] : ''; ?></div>
  <?php if ($i != ($max - 1)): ?>
    <div class='separator'>------</div>
  <?php endif; ?>
<?php endfor; ?>

```

This can obviously be tweaked to add a default value if a field lengths are different, or skip the checking if you *know* that each "before value" will have a corresponding "answer value".

Also, if using default "unlimited fields", a user could rearrange them via drag and drop and potentially screw up your data. If this is a concern for you, you may want to look at Multigroup for CCK3.

---
Tags: 6, theming, entities
---


# Question
Title: Hook not getting called (image_title module)
I'm attempting to use the `image_title` module to replace a node's title by an uploaded image. I thought it was working, but I've since discovered that it was only showing for me, not for anyone else on the site. =(

In debugging, I inserted the following into the `image_title_preprocess_page()` function:

```
$fh = fopen('/tmp/myfile', 'w');
fwrite($fh,date('r') . " starting page\n");

```

and I've found that this hook isn't getting called for anonymous users. I can't think of why that would happen. I also don't know much about the process by which hooks are run, though.

Perhaps page caching is causing the hook not to be called?

EDIT: If I just bypass the web server & call `php index.php` directly, `image_title_preprocess_page()` does get called, but then it does a `SELECT image FROM {image_title_menu}` and it finds nothing relevant. I have to wonder why it's using the 'page' hook instead of the 'node' hook in the first place though. Maybe this module just plain doesn't work.

I'm using Drupal 6.22, and while I'm investigating this (and maybe after, too) I've got a github fork here: https://github.com/kenahoo/drupal-image\_title .

Thanks.

# Answer
> 1 votes
Figured it out. There was this crazy code in `image_title_nodeapi()`:

```
function image_title_nodeapi(&$node, $op, $teaser, $page) {
  if ( !user_access('create image titles') ||
       (variable_get('image_title_'. $node->type, 1) == 0) ) {
     return; // do nothing ...
   }

```

Which meant people could only see the images if they could also ***create*** images. Not real bloody useful! Fixed here: https://github.com/kenahoo/drupal-image\_title/commit/a4458676e7a6d1e00839a3d0e02a9d6c4f01fe2c

**Update:** on Paul's advice I created a fork in the Drupal Sandbox area: http://drupal.org/sandbox/kenahoo/1411716 . I'm probably going to delete the github.com project now.

# Answer
> 1 votes
A quick search of the issue queue yielded this.

Apparently the maintainer has been fixing it since Sep 2010. :-) I just fixed it, patch is there on that issue queue. Ask if you need to know how to apply the patch.

Also rather than manage a github fork, you should work on a local copy of the official repository and submit patches. That way it's much more convenient for the maintainer if you end up fixing it.

---
Tags: 7, hooks, media
---


# Question
Title: How can I update or insert a row with NULL fields using query builder?
In Drupal 7, I'm being sent an array of values from a user submission that are being mapped directly to a database table.

Some of those are blank and I'd like to set those fields to SQL-style `NULL` in the database.

To do this, my values array has the empty or blank fields set to PHP's `NULL`:

```
array('field1' => 'value1', 'field2' => NULL)

```

And I'm using `db_update()` like this:

```
$result = db_update('table_name')
  ->fields($record)
  ->condition('cmid', $form_state['values']['cmid'])
  ->execute();

```

However, `db_update()` doesn't appear to like `NULL` values in the `$record` array. I'm not seeing any sort of errors, unfortunately, except that no updates are being made to the database and that `$result` is returning a falsy value.

How should I be using `db_insert()` or `db_update()` if some my values may be blank at times, and I'd like these to equate to setting those respective database fields to `NULL`?

# Answer
`db_update()` does allow `NULL` to be used for field values. To confirm this, check out the core table, `block_custom`, which allows both `block_custom.body` and `block_custom.format` to be `NULL`.

First, insert some dummy data either through the block administration screen or via SQL:

```
INSERT INTO block_custom (body, info, format)
  VALUES ('Lorem Ipsum', 'Test block', 'plain_text');

```

Now run the following code:

```
db_update('block_custom')
  ->fields(array('body' => NULL))
  ->condition('info', 'Test block')
  ->execute();

```

If you look at the table after executing, `block_custom.body` will be set to `NULL`.

`db_insert()` works too:

```
$fields = array(
  'body' => NULL,
  'info' => 'Test block 2',
  'format' => 'plain_text',
);

$result = db_insert('block_custom')
  ->fields($fields)
  ->execute();

```

So there's something else wrong with your statement. Two things to check:

* Ensure `$record` really has `NULL` values in the `db_update()` query. `var_dump()` the array just before the `db_update()` and ensure nothing's modified the values.
* Check the condition statement. If set to a condition that doesn't match any of the rows in the table, the update won't occur and `$result` will contain a falsy value. Since it's perfectly value to have an `UPDATE` query that matches no rows, it won't throw an exception or return an error.
> 3 votes

# Answer
The following thread seems to contain your answer:

Null Values Not Inserted Into Database Using db\_insert.

Specifically:

> As your error message states, the column does not allow null values. Since the database won't accept null values for that table.column, you will need to send it something other than null, i.e. an empty string '' or whatever you decide the appropriate non-null value is.
>
> There is no getting around a column level constraint on a database unless you modify the table.column so that it allows nulls. That is not recommended, since such constraints are defined for a reason

This answer also seems to give some more insight into the Field API: PDOException: Incorrect decimal value for a field which is legitimately null
> 1 votes

---
Tags: database
---


# Question
Title: When creating an autocomplete form in a custom module how do tell Drupal what modules I need?
I want to create an auto-complete form in my custom module that will be loaded in a block. Drupal doesn't seem to be loading the necessary Javascript libraries to work properly. How do I know what needs to be loaded and how/where do I tell Drupal to load these libraries?

hook\_block\_view:

```
function my_module_block_view($delta = '') {
    //The $delta parameter tells us which block is being reqested.
    switch ($delta) {
        case 'my_module_my_block':
            $block['subject'] = t('Block Subject');
            $block['content'] = drupal_get_form('my_module_my_form');
            break;
    }

    return $block;
}

```

Form code:

```
function my_module_my_form($form, &$form_state) {
    $form = array();

    $form['term'] = array(
        '#type' => 'textfield',
        '#autocomplete_path' => 'my-module-autocomplete'
    );

    $form['submit'] = array(
    '#type' => 'submit',
    '#value' => 'Add',
  );

    return $form;
}

```

The form loads, the field is there, but auto-complete isn't working :(

If I call the my-module-autocomplete path I do get a valid response back when compared with a Content Type edit form. The ajax spinner in the input field never appears so the ajax isn't being called.

# Answer
> 2 votes
See the examples module for a straight forward AJAX Example.

# Answer
> 1 votes
Genuinely non-trivial, so here are some links:

Drupal AJAX API. Alternately, `drupal_add_js()`

---
Tags: 7, ajax
---


# Question
Title: What do I need to create a custom form widget?
I used `hook_field_widget_info()` and `hook_field_widget_form()` to create a new widget for the user reference module. The problem is when I select a value in content edit form using my widget, selected value is not shown in node display page. Also when I go back to the edit form, my selected value is not the default value(is not saved).

Does it need anything else to work properly?

```

function mymodule_field_widget_info() {
    return array(
       'custom_user_widget' => array(
            'label' => 'Custom user widget',
            'field types' => array('user_reference'),
            'behaviors' => array(
                'multiple values' => FIELD_BEHAVIOR_DEFAULT,
                'default value' => FIELD_BEHAVIOR_DEFAULT,
            ),
        ),
    );
}
function mymodule_field_widget_form(&$form, &$form_state, $field, $instance, $langcode, $items, $delta, $element) {
    if ($instance['widget']['type'] == 'custom_user_widget') {
        $element['uid'] = array(
            '#type' => 'select',
            '#options' => array(1=>'a', 2=>'b', 3=>'c'),
            '#title' => t('Username')
        );
        return $element;
    }
}

```

# Answer
> 3 votes
You need to implement the "view hook":

```
/**
* Implements hook_field_formatter_view().
*/
function mymodule_field_widget_field_formatter_view($entity_type, $entity, $field, $instance, $langcode, $items, $display) {
    $element = array();

    switch ($display['type']) {
    case 'custom_user_widget':
    $element[] = 'add here what you want to show';
    break;
    }
    return $element;
}

```

---
Tags: 7, entities
---


# Question
Title: Drupal 6 Views "No result behaviour" use a view
With the Views module for Drupal 7 you can set a "No result behaviour" that uses another View rather than just text. I can't see the same functionality in Views 2 for Drupal 6. Is it possible to extend Views to do this?

The motivation for this is that we have a home page driven by a View that displays the recent contents from a user's groups; if the user hasn't joined any groups yet then we want to display a different View using content from all groups.

# Answer
> 4 votes
You can simulate this if you instantiate the view in code. The general steps are

1. Make a custom block.
2. In the block view callback, instantiate and execute the view you want, but don't generate output.
3. Check the number of rows. If zero, then repeat #2 with your alternate view.
4. Generate the output for the view, and add to the block output.
5. Use the block in place of the view where you need to.

If you do everything properly, all of your view templates will be used, so you aren't really losing anything.

All of the views related function are documented at drupalcontrib.org, but I think that is the Drupal 6, Views 3 version. Googling on `views_get_view` will also get you started and should lead to examples of generating views with code. If you have Advanced Help installed, you will also see some information there.

I have done something similar before, but I can't find the code. I can remember, I will update the answer with some stubbed out code.

---
Tags: views, 6
---


# Question
Title: OG: How to import 2 related nodes from CSV files using Migrate module?
I would like to import 2 related nodes (*Organic Group* and *OG group content*) from 2 CSV files using Migrate module but I cannot find a proper CSV migrate class example or module. I use Drupal 7.

```
OG Group
  |
  |--OG group content

```

file formats:

```
(a) OG Group file
=============================================
gid | group_title | group_body | group_admin

(b) OG group content
==================================
nid | gid | node_title | node_body

```

relationship:

```
{a.gid} 1..(one-to-many)..* {b.gid}
{a.group_admin} *..(many-to-one)..1 {users.uid}  // group admin is one of existing users uid that should have the OG group administration membership rights

```

Where can I find a sample CSV migration class for Migrate module ?

Migrate OG is for D6 only Migrate Extras contains classes for OG for D7 but I could not find an example for this scenario.

# Answer
> 6 votes
Okay so I'm assuming that you haven't used Migrate before. If you'd like some background reading take a look at the slides for the presentation I'll be giving at DrupalCon in Denver: http://denver2012.drupal.org/sites/default/files/slides/Migrate\_0.pdf It should help you understand some of the concepts.

One thing that's important to point out is that you'll need two migrations:

1. Using (a) and MigrateSourceCSV as a source and—assuming the groups will be nodes—MigrateDestinationNode as a destination.
2. Using (b) and MigrateSourceCSV as a source and MigrateDestinationOGMembership (as you noted part of Migrate Extras) as a destination.

The CSV files are actually really easy to use as a source. You can see an example of it in the Migrate docs: http://drupal.org/node/1152158

In your case you could setup the source for (a) with:

```
// The definition of the columns. Keys are integers, values are an
// array of field name then description.
$columns = array(
  0 => array('gid', 'Id'),
  1 => array('group_title', 'Title'),
  2 => array('group_body', 'Body'),
  3 => array('group_admin', 'Admin'),
);

// Instantiate the class using the path to the CSV file and the columns.
$this->source = new MigrateSourceCSV('path/to/a.csv', $columns);

```

You'll also need to know something about your source when you setup the Map because it needs to create a field to store the source ids in... since gid's are basically nid's you can just cheat and use that source's schema definition:

```
$this->map = new MigrateSQLMap($this->machineName,
  MigrateDestinationNode::getKeySchema(),
  MigrateDestinationNode::getKeySchema()
);

```

---
Tags: 7, organic-groups, importing-exporting, migrations
---


title: Auto create node reference in Drupal 7

text:
# Question
Title: Auto create node reference in Drupal 7
I have made a new content type called wall and used user reference on it. Is there a way to auto create node whenever a new user is registered? I found the Autocreate Node Reference module but it doesn't have version 7 so I'm looking for an alternative.

# Answer
This is a good example where Rules module can help you. I myself probably just write some custom code, since that's easy for me. But if you don't want to/can't do this, Rules can help you.

You can setup a rule, that is executed when a new user is created that will create a content of the chosen type. With tokens you can populate the values needed.

Using Rules can be a bit complex, but it's very powerful.
> 2 votes

# Answer
If you're going to write your own module. You can use hook\_user\_insert() to perform actions when a new user is added.

Then use node\_save() to insert a new node
> 1 votes

# Answer
There is the Node Reference Create module for Drupal 7 (and 6) which does this. But probably you need to write a custom module to create a node after a user has registered.
> 0 votes

# Answer
In addition to what googletorp mentioned, do you think the link below would be of any help?

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

---
Tags: nodes, users, entities
---


# Question
Title: Using hook_theme_registry_alter to only modify specific pages instead of all pages
I have a custom module which invokes the hook\_theme\_registry\_alter() to modify the presentation of some input fields.

However, I've discovered that the overridden styling is affecting ALL input fields on my entire site.

This is not good!

How to I make it so that my implementation of the hook\_theme\_registry\_alter() is only seen on my module's pages?

Here is my function, and it is applying the theming functions to ALL radio and form elements on our site.

```
function MY_MODULE_theme_registry_alter(&$theme_registry) {
  if (isset($theme_registry['radio'])) {
    $theme_registry['radios']['function'] = "MY_MODULE_radios";
    $theme_registry['radio']['function'] = "MY_MODULE_radio";
    $theme_registry['form_element']['function'] = "MY_MODULE_element";
  }
}

```

# Answer
> 1 votes
For simple alterations, instead of implementing `hook_elements()`, you could simply implement `hook_form_alter()` or it's cousin `hook_form_FORM_ID_alter()`. Both of these functions will effectively allow you to (as their name suggests) alter a form's input elements, and they are much easier to implement than `hook_elements()`. The former gets called for every function in the website, while the later only gets called for the `FORM_ID` that you specified in your hook implementation.

If the ID of the form you wish to modify is `my_form`, then `hook_form_FORM_ID_alter()` would be written as `hook_form_my_form_alter()`. If you want a more thorough explanation of these two hooks, I highly recommend reading Lullabot's writeup on modifying Drupal 6 Forms.

# Answer
> 0 votes
Instead of implementing `hook_theme_registry_alter()` that changes the theme implementations for every module, you could define new form fields using hook\_elements(). In this way you can implement a new radio field that is used only from your module, and that render a radio field in a customized way.
The default field definitions implemented by Drupal are contained in system\_elements(), which defines the form fields you are interested to using the following arrays:

```
  $type['radios'] = array(
    '#input' => TRUE,
    '#process' => array('expand_radios'),
  );
  $type['radio'] = array(
    '#input' => TRUE,
    '#default_value' => NULL,
    '#process' => array('form_expand_ahah'),
  );

```

Using your form fields, you would just replace code similar to the first snippet with code similar to the second snippet.

```
$form['posting_settings']['comment_preview'] = array(
  '#type' => 'radios',
  '#title' => t('Preview comment'),
  '#default_value' => variable_get('comment_preview', 1),
  '#options' => array(t('Optional'), t('Required')),
);

```

```
$form['posting_settings']['comment_preview'] = array(
  '#type' => 'mymodule_radios',
  '#title' => t('Preview comment'),
  '#default_value' => variable_get('comment_preview', 1),
  '#options' => array(t('Optional'), t('Required')),
);

```

As only your module would use the "mymodule\_radios" form field type, only your module would render the "radios" form field in a different way.

In Drupal 7, the hook has been renamed to hook\_element\_info().

For more information, see Creating Custom Elements Using Drupal 6.x.

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


# Question
Title: What cache tables should I keep on Memcache on a multi-site server?
I can spare 64-96Mb of memory on my VPS running a dozen Drupal 6 and 7 sites. In this situation, what cache tables should I keep on Memcache, and why?

I realize cache\_update and cache\_form are not proper caches, but my question rather assumes it's better to have a few well-cached tables than lots of poorly cached ones. Is this assumption correct?

# Answer
> 1 votes
I guess the question is *if* and *when* those tables would be "poorly cached". This will depend completely on the actual request load of your website. Without detailed insight it's hard to give you a concrete recommendation, except that "premature optimization is the root of all evil" (D. Knuth).

Therefore, simply start with caching all tables in Memcache and then measure how effective (hits vs. misses) Memcache works. You could do this with the Memcache admin module or, with a bit more effort, using Munin. Then you'll see if you actually should shift some RAM from the more ineffective tables to the more frequented ones. That's exactly what we do to optimize Memcache on our Drupal hosting clusters.

---
Tags: 7, caching, performance
---


# Question
Title: Where does Drupal render the content of the <head> tag?
I'm calling drupal\_add\_html\_head() a few times to add meta data for facebook integration. To my surprise, this data is not rendered in the order I add it.

Where is this data actually rendered? I would like to examine the code so I can understand the logic behind it.

I'm aware there's hook\_html\_head\_alter too, but without understand the render order, messing with the order of input data is not likely helpful.

# Answer
template\_preprocess\_html() gets the tags for the `<head>`, and adds them to the html.tpl.php template file as `$head`.

The template file looks like this:

```
..
<head profile="<?php print $grddl_profile; ?>">
  <?php print $head; ?>
  <title><?php print $head_title; ?></title>
..

```
> 3 votes

---
Tags: theming
---


title: Add another module

text:
# Question
Title: Add another module
I'm using the Add another module to insert multiple items for one field.

How can I remove the items I added with the module?

# Answer
> 2 votes
This discussion resulted in the Unlimited Field Remove module, which works great for Drupal 7 and may be going into the 8.x core.

---
Tags: 7, entities
---


# Question
Title: Creating rollover tooltip for a view (Netflix Style)
Here is my scenario: I'm trying to create a view that displays images, and some additional information on rollover -- Something similar to how Netflix does it, and I'm trying to determine the most feasible way to do this. I've found the Beauty Tips module, but since my view is inside a panel, I'm not really sure if this module will do exactly what I'm looking for. Any tips on how this could be implemented would be really helpful. (using Drupal 7 btw)

# Answer
> 2 votes
You probably want to use the Views Tooltip module, which allows you to do exactly that. It depends on the Tipsy tooltip module, and works with Drupal 7.

---
Tags: 7, views, tooltips
---


# Question
Title: How to change the HTML output of link to image file?
With Manage Display of image field, I set '**Link image to**' to **File**.

so when user clicks the styled image, will link to original file, I want to change the html output of the link. How may I do so?

# Answer
> 2 votes
The 'proper' answer to this question is: Use or make another formatter for image fields. For instance: Image URL Formatter is probably close enough for you to hack on.

If, when you're done, you feel generous... Make a sandbox project on drupal.org and share. :-)

# Answer
> 2 votes
Install the devel themer module. After enabling it you can point to whatever you want to change. It will tell you which theme method is actually called what options you have to implement your own one.

---
Tags: media, theming, navigation
---


# Question
Title: Why is an integer variable in PHP interpreted as a string literal when passed from Drupal to JavaScript via Drupal.settings?
This is in Drupal 7.

I'm attaching some JavaScript via `drupal_attach_js()`, using "settings\` to be able to pass the "height" parameter to a JavaScript function. The height is used in a modal dialog, and it will vary depending on the amount of data that the modal will contain.

Here is my JavaScript code:

```
(function ($) {

  Drupal.behaviors.designer = {
    attach: function (context, settings) {
      // ...some code to activate modal...
      height: settings.designer.jquery_modal_height,
      // ...some more code...
    }
  };

})(jQuery);

```

If I run `console.log(settings.designer.jquery_modal_height)`, then the console displays the value of this variable, but the actual "height" parameter seems to take the code literally and never applies it's actual *value*.

Am I doing something wrong?

# Answer
```
...
  Drupal.behaviors.designer = {
    // attach is a property of Drupal.behaviors.designer, that points to a method.
    // This method will later on get called by Drupal core on initialization.
    attach: function (context, settings) {
      // Here this doesn't make a lot of sense.
      // Here you are writing height as if it were the property of an object.
      // Technically it is not wrong syntax because everything in JavaScript is an
      // an object. That means methods are objects too! Which also means that your
      // attach() method above supports both properties and methods.
      // However, here practically you are assigning the contents of settings.designer.jquery_modal_height
      // to the height property of the attach() method.
      height: settings.designer.jquery_modal_height,
    }
  };
...

```

So basically what you are saying above is

```
// Add the height property to the attach() method, and add some value to it.
Drupal.behaviors.designer.attach.height = settings.designer.jquery_modal_height;

```

I don't think you want to do that! Of all the Drupal JavaScript objects there are, I would not consider the attach() method the most durable object.

If you want to use the contents of `settings.designer.jquery_modal_height`, you either pass it to another method, or assign it to a more durable object. For example.

// Assuming you assigned the string "foo" to settings.designer.jquery\_modal\_height in PHP.

```
someFunction(param1, param2) {
  console.log(param1);
  console.log(param2);
}

var someRandomObject = {
  aProperty = "";

  someRandomMethod: function() {
    console.log(this.aProperty);
  }
}

Drupal.behaviors.designer = {
  myCustomMethod: function(param) {
    console.log(param);
  }

  attach: function (context, settings) {
    // Consume the contents of settings.designer.jquery_modal_height.
    // This should print your string properly.
    // prints "foo"
   console.log(settings.designer.jquery_modal_height);

    // Could print "foo". Maybe you should consider accessing myCustomMethod() through
    // the context variable passed into attach().
    console.log(Drupal.behaviors.designer.myCustomMethod( settings.designer.jquery_modal_height);

    // Probably won't work. "this" right now probably refers to "attach" and not "designer"
    console.log(this.myCustomMethod(settings.designer.jquery_modal_height));

    // Here we assign it to a local variable. Not a very durable storage location
    // because we are within a closure right now. As soon as the attach() method
    // finishes it's execution, localVar goes Ka-Poof!
    var localVar = settings.designer.jquery_modal_height;

    // But we can do some stuff with it in the meantime.
    // Should print "foo bar".
    someFunction(localVar, " bar");

    // Here we store our "Drupal setting" in a relatively more durable object.
    someRandomObject.aProperty = settings.designer.jquery_modal_height;

    // Should print "foo".
    someRandomObject.someRandomMethod().
  }
};

```

So the short answer is: you're probably doing it wrong, revise your code ;)
> 1 votes

# Answer
If you do

```
{
  ..
  height: settings.designer.jquery_modal_height,
  ..
}

```

You are doing it right, else you should do

```
..
var height = settings.designer.jquery_modal_height;
..

```

Most likely it's not the variable that's the problem but some other part of your code.
> 1 votes

---
Tags: 7, javascript
---


# Question
Title: Migrating multiple values into a single file field in Drupal 7 with Migrate 2.2
I have a file field that can have multiple downloadable files for an image node type. These images will have several versions (psd, jpg, eps) that will be downloadable. I would like to be able to append multiple values to this field. How would I do that when they are coming from multiple source columns (i.e. eps\_filename, jpg\_filename, psd\_filename)?

I found related documentation here: http://drupal.org/node/1012810 But that documentation is for taxonomy terms where the details of the value can simply be a string with a separator. For this I am using MigrateFileFieldHandler::arguments(), so I can't just give it a separator.

Further what I would like to do is also be able to come back later and append more files to the migrated nodes. This is because the larger files will take longer to get on the server, so their smaller counterparts (jpg, png, etc) will be loaded first and then adding the eps files later. Now I already figured out how to update the previously migrated nodes using systemOfRecord. But I am not sure how to append to a multi-value field.

I am using Drupal 7 and the Migrate module version 2.2. Here is some sample code I am using for migrating the data initially into the file field.

```
$jpg_arguments = MigrateFileFieldHandler::arguments(NULL,
  'file_link', FILE_EXISTS_RENAME, 'en', array('source_field' => 'jpg_name'),
  array('source_field' => 'jpg_filename'), array('source_field' => 'jpg_filename'));

$this->addFieldMapping('field_file', 'jpg_uri')
     ->arguments($jpg_arguments);

```

I suspect the trick is using the prepareRow() function. But so far I have not been able to get that to execute yet.

Any ideas? I really appreciate any help.

Thanks!

# Answer
> 1 votes
Actually I figured this out last month, but just got back to commenting here. The solution was far more complex than what anyone has suggested. I actually had to extend the MigrateDestinationNode class and create my own import function that is a modified version of the one used in that class. I will paste the source code below.

Essentially what I had to do was modify the import where it tries to do an update on the existing node when the System of Record is set to destination to check for the field type that I am saving the file to and merge the file field data of the file that is already on the node with the one I am adding.

I also had to make sure that I used this new extended class as the destination and set the System of Record to Migration::DESTINATION.

Here is the code:

```
<?php
class ImageAssetNodeAddEPSMigration extends BasicClientMigration {
  public function __construct() {
    parent::__construct();

    //This allows us to update the existing record.
    $this->systemOfRecord = Migration::DESTINATION;

    $this->description = t('Image Asset Files - Adding the EPS files');
    $this->dependencies = array('ImageAssetNode');

    $this->map = new MigrateSQLMap($this->machineName,
      array(
        'destid1' => array(
          'type' => 'int',
          'not null' => TRUE,
          'description' => 'Node ID.',
          'alias' => 'an',
        )
      ),
      MigrateDestinationNode::getKeySchema()
    );

    // We get the data from the database for this.
    $query = db_select('migrate_map_imageassetnode', 'an')
        ->fields('an', array('destid1'));
    $query->innerJoin('migrate_client_image_asset_node', 'ta', 'an.sourceid1 = ta.fcid');
    $query->fields('ta', array('eps_psd_filename', 'eps_psd_name', 'eps_psd_uri', 'fcid') );

    // Passing the cache_counts option means the source count (shown in
    // drush migrate-status) will be cached - this can be very handy when
    // dealing with a slow source database.
    $this->source = new MigrateSourceSQL($query, array(), NULL,
      array('cache_counts' => TRUE));

    // Set up our destination - nodes of type migrate_example_beer
    $this->destination = new MigrateDestinationNodeExtended('media_images');

    /*
      Assign mappings TO destination fields FROM source fields. To discover
      the names used in these calls, use the drush commands
      drush migrate-fields-destination ImageAssetNode
      drush migrate-fields-source ImageAssetNode
    */

    // Mapped fields
    $this->addFieldMapping('nid', 'destid1')
         ->description(t('The original node id.'));

    // Copy an image file, write DB record to files table, and save in Field storage.
    // Note we specify the source query fields that will map to the file alt/title/description
    // values.

    $eps_arguments = MigrateFileFieldHandler::arguments(NULL,
      'file_link', FILE_EXISTS_RENAME, 'en', array('source_field' => 'eps_psd_name'),
      array('source_field' => 'eps_psd_filename'), array('source_field' => 'eps_psd_filename'), NULL, TRUE);

    $this->addFieldMapping('field_file', 'eps_psd_uri')
         ->arguments($eps_arguments);

    // Add fields that are mapped via argument
    #$this->addFieldMapping(NULL, 'eps_psd_uri');
    $this->addFieldMapping(NULL, 'eps_psd_filename');
    $this->addFieldMapping(NULL, 'eps_psd_name');

    // No unmapped source fields
    $this->addUnmigratedSources( array('fcid', 'jpg_uri', 'jpg_filename', 'jpg_name', 'category_tid') );

    // Unmapped destination fields
    $this->addUnmigratedDestinations( array('is_new', 'name', 'created', 'changed',
      'status', 'promote', 'revision', 'language', 'sticky', 'uid', 'revision_uid',
      'title', 'body', 'field_image', 'field_keywords', 'field_download_count',
      'field_images_category', 'field_media_status', 'field_media_audience',
      'field_roles_download', 'field_roles_share', 'field_roles_view', 'path', 'comment',
      'bookmarks', 'cart', 'download', 'pathauto') );
  }
  /*
  public function prepare(&$node, &$row) {

  }*/

  public function prepareRow($current_row) {
    //If the file does not exist then skip it.
    if (!file_exists(drupal_realpath($current_row->eps_psd_uri))) {
      return FALSE;
    }

    $result = db_query("SELECT ff.* FROM field_data_field_file ff INNER JOIN migrate_map_imageassetnode ian ON ff.entity_id = ian.destid1 WHERE sourceid1 = :sid", array(':sid' => $current_row->fcid));

    //If there is more then one file field entry attached to the node then skip.
    if ($result->rowCount() > 1) {
      return FALSE;
    }
  }
}

class MigrateDestinationNodeExtended extends MigrateDestinationNode {
  /**
   * Basic initialization
   *
   * @param string $bundle
   *  A.k.a. the content type (page, article, etc.) of the node.
   * @param array $options
   *  Options applied to nodes.
   */
  public function __construct($bundle, array $options = array()) {
    parent::__construct($bundle, $options);
  }

  /**
   * Import a single node.
   *
   * @param $node
   *  Node object to build. Prefilled with any fields mapped in the Migration.
   * @param $row
   *  Raw source data object - passed through to prepare/complete handlers.
   * @return array
   *  Array of key fields (nid only in this case) of the node that was saved if
   *  successful. FALSE on failure.
   */
  public function import(stdClass $node, stdClass $row) {
    // Updating previously-migrated content?
    $migration = Migration::currentMigration();

    if (isset($row->migrate_map_destid1)) {
      // Make sure is_new is off
      $node->is_new = FALSE;

      if (isset($node->nid)) {
        if ($node->nid != $row->migrate_map_destid1) {
          throw new MigrateException(t("Incoming nid !nid and map destination nid !destid1 don't match",
            array('!nid' => $node->nid, '!destid1' => $row->migrate_map_destid1)));
        }
      }
      else {
        $node->nid = $row->migrate_map_destid1;
      }

      // Get the existing vid, tnid so updates don't generate notices
      $values = db_select('node', 'n')
                   ->fields('n', array('vid', 'tnid'))
                   ->condition('nid', $node->nid)
                   ->execute()
                   ->fetchAssoc();

      $node->vid = $values['vid'];
      $node->tnid = $values['tnid'];
    }

    if ($migration->getSystemOfRecord() == Migration::DESTINATION) {
      if (!isset($node->nid)) {
        throw new MigrateException(t('System-of-record is DESTINATION, but no destination nid provided'));
      }

      $old_node = node_load($node->nid);

      if (!isset($node->created) && isset($old_node->created)) {
        $node->created = $old_node->created;
      }

      if (!isset($node->vid) && isset($old_node->vid)) {
        $node->vid = $old_node->vid;
      }

      if (!isset($node->status) && isset($old_node->status)) {
        $node->status = $old_node->status;
      }

      if (!isset($node->uid) && isset($old_node->uid)) {
        $node->uid = $old_node->uid;
      }
    }

    // Set some required properties.
    // Set type before invoking prepare handlers - they may take type-dependent actions.
    $node->type = $this->bundle;

    if ($migration->getSystemOfRecord() == Migration::SOURCE) {
      if (!isset($node->language)) {
        $node->language = $this->language;
      }

      // Apply defaults, allow standard node prepare hooks to fire.
      // node_object_prepare() will blow these away, so save them here and
      // stuff them in later if need be.
      if (isset($node->created)) {
        $created = MigrationBase::timestamp($node->created);
      }
      else {
        // To keep node_object_prepare() from choking
        $node->created = REQUEST_TIME;
      }

      if (isset($node->changed)) {
        $changed = MigrationBase::timestamp($node->changed);
      }

      if (isset($node->uid)) {
        $uid = $node->uid;
      }

      node_object_prepare($node);

      if (isset($created)) {
        $node->created = $created;
      }

      // No point to resetting $node->changed here, node_save() will overwrite it
      if (isset($uid)) {
        $node->uid = $uid;
      }
    }

    // Invoke migration prepare handlers
    $this->prepare($node, $row);

    if (!isset($node->revision)) {
      $node->revision = 0; // Saves disk space and writes. Can be overridden.
    }

    // Trying to update an existing node
    if ($migration->getSystemOfRecord() == Migration::DESTINATION) {
      // Incoming data overrides existing data, so only copy non-existent fields
      if ( !isset($old_node) || ( isset($old_node) && (empty($old_node) || !is_array($old_node)) )) {
        $return = FALSE;
      }
      else {
        foreach ($old_node as $field => $value) {
          // An explicit NULL in the source data means to wipe to old     value (i.e.,
          // don't copy it over from $old_node)
          if (property_exists($node, $field) && $node->$field === NULL) {
            // Ignore this field
          }
          elseif ($field == 'field_file') {
            $file_field = $node->$field;
            $lang_files = array();

            // We can import this, got to do it on a per language basis
            foreach ($value AS $lang => $files) {
              if (isset($file_field[$lang])) {
                $new_node_files = $file_field[$lang];
              }
              else {
                $new_node_files = array();
              }

              $lang_files[$lang] = array_merge($new_node_files, $files);
            }

            $node->$field = $lang_files;
          }
          elseif (!isset($node->$field)) {
            $node->$field = $old_node->$field;
          }
        }
      }

    }

    if (isset($node->nid) && !(isset($node->is_new) && $node->is_new)) {
      $updating = TRUE;
    }
    else {
      $updating = FALSE;
    }

    migrate_instrument_start('node_save');
    node_save($node);
    migrate_instrument_stop('node_save');

    if (isset($node->nid)) {
      if ($updating) {
        $this->numUpdated++;
      }
      else {
        $this->numCreated++;
      }

      // Unfortunately, http://drupal.org/node/722688 was not accepted, so fix
      // the changed timestamp
      if (isset($changed)) {
        db_update('node')
          ->fields(array('changed' => $changed))
          ->condition('nid', $node->nid)
          ->execute();

        $node->changed = $changed;
      }

      // Potentially fix uid and timestamp in node_revisions.
      $query = db_update('node_revision')
                 ->condition('vid', $node->vid);

      if (isset($changed)) {
        $fields['timestamp'] = $changed;
      }

      $revision_uid = isset($node->revision_uid) ? $node->revision_uid : $node->uid;

      if ($revision_uid != $GLOBALS['user']->uid) {
        $fields['uid'] = $revision_uid;
      }

      if (!empty($fields)) {
        // We actually have something to update.
        $query->fields($fields);
        $query->execute();

        if (isset($changed)) {
          $node->timestamp = $changed;
        }
      }

      $return = array($node->nid);
    }
    else {
      $return = FALSE;
    }

    $this->complete($node, $row);
    return $return;
  }
}
?>

```

Pastebin Link as well: http://pastebin.com/ykzgVvCF

# Answer
> 1 votes
I think what you need is prepareRow. Here is code from the migrate baseball example where multiple fields are merged into a single array field.

```
 function prepareRow($row) {
    // Collect all the batters into one multi-value field.
    for ($i=1; $i <= 9; $i++ ) {
      $key = "visiting_batter_$i";
      $visiting_batters[] = $row->$key;
      $key = "home_batter_$i";
      $home_batters[] = $row->$key;
    }
    $row->visiting_batters = implode(',', $visiting_batters);
    $row->home_batters = implode(',', $home_batters);
    $row->title = "$row->home_team vs. $row->visiting_team. " . gmdate('M d, Y', strtotime($row->start_date));
  }

```

(from the file migrate\_example\_baseball.migrate.inc)

However I have been having mixed results with prepareRow in my own code, so while this looks straight forward I can't guarantee that it will work.

# Answer
> 1 votes
hmmrr. It might be easier not to do this in 1 pass ... but a 2 step migration. Create your new parent record in 1 migration task, then back-fill in your N file\_fields with the new node or entity id as a second migration task.

furthermore, while you've looked into System of Record -- my understanding of this feature is it only works for DB schemas which are 1:1 between your old DB and the new DB schema. Eg, a multiple value field entry cannot be inspected because could be N-fields in a row in an old DB and for instance N-rows crossreferenced to a parent row id in the new DB.

I have used the "Query in Prepare" method, I tried the group\_concat version too .... so that's my 2 cents on the matter.

---
Tags: 7, entities, media, migrations, files
---


# Question
Title: How to manually uninstall/purge modules?
I have a module `Media: YouTube` which is being buggy when attempting to uninstall. I disabled it in the modules along with its dependencies, and when I go to the uninstall tab and perform the uninstall operation, it returns a blank screen. I go back to the module page, and it's still there (along with 3 other modules that need this one uninstalled first before the others can be removed).

Is there a general method of purging modules from the backend? I have full access to the server and database as well.

EDIT: Checked logs and found a PHP error:

> \[Thu Jan 19 13:12:21 2012\] \[error\] \[client 192.168.xxx.xxx\] PHP Fatal error: Call to undefined function media\_youtube\_variable\_default() in /var/www/drupal/sites/all/modules/media\_youtube/media\_youtube.install on line 19, referer: http://vulcan/drupal/?q=admin/modules/uninstall/confirm&render=overlay

Sounds like it's just a badly written module?

# Answer
This is a known bug. Replace the module with the most recent DEV version, update, and then try uninstalling again
> 3 votes

---
Tags: 7, installation
---


# Question
Title: Adding alt/title attributes to uploaded images
I've created a galley using fields and views thanks to this tutorial: http://jamestombs.co.uk/2011-05-26/create-album-based-image-gallery-drupal-7-using-fields-and-views

But now I can't figure how to add the usual ALT and TITLE attributes to the gallery images. The only option available is to delete the images.

Thank you.

# Answer
The tutorial you are referencing states this, "On the next screen just press Save field settings." This is where the issue starts. You have to edit the image field he tells you to create and, instead of hitting 'just save' you have to enable the options for ALT and TITLE fields, about 3/4 down the page.

Then, when you upload image, each image will display a place where you can fill these out.

Then, in views, you will have two more options - Content: Image (some\_field) ALT, and Content: Image (some\_field) Title. You can then select these as fields and theme them as needed to be part of your image gallery
> 1 votes

---
Tags: entities, media
---


# Question
Title: How to alter the languages available in a form
I have a multilanguage site. When I go to edit a node, all the languages of the site are available. I only want some of the active languages to appear in the dropdown for certain users (for various complicated reasons).

In Drupal 6 I did this:

```
function example_form_alter(&$form, &$form_state) {
    //example_language_list returns an array in the from of   ("en"=>"English") etc
    $languages = example_language_list($form['#node'], TRUE);
    $form['language']['#options'] = $languages;
    if (count($languages)==1) {
        $form['language']['#disabled'] = TRUE;
    }
}

```

Any idea how I do this in Drupal 7?

# Answer
OK: found the answer for anyone else. In D7, the i18n implements a callback that happens AFTER the form is rendered, so you need to add a callback as well. So:

```
function example_form_node_form_alter(&$form, $form_state) {
   $form['#after_build'][] = '_example_form_node_form_alter';
}

function _example_form_node_form_alter($form, &$form_state) {
  //example_language_list returns an array in the form of ("en"=>"English") etc
  $form['language']['#options'] = example_language_list($form['#node'], TRUE);
  if (!i18n_node_language_options($node, 'required')) {
    $form['language']['#options'] = array(LANGUAGE_NONE => t('Language neutral')) + $form['language']['#options'];
  }
 return $form;
}

```
> 6 votes

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


# Question
Title: How does Drupal handle autoloading of classes?
How does Drupal handle autoloading of classes through modules? For instance, if I have an Events module, and I declare a class called Event, and then in the .info file I include the class file, how is this registered?

The problem is that I'm trying to dynamically get an array containing all loaded class names. get\_declared\_classes() does not return the names of all my classes declared in this manner, so I'm assuming that they're autoloaded somehow. Following the suggestions from another stack overflow question, I tried getting all of them with spl\_autoload\_functions(), but that was also unsuccessful.

Any ideas?

# Answer
> 14 votes
All files listed in .info files are parsed when modules are rebuild (Only changed/new files in that list are, for performance reasons).

That information is then stored in the `{registry}` and `{registry_files}` tables. So if you want to get all classes or those according to a given naming pattern, you can query those tables.

# Answer
> 7 votes
Drupal maintains a code registry and uses it for its classes autoloader. To populate this registry with your module's classes, you should add their files to the files\[\] entry in it's .info file:

```
files[] = includes/Foo.inc
files[] = includes/Bar.inc

```

PHP's class autoloading will make sure that the parent class file is also loaded.

Credit to user pier-buyle for this answer, see his original answer here for the same question.

Hope that helps

# Answer
> 5 votes
`spl_autoload_functions()` returns the list of the autoload functions that have been registered with `spl_autoload_register()`. Drupal registers two autoload functions: one for the classes (drupal\_autoload\_class()), and one for the interfaces (drupal\_autoload\_interface()).

Both the functions use \_registry\_check\_code(); using its code, you can write a function that lists all the classes implemented by Drupal 7 modules.

# Answer
> 3 votes
If you have added an entry to the files\[\] array of the .info file, you will have to go to your modules administration section and click on "save configuration". This will get drupal to refresh the .info information, and the new entries will be registered.

# Answer
> 1 votes
I have found that declaring my include files in the info file does not get them recognized when I start running the module. If I have a class Event in the file event.inc. but crate an object in the module, it is not recognized. I add the line

```
include_once ('CMatArticleHandler.inc');

```

prior to the $variable = new event(); line. Im' new at this so there may be more to it then this, but it has worked so far.

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


# Question
Title: How do I change the field title on the "Generate automatic URL alias" checkbox in pathautho?
How do I change the title of the checkbox "Generate automatic URL alias" on the pathauto fieldset on the node add page?

In my hook\_form\_node\_form\_alter I don't see this anywhere in the $form.

# Answer
> 2 votes
One option is to utilize the String Overrides module. Depending on exactly what you are trying to do, it may be a bit easier to administer and manage this change via the admin rather than in code.

---
Tags: 7, hooks, forms, path-aliases
---


# Question
Title: How can I let users enter the cck value once and then protect the field from editing?
I have several cck fields that shouldn't be modified once after the node is created. For example like fields for gender, name, birth date and so on. Is it possible to hide or make them unable to edit those fields by users after the node creation? I thought maybe I could do that by Rules but unfortunately it seems that there is no action for hiding cck field forms though it has the condition for "if field has a value".

# Answer
I think the link below will be helpful to you..

Code snippet: How to set the disabled or readonly attribute of a CCK field

Check this link and let me know if in case of any query.

Thanks.
> 2 votes

# Answer
I've not used the module, but Field Permissions appears to create the level of permissions you are looking for, eg, it grants users permission to CREATE a CCK field value separate from the permission to EDIT it.
> 0 votes

---
Tags: entities, 6, rules
---


title: Module enhancement file

text:
# Question
Title: Module enhancement file
Hi guys (and gals) I'm trying to create a simple enhancement to one of my modules .inc files and am messing something up somewhere, and was hoping someone with sharp eyes can point it out. Even though it is extremely easy to just insert one line into the contrib file, do to our companies "best practices" I need to add this in another way.

I am trying add one extra variable into the $services array of the gigya\_get\_networks function, the function in gigya.inc is

```
function gigya_get_networks() {
  $services = array(
    'facebook' => 'Facebook',
    'myspace' => 'MySpace',
    'twitter' => 'Twitter',
    'google' => 'Google',
    'yahoo' => 'Yahoo',
    'aol' => 'AOL',
    'blogger' => 'blogger',
    'wordpress' => 'WordPress',
    'typepad' => 'typepad',
    'liveJournal' => 'liveJournal',
    'hyves' =>  'hyves' ,
    'veriSign' => 'veriSign',
    'linkedin' =>  'LinkedIn',
    'liveid' => 'Windows Live ID',
    'openid' => 'OpenID',
    'orkut' => 'Orkut',
  );
  return $services;
}

```

I created a new module in /custom/utilities/gigya\_enhancements with the following

gigya\_enhancements.info

```
name = Gigya Enhancements
description = Provides Gigya enhancements.
package = Gigya
php = 5.2

files[] = gigya_enhancements.module

dependencies[] = gigya

version = 7.x-3.1
core = 7.x

```

and a gigya\_enhancements.module with the following

```
<?php
/**
 * Implements hook_get_networks().
 */
function gigyas_enhancements_get_networks() {

  // Add Vkontakte to existing services.
  $services = array(
    'vkontakte' => 'VKontakte',
  );

    // shortcode: return $services['vkontakte'] = 'VKontakte';

  return $services;
}

```

But I'm not returning my additional array parameter, would someone mind explaining what I (evidently) have done wrong? Is it something to do with me trying to operate on an \*.inc file maybe?

Thanks everyone.

# Answer
Just adding an extra module with a similarly-named function won't guarantee that gigya will call that function. If Gigya's module has hooks (Google doesn't seem to be able to tell me at a glance), then that's the source for how to do what you're trying to do.

Also, you never need to put your .module file in files\[\]. That's only for files in the module that declare classes.
> 2 votes

---
Tags: 7, hooks
---


# Question
Title: Views - No results behavior with Exposed filter criteria
I have a views setup with one title field, exposed filter criteria and No results behavior (Simple Text). Problem is No results behavior shows before user applied any filter criteria. I need No results behavior to show up only if filter criteria didn't find any content. Help please and thank you!

# Answer
> 1 votes
I think you selected the **Autosubmit** option in the exposed form settings.

> > Autosubmit
> > Automatically submit the form once an element is changed

---
Tags: views
---


# Question
Title: D7 views list of nodes with node reference count
I have two content types **A** and **B**. The content type **B** has a node reference to **A**.
I would like to create a views list which show nodes of **A** with no. of node count of **B**.
It is very similar to a list of nodes which comment count for each.

# Answer
> 2 votes
I am not too up on D7, but the Nodereference Count module has worked for me in D6 and there appears to be a D7 version.

# Answer
> 1 votes
I've done something similar 2 weeks ago. Basically you need to use a setting called **Use aggregation**, which can be found in the Views **Advanced** tab. By enabling it, you will have extra "Aggregation settings" for each field, where you can choose between (COUNT, COUNT DISTINCT, SUM, AVERAGE, etc.). A possible workflow would be:

1. Enable aggregation (Views Advanced tab --\> Use aggregation).
2. Use a relationship (in your case the node reference field).
3. Add `Content: Nid` field and make it use the relationship.
4. Change the Aggregation Settings for the `Content: Nid` field to **COUNT**

That should be all!

---
Tags: views, nodes
---


# Question
Title: How to find the number of clicks on a flash banner?
There is a flash banner in a Drupal website. I want to know number of clicks on that flash banner.

**My Question**: Is there such option in Drupal (in Joomla there is one).

# Answer
> 4 votes
I would recommend using Google analytics and attach a click event to the banner. using a module would introduce unnecessary overheads

# Answer
> 1 votes
You can follow WestieUK by installing the Google Analytics-module on your website or you can install the Click-module (Drupal \< 6 only) so the admin can see exactly on which links, images,... are clicked by the users.

Or you can use the Advertisement module, which will allow you to place a banner on your site and the module tracks down the traffic it's generating. And Flash is a supported format!

---
Tags: nodes
---


title: Content changes history

text:
# Question
Title: Content changes history
is it possible to view content changes history (author - date) ? We have many users modifying content in our website, and I'd like to know who made each change.

# Answer
> 4 votes
The Revisioning-module is exactly what you are looking for. It keeps revisions of every change and offers you the possibility to moderate the content.
I use it for a few project and I'm very happy with the results!

# Answer
> 2 votes
If you want to see the differences between revisions the diff module would be handy as well.

---
Tags: 6
---


# Question
Title: How do I theme a menu to have a wrapper div with menu name?
The default menu theme function doesn't output the menu name (see below).

```
function theme_menu_tree($variables) {
  return '<ul class="menu">' . $variables['tree'] . '</ul>';
}

```

I've inspected $variables, and that doesn't contain the menu name. Does anyone know how I can theme a menu so that its name is in a wrapper div?

# Answer
> 5 votes
`theme_menu_tree()` is a theme wrapper function: it's called after the render array for the menu tree is rendered, and thus, after you have a chance to modify the rendered output.

Additionally, you can't pass any arbitrary data to a theme wrapper function: it'll always receive the rendered output of the children.

So to do what you want to do, where you have a wrapper `<div>` that has an ID, you need to modify the menu tree render array to call your own theme function that adds it.

### Practical example

Let's say you're trying to do this for all menu blocks (a common use-case for menu trees): `menu_block_view()` populates the content of the block with `menu_tree($delta)`, where `$delta` happens to be the menu name corresponding to the block.

Now, `menu_tree()` calls `menu_tree_output()`, which is where the render array that calls `theme_menu_tree()` is built.

So, what you want to do is modify the contents of the block after the render array is built, to replace `theme_menu_tree()` with your own theme function that adds your `<div>` with ID. To do that, implement `hook_block_view_alter()`:

```
/**
 * Implements hook_block_view_alter().
 */
function MYMODULE_block_view_alter(&$data, $block) {
  // Check to make sure this is a menu block
  if (in_array($block->delta, menu_get_names())) {
    // Replace the theme wrapper function with a theme function
    // and add the menu name to the render array
    unset($data['content']['#theme_wrappers']);
    $data['content']['#theme'] = 'MYMODULE_menu_tree_with_id__' . $block->delta;
    $data['content']['#menu_name'] = $block->delta;
  }
}

```

Replace `MYMODULE` with your module's short name. Once implemented, create the theme function `theme_MYMODULE_menu_tree_with_id()` to handle wrapper `<div>`:

```
/**
 * Implements hook_theme().
 */
function MYMODULE_theme() {
  $theme = array();
  $theme['MYMODULE_menu_tree_with_id'] = array(
    'render element' => 'element',
  );
  return $theme;
}

/**
 * Returns a menu tree with an id corresonding to the menu name.
 */
function theme_MYMODULE_menu_tree_with_id($variables) {
  $output = '<div id="' . $variables['element']['#menu_name'] . '">';
  $output .= '<ul class="menu">' . drupal_render_children($variables['element']) . '</ul>';
  $output .= '</div>';

  return $output;
}

```

---
Tags: 7, routes, theming
---


# Question
Title: extend('PagerDefault') doesn't call pager_default_initialize
My code:

```
   $num_per_page = 1;

   $query = db_select('redagavimas', 'r')
      ->fields("r");
   $query->join('dusers', 'd', 'd.id = r.user');
   $query->join('companies', 'c', 'c.id = r.company');
   $query->join('documents', 'doc', 'doc.id = r.doc');

   $query->addField('d', 'name');
   $query->addField('d', 'surname');
   $query->addField('c', 'name', 'company');
   $query->addField('c', 'id', 'companyID');
   $query->addField('doc', 'name', 'docname');
   $query->addField('r', 'user', 'did');

   $query->extend('PagerDefault')->limit($num_per_page);
   $query->extend('TableSort')->orderByHeader($header);

   ....

   $result = $query->execute();

   ....

     '#suffix' => theme('pager', array( 'tags' => array())),

```

I don't see any pager; If I call somewhere `pager_default_initialize()`, then I see the pager. What I did wrong?

**EDIT :**

I try:

```
echo $query->extend('PagerDefault')->limit($num_per_page)->getCountQuery();

```

and get query, which `return >100` rows.

# Answer
> 8 votes
As documented on the See the Extenders page on drupal.org:

> To use an extender, you must first have a query object. From the query object, the extend() method will return a new object that should be used in place of the query object. For example:

```
$query = $query->extend('PagerDefault');

```

> The above line takes a select query, creates a new PagerDefault query object that contains the original select query, and returns the new object. $query may now be used as if it were the original query object but with additional methods now available.
>
> Note that $query is not altered in place. The new object is returned from extend(), and if it is not saved to a variable it will be lost. For example, the following will not do what you expect:

So, you first line should looks like:

```
$query = db_select('redagavimas', 'r')->extend('PagerDefault')->fields("r");

```

# Answer
> -1 votes
You have to print the theme function like this:

```
print theme('pager', array('tags' => array());

```

---
Tags: database
---


# Question
Title: Drupal Ubercart Merchant ID and Key are incorrect?
When I checkout in Ubercart the merchant key and merchant id are incorrect. In my configuration they are correct, but when the login credentials are displayed during checkout, they are jumbled.

I am using the uc\_domain module to manage different payment gateways per domain. My original domain is working correctly, but my new domain, as seen in the image, is not working correctly.

The main error that I am getting is this:

> DOMDocument::loadXML() \[function.DOMDocument-loadXML\]: error parsing attribute name in Entity, line: 1 in .../ubercart/payment/uc\_cybersource/uc\_cybersource.soap.inc on line 31.

Screenshot: http://yfrog.com/gzv1tpp

# Answer
> 0 votes
To fix this issue I made sure that the proper soap packages were installed. Then I went on to create new credit card encryption keys for each domain. Right now I am waiting on SSL certs so that Drupal can generate new credit card encryption keys for each domain. I hope it works!

---
Tags: ubercart
---


# Question
Title: How to hi-lighten with red border when multi check box fails validation.
I've been searching around for days but can't find the solution.. I know this is a core bug and have found two solutions on http://drupal.org but both of them don't work for multi check box validation on my site (It works for single check box and multi radio buttons though).

These are what I have found:

Required radios/checkboxes are not validated (D6)

move checkboxes error class to parent div, so that checkboxes can be given a red border like other fields

My problem is that it's not outputting the error classes only for multi check box even after using those methods above. Any idea how to fix this?

# Answer
Have you tried this module: Checkbox Validate ?

> Corrects bugs in Drupal core:
>
> * Checkboxes set as required not displaying required symbol (install this module to display)
> * Checkboxes set as required behave as optional (install this module to make behave as required field)
>
> This is the related D6 issue: #259292: Required radios/checkboxes are not validated (D6).
> 1 votes

---
Tags: 6, forms
---


title: Transactions and form api

text:
# Question
Title: Transactions and form api
Is it possible to use FAPI and transactions?

I need to implement a validation that makes a query to check something and on the submit I need to update the database.

I thought to open a transaction on the validation callback and set it on the $form\_state and then commit my transaction on the submit handler. I didn't liked this solution but was the best that I could think.

How do you solve this kind of things on drupal? What do you think about my solution?

# Answer
Can you use FAPI with transactions: Yes.

But you can't or rather shouldn't use it the way you describe. Transactions only take effect when you commit them, so there really is no point in starting the transaction in the validation. Also what happens if you have a validation error, you won't commit the transaction. I believe that starting a transaction will effect other incoming queries as well.

Transactions are only good if you want to do multiple queries at once, and do all or nothing. Like insert data in main table and revision table and then update the revision number in main table.

What are you trying to do that makes you think that you should make transaction in such a way?
> 2 votes

---
Tags: 7, forms, database
---


# Question
Title: Node body not preserving HTML formatting?
The body area of my node is set to WYSIWYG. When I enter in HTML formatting (using the WYSIWYG buttons), it doesn't make it to the content type template:

```
print $node->content['body']['#value'];

```

Why doesn't the HTML come through? How can I print the node body to the page and preserve the HTML formatting? What am I doing wrong here?

Thanks!

# Answer
> 2 votes
Your input format is likely "Filtered HTML", or something other than "Full HTML". Check the input format (below the body textarea when editing the node).

---
Tags: wysiwyg, theming, nodes
---


title: Link to a file field in the body text?

text:
# Question
Title: Link to a file field in the body text?
I have a content type that has a file field. I would like the body field to be able to link to the file. E.g. *"Our research (PDF download) shows..."* with the link becoming the download path for the file.

I can see the challenge: the path may not even exist at the time of creating the content. Is this something the token module can help with?

# Answer
> 1 votes
You could add this inside your node-my\_content\_type.tpl.php file:

```
if (isset($node->field_my_file[LANGUAGE_NONE])) {
  print str_replace('[field_file:1]', file_create_url($node->field_my_file[LANGUAGE_NONE][0]['uri']), $node->body[LANGUAGE_NONE][0]['value']);
} else {
  print $node->body[LANGUAGE_NONE][0]['value'];
}

```

If the file exists, it will be printed as a link in place of the placeholder \[field\_file:1\] in your body.

# Answer
> 1 votes
Not 100% exactly what you're asking for, but it may solve your requirement:

The IMCE module allows you to upload documents (and images) and integrates them in the body text. You don't need a separate file field if all you need is a document integrated into your text via a link.

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