# Question
Title: Related Content with References in Drupal 7
I have made this website using Drupal 7 a year ago, where the References module plays a key role.

Say I have two content types movie and actor, and the content type movie has a references field which references actor nodes. Now, how do I have a block which lists other movies which the actors in this movie are referenced?

Something seems to be here: http://drupal.org/node/370227 but that doesn't seem to work for Drupal 7.

Also, as I have more than 1000 nodes in content type movie, I prefer not to move from References field also, my all my urls are like example.com/content-example

Thanks!

# Answer
> 2 votes
I am sure you could do all of this in one view using a contextual filter and using that as a relationship to point to the movies in question, but, if you don't mind some php coding, you can do all of this pretty easily yourself and one simpler view.

```
1.  create a view that has a contextual filter using the actor reference field, eg,
it returns just the movies that contain that actor, and in fields, just nid of the
movie node should be sufficient.  Make sure that this will reference any actor in the
movie, eg, all of the values of this field, not just the first one.

```

Then in your block hook, put in something along the lines of:

```
$node=menu_get_object();

$movies=array();
foreach ($node->NAME_OF_ACTOR_REFERENCE_FIELD as $actor) {
   $view=views_get_view('NAME_OF_VIEW_ABOVE');
   $view->set_arguments(array($actor['nid']));
   $view->execute();
   foreach ($view->result as $result) {
      $movies[$result->nid]=$result->nid;
   }
}

```

Assuming this is displayed on a page that is displaying a movie of course, what this does is grab the actors referenced in that node and then loops through them, grabbing each movie that has referenced them as well, and then stores that in an array. Since we key this array to the movie's nid, we also create a unique list of movies.

So, now we have a list of movie nids so we can do something like:

```
foreach ($movies as $nid) {
  $node=node_load($nid);
  $content.='<div class="movie-title-link">' . l($node->title, $node->path) . ' </div>';
}

```

and return $content as the content of the block and style it however you want with css.

Caveat: I am just learning D7 and a lot of times D6isms creep into play, and most of the above is just typed in from memory, so there may be subtle things you'll need to adjust (`drupal_set_message()` and `print_r()` are your friends) but this hopefully will help out.

---
Tags: 7, views, blocks, nodes
---


# Question
Title: On the user edit page, how can I show the "Help text" for my fields after the "Label" and before the selection widget?
I have a field on the user edit page that looks like this:

Label: What kind of fruits do you like?

* (checkbox) Apples
* (checkbox) Bananas
* (checkbox) Grapes
* (checkbox) Oranges
* (checkbox) Pears

Description: Check all that apply.

The actual list of checkboxes is quite long (20 or so items) and so I would like to put the description after the label and before the checkboxes-- preferably for all fields displayed using the checkbox widget provided by the select (or other) module.

How can I adjust where the description is displayed?

# Answer
> 1 votes
Install the theme developer module and point to your widget. It will tell you which hooks and templates are rendering it and what functions/templates you can use to override this functionality.

Often I find myself first copying the default code to the custom function/template and then twicking it to my needs.

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


# Question
Title: How to render a node image separately from the rest of the node content
I want to know the variable name for the image which renders with content; being more specific when I render my content with the following code:

```
<?php
  print render($content);
?>

```

It renders my node image, title, body, and tags. I want to put a `<div>` around my image, but I don't know how to specifically do it in my node.tpl.php. I found out how to render my tags, but I have no luck with images.

# Answer
What you need is the *machine name* for your field. This can be found by browsing to the content type in the admin, and seeing the value in the machine name column in the table. Within your node.tpl.php you can then access it using:

```
 print render($content['field_machine_name']);

```

By way of a more comprehensive description of how to render different elements of your node within the node.tpl.php, please see the rest of this answer.

You can implement this in a corresponding node template for your theme: In your theme directory, copy the default `node.tpl.php` from Drupal itself (resides in `root_directory/modules/node/node.tpl.php`, then make a second copy, `node--content_machine_name.tpl.php`. The variable you're interested in is an array which contains all the contents of the node you're about to display (from the Drupal API docs):

> $content: An array of node items. Use render($content) to print them all, or print a subset such as render($content\['field\_example'\]).

Using the `$content` array within this template then allows you to print either sections of the array (field by field for example), or to print the whole array, or to hide sections in the print of the whole array to display later.

By way of a couple of examples:

To print a specific field output:

```
<div class="example_field">
    <?php print render($content['field_name']); ?>
</div>

```

Or to delay the printing of a field until after you've printed the rest of the content. (This is used in the default `node.tpl.php` to print comments after the article content .

```
<?php
    // Don't print the comments during the main content run
    hide($content['comments']);

    // Render the main content array
    print render($content);

    // Then render the comments last
    print render($content['comments']);
?>

```

Which will print the field after the main content block. For more information check out the node.tpl.php docs.
> 3 votes

---
Tags: 7, nodes
---


# Question
Title: just installed 7.12 - but got stuck - how to access the backend and login
good day dear drupalers,

just installed 7.12 - but got stuck - how to access the backend. i have no glue.

see the page: http://www.boysday.org \- i do not know how to proceed. how can i see the backend.

**btw.** i do not know the passwd. and the admin-login-name. and i do not know the link to the login page: i was in a hurry while i installled all.

see the result on http://www.boysday.org :

```
Page not found
The requested page "/" could not be found.

```

**question 1:** can the data (login name and passwd) be accessed via the backend!? Can i obtain the data to access the backend of the freshly installed D 7.12 while i look at the backend of the site - with phpmyadmin.

**question 2:** if i have the data - where to go - which link should i follow to acess a login-screen?

look forward to hear from you

greetings

**btw:** there was a lot of noise during the installation - have a look at this folllowing data: - what do you say...!?

http://boysday.org/install.php?profile=standard&locale=en&op=start&id=1

```
Warning: opendir(modules/simpletest/tests/themes/test_theme) [function.opendir]: failed to open dir: Too many open files in file_scan_directory() (line 2034 of /home/vhost/WWW/boysday.org/includes/file.inc).
Warning: opendir(modules/field/modules/list/tests) [function.opendir]: failed to open dir: Too many open files in file_scan_directory() (line 2034 of /home/vhost/WWW/boysday.org/includes/file.inc).
Warning: opendir(modules/update/tests/themes/update_test_basetheme) [function.opendir]: failed to open dir: Too many open files in file_scan_directory() (line 2034 of /home/vhost/WWW/boysday.org/includes/file.inc).
Warning: opendir(modules/update/tests/themes/update_test_subtheme) [function.opendir]: failed to open dir: Too many open files in file_scan_directory() (line 2034 of /home/vhost/WWW/boysday.org/includes/file.inc).
Warning: opendir(modules/block/tests/themes/block_test_theme) [function.opendir]: failed to open dir: Too many open files in file_scan_directory() (line 2034 of /home/vhost/WWW/boysday.org/includes/file.inc).
Warning: opendir(modules/simpletest/tests/themes/test_theme) [function.opendir]: failed to open dir: Too many open files in file_scan_directory() (line 2034 of /home/vhost/WWW/boysday.org/includes/file.inc).
Warning: opendir(modules/field/modules/list/tests) [function.opendir]: failed to open dir: Too many open files in file_scan_directory() (line 2034 of /home/vhost/WWW/boysday.org/includes/file.inc).
Warning: opendir(modules/update/tests/themes/update_test_basetheme) [function.opendir]: failed to open dir: Too many open files in file_scan_directory() (line 2034 of /home/vhost/WWW/boysday.org/includes/file.inc).
Warning: opendir(modules/update/tests/themes/update_test_subtheme) [function.opendir]: failed to open dir: Too many open files in file_scan_directory() (line 2034 of /home/vhost/WWW/boysday.org/includes/file.inc).
Warning: opendir(modules/block/tests/themes/block_test_theme) [function.opendir]: failed to open dir: Too many open files in file_scan_directory() (line 2034 of /home/vhost/WWW/boysday.org/includes/file.inc).

```

what do you say...!? ,look forward to hear from you!!

# Answer
You won't be able to get the password from the database, but you *will* be able to get the email address for user 1 and then request a new password by email.

Have a look in the `users` table for the email address for the entry with a `uid` of 1. Then go to http://mysite.com/user/password, pop in that email address, and wait for instructions to be emailed to you.

After you've re-gained access to the site you can log back in again at any time by going to http://mysite.com/user. The admin backend will most likely be at http://mysite.com/admin, unless someone has changed it (this is unlikely).

The errors you got during install are because of a UNIX limit on the number of open files/file descriptors in the system. Take a look at this article for some suggestions on how to increase that limit so you don't run into the same error again.

It might be that you need to raise this limit and then re-install the site again...I'm not sure if the errors you've received will have stopped the site from being installed properly or not.
> 3 votes

---
Tags: 7, installation
---


# Question
Title: how to update a node field value with jQuery callback the drupal way?
added the callback for jQuery to the hook\_menu in my module.

```
// callback for jQuery with nid and new status as arguments
$items['vacancies_manage/status_callback/%/%'] = array(
    'page callback' => '_vacancies_manage_status_update_callback',
    'page arguments' => array(1,2),
    'access callback' => array('manage own vacancies'),
    'type' => MENU_CALLBACK,
);

return $items;

```

but how do I call this callback from the module using jQuery instead of just the link? Is there a drupal way for this?

# Answer
The jQuery would be pretty simple, something like this:

```
$('#link-id').click(function() {
  $.ajax({
    url: '/vacancies_manage/status_callback/' + id1 + '/' + 'id2',
    data: {'arg1': 1, 'arg2': 2},
    success : function(data) {
      alert(data);
    }
  });
});

```

You'll need to replace `id1` and `id2` with the arguments appropriate to your situation, and `arg1` and `arg2` with whatever you want your POST vars to contain.

Then you just need to make sure that you callback actually prints directly to the page, and doesn't return the entire rendered Drupal page so that the jQuery code can receive a response:

```
function _vacancies_manage_status_update_callback() {
  // Do something with $_POST vars here

  // Print something, perhaps a status message to be picked up in jQuery
  print 'OK';
  drupal_exit();
}

```
> 1 votes

# Answer
The correct way to do this is by using jQuery.ajax. There is a Drupal specific version of this, called Drupal.ajax.
> 1 votes

---
Tags: 7, javascript, routes
---


# Question
Title: Error when trying to edit and save a user field
When trying to update the settings of an integer field in the user fields, there is an error on saving and the logs show the following error:

> PHP Fatal error: Call to undefined function element\_validate\_number() in /var/www/vhosts/**\****/includes/form.inc on line 1361

# Answer
`element_validate_number()` was added in Drupal 7.6 (or 7.8, I can't quite remember) so it may be that you have an older version of core that doesn't contain that function.

If you can't upgrade your version of core, try adding this into a module file, it should save you the headache:

```
if (!function_exists('element_validate_number')) {
  function element_validate_number($element, &$form_state) {
    $value = $element['#value'];
    if ($value != '' && !is_numeric($value)) {
      form_error($element, t('%name must be a number.', array('%name' => $element['#title'])));
    }
  }
}

```

In case you're interested `element_validate_number()` is the replacement for the deprecated `_element_validate_number()`.
> 2 votes

---
Tags: entities
---


# Question
Title: Multi Axes Voting using Fiverstar, Views, Reference
I have tried several different tutorials on how to accomplish this. Most were for drupal 6, but there were few for drupal 7 but none seem to make sense to the modules being used currently that are in dev or stable. The Node Review module seems to be the closest thing to what I need but that requires some hacking to make it work for my particular use. I have several other modules that I've experimented with. Rate 7.x-1.3 Seemed to have potential.

How would I be able to make a system like the following use these modules?;

* Node Reference 7.x-2.0+8-dev
* Fivestar 7.x-2.0-alpha1+22-dev
* Views 7.x-3.3

What I am looking for a content-type: Business. These will have several businesses that people can rate based on different criteria. Multi Axes Rating on separate page or tab. The Review can be a separate content type. Not required thou.

# Answer
> 0 votes
You can add as many vote fields (using Rate or Fivestar) as you want to your Reviews, one vote for each criteria you want to make available. Your Reviews can be a new Content-Type (then you would use a Relationship in the Business View) or you can use Comments (of Business) for this propose. Both Content-Type and Comments are customizable: you can add fields to them.

My first choice would be to add *n* Fivestar rating fields to Business's Comments. You can do that in Business Content-Type Edition, in the "Comment Fields" tab.

But if you want each user to make only one review and have more control/customizations, then a new Content-Type for Reviews can make your life easier.

---
Tags: 7, rating
---


# Question
Title: "&" displaying as "&" in Views exposed filter
So I'm not sure where this happening, but would love to understand & fix it.

The same data is being displayed elsewhere on the website without the above issue, only in this exposed filter (& the content editor form) does it seem to happen.

In the configure filter window the ampersands appear as expected:

The filter is referring to a node reference field:

If I go to edit one of these content types, the ampersands DO NOT appear correctly either (in select list / drop-down box), only in the configure filter window do they appear correctly.

I checked the database & it's saved in "&" form, so somewhere Drupal is converting it...

I could write a javascript snippet to fix it, but I'd like to understand & fix it the "Drupal way"

# Answer
> 3 votes
So I used this jQuery search & replace to fix it client side, I still want to find & fix the issue the proper way & will update this when I do. Here is my resulting jQuery snippet:

```
(function ($) {
$(document).ready(function(){
    $("form#views-exposed-form-maps-page select#edit-destination option").each(function(){
        var text = $(this).text();
        text = text.replace("&", "&");
        $(this).text(text);
    });
});
}(jQuery));

```

# Answer
> 1 votes
It depends on where the exposed filter is coming from. My guess is that on render, the value is escaped twice, one for the label and once for the form itself. Without more info it's not really possible to give a more precise answer.

# Answer
> 1 votes
I had the same problem with a h1 title, my solution was to change from:

```
<?php if ($title): ?><h1 class="title"><?php print $title; ?></h1><?php endif; ?>

```

to

```
<?php if ($title): ?><h1 class="title"><?php print str_replace('&', '&', $title); ?></h1><?php endif; ?>

```

Hope it helps you

---
Tags: views
---


title: Node form – self changing theme

text:
# Question
Title: Node form – self changing theme
I'm adding different way of node editing so I have this code in my module:

```
$items['node/%node/edit-full'] = array(
'title' => 'Full edit',
'page callback' => 'node_page_edit',
'page arguments' => array(1),
'access callback' => 'node_access',
'access arguments' => array('update', 1),
'weight' => 0,
'type' => MENU_LOCAL_TASK,
'file' => 'node.pages.inc',
'file path' => drupal_get_path('module', 'node'));

```

What is disturbing.. it changes theme from admin to regular. Instead of Seven Theme I see regular website theme. Am I missing some variable in my definition?

# Answer
You need to implement `hook_admin_paths()` to tell Drupal to use the admin theme for your URL pattern:

> Modules may specify whether or not the paths they define in hook\_menu() are to be considered administrative. Other modules may use this information to display those pages differently (e.g. in a modal overlay, or in a different theme).

In your case the code would look a lot like this:

```
function MYMODULE_admin_paths() {
  $paths = array(
    'node/*/edit-full' => TRUE
  );
  return $paths;
}

```

Once you've cleared the caches your pages should now be using the admin theme.
> 2 votes

---
Tags: forms, theming, nodes
---


# Question
Title: CKEditor with CKFinder - removing the 'Browse Server' button, but only for certain profiles
I have a number of CKEditor profiles, some of which use CKFinder to upload images. However, for one profile I want to remove the option to browse the server within the CKFinder dialogue, whilst retaining it for another profile.

Is this possible?

There's a similar question answered here, but it only deals with removing the button globally (as far as I can see):

https://stackoverflow.com/questions/3610041/ckeditor-with-ckfinder-disable-filebrowser-keep-upload-functionality

# Answer
In case anyone else end up on this link to look for a solution. I am using wysiwyg, IMCE, IMCE wysiwyg api bridge, and ckeditor.

```
Configuration -> Media -> IMCE -> Role-profile assignments

```

select User-1 or any other profile according to your setting.
> 1 votes

---
Tags: 6, wysiwyg
---


# Question
Title: Should I source control contribed modules in my project?
I've been told that while developing I should source control everything under `sites/` into my code repository (e.g SVN).

Assuming I'll never touch any of the contrib modules I use (`ctools`, `views` etc) but will only create my own theme, should I still do that?

Or should I just source control everything under `sites/all/themes/`?

thanks

# Answer
> 10 votes
In my team, we have moved to only sourcing what is specific to our current project. If we are using Views for example, we add the appropriate entry to our drush make-file, and version *that*, but not the module itself.

This leaves us with a very small repository, consisting of any custom modules specific to the current site, the current theme, and features exports.

Unless you absolutely can't use drush and drush make, I don't see why one should version control code that is well versioned somewhere else. And if you intend to hack on one of modules, then you should add that as a submodule, again, not versioning the code in your own repo. (I believe this is called a vendor branch in SVN).

**Edit:** For more details and a more advanced setup, you can take a look at this repository: git@github.com:letharion/Drupal-build-scripts.git The scripts are written in bash to support my teams workflow which includes a building a base-install profile (NodeStream), then our site-specific profile on top of that, a make file for each profile, hooks for applying patches or making other changes on individual build steps etc. I hope I will find the time to re-write it as a drush extension in the near future.

# Answer
> 6 votes
As a counter to @Letharion's answer, putting everything in SVN makes sense for some organizations and it really depends on how you do your rollouts. Putting contrib modules and themes in SVN can make sense if you ever need to go "back in time" and look at an old version of a site.

One example of this is handy when you suspect a bug in a contrib module, or are seeing different behavior. Being able to restore a full version from the past can help.

I have also found it handy to have a full site snapshot in SVN when I need to figure out what a client did to a site. I can take a full snapshot of their version, and stick it in SVN as a branch and compare.

---
Tags: 7
---


# Question
Title: Error when I try to make a local translate.
I get this error when I try to make translation:

> Not saved locally due to invalid HTML content.

take a look a my capture, first one shows the text to be saved as the translation, and the second capture shows the error message:

# Answer
> 1 votes
It's happening because you have `<div>` tags in your translation text.

`locale_string_is_safe()`, the function used to make sure the string provided for translation is safe, has this to say about the allowed tags:

> The allowed tag list is like filter\_xss\_admin(), but omitting div and img as not needed for translation and likely to cause layout issues (div) or a possible attack vector (img).

So basically you need to remove the `<div>` tags and your translation will work just fine.

If you're interested in the chain of functions called so you can check the logic for yourself, it's as follows:

Since `locale_string_is_safe()` *does* allow `<span>` tags you might consider using those instead. If you need the element to be block level then you can just use CSS to do that.

---
Tags: i18n-l10n
---


title: How to add a class or id wrapper to a

text:
# Question
Title: How to add a class or id wrapper to a
I added a footer to a view and I need to give this footer a wrapper class or id. How can I accomplish with this?

# Answer
> 0 votes
You can also theme this footer using the oft forgotten cascading properties of CSS, eg, if your view is named foobarbaz:

```
 .view-foobarbaz .view-footer {
    color: red;
    font-weight: bold;
 }

```

will make all the footer text bold and red.

# Answer
> 1 votes
You an can put HTML in there, just make sure you choose an Input Format (Text Formats in D7) that allows you to use the HTML tags you'll be putting in there.

# Answer
> 0 votes
```
$('#yourfooter').addClass('yourClass');

```

Or views-view--YOURVIEWNAME.tpl.php and you can add you class there.

Do you want to give it to the footer or to the field? You can even write in the field `<div class="yourclass">it is easier to smash an atom than a prejudice.</div>`

---
Tags: views
---


# Question
Title: List all Ubercart product fields found in uc_product_field_extra_fields()
I am trying to use the Fields API to list all of the Ubercart product fields (cost, model, sell\_price, weight, etc). I have tried

```
entity_get_info('node')
field_info_bundles()
field_info_instances('node', 'product')
field_info_extra_fields('node', 'product', 'form')

```

`field_info_instances()` gives me the image field and the catalog taxonomy, but none of them return the fields added by uc\_product\_field\_extra\_fields(). I thought for sure `field_info_extra_fields()` would return it, but all I get back is `title` and `path`. What is the correct API call to list these fields? I don't need them in display form or anything like that.

I'm using Drupal 7.12 and Ubercart 3.0.

# Answer
> 0 votes
It turns out that in `uc_product_field_extra_fields()`, the extra fields are defined for 'display' and not for 'form'. The correct call is `field_info_extra_fields('node', 'product', 'display');`

---
Tags: ubercart, entities
---


# Question
Title: Search for user by specific 12 digit ID number
I'm building some functionality into a drupal 7 site that will let users search for another user, by a 12 digital identity number (for example: ZD-3423FGIO-XZ)

How would I go about doing this? Would I need to create some custom code to insert a new field in the user table that creates a custom number then modify the search functionality, or would I just use a module to do this?

Any help would be great!

# Answer
> 5 votes
It seems to me like a typical use case for Field UI and Views. No code needed.

Video tutorials on Drupal 7, (Fields from episode 9), and Views.

---
Tags: 7, users, search
---


title: hook_theme not being called in module

text:
# Question
Title: hook_theme not being called in module
I'm working on a module that has a custom output for the form that's being called, and this form has multiple pages. The multiple page part is being called correctly, but I can't get the theme to render the form.

I've got the following code:

```
<?php

// Page callback to render the form
function mymodule_main() {
    return drupal_render(drupal_get_form('mymodule_form'));
}

// Picks which form to call
function mymodule_form($form, &$form_state) {
    drupal_set_message('Picking form to use');
    if(!empty($form_state['page_num']) && $form_state['page_num'] == 2) {
        drupal_set_message('Form 2');
        return mymodule_form_two($form, &$form_state);
    } else {
        drupal_set_message('Form 1');
        return mymodule_form_one($form, &$form_state);
    }
}

// Form definition for the first page
function mymodule_form_one($form, &$form_state) {
    return array(
        // ...
        '#theme' => 'mymodule_theme_one',
    );
}

// Hook theme call
function mymodule_theme() {
    drupal_set_message('Hook Theme has been called');
    return array(
        'mymodule_theme_one' => array('render element' => 'form'),
    );
}

// My custom theme for the first page
function theme_mymodule_theme_one($vars) {
    drupal_set_message('Theme for first form has been called');
    // Code to style the form
    return $output;
}

```

In the `theme_mymodule_theme_one` function I move some of the form definition things around, unset some variables for output, etc. When I visit my page I defined in my hook\_menu() call I get the form I defined in `mymodule_form_one` but without any of the work done in `theme_mymodule_theme_one` and I only get the following two messages:

* Picking form to use
* Form 1

I don't see any of the other messages.

**Edit**

I've cleared the cache manually as well as disabled and re-enabled the module and the theme code still is not being called.

# Answer
> 1 votes
The only thing you should need to do is clear Drupal's cache; hook implementations are cached so once you've written the function you need to clear the cache to get the new data into the registry.

One other small thing, you probably shouldn't be returning an array like you currently are from your form builder function.

I'm pretty sure Drupal sets up the `$form` variable it passes into the function through `drupal_get_form` with some required details, so returning an array (and not the original `$form` element) will probably mean your return from the function is missing something. The usual way would be to do it like this:

```
function mymodule_form_one($form, &$form_state) {
  $form['#theme'] = 'mymodule_theme_one';

  return $form;
}

```

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


# Question
Title: Drupal, Crawlers, and Migrating from a Query string based site to a Clean URLs site
I have a (potentially huge) problem that I did not anticipate. I just built a beautiful new site for the organization I work for. It is a massive improvement over the previous site. The site is also, I'd say, larger than average.

The previous site utilized query strings to navigate around the site, and in a really awful, highly customized fashion. Basically all page URLs looked something like /index.php?page=/path/to/page.php&stuff=4|5|3|1.

The new site utilizes clean URLs.

Now the problem. Crawlers from all over are rampaging through the site and causing high CPU utilization (~50% at all times). I have caching enabled as well as JavaScript and CSS aggregation.

Here's an example URI from the access log:

`/?p=1%7C26%7C31%7C33%7C2%7C7&page=publications.php`

In the current scheme that should just return a 404 in my opinion because that literally represents nothing. Instead it's returning 200 OK which is wrong in so many ways, but technically is right because you do in fact get the home page back. In fact, every single "page" that the crawlers look at right now 90% of the time it's getting back the homepage because it's either looking at /index.php?querystring or /?querystring where of course Drupal does nothing with the query string and just returns the homepage!

I'm not entirely sure how to communicate the correct HTTP status codes to the crawlers. Any advice is much appreciated at this time. I now understand why Google implores you to build sites with clean URL schemes...

# Answer
> 1 votes
You need to handle this in your `httpd.conf` or `.htaccess` before Drupal handles it.

Your best bet is to come up with some rewrite rules and 410 Gone them. Something like this

```
RewriteEngine On
RewriteBase /
RewriteCond %{QUERY_STRING} page=(\w+)&stuff=(\w+)
RewriteRule ^(.*)$ - [G,L]

```

should be a start. You need to play with the query string to match the inbound requests.

---
Tags: 7, uri
---


# Question
Title: When using a view in "Unformatted list" format with inline fields, how can I most cleanly add a break between the fields?
I have a view like this:

* Field A (Inline)
* Field B (Inline)
* Field C (Inline)
* Field D

I would like it to display like this:

* Field A label: value Field B label: value
* Field C label: value
* Field D

Obviously, I need to create a break after the value for Field B. However, what is the best way to do this? CSS in my stylesheet? Rewrite the HTML for the display of Field B? Add a "Custom text" field within the view? It seems like there must be a simpler way...

I hardly ever work with themes so I'm at a loss of how to best address even this basic formatting issue.

EDIT: I've realized that a solution that makes the view label inline but not the whole field would also work, but I don't know how to do this...

# Answer
> 1 votes
You can create a custom layout with Panels module then use that layout inside your view by choosing Panel Fields as rows style and assigning your fields to different regions of the layout.

# Answer
> 1 votes
I would say CSS is the better route because it separates your content from your layout just as CSS does with respect to HTML. Also, if you decide to change your layout later on, CSS will most probably be easier (and more obvious) to change than some fake data in a view forcing that is forcing/hardcoding your layout.

---
Tags: views, theming
---


title: Manage a MySql Database using Drupal

text:
# Question
Title: Manage a MySql Database using Drupal
I want to have something similar to phpmyadmin(not as robust as it though) Is there any way that I can display the contents in my database in a table and allow download of the content(there is a blob field in the table which contains a file). Also the users must be able to add content into the database : as in just upload a new file to the database.

# Answer
For me also need a phpmyadmin for drupal.So i copied a latest phpmyadmin to my modules (sites/all/modules/) folder of drupal.Then i just request in my browser like "http://localhost/proj1/sites/all/modules/mysql/index.php".The phpmyadmin page home page run successfully and asked me a username and password.I gave them, it logged in and showing me all the tables inside the db.Try this way.Also carefull with normal user db operation.I don't know how to configure permission of phpmyadmin with drupal users.
> -4 votes

---
Tags: database
---


# Question
Title: How do you use forms to populate content type fields?
Drupal 7. Custom module. I have a content type 'RFI' with a handful of fields I created with Drupal UI. I want a user to: fill out a form & click submit while drupal: saves fields to database, creates a new node of 'RFI' and populates the fields of the node with the content provided by the form's corresponding fields.

From what I understand:

Build a form with fields (taking from the 'DBTNG examples' module just for clarity):

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

$form['add'] = array(
'#type'  => 'fieldset',
'#title' => t('Add a person entry'),
);
$form['add']['name'] = array(
'#type'  => 'textfield',
'#title' => t('Name'),
'#size'  => 15,
);
$form['add']['surname'] = array(
'#type'  => 'textfield',
'#title' => t('Surname'),
'#size'  => 15,
);
$form['add']['age'] = array(
'#type'  => 'textfield',
'#title' => t('Age'),
'#size'  => 5,
'#description' => t("Values greater than 127 will cause an exception. Try it - it's a    great example why exception handling is needed with DTBNG."),
);
$form['add']['submit'] = array(
'#type'  => 'submit',
'#value' => t('Add'),
);
return $form;
}

```

Here the form fields are saved to database with database API.

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

// Save the submitted entry.
$entry = array(
'name'    => $form_state['values']['name'],
'surname' => $form_state['values']['surname'],
'age'     => $form_state['values']['age'],
'uid'     => $user->uid,
);
$return = dbtng_example_entry_insert($entry);
if ($return) {
drupal_set_message(t("Created entry @entry", array('@entry' => print_r($entry, TRUE))));
}
}

```

Now here is how I know how to create a node of RFI type. How do I take the values of the fields above \[name\], \[surname\], \[age\] and have them related to corresponding fields in my content type?

```
function rfi_build_type($form, &$form_state){
$node = new stdClass();
$node->type = 'rfi';
$node->name = '';
$node->surname = '';
$node->age = '';
$node->language = 'en';
$node->uid = 1;
node_save($node);
}

```

I was thinking that since the fields have been saved already, that I could use a database query to get these values, but intuition tells me I'm overlooking something.

Thank you!

# Answer
> 1 votes
You seem to be going in a slightly wrong direction with this (until I'm missing or not understanding something). If your goal is to create a node based on the data users send via a custom form then it can be done in the form submit handler. Fields added via the GUI don't need separate handling. For example if you are using node\_save() then adding a custom field value could look similar to this:

```
$node->language = LANGUAGE_NONE; // Or e.g. 'en' if locale is enabled.
$node->field_name[$node->language][0]['value'] = $form_state['values']['name'];

```

and with drupal\_form\_submit():

```
$new_form_state['values']['field_name'][$node->language][0]['value'] = $form_state['values']['name'];

```

There's a solid amount of information available about this on the web that you might want to check out for further assistance (like this, this and this).

---
Tags: forms, nodes
---


# Question
Title: Is there any way of adding the exact same login options of StackExchange websites in a Drupal 7 site?
I think that the title is pretty descriptive but I would like to be as detailed as possible so let me list all the login options that I would like my drupal site to have available:

* Open ID
* Stack Exchange
* Facebook
* Yahoo
* Gmail
* Wordpress
* Blogger
* AOL
* Google Profile
* Verisign (optional)
* LiveJournal (optional)
* Clickpass (optional)
* ClaimID (optional)

So, is there any solution to implement this in a Drupal 7 website?

# Answer
Your requirements are pretty big, to say the least!

That being said, I have used Janrain (now named rpx) module with great success in the past.

It can easily implement many of the services on your list in a drupal site. The only con is that it depends on having an account on 3rd party code provider's site, I think they act as a gateway so it is less efficient than a well-built custom solution performance-wise, ***but*** they offer *many* features and the service they provide works very well out of the box with very little configuration.

I highly recommend it for anyone needing 3rd party login services in their app.
> 1 votes

# Answer
StackExchange uses the JavaScript OpenID Selector. Drupal can use the JavaScript OpenID Selector by means of the OpenID Selector module.
> 2 votes

---
Tags: 7, users
---


# Question
Title: Theme the “save” button in a profile page, on a Drupal 6 installation?
How do you theme the "save" button in the profile page (user/uid), on a Drupal 6 installation? I´ve tried and when I try to theme it, it theme all "save" buttons on the site.

Thanks!!

Rosamunda

# Answer
> 3 votes
Found it! I thought I would post it here just in case anyone wonders the same... HOOK\_FORM\_ALTER!

Yay, it was sooo easy with that. **With hook\_form\_alter you can add a prefix and a suffix with the css classes**, and that´s it.

This video podcast of mustardseedmedia helped me A LOT.

Cheers,

Rosamunda

# Answer
> 0 votes
It's a bit unclear what you mean by "theme", but if you need to change the markup, you could create a custom theme function for the form itself and handle how the save button should look like there. If you overwrite the theme function for the submit button in your theme, you are going to change all submit buttons like you experienced.

---
Tags: theming
---


title: Dripping Content for every User

text:
# Question
Title: Dripping Content for every User
a customer asked me about content dripping in drupal. he said that it works in wordpress, but he need that in drupal.

so first of all what is content dripping? He need its for his own customers, who pay for a abo of its site content. So the abo runs for e.g. 10 weeks and the user gets 10 nodes with content on them, e.g. chapters of a book.

So what he needs now is that the content "dripps" to the user, so the user gets every week a new chapter.

My first intention was to use rules, trigger and node\_access to build up a custom set of rules to give the user the permissions once a week.

Then i searched around a lot and found a php script what does excactly that. It gets a list of all members, looks for the date of the abo and checks against a cck field in the node, and if the date is higher than the week of the abo + abo registration date, the content gets accessible.

but it would be much easier and better if i had a module...

So is there any module that does excatly that? As far as i know is content dripping a well known method in online marketing, so maybe there is something?

# Answer
> 1 votes
You could in fact develop your own module to do the above - for example, set a value attached to each user account of number of 'drips' left, which is then decremented by each pageview/similar, and then the total is refreshed at the start of the next billing period, for example by using a scheduled task implemented via the cron system.

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


# Question
Title: Offload cached pages to different Apache process
On our Drupal 6 and Drupal 7 sites each idle Apache process averages 60-100MB each. When the page gets loaded from cache only about 10MB is really needed, but sometimes a page is not cached yet so the process jumps up to 60-100+MB.

We use prefork, so each apache process stays about 60-100MB in size, when in reality 99.99% of the page loads are cached and the processes could easily be down to 10MB.

Our MaxClients settings could be about 5x greater if there were a way to keep the apache sizes down to 10MB.

Is there a way to have two apache processes available, one with a low maxclients for non-cached pages and one with a high maxclients for cached pages? And also, is there a way to route cached & non-cached requests to different processes?

# Answer
It is not a direct answer to your question, but play around with setting `MaxMemFree` and `MaxRequestsPerChild` in the prefork section of your `httpd.conf`. `MaxMemFree` should force Apache to free memory that it doesn't need, and `MaxRequestsPerChild` will force Apache to fork a new process (and free memory in the process) after servicing a particular number of requests. You may have some performance impacts, but gain memory improvements.
> 2 votes

# Answer
I'd suggest moving to the idea of a dedicated, lightweight, configurable cache daemon, for example Varnish which can run in its own right, taking the load off apache for the majority of cache hits for the site, and can even be moved onto a separate physical server in the future should you still need more power.
> 1 votes

# Answer
Apache would need to know if the cache exists if it where to route the process; it currently doesn't. http://httpd.apache.org/docs/trunk/mod/mod\_dbd.html might be one idea if you wish to create your own apache module that will query the cache\_page table. Another option is to look at using something like boost http://drupal.org/project/boost which will not start up PHP on page cache hits.
> 0 votes

---
Tags: caching
---


# Question
Title: Local server doesn't work, directly web on local server go to www
I have a local host and website designed by drupal, I downloaded a website to local host but when I want to open local web directly go to www not to local, please can help me?

# Answer
You probably have a full URL somewhere in your .htaccess file, in the root directory. Search for `Rewrite` directives.
> -1 votes

---
Tags: 7
---


# Question
Title: Getting the source URL of image in Media Gallery Module
I need one more thing to get my custom lightbox running in the Media Gallery module for Drupal 7.

The link that is clicked which leads to a custom page which contains the image is at this moment the following:

```
l($image, $link_path, array('html' => TRUE, 'attributes' => $attributes)) : $image;

```

The thing is that I want to link directly to the image, and not to a page where the image is on! I know that this is hard to understand so I'll try to clarify. At this moment, when you click the link you will be directed to something like this: /media-gallery/detail/xxx/xxxxx

But I want it to link to the image itself (e.g. /files/folder.1.JPG) and I can't seem to find where the image is transformed into a page on itself. Does anyone have ANY idea? I would be soooo grateful!

Thanks a lot you guys. EDIT: I have found that the generated link can be edited by the following snippet of code in colorbox-display.js:

```
var $ = jQuery, $galleries, $gallery, href, $links, $link, $dummyLinksPre, $dummyLinksPost, i, j;
    // Add a colorbox group for each media gallery field on the page.
    $galleries = $('.field-name-media-gallery-media');
    for (i = 0; i < $galleries.length; i++) {
      $gallery = $($galleries[i]);
      $links = $('a.sbEnabled', $gallery);
      $dummyLinksPre = $gallery.parent().find('ul:has(a.shadowbox-supplemental-link.pre)');
      $dummyLinksPost = $gallery.parent().find('ul:has(a.shadowbox-supplemental-link.post)');
      $dummyLinksPost.appendTo($gallery);
      $links = $links.add('a', $dummyLinksPre).add('a', $dummyLinksPost);
      $links.attr('rel', 'shadowbox-' + i);
      for (j = 0; j < $links.length; j++) {
        // Change the link href to point to the lightbox version of the media.
        $link = $($links[j]);
        href = $link.attr('href');
        $link.attr('href', href.replace(/\/detail\/([0-9]+)\/([0-9]+)/, '/lightbox/$1/$2'));
      }
}

```

Unfortunately this doesn't bother to work.

# Answer
The link you're looking to override is hard coded into the `template_preprocess_media_gallery_media_item_thumbnail()` function in the Media Gallery module.

Fortunately, as it's a preprocess hook for a theme function, you can yourself override it in your site's theme. It does mean having to duplicate some code from the original preprocess function, and also another theme function so you can add the `rel` attribute, but it's not too much. You'll also need to implement `hook_js_alter()` to remove the colorbox js the the Media Gallery module adds by default.

Place the following code in your theme's template.php file and replace all occurrences of `THEMENAME` with your theme's name:

```
function THEMENAME_preprocess_media_gallery_media_item_thumbnail(&$variables) {
  $element = $variables['element'];

  // Only make the changes for images, no other media type.
  if (strtolower($element['#bundle']) != 'image') {
    return;
  }

  $format = $element['#media_gallery_entity']->media_gallery_format[LANGUAGE_NONE][0]['value'];
  $lightbox = is_numeric(strpos($format, 'lightbox')) ? TRUE : FALSE;

  /*
   I'M PRESUMING HERE THAT YOU'RE ADDING THE SHADOWBOX SCRIPT USING ANOTHER
   METHOD (PERHAPS IN THE THEME'S .info FILE). IF THAT'S NOT THE CASE JUST
   UNCOMMENT THE FOLLOWING LINE AND CHANGE THE PATH TO ADD IT HERE

   if ($lightbox) {
     $element['file']['#attached']['js'][] = drupal_get_path('theme', 'THEMENAME') . '/path/to/shadowbox.js';
   }
  */

  // Get the rendered file without annoying DIV wrappers.
  $element['file'] = array('#theme' => 'media_gallery_file_field_inline', '0' => $element['file']);
  $image = drupal_render($element['file']);

  $gallery_id = $element['#media_gallery_entity']->nid;
  $media_id = $element['#file']->fid;

  // Add a class that is a more targeted version of what template_preprocess()
  // automatically adds for this theme hook, to enable per-type (e.g., video vs.
  // image) styling.
  $variables['classes_array'][] = drupal_html_class('media_gallery_media_item_thumbnail_' . $element['#file']->type);

  // Add a class for the wrapper.
  $variables['classes_array'][] = 'media-gallery-item-wrapper';

  // Create an array of variables to be added to the main thumbnail link.
  $link_vars = array();
  $link_vars['image'] = $image;

  // THIS IS WHERE YOU MAKE THE CHANGE TO THE LINK PATH. YOU MENTIONED THAT
  // YOU'VE ALREADY MANAGED TO ADD THE 'rel' ATTRIBUTE THAT YOU NEED SO I WON'T
  // ADD THAT HERE
  // Old code: $link_vars['link_path'] = "media-gallery/detail/$gallery_id/$media_id";

  // New code:
  $style_name = 'media_gallery_large'; // Name of the image style for the full sized image you want to link to
  $url = image_style_url($style_name, $element['#file']->uri);
  $link_vars['link_path'] = $url;
  $link_vars['rel'] = 'shadowbox'; // The rel attribute
  // End new code

  $link_vars['classes'] = array('media-gallery-thumb');
  $link_vars['title'] = $element['#bundle'] == 'image' ? t('View larger image') : t('Watch video');
  // Add the image as a link to the detailed view
  $variables['media_gallery_item'] = theme('media_gallery_item', $link_vars);

  // Set the variables to theme the metadata.
  $meta_vars = array();
  $meta_vars['location'] = $element['#media_gallery_entity']->media_gallery_image_info_where[LANGUAGE_NONE][0]['value'];
  $meta_vars['title'] = isset($element['media_title']) ? $element['media_title'][0]['#markup'] : '';
  $meta_vars['link_path'] = $link_vars['link_path'];

  // Theme the metadata.
  $variables['media_gallery_meta'] = theme('media_gallery_meta', $meta_vars);
}

function THEMENAME_media_gallery_item($variables) {
  $image = $variables['image'];
  $link_path = $variables['link_path'];
  $attributes = array();
  if (!empty($variables['classes'])) {
    $attributes['class'] = $variables['classes'];
  }
  if (!empty($variables['title'])) {
    $new_image = str_replace(array('title=""', 'alt=""'), array('', ''), $image);
    $image = str_replace('/>', ' title="'.$variables['title'].'" alt="'.$variables['title'].'" />', $new_image);;
  }

  // Below is the only change to this function, just to add the rel attribute.
  if (!empty($variables['rel'])) {
    $attributes['rel'] = 'shadowbox';
  }

  // Add sliding door top div and wrappers
  $item = '<div class="media-gallery-item"><div class="top"><div class="top-inset-1"><div class="top-inset-2"></div></div></div><div class="gallery-thumb-outer"><div class="gallery-thumb-inner">';
  // Create a link around the image
  $item .= empty($variables['no_link']) ? l($image, $link_path, array('html' => TRUE, 'attributes' => $attributes)) : $image;
  // Add sliding door bottom div and close wrappers
  $item .= '</div></div><div class="bottom"><div class="bottom-inset-1"><div class="bottom-inset-2"></div></div></div></div>';
  return $item;
}

function THEMENAME_js_alter(&$js) {
  // Remove the media gallery colorbox js. It interferes with the rel attribute.
  if (isset($js['sites/all/modules/media_gallery/colorbox-display.js'])) {
    unset($js['sites/all/modules/media_gallery/colorbox-display.js']);
  }
}

```

I've added some comments to the code to explain what's happening so it might be worth giving the code a quick glance over.

After you've cleared Drupal's caches you should get exactly what you're after :)
> 4 votes

---
Tags: theming
---


title: Really customized themes

text:
# Question
Title: Really customized themes
I've been toying around with Drupal 7 for a couple of weeks now, and I think I understand how the theming system works, but I have a question.

I'm looking at Zen's default theme right now, and I understand that you're supposed to tweak the CSS files in the starterkit to begin building a more substantial sub-theme, but what if I wanted to change the layout of the page altogether?

Currently the Zen theme has the regions laid out something like this (please pardon the massively crude drawing, I just wanted to illustrate something):

And if I wanted it to be laid out like this instead:

Which of the theme files am I supposed to edit/hack? I'm assuming it's either page.tpl.php or html.tpl.php. Or is this something that's supposed to be done with CSS?

# Answer
Like Countzero said, regions is the Drupal way. If we have a look at the `seven.info` file of the Drupal theme Seven:

```
regions[content] = Content
regions[help] = Help
regions[page_top] = Page top
regions[page_bottom] = Page bottom
regions[sidebar_first] = First sidebar
regions_hidden[] = sidebar_first

```

You could simply add your banner here.

```
regions[content] = Content
regions[banner] = Banner
regions[help] = Help
regions[page_top] = Page top
regions[page_bottom] = Page bottom
regions[sidebar_first] = First sidebar
regions_hidden[] = sidebar_first

```

`page.tpl.php` would be the best place to print your banner, again we have a look at the Seven theme.

```
<div id="branding" class="clearfix">
  <?php print $breadcrumb; ?>
  <?php print render($title_prefix); ?>
  <?php if ($title): ?>
    <h1 class="page-title"><?php print $title; ?></h1>
  <?php endif; ?>
  <?php print render($title_suffix); ?>
  <?php print render($primary_local_tasks); ?>
</div>

<!-- Print our custom banner region! -->
<!-- START {{{ -->
<?php if ($page['banner']): ?>
  <div id="my-awesome-banner"><?php echo $page['banner']; /* echo is faster then print */ ?></div>
<?php endif; ?>
<!-- }}} END -->

<div id="page">
  <?php if ($secondary_local_tasks): ?>
    <div class="tabs-secondary clearfix"><ul class="tabs secondary"><?php print render($secondary_local_tasks); ?></ul></div>
  <?php endif; ?>

  <div id="content" class="clearfix">
    <div class="element-invisible"><a id="main-content"></a></div>
    <?php if ($messages): ?>
      <div id="console" class="clearfix"><?php print $messages; ?></div>
    <?php endif; ?>
    <?php if ($page['help']): ?>
      <div id="help">
        <?php print render($page['help']); ?>
      </div>
    <?php endif; ?>
    <?php if ($action_links): ?><ul class="action-links"><?php print render($action_links); ?></ul><?php endif; ?>
    <?php print render($page['content']); ?>
  </div>

  <div id="footer">
    <?php print $feed_icons; ?>
  </div>

</div>

```

Hope this helps. Of course this is absolutely basic stuff and should only help you getting started.
> 5 votes

# Answer
Different layouts for different pages is one of the many things that the Panels module can do. It works alongside your base theme. The base theme sets up general things, gets your site looking consistent, and gives you the opportunity to customize it. Panels gives you much greater flexibility for creating different layouts for different parts of your site, than the normal blocks in regions combo gives you.
> 5 votes

# Answer
Using Zen, or any other theme for this matter, the concept in Drupal is Region, which are defined in the theme.info file, in the form :

`regions[title] = title_region`

`regions[body] = body_region
...`

You then have to output $title\_region and $body\_region in the relevant theme files, i.e page.tpl.php for D6.

The overall layout must of course be handled in the CSS file, as in layout.css.
> 3 votes

---
Tags: theming
---


title: Zen sub-theme block page problems

text:
# Question
Title: Zen sub-theme block page problems
I have just began re-themeing a client website with a Zen STARTERKIT.

I noticed the drag'n'drop handle for grabbing and moving blocks is not showing up. This of course means I can't reposition blocks.

I scrapped the theme and started again with a fresh install of Zen but I got the same problem.

Can anyone help me?

# Answer
> 1 votes
It is likely that something in the sub theme is wrong. There are several steps to go through. They are detailed in starter kit readme.

# Answer
> 1 votes
Are you including an extra copy of jQuery? Just had an issue where the problem was an extra jQuery inclusion. The grippies were not showing up. Removed the extra jQuery include file and it works as expected.

Some other things to check:

* JS aggregation (turn it off)
* Ensure that `<?php echo $scripts; ?>` is inside the `<head>` tag.
* Verify is that the module "Theme Developer" is deactivated.

Check out this thread and this thread for more information.

---
Tags: theming, blocks
---


# Question
Title: Commerce Product Display Node using Multiple Fields?
Hello after reading How do I display my products? I was impressed how easy it is to have a display node have a simple attribute system for a product.

For example Clothes can have a product reference field for different sizes.

For more complex use case can we have multiple fields?

For example Clothes size and color with each combination having a different product. I understand this requires many more products as a result.

Has anyone talked about this use case or know of a workflow / module here?

# Answer
Yes you can do this. Just 2 list fields for your product type, 1 for color and 1 for size.

When creating your products, have the clothes of the same size use the same image.

When you create a product display node, you will see both of the select lists displayed. When you select a different color the image will change.

The issue I am having is that when selecting option 2 and then option 1, option 2 will reset back to its default value. The risk is that a customer will not notice and order the wrong product.
> 1 votes

# Answer
http://drupal.org/project/commerce\_bpc

Looks like the best way atm However there is still the UI problem of one select list between all the possible variations.

Ideally we need two select lists being displayed on the node for both attributes eg size and color.
> 0 votes

---
Tags: commerce, entities
---


# Question
Title: Track clicks in Drupal 7 and querying with Views
I'm looking to log clicks from generated URLs that are sent via email. I need to be able to query these log entries and display the results to my users using the Views module.

What I need to track.

* Unique ID from URL clicked.
* Date and Time URL was clicked.
* Node reference (Predefined from UID)
* User reference (Predefined from UID)

Currently, my plan is to create a new content type and use references as a makeshift logging system, but this seems very bulky and expensive. Is there a way to drastically improve node\_save() performance?

What would be the recommended way to accomplish a click log in Drupal? Low overhead and Views integration are important.

# Answer
> 2 votes
You want analytics/statistics tracking on some urls ? This has little to do with emails, or Views.

Typically you would use something like Google Analytics. There is a free open-source version with Drupal integration called Piwik. The Piwik module lets users see analytics detail(s). You may be able to setup a "Goal" per user of the urls they should be able to see tracking for, see also the sister module Piwik Reports.

The builtin Statistics module can count page views ... you could try to integrate it into Views maybe if you want. The Statistics Pro module has no D7 port yet, and sounds like what you want.

---
Tags: 7
---


title: How to build an egg timer in Drupal

text:
# Question
Title: How to build an egg timer in Drupal
I would like to implement a reminder functionality on a website, where a (anonymous) user can define a time for a (pop-up) reminder to fire automatically. Think of it as a digital egg timer, where you are reminded after some 5 minutes that your eggs are hard boiled... ;-).

My initial idea was to save the due time in $\_SESSION\['reminder'\] and let Drupal check at each cron run whether the reminder is due. However, this approach fails because hook\_cron operates on a global level and therefore does not recognise $\_SESSION variables. On the other hand, saving the due time in, say, a node field does not make sense either: Drupal would find all due reminders and fire a pop-up which would be visible to every user currently on the site! So summing up, I need to find a way to initiate a process at a given time that is restricted to a particular session. Can anyone give me advise on how to go for this one?

Also, I need the reminder to pop up at the very top of all running applications in order not to be missed by the user. This is obviously something that all pop ups would like to achieve, so a user would probably have to give special pop-up permissions to this site. But how can I program such a pop-up, and what special settings are required? Alternatively, I could display the reminder as a (browser independent) system message, like the messages when receiving an MS Outlook email for example. Does anybody know whether and how this can be easily achieved?

I am sorry that this request is a bit vague, but it's really more about the general strategy and I haven't reached the level for detailed questions yet. So I would highly appreciate your ideas and experiences in similar applications in order to get inspired.

# Answer
> 1 votes
You have two approaches.

You could create a non cacheable block, that will check a session\_variable, if a timer is set and the time is passed. If is has, it will render something, else it will be invisible. The will create the pop up on page refresh.

Alternative you can use a javascript and use `setInterval` to check if the time has passed and then display a popup. You would then have to add the javascript info on page load.

---
Tags: 7, cron
---


# Question
Title: How to decide between Activity or Heartbeat (or DIY Rules?)
I wish to create a site with status updates, and thus I want people to see those status updates.... (I am looking at the Facebook Style Statuses / Statuses module.)

It seems that I need to use either Activity or Heartbeat modules to get a stream of activity. However they both do similar things. How do I choose between the two? Is there a comparison anywhere?

I've seen a lot of discussion comparing them back in 2009 and talking about creating a unified version. However that discussion doesn't take into account Drupal 7 and doesn't seem to have resulted in a clear winner.

# Answer
I am developing an SNS site and I chose Heartbeat. I would choose Heartbeat again today for the following reasons:

* Heartbeat has a stable D7 release. Activity hasn't had any commits in 32 weeks (as of March 24, 2012) and is still in dev; there is no stable release yet.
* Acquia chose Heartbeat over Activity for Drupal Gardens.
* Heartbeat has rules integration. This makes it very easy to customize to do what you want it to do, especially because you get access to tokens through the token module. Activity lacks rules support.
* Heartbeat has solid internationalization support. This was a requirement as my site is multilingual.
> 4 votes

---
Tags: heartbeat
---


title: Using Revision with Views

text:
# Question
Title: Using Revision with Views
I'm creating a page to list any content that needs moderation, which in my case includes new content and pending revisions.

I have the pending revisions down, by setting

* Fields
    + Content: Nid
    + Content revision: Title (Title)
    + Content revision: Updated date (Last Revised)
    + Content revision: Vid
* Filter Criteria
    + Content revision: State (= Pending)
    + Content: Revision moderation (=Moderated)
    + Content: Published (YES)

Now how do I add in content that hasn't been published that requires moderation, BUT don't pull prior content that has been set to unpublished?

I've tried opening up the filter for Content:published and selecting the ANY option and excluding it from display. However, When you unpublish content, the revision for it asks for moderator attention as if it was a new revision waiting to be published. So it grabs ALL unpublished content as opposed to only the new content waiting to be published.

# Answer
> 1 votes
For your revisions, I assume you're using the revisioning module.

Why not just remove the Content: Published filter entirely? Any node with a pending revision should be moderated.

On my site, when I unpublish a node, unpublishing it alone does not cause it to have a pending revision. In other words, if the most recent version of a node is published, unpublishing that node does not create a pending revision.

However, if you unpublish a node with a pending revision, that node will still have a pending revision after it is unpublished. There is no way to use views alone to distinguish between a node with a pending revision that was "set" to unpublished and one that isn't published yet.

To implement such a workflow, I would suggest using the flag and rules modules. Roughly, the steps I would take would be:

1. Create a global flag called "Intentionally unpublished."
2. Create a rule that automatically flags nodes when they are unpublished.
3. Add the flag as a relationship to your view and filter based on the existence of the flag.

---
Tags: 7, views, nodes
---


# Question
Title: Theming long lists of checkboxes- How can I divide lists of checkboxes into multiple columns?
Some of the fields on my user edit pages contain very long (more than 10 items) lists of checkboxes. How can I theme such lists so that they are displayed in multiple columns instead of one long list?

# Answer
Quick and dirty:

```
.form-radios,
.form-checkboxes {
  margin-left: 5px;
}

.form-radios .form-item,
.form-checkboxes .form-item {
  font-size: 64%;
  width: 19%;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  display: inline-block;
  margin: 0px;
}

```

and play around with the font-size and width to your specifics. If you want to restrict this to a specific form, just add its id to the mix, eg:

```
#FORM .form-radios, ...

```
> 2 votes

# Answer
You did not mention if you use Drupal 7 or the content profile module. But you can use this module for CCK (content in D7) field: multicolumncheckboxesradios. Worked well for me out of the box for a large project.
> 1 votes

---
Tags: theming
---


# Question
Title: How can I remove the title in a specific node?
I am working in Drupal 7.

How can I remove or hidden the title in a specific node (not in the content type of the specific node)?

# Answer
> 3 votes
You can use the Automatic Nodetitles module.

> "auto\_nodetitle" is a small and efficient module that allows hiding of the content title field in the form. To prevent empty content title fields one can configure it to generate the title by a given pattern.

If you want to hide the title for the particular node or content type, then you should use hook\_form\_alter().

# Answer
> 1 votes
You can write a specific page template for that node, and remove the title tag from that template.

---
Tags: nodes
---


title: print result of a node_load()

text:
# Question
Title: print result of a node_load()
I would like to print the result when calling the `node_load()` function. All I get is an error... How do I get something on my screen?

Here is the code I try:

```
$form = node_load(1473);
print render($form);

```

And the error:

```
Recoverable fatal error: Object of class stdClass could not be converted to string in include() (line 10 of ...

```

How can I display the content of `$form` properly?

# Answer
> 18 votes
You should use the `node_view()` function to prepare the correct output for your required view mode:

```
$view_mode = 'teaser'; // Or 'full' for example

$node = node_load(1473);

$view = node_view($node, $view_mode);

print render($view);

```

# Answer
> 0 votes
I think you are trying to get the array structure of a node you can dot it with the help of below code.

```
<?php echo "<pre>"; print_r(node_load(1473)); echo "</pre>"; ?>

```

---
Tags: nodes
---


# Question
Title: Cache problem in Drupal 6  when updating node
When I update a node programmatically the node is updated successfully, but it doesn't display updated content. It only display the previous content.

How can I make the node display the updated content?

# Answer
Assuming D6, You have to use the reset flag (third argument) in your node\_load.
> 3 votes

# Answer
You can clear cache with the help of below code

```
<?php include_once './includes/bootstrap.inc'; drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL); drupal_flush_all_caches(); ?>

```
> 0 votes

---
Tags: 7, nodes, hooks, caching, media
---


# Question
Title: Commerce Module - Changing product in a display node makes the image revert back to default
I am having some trouble with the D7 Commerce module.

I have a t-shirt product type with three fields; 'shirt size','shirt color' and a image. Each shirt that is a different size but the same color uses the same image. Shirts with different colors use a different images.

For one product display node, I select a small,medium,large shirt size for both white and black colors. So 6 products total for one node. This way the user can select color and size for the shirt on a single page.

When a user selects a different color the image changes to that color version of the shirt, which is great. However whenever the user chooses a different size after already picking a non-default color, the image reverts back the the default color+image. So the user would have to select the color again. Or even worse, not realize that the color changed and order the wrong color.

How can I make it so the color+image doesn't change back to default when a different size is chosen?

# Answer
Haven't found a solution to this, but a workaround I am using is to disable the 'enable as attribute' of both list fields, this makes it so there is only one list in the add to cart form. The list will have a option for each product that the node references, so if you have a lot of products, this can create a long list.

To do this, go to producttype \> manage fields \> edit (list field) and turn off 'enable this field to function as an attribute field on Add to Cart forms.' Then save. You have to do this for each list field.

I will edit if I find a direct solution.
> 0 votes

---
Tags: 7, commerce
---


# Question
Title: How can I add a custom "Date" field as a field in a view?
I created a custom Content Type called "Event". In it, I use a custom "Date" field (from the Date module). When I try to create a View that displays all of the Events sorted by their Date, I can do this. However, when I try to add a *field* for "Date" so that I can display it in the output, "Date" is not shown in the list of fields. Is this because not all content types have a "Date" field? How can I get around this?

# Answer
I'm not sure why you're having trouble. I just did this and it worked. Here's what I did.

1. Add a "Date" field (widget: select list) to Content Type A.
2. Create a view that shows items of Content Type A.
3. Click Add next to Fields and search for the label for my "Date" field.

You should try looking through/searching your list of fields again. It should be there. (Even when a view is filtered to a specific content type, the Views module will often allow you to select fields that are not associated with that content type.)
> 1 votes

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


# Question
Title: How can I create a friendship that must be approved with the Relation module?
I'm trying to learn how to use the Relation module. The Node One Screencasts are very helpful in showing how to set up a "User A and B are friends" type relation. However, most SNS sites require friends to approve each other.

How would one go about setting up an approval mechanism? The rules module? What, roughly speaking, would such a set up look like?

# Answer
> 1 votes
Rules is just a handy "programmatic tool" (and API) to encapsulate things. Relation is a way to express -- well Relations.

In my opinion, using just relation and either Views or RelationQuery or EntityFieldQuery you can come up with what you need.

You just need more than 1 Relation.

Something like 1 relation of: UserA \<- are\_friends -\> UserB

to express a global "friends list" of users within your site. You could make another relation a\_user \<- has\_friends -\> user(s) which could be 1 users friends list.

Another relation: UserA \<- is\_a\_friend\_request -\> UserB (1-way relationship)

The is\_a\_friend\_request relation could have an attached field of 'request\_status' which is a "select list" field type for instance with "approved" and "denied" or "ignore" as options.

A view could be made to show to any user of their "friend\_requests". Acting on a friend request adds a recipient user to a given user's "are\_friends" relationship.

I'm not sure if this is a naive way of looking at your problem ... you could definately use rules in there somewhere ... but its not a necessity.

---
Tags: 7, entities
---


title: What are Drupal Apps?

text:
# Question
Title: What are Drupal Apps?
I've been seeing the use of Apps. What are drupal apps?

Are they just glorified Features with a backend UI? What are the differences between the two on a lower level? The apps project page only gives a pretty high level understanding.

# Answer
> 2 votes
Have you read the Open App Standard http://groups.drupal.org/open-app-standard/oas ? Here's an excerpt that might help:

> What is an app? Before we say what an App is it’s helpful to know who it’s for: An App is for the end user, typically a non-technical user of a Drupal site such as the site administrator....
>
> ...Technically, an App is a collection of new or existing Drupal functionality, including Modules, Features, and Themes along with some simple additional code that publishes the existence of the App to the rest of the App infrastructure.
>
> What distinguishes an App from a Module or Feature is that the App includes all of the additional polish, end-user UI, configuration UI, sample content, and documentation that are needed to fully meet a specific need. Whereas Modules and Features are more developer-centric and provide building blocks for larger functionality, Apps are larger blocks of completed functionality.

---
Tags: features
---


# Question
Title: Drupal 7 Views, paths, node associations via taxonomy
After many hours I still cannot wrap my head around what is needed to make my situation work. Here it is:

I current am using clean URLS like so /artists/name-of-artist routes content type Artist. I have content types: Arists, Album Releases, Tour Dates, and Media. I would like to tie everything together using vocabulary Artist Tags (yes, even Artist content type would get tagged). So, say for example I have "Test Artist" in Artist content. I tag it with "Test Artist" Artist Tag. I also create an Album Release tagged "Test Artist". My question now is when visiting /artist/test-artist how do I have a view that shows not only the dat from that artist node but also from the Album Release node tagged "Test Artist".

I have already tried Node Reference. This is not an ideal solution for me as I want the flexibility of library categorization via taxonomy. I just can't understand how I can pull in another node's content based on /artist/test-artist Artist Tag field.

I forgot to mention that I am using the latest version of Drupal 7, and Views 3.

# Answer
Sorry for a general answer, but it may get you in the right direction anyway.

What you seem to need is to establish relationships in `views`. By adding a relationship, you just add an object you would like to refer to. Once you add a relationship (on the right hand side, in Advanced panel), additional fields appear in the Add Field and Filter dialogs. Note the dropdown list that appears in field-related dialogs that contains relevant relationships that you have defined. You may also have a cascaded relationship (a relationship that uses another relationship).

All that translates later into the `WHERE` clause of the final query which filters what you want to show/hide.

To use the elements of the path, you want to use Contextual filter where you specify which part of the URL means what.

One thing to remember is that, even though you have clean URLs turned on, there is an "unclean" URL query behind the scenes which contains stuff like term IDs or node IDs. Perhaps it'd be useful for you to turn the clean URLs off for a moment, and play for a while just to see what kind of URLs will be used by views contextual filter. Or put `<?php print $_GET['q'] ?>` somewhere in the `page.tpl.php` for testing convenience.
> 1 votes

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


# Question
Title: How to add a country to the location module?
I have a requirement to add additional countries to the location module.

I need to add England, Scotland, Wales and Northern Island.

I suppose they could be provinces, but I can't figure out how to do that either.

Many thanks for any help :)

PS. I would be using the county codes for css so country would be better.

# Answer
So maybe my question wasn't worded in the best way, but I have found the answer.

All countries in Drupal (at least in 7) are taken from the `/includes/iso.inc` file. This includes Location and Address Field.

You can add countries to this list via `drupal_alter`

An example:

```
<?php
function hook_countries_alter(&$countries) {
  // Elbonia is now independent, so add it to the country list.
  $countries['EB'] = 'Elbonia';
}
?>

```

Putting this in a custom module will enable you to add countries as you require. You *must* use a 2 letter iso code!
> 4 votes

---
Tags: 7, location
---


# Question
Title: Openlayers views , center map to each geofield
I have setting geofield in profile for each user , and make a view that list the location of the current user post (" I'm here ") , but the map isn't centered well to show up the marker , and when you zoom out it shows the markers.

So how do I get my map centered for each user geofield ?

# Answer
> 9 votes
1. Go to /admin/structure/openlayers/maps
2. Choose the map you are using to display your geofield on the user
3. Select the behaviors tab
4. Check off Zoom to Layer
5. Select geofield\_formatter
6. Enter your zoom level

Note: If I misunderstood your question, and you were actually referring to centering on the markers on your view that compiled all of the users, then just select your view name in the 'Zoom to Layer'.

---
Tags: views, javascript
---


title: how to display node page using views

text:
# Question
Title: how to display node page using views
I have used panels to override the node pages(node template). I have created a views block, it has an image field and its output has been rewritten so that it is rendered as a image link. Now, I want to configure the views such that it will display the panels page(node page that has been overridden by panels).

What will be the URL of image link so that it points to node page. And also it has to pass certain arguments to the node page. How to do it?

I am using D7

# Answer
You've got it backwards-- you don't want to use views to display the panel. Instead, you want to use panels to display the view.

I will try to explain how this works as simply as I can. Panels overrides the node page display. Therefore, the display must be changed in Panels.

You can add your views block to the panels display. To do this, you can use a Contextual Filter. The Contextual Filter is the "argument" that views needs to display the content. Panels will provide this argument (the value for the contextual filter) because it is the one overriding the display.

Explaining how views and panels work in detail is beyond the scope of what I can do here but I will refer you to Node One's excellent free videos on learning views and learning page manager/panels.
> 2 votes

---
Tags: 7, views, nodes
---


# Question
Title: When the "Body" field is required, how can I force users to input, say, at least 400 characters?
For example, this site (Drupal Answers) has this feature-- if you input too little text in the text box, the interface prompts you to write more. Is there a module to do this? I tried various searches but I haven't been able to find anything.

# Answer
You should be able to just use the Field validation module to set a minimum length on the body field.

> This module adds an extra tab to each field instance, allowing you to specify validation rules for your field instances.
>
> By using the hooks provided by this module, you can also define your own validation rules in your own modules.
> 5 votes

# Answer
If you are comfortable with code, the basic approach is to hook\_form\_alter the node\_form and add an additional #validate to the field. Just note that allowing markup in the field will count towards charaters. You may want to base your count off of what strip\_tags returns, rather than the actual field value.
> 2 votes

# Answer
In addition you could implement an 'n characters to go' counter for minimum length (a la stackoverflow) with javascript/jquery which counts before submission.
> 2 votes

---
Tags: 7, entities
---


# Question
Title: How can the admin of a group edit all members default profiles? Is that possible? (Drupal 6 installation)
I need to do this in a Drupal 6 installation, with the Organic Groups module:

**The user that has administrator rights within a group can edit all members default profiles.**

I just want the admin of an OG to be able to change each user´s email address, but the line above reflects the generic use case.

Any thoughts on how to complete that task?

Thanks!!!

Rosamunda

# Answer
> 1 votes
As mentioned in my other answer, user profile access does not have any kind of ACL system, which requires more hackish workarounds.

Instead of the `hook_menu_alter()` approach I described, you could instead embed the same form in a second menu path, this one at something like `og/%node/user/%user/edit`. At this path, the group context is active, which means you could simply use og\_is\_group\_admin() as the menu access callback and the form should work.

By placing the same form in this second location, all modules that tweak the form should apply unless they are misusing the path to get user id arguments. You could also use some kind of trick in a `hook_form_alter()` to recognize that a given instance of the form is generated at your special path, and use that to remove form elements you do not want to share with group administrators.

# Answer
> 1 votes
User Profile Access does not have elaborate access control in the fashion of nodes, so the answer is a custom module that takes over the profile edit page's menu access callback.

Use `hook_menu_alter()` on `user/%user/edit` and set `'access callback'` to `custom_user_edit_access`. In that function, run the original access logic to preserve normal behavior, but then add another layer that checks to see if the current user is an administrator in the group and if the active user profile's user is in the group.

For D6, you can either check the user data structure directly, or use the API functions `og_is_group_member()` and `og_is_group_admin()`.

If you want to special-case the email field to a specific permission once the user has access to the form, that's a case for `hook_form_alter()` and changing the email field's `#access` element to use a new permission or an access callback with logic of it's own.

---
Tags: 6, users, organic-groups
---


title: Blob in Data module

text:
# Question
Title: Blob in Data module
I am using the Data module in Drupal 7, and I have created a view which shows my table. I have a blob in my table and this is filling my page with content.

Is there any way that I can get the blob to display as a link, and the file must be downloaded when clicked?

# Answer
> 0 votes
Fixed the problem by doing this

```
if($vars['fields'][$field] == 'content')
    {
         $field_output = "<form action=\"download.php\"
 method=\"POST\">
        <input  type=\"submit\" name=\"download\" value=\"Download\">
            <input type=\"hidden\" name=\"did\" value=\"$num+1\">
                </form>";

    }

```

and download.php needs to have something like this

```
 <?php

if(isset($_POST['id']))
{
    $table = 'tablename';
    $download_id = $_POST['id'];
    $q="SELECT * FROM {$table} where id = $download_id";
    $link = mysqli_connect(...);
    $res = mysqli_query($link,$q);
   if($res)
   {
   $row = mysqli_fetch_assoc($res);
    $id = $row['id'];
    $name = $row['name'];
    $status = $row['status'];
    $content = $row['content'];
    header("Content-type: required type");
    header("Content-Disposition: attachment; filename=$name");
    echo $content;
    exit;
   }
   else{
   echo "Cannot download";}

}
?>

```

Now I wish to know how to to access tables in a different database than the default drupal database mentioned in settings.php.I added another database in the settings.php which has the required table but I am not able to adopt tables from there.(They do not show up in the orphaned tables list).Is there a place where I can change so that the data module only sees the new database and not the default database

---
Tags: views, database
---


# Question
Title: Can Google Bot Crawl authenticated pages?
I am using Organic Groups and most of the pages i.e Discussions and related pages are only accessible to an authenticated user, can google bot crawl all these pages as well or is thrown a 403 error ?

# Answer
Drupal will send a 403 response for any protected pages to any user agent, including the Googlebot, unless that user agent has been authenticated by Drupal and has a valid session cookie.

If your pages are only accessible by users with the "authenticated user" role, Google will not be able to crawl them.
> 3 votes

# Answer
Google bot, as any other web crawler, has access to any pages to which anonymous users have access. If the page is visible only to users with a specific permission, you should assign that permission to the anonymous user.
> 0 votes

---
Tags: search
---


# Question
Title: Set mod-rewrite to forward everything accept for one subdomain
I am trying to set up mod rewrite to forward the site example.com to www.example.com. This is fairly easy, because there is a line in the built in .htaccess file that I just have to uncomment. The problem is, I can't figure out how to set it so that all domains of example.com forward to www.example.com, accept m.example.com which I want to keep the same. These are the line's I'm using right now:

```
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule ^ http://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

```

How can I set it to so that only m.example.com stays the same?

# Answer
> 2 votes
Something like this should do it:

```
RewriteCond %{HTTP_HOST} !^(www|m)\. [NC]
RewriteRule ^ http://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

```

---
Tags: redirection, .htaccess
---


# Question
Title: Deploying to multiple hosts using Webistrano
We're using Webistrano to deploy our Drupal sites to testing and production.

The recipe we're using is as follows:

```
namespace :drupal do
  desc "symlink_files"
  task :symlink_files do
    invoke_command "ln -s #{deploy_to}/shared/files #{deploy_to}/current/drupal/sites/default/"
    invoke_command "ln -s #{deploy_to}/shared/settings.php #{deploy_to}/current/drupal/sites/default/"
  end

  desc "refresh_configuration"
  task :refresh_configuration do
    invoke_command "cd #{deploy_to}/current/drupal; drush #{drush_options} -y fr-all"
    invoke_command "cd #{deploy_to}/current/drupal; drush #{drush_options} -y updb"
    invoke_command "cd #{deploy_to}/current/drupal; drush #{drush_options} cc all"
  end
end

after 'deploy:symlink','drupal:symlink_files','drupal:refresh_configuration'

```

This method is working great for single-host deployments, but fails for multi-host deployments. The reason is that the `refresh_configuration` task will run on each host, causing all kinds of race conditions and corruption on the central database server.

My question is, can anyone suggest a way to fix the Webistrano setup to only run `refresh_configuration` task on one server only?

PS. I'm not interested in changing the deployment system to Aegir or anything else.

# Answer
As per this Capistrano Wiki page, you can restrict tasks and single commands to specific `:roles` and `:only` attributes:

```
task :migrate, :roles => :db, :only => { :master => true } do
  # ...
end

task :other do
  run "migrate", :roles => :db, :only => { :master => true }
end

```

Using this, I was able to run the `refresh_configuration` task to run on a server with a specific attribute.
> 0 votes

---
Tags: drush, deployment
---


title: Is aegir a good choice for me?

text:
# Question
Title: Is aegir a good choice for me?
I want to use aegir for a website that users can create their own sub-sites.

From aegir installation guide:

> when a new site is installed, the web server will be automatically configured (vhost) and restarted

Does this mean that every time a new subsite will be created, server restarts and will be out of access for a few seconds?

# Answer
> 2 votes
Aegir is a powerful tool to manage hosting environments, deploy new versions of your site, clone a live site to a testing environment... Stuff like that. I don't know which kind of users you're talking about, but I would only give access to experienced Drupal developers. If you want 'normal' end users of a site to be able to setup their own subsite, maybe http://drupal.org/project/subdomain is right for you.

# Answer
> 2 votes
The whole server doesn't restart when a site is added, only Apache, and it's just a graceful restart, so no real downtime..

Also, if what you mean by 'subsite' is http://example.com/subsite1, /subsite2, /subsite3, Aegir doesn't support that at this stage. Subdomains will work fine, but not 'subfolder' sites. See http://community.aegirproject.org/faq#Can\_I\_use\_the\_subdirectory\_multisite\_feature\_of\_Drupal\_in\_Aegir

---
Tags: 7, aegir, subsites
---


# Question
Title: Best method to upload / link to multimedia files in D6?
I need a solution to allow users to upload multimedia files (audio, video, images, documents, links to such) to a node. Ideally, something like a combination of FileField + Embedded Media Field that supports different media and styles the viewer accordingly.

I know that module Media is supposed to solve this problem on D7, but I'm looking for a D6 solution.

I've tried:

* jQuery Media but it doesn't handle many file types that I need - plus I prefer a server-side solution.
* Styles + FileField Styles but they just don't work.

# Answer
> 0 votes
My solution was to use 2 multiple-value fields in my media content type:

* A FileField with a custom formatter that detects the MIME type of the uploaded file and renders a different theme for known type/subtype combinations, defaulting to the standard FileField link.
* An oEmbed field with Embed.ly support for media links. This API works much better than EMField.

The whole trick was to theme the media views and forms such that media from both those fields make up a single visual list, not two.

# Answer
> 0 votes
Have you looked at the MediaFront module? Here is a quote about it (from the module's project page):

> ... is a front end media solution for Drupal. It employs an innovative and intuitive administration interface that allows the website administrator to completely customize the front end media experience for their users without writing any code. In addition, this module provides an interface to which 3rd party media players can integrate and utilize settings presets to display rich media. Out-of-the-box, this module provides two media player solutions.

# Answer
> 0 votes
Have a look at ShadowBox, it supports a lot of formats and the FileField module which I think is essential for your set up:

> **Media extensions supported:**
> \- Images (png, jpg, jpeg, gif, bmp)
> \- Video (avi, mpg, mpeg)
> \- Quicktime (dv, mov, moov, movie, mp4)
> \- Windows Media Player (asf, wm, wmv)
> \- Flash (swf, flv)
> \- IFrame (asp, aspx, cgi, cfm, htm, html, pdf, pl, php\*, phtml, rb, rhtml, shtml, txt, vbs)

Source: Comparison of Lightbox-type modules.

There's algo the Lightbox2 module with is aroung since a long time and have quite a big installed base.

---
Tags: files, media, nodes
---


# Question
Title: Providing "translations" based on region rather than language
We are using FAPI to create some custom forms (actually extending the registration form) and want to provide different form labels based on a Country of Residence. For example if in Australia they will be asked to enter "City/Town/Suburb" but if they're in New Zealand the label will be "City".

Is this something that can be done and managed with Drupal's base translation modules? My understanding so far is that most of this functionality is at the language level rather than "regional" settings. If not, what would be a plan for managing this in a maintainable way?

Thanks.

# Answer
> 0 votes
The addressfield module does this. You can check their code to see how you can implement such a feature in D7.

---
Tags: forms, i18n-l10n
---


title: Search API Attachments not working

text:
# Question
Title: Search API Attachments not working
I'm running Drupal 7.12. I have a requirement to index files attached to nodes. (DOC, PDF, XLS, etc).

After quite a bit of trail and error, reading and searching I have been unable to get any of the attachment file indexing modules to work.

Search API Attachments seems the most promising but after configuring it doesn't seem to index any of the documents. It does call Tika to process attachments to new nodes, but doesn't seem to re-index any existing nodes. Searching on any file contents yields no results.

Any thoughts on what I should investigate to track this down would be greatly appreciated. Anyone running this module successfully? If so how did you configure it.

More info:

I followed these instructions: http://permalink.gmane.org/gmane.comp.php.drupal.support/22390

To see if I can track this down:

* I configured a fresh installation of Drupal 7.12.
* I installed Search API, Search API DB and Search API Attachments

+ projects/search\_api\_db-7.x-1.x-dev.tar.gz
    + projects/search\_api\_attachments-7.x-1.2.tar.gz
    + projects/search\_api-7.x-1.0.tar.gz
* I installed Tika and verified that it is working per instructions.
* I created a field called Attachment1 of type File for the "Article" content type: structure -\> content types -\> article. label: Attachment1 name: field\_attachment1, field: File.
* I created a search server in Configuration -\> Search and metadata -\> search api using the database service class.
* I then edited the Default Node Index to use the search server I defined and enabled it.
* I then went to the Default Node Index fields and using "Add Related Fields" added Attachment1 » The file.
* I checked the box next to Attachment1 \>\> The file and Attachment content: field\_attachment1
* I created a single Article and attached a word document to it.
* I ran the cron service from the admin menu.
* In the database I ran select * from search\_index and I notice that only the terms from the node content are present, nothing from the document that I uploaded.
* I verified that Tika was being called by adding the syslog call prior to shell\_exec which yields:

> Mar 17 13:32:06 xeon httpd: Calling Tika: java -Dfile.encoding=UTF8 -cp '/usr/local/tika' -jar '/usr/local/tika/tika-app-1.0.jar' -t 'http:///drupal/sites/default/files/Resume\_0.doc'

However, if I select to re-index the site by going to Configuration -\> Search and metadata -\> search settings -\> clear index and re-run cron I notice that Tika is NOT being called.

Also I notice that selecting clear index does not affect the search\_index table. (Should it?)

I have separately verified that Tika is properly extracting the text from the document by logging it to a file prior to the call.

My feeling is that I'm missing something obvious.

# Answer
Ok, this looks like part of this is a case of PEBKAC. Or maybe could be considered an issue of documentation.

It looks like the default search box form does not interface with search API and that in order for the search API indeces to be used you must use the Search API Pages module.

However, re-indexing definitely does NOT re-index attachments on existing nodes. I'm not sure whether it's supposed to or not but that is what threw me to believe it was not working.
> 2 votes

# Answer
Did you select the "File Attachments" option in the Workflow tab of your index?
> 1 votes

---
Tags: 7, search
---


# Question
Title: How to programmatically assign/add new groups to the OG in Drupal Commons 6.25
How to programmatically add new groups to Organic Groups in Drupal Commons 6.25? I have to do that for approximately 3000 groups. A preliminary test cycle that generates 50 will be the first step.

Which methods are preferable?

By the way, the images are stored in sites/default/files/imagecache/group\_images\_medium/group\_images.

### Questions that arise

* Are the images, and the corresponding paths referenced in the database somewhere?
* How can I do the mass-upload of the image and besides that, the mass-creation of groups?
* Which tables of the **tables of OG** are necessary?
* Is it enough to take the "og" table itself?

**PS:** An ongoing attempt with comments for Drupal 6 can be seen here: http://drupal.org/node/79874.

# Answer
> 2 votes
I am the author of og\_massadd (which is quite buggy as it is now, unfortunately), but that module is only for adding users to an OG. But if I understand you correctly, you want to create the actual organic groups?

Doing this through PhpMyAdmin will probably be very cumbersome. You would need to add records to node, revisions, any CCK-tables (if your group nodes have CCK fields), og, og\_uid (for group memberships) as a minimum. For addding content to your groups, you would need to add to node, revisions (CCK-tables if necessary) and og\_ancestry.

It is a bit easier creating a group programmatically:

```
$groupnode = new stdClass();
$groupnode->type = 'gruppe'; // Group node type
$groupnode->status = 1;
$groupnode->uid = $owner_uid;
$groupnode->title = $title;
$groupnode->body = $body;
$groupnode->og_selective = $group_acces_level;
$groupnode->og_register = OG_REGISTRATION_NEVER;
$groupnode->og_directory = OG_DIRECTORY_CHOOSE_FALSE;
$groupnode->og_private = variable_get('og_private_groups', OG_PRIVATE_GROUPS_CHOOSE_FALSE);
$groupnode->{_integration_cGroupType}[0]['value'] = $cGroupType_content; // CCK field

node_save($groupnode);

if ($groupnode->nid) {
  og_insert_group($groupnode);

  // Set space (if spaces_og is used)
  //$ogspace = spaces_load('og', $groupnode->nid, TRUE);
  //$ogspace->controllers->variable->set('spaces_preset_og', $spacepreset);

  og_save_subscription($groupnode->nid, $owner_uid, array('is_active' => 1, 'is_admin' => 1));
} else {
  dpm('OG creation failed :(');
}

```

---
Tags: 6, organic-groups
---


title: Where to declare menu hook

text:
# Question
Title: Where to declare menu hook
I'm working through the second post in this thread, so I can call a custom method from jQuery. https://stackoverflow.com/questions/4834132/how-to-pass-jquery-variable-to-drupal-ajax

(I already have a html form, so the Forms API doesn't really help me)

The post mentions a menu\_hook, but always describes the hook, as belonging to a module. I only plan on adding one method, so I don't really want (or know) how to create a module from scratch.

Is it possible to add the menu hook to my template.php, or another file which already exists?

# Answer
You should create your own module for your hook\_menu. It's not hard or bad in any way. :) It's also near trivial.

in sites/all/modules/custom\_module create two files:

custom\_module.info with

```
name = My custom module
core = 7.x

```

custom\_module.module with (copied from linked to question)

```
<?php
function custom_module_menu() {
  return 'my_custom_callback/%' = array(
    'title' => 'My Custom Callback',
    'description' => 'Listing of blogs.',
    'page callback' => 'my_custom_php_function',
    'page arguments' => array(1),
    'access arguments' => array('access content'),
    'type' => MENU_CALLBACK,
  );
}

```

And you have a new module with a hook menu entry. Replace `core = 7.x` with `core = 6.x` if you want this to work for D6 instead of 7. And replace `custom_module` everywhere if you call the module something else :)
> 6 votes

---
Tags: hooks, javascript
---


# Question
Title: Form validator and submit handler is not getting called
I've created a Form using my module, which looks like this, then I've created a \_validate & \_submit handler (please see the linked file above). Then, in my front page, I printed the form using:

```
$form = drupal_get_form('mymodule_signin');
print render($form);

```

But when I'm submitting the form, the validate & submit handlers are not getting called, I'm getting redirected back to the front page. However, I created a submit button but when I was clicking it, ***the form was not getting submitted***, so I submitted the form using jQuery's `.submit()` method to submit the function!

Can anyone help me why the form was not getting submitted first time, and finally when it was submitted *(using javascript)* the handler was not getting called? Here goes the template file I used to render the form.

**PS.** I created an entry in the `hook_menu()` and when I submit form using this page, the form gets submitted (calls validate handler). But it is **not** calling validate/submit handler when I submit it in my front page. :(

# Answer
I think you should have an element of type `submit` in your form function.
> 1 votes

---
Tags: 7, forms
---