# Question
Title: Running EntityFieldQuery on restricted content (with cron)
I’ve got a small issue running the following query:

```
$qry = new EntityFieldQuery();
$qry->entityCondition('entity_type', 'node')
        ->propertyCondition('status', 1)
        ->propertyCondition('changed', $since, '>')
        ->fieldCondition('group_audience', 'gid', (array) $groups, 'IN' );

```

When I run this manually as user #1 it is all fine. When I run this through cron (which has no user) the organic group access control appears to forbid returning any results (based on no permissions for the current user I guess). This issue is with the last fieldCondition, when removed, it all works as expected.

# Answer
Cron runs as the anomymous user. The idea is that it should only call APIs that don't require users. EntityFieldQuery however allows you to either bypass node access checks, or to set the user the query will run as.

Option 1: Set the user to run the query as:

```
$query = new EntityFieldQuery;
$result = $query
  ->fieldCondtition(...)
  ->addMetaData('account', user_load(1))
  ->execute();

```

Option 2: Bypass node access by setting the `DANGEROUS_ACCESS_CHECK_OPT_OUT` tag (since Drupal 7.15 I believe)

```
$query = new EntityFieldQuery();
$result = $query
  ->fieldCondition(...)
  ->addTag('DANGEROUS_ACCESS_CHECK_OPT_OUT')
  ->execute();

```

Option 3: You can run your cron code as another user by setting the `$user` global variable. For instance:

```
function mymodule_cron() {
  global $user;
  $original_user = $user;
  $old_state = drupal_save_session();
  drupal_save_session(FALSE);
  $user = user_load(1);
  _mymodule_do_some_stuff();
  $user = $original_user;
  drupal_save_session($old_state);
}

```

Option 1 is the cleanest way to do what was requested - it relies on an existing functionality to run a query as a different user. You can use user 1, or create a custom user who has exactly the permissions you require for your operation.

Option 2 is functionally equivalent to using Option 1 with user 1. It is less flexible than option 1, so there isn't really a case to use it (but included here for completeness).

Option 1 and 2 are limited to entity field query, which is what the OP asked. To do other operations as another user, you need to impersonate that user completely - which is what Option 3 does.
> 4 votes

---
Tags: 7, organic-groups, database
---


title: Interview module

text:
# Question
Title: Interview module
Drupal 7: In my new website there i want to add an interview section. I will explain it. I need a section to add client interview details. In this section there may be some questions and its answers. How can we add questions and its answers?I will create a content type for this.

But i want to know how can we setup fields for an input form for this?

I'm sorry ,if it is a foolish question.

# Answer
Use the Field collection module,

> Provides a field-collection field, to which any number of fields can be attached.
>
> A field collection is internally represented as an entity, which is embedded in the host entity. Thus, if desired field collections may be viewed and edited separately too

Then add field collection field with fields question and answer. Give Number of values as unlimited .
> 0 votes

# Answer
You can use webform for this. By using webform you can create a set of questions and then that form can be given to all attendees, who will be giving answers. So you can have whole set of data from different users who have given answers to your questions.

drupal.org/project/webform
> 1 votes

---
Tags: forms
---


# Question
Title: What happens to the return array of hook_views_default_views after the function finishes?
`hook_views_default_views` returns an array of `$views` objects. Immediately after that function has finished, where does it send the `$views` object it returns?

Obviously that array is passed to another function where it's iterated over and something is done with the data. That's what I want to investigate - what views is doing with the data.

I checked views.module and other files and saw a lot of references to ctools functions, but then got a little lost.

What and where is the function that handles that return value?

# Answer
ADDITION/CORRECTION:

For Views in Drupal7, the cache is built up by Ctools and its `_ctools_export_get_defaults()` function that is defined in `.../ctools/includes/export.inc`. It is called many ways down the line from `views_get_all_views()`:

```
function views_get_all_views($reset = FALSE) {
  ctools_include('export');
  return ctools_export_crud_load_all('views_view', $reset);
}

```

where `ctools_export_crud_load_all()` eventually calls it. The kicker for grep'ing around to find this is that it uses `$function = $module . '_' . $export['default hook'];` to cycle through all the modules that implement the hook, and that is defined in `views.install`:

```
'default hook' => 'views_default_views',

```

so it certainly took a bit to find but it is a nice api way to allow all sorts of modules to export objects in a defined fashion. I won't include the code here as it's a bit more verbose than the D6 version below but do let me know if you need any other help on this.

MY BAD: The following for D6....D7 answer above but I'll keep this in here if anyone in D6land ever needs an answer:

If what you are asking is where does Views build up its cache of default views, it does this via the `_views_discover_default_views()` function found in `.../views/includes/cache.inc`:

```
/**
 * Scan all modules for default views and rebuild the default views cache.
 *
 * @return An associative array of all known default views.
 */
function _views_discover_default_views($reset = FALSE) {
  static $cache = NULL;

  if (!isset($cache) || $reset) {
    $index = views_cache_get('views_default_views_index', TRUE);

    // Retrieve each cached default view
    if (!$reset && isset($index->data) && is_array($index->data)) {
      $cache = array();
      foreach ($index->data as $view_name) {
        $data = views_cache_get('views_default:' . $view_name, TRUE);
        if (isset($data->data) && is_object($data->data)) {
          $cache[$view_name] = $data->data;
        }
      }
    }
    // If missing index, rebuild the cache
    else {
      views_include_default_views();
      $cache = array();

      foreach (module_implements('views_default_views') as $module) {
        $results = call_user_func($module . "_views_default_views");
        if (!empty($results) && is_array($results)) {
          foreach($results as $name => $view) {
            // Only views with a sufficiently high api version are eligible.
            if (!empty($view->api_version) && $view->api_version >= 2) {
              // Do not cache dead handlers.
              $view->destroy();
              if (!isset($cache[$name])) {
                $cache[$name] = $view;
              }
              else {
                watchdog('view', "View name '@name' is already taken", array('@name' => $name), WATCHDOG_ERROR);
              }
            }
          }
        }
      }

      // Allow modules to modify default views before they are cached.
      drupal_alter('views_default_views', $cache);

      // Cache the index
      $index = array_keys($cache);
      views_cache_set('views_default_views_index', $index, TRUE);

      // Cache each view
      foreach ($cache as $name => $view) {
        views_cache_set('views_default:' . $name, $view, TRUE);
      }
    }
  }

  return $cache;
}

```
> 2 votes

---
Tags: 7, views
---


title: reCaptcha not working on webform

text:
# Question
Title: reCaptcha not working on webform
I am using a Webform module to create a form to which I would like to add recaptcha. I've gone through the readme files for both captcha and recaptcha modules and all the configuration settings look fine.

The only thing I am unsure about is on admin/config/people/captcha general settings page.... I am trying to add a new form id to reflect my webform (webform-client-form-25) but it won't accept it. It says "Illegal form\_id".

I've got the public and private keys set.

Skip CAPTCHA is NOT selected for any role.

From the view source:

How do I get the recaptcha working for my webform?

# Answer
> 3 votes
Since people may not check the comments for the answer:

Yaazkal suggested in comments try using webform\_client\_form\_25

Hyphens(-) are generally translated into underscores(\_) for machine names in drupal.

---
Tags: webforms, captcha
---


title: Remove post featured image

text:
# Question
Title: Remove post featured image
I want to remove post featured image from http://bit.ly/XkE8vG.
I have tried a lot by looking in to theme files but couldn't find any way.

# Answer
Go to the content types page on admin/structure/types, click on "Manage display," and drag the field to the "Hidden" set.

**For D6**

You can do the same in `node-type/<type>/display`. Click exclude/ make the select box to hidden.

Also you can use this code in node.tpl.php.

```
if ($teaser) {
  // node is being displayed as a teaser
  // Anything here will show up when the teaser of the post is viewed in your taxonomies or front page
} else {
  //all other cases
  //Anything here will show up when viewing your post at any other time, e.g. previews
}

```
> 2 votes

---
Tags: nodes
---


# Question
Title: Disallow access to member files when they are in public file system
I have case where I want to make it impossible for the users to access file directly (http://www.mydomain.com/members/file.pdf), but want to allow downloading this file only if link is displayed on Drupal page, that user has privilege to see.

I know it can be easily done if those files are outside webroot and defined as private filesystem.

But is there any alternative solution, Apache way, php/Drupal way to achieve this for files that are not in private filesystem?

Those member files are of various extensions, so I could not just disallow by extension.

I have asked simmilar question before, but as I understood, proposed `hook_file_download` way works only for private file system setup.

# Answer
> 1 votes
To Apache or any other web server, seeing

```
<img src="http://www.foo.com/bar.jpg">

```

in html and a user typing `http://www.foo.com/bar.jpg` into their browser directly is basically the same thing so the quick answer is "no, not really, at least from a drupal standpoint." You could obfuscate the path with some javascript trickery but that's about it.

Now, you could look into Apache referrer access, a quick link about allowing access from specific referrers might shed some possibilities on it for you, but now you are certainly outside of drupal :)

---
Tags: files
---


# Question
Title: I need to load DB configuration dynamically in Drupal 7
Can I put `variable_get` in `settings.php` to load DB settings dynamically or there is a better way.

# Answer
> 3 votes
You can use `Database::addconnectionInfo()` to define a new connection at runtime, like this:

```
Database::addConnectionInfo('extradb', 'master', array(
  'database' => 'mydb',
  'username' => 'myname',
  'password' => 'mypass',
  'host' => 'localhost',
  'port' => '',
  'driver' => 'mysql',
  'prefix' => '',
));

```

You can then use `db_set_active('extradb')` to switch to it.

# Answer
> 4 votes
Drupal allows you to override settings using the $conf\[\] array in settings.php. They will be then available via variable\_get('key', 'default') in any module.

See 'defining site variables' and variable\_get()

The pattern we use is that any defaults go into install.php. starts with:

```
function hottopicsnotify_install() {
  variable_set(HOTTOPICSNOTIFY_CONTENT_TYPES_VAR, 'hottopics_node_form');

```

Override the variables with an admin form where needed. e.g.

```
function hottopics_settings($form, &$form_state) {

```

Read using variable\_get. e.g.:

```
'#default_value' => variable_get(HOTTOPICSNOTIFY_EDITORIAL_CRON_KEY, ''),

```

# Answer
> 0 votes
Have a look at

db\_set\_active

You can switch the the active database connection that way.

Define the databases in settings.php, then switch to one with

```
db_set_active('legacy'); // example
// Query stuff using DB API

```

and switch back to default with

```
db_set_active();

```

It's also possible to define the database connection later in code, but hopefully db\_set\_active will suffice.

---
Tags: configuration
---


# Question
Title: Can Views output only the first vocabulary term?
Is there an easy way in Views to output the first vocabulary term only?

# Answer
Edit the term reference field in your view, and under "Multiple Field Settings" check "Display all values in the same row". You will be presented with further options. You will probably want Display options to be Simple Separator, then change "Display \[all\] value(s)" to "Display \[1\] value(s)", apply and save your view.
> 0 votes

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


title: How to share a menu across more website

text:
# Question
Title: How to share a menu across more website
I've got a main website where it's possible to create and change menu items and I need to share this menu with other websites and programmatically(once per week or once per day) the other websites will import and override the menu.

This is very useful when a company has got more websites and wants to use the same footer menu for all its websites.

Do I need to use just Feeds and Rules to achieve it? Is it possible to achieve it without adding the main website db menu in settings.php in all the other websites?

Thanks in advance

# Answer
> 1 votes
I think the idea of using a feed is an attractive one. I don't think there's any way to push a menu definition out as a feed using existing modules, though.

I'd write a very simple module to provide a single callback that would fetch the menu definition and theme it as xml or json (easier). That could then be fetched at intervals by your other sites.

---
Tags: 7, routes, feeds
---


# Question
Title: Creating a View of nodes with field for workbench moderation state without showing every revision?
I am trying to create a table view of nodes with fields for node title and moderation state. (There are other fields but I'm omitting them for simplicity).

Currently, it's displaying a new table row for every single revision of the node. I only want to see one row per node, whatever the current state is. Grouping is not sufficient, since there are fields that are not the same across revisions.

# Answer
Immediately after asking this question, I realized there is a filter criterion that can be added for this.

`Workbench Moderation: Current` can be set to filter based on whether a revision is the current one, and all previous ones can be excluded.

This will also exclude nodes that haven't been created or edited since the enabling of Workbench Moderation for their node type but will include newly created or edited ones.
> 2 votes

---
Tags: views, nodes, workbench
---


title: How to migrate one node into two nodes

text:
# Question
Title: How to migrate one node into two nodes
I have a D6 installation with a very large content type (i.e. a lot of fields) called field\_data. I need to migrate the field\_data nodes out of D6 and into a new D7 instance. This D7 instance has two content types called field\_data and accomplishments. The accomplishments content type has a field that is a node reference to the appropriate node of the field\_data type. Essentially I am exporting one content type and need to import each node as two nodes that reference each other. I have looked into the feeds module and don't see a way to do this. What is the best way to do this?

# Answer
> 0 votes
This will not be simple, as it is a requirement which is probably unique to your site. I know of no modules designed for this scenario. In general terms, you need to do the following.

1. Import the field\_data content WITH all the fields into your D7 field\_data type.
2. Create your accomplishments content type, and clone each field\_data type to an instance of the accomplishments type, recording the nid of the source instance (field\_data). Look at the Node Clone module to see how it is done. (Note: This module will not do this out of the box. You will have to hack it to do what you want.) You can probably use hook\_node\_presave to change the bundle and move the nid to the term reference field, then blank $node-\>nid to create a new node. Using Feeds or Backup and Migrate will not give you the nid for the node reference.
3. Delete the unwanted fields from the D7 field\_data type.

You might also be able to accomplish this through direct manipulation of the database, but it is probably best to do it 'the drupal way' to avoid any artifacts which you might introduce in the direct query method.

Good luck.

# Answer
> 0 votes
The migrate module can do it. It is however quite tricky to use. Start by reading the basics of the documentation

This page: http://drupal.org/node/1513766 covers the migration of books. But is quite a good start for any kind of node.

You will need to expand the node\_query() function with leftJoins to all the d6 fields. (Look them up in your database, you can join them by nid.) Because of the joins you can make the input field list as big as you want.

Then in the map (node\_field\_mapping() function) you can add all fields of your new type.

---
Tags: feeds, nodes, importing-exporting
---


# Question
Title: Is it possible customize user login page on Adaptive Theme?
I tried many solutions for change my mysite.com/user page. I want, only login-register-forgotten form is visible, other block hidden. But what i try a solution, don't working.

Is it possible? How can i do this?

This is my past question: https://drupal.stackexchange.com/questions/65475/error-when-creating-a-custom-page-in-d7

# Answer
> 1 votes
If you wish to hide blocks, go to the block configuration page (/admin/structure/block), celect 'configure' for the blocks you wish to hide, and under 'Block Visibility Settings' on the 'Page' tab select 'All pages except those listed '. Then if your login url is '/user/login', enter 'user/login' in the box. If you enter 'user/\*' it will exclude the block from all pages matching the pattern.

---
Tags: 7, users, theming
---


# Question
Title: Reverse geocoding (country) from geofield with coordinates
is there a quick way to do a reverse geocoding from a geofield field containing geographical coordinates?

I just need the country name, so I wonder if there is some service with more allowance than the Google API, or even a hosted solution with country coordinates and a drupal module quering it???? (as it seems to be a Drupal module for everything)

# Answer
this is a question that I asked to myself some time ago. I suggest to start from the geocoder module. This module "translate" an address to a lat./lon. parameter that could be displayed in a map. Reversing this process - if I understand correctly your question - seems to be a WIP: actually, no out-of-the-box solution. But you can check and try the suggestions in this discussion.
> 2 votes

---
Tags: 7, location
---


# Question
Title: Grouped exposed filters just don't work on tags
So I created a nice gallery view and I wanted to add an exposed filter on tags so that my users could filter the content in it.

I created the proper tags ("photo" and "video" for example), created my **tags** filter using the "autocomplete" setting, checked the "Expose this filter" combobox and checked the "Grouped filters" radio.

Then, I added my two corresponding rows, giving them the respective values "is one of" =\> "photo" and "is one of" =\> "video", and left the default row to "Any". I have two nodes containing the tags "photo" for one, and "video" for the other.

Yet when I save everything and go to my gallery view, not only do I not get anything displayed even on the "any" filter, I get this error message:

```
Unable to find term: all

```

When I try to use my filters I don't get anymore things, but these messages:

```
Unable to find term: 1

Unable to find term: 2

```

These numbers are written in the "?field\_tags\_tid=" of my URL when I click my exposed filter buttons, but they are not even the corresponding tids of my two tags: "photo" is 11 and "video" is 12...

Even weirder: when on the admin side I change settings of my **tags** filter to "Dropdown" instead of "Autocomplete", this time I DO get the correct content displayed on my view for the "any" filter, but still nothing for the "Photos" and "Videos" filter, which still point to "?field\_tags\_tid=1" and "?field\_tags\_tid=2". But this time, no errors displayed.

Sadly, I cannot even try to put the right tid in my URL. I get the following error:

```
An illegal choice has been detected. Please contact the site administrator.

```

Is this drupal thing completely broken or am I just terribly unlucky?

# Answer
Delete all your existing filters. I think you have misunderstood how they work.

Then add a single filter on the term reference field (field\_tags?), expose to visitors, reduce duplicates, and make sure the filter is NOT required. Do not check anything else!

Submit, save your view, and you should have an exposed filter with the options '-Any-', 'Phpto' and 'Video'.

EDIT:

After much discussion, step by step:

1. Go to /admin/structure/taxonomy and set up a vocabulary calling it whatever you wish (lets say 'media'). Then add terms to the vocabulary like 'Photo', 'Video' etc. If you have already done this, skip to step 2.
2. In your content type, go to 'Manage fields' and add a term reference field to the type (lets call it 'Media') using the media vocabulary.
3. Go to /admin/modules and disable Better Exposed Filters.
4. Edit your view and delete all the current filters in the view. Save the view.
5. Now add a filter on the taxonomy reference field (eg field\_media). Click Add and configure fiter, on the first modal select 'Dropdown' and click 'Apply and Continue'.
6. On the next modal, check 'Expose this filter to visitors, to allow them to change it'. The 'Filter type' should be 'Single filter'. Make sure 'Required' is not checked. Leave the operator as 'Is one of'. The only other box you should select is 'Reduce duplicates. Now click 'Apply' and save your view.

You will now see a dropdown list with all the terms in the vocabulary you created, plus the option -Any- at the top.
> 0 votes

---
Tags: 7, views
---


# Question
Title: store session variable and access it through javascript?
In drupal, how do you store/read session variables? Also, how can i access a stored session variable through javascript?

I'm trying to store whether if a user has closed my modal or not so it doesn't pop up for another day.

# Answer
> 4 votes
Accessing a session variable in Drupal is not different from how it is done with plain PHP: with `$_SESSION`.

As for reading them with JavaScript, it is enough to use code similar to the following one.

```
// PHP
drupal_add_js(array('myModule' => array('key' => $_SESSION['key'])), 'setting');

```

```
// JavaScript
key = Drupal.settings.myModule.key;

```

---
Tags: javascript, sessions
---


title: Webform Conditional auto un-select

text:
# Question
Title: Webform Conditional auto un-select
I am using Webform 7.x-4.0-alpha6.

I have configured a number of radio options in a "parent" component. When each of the radio buttons are selected, different "child" components showup. Each child is unique to each radio button in the parent. Like the following:

parent =\> radio#1 radio#2 radio#3

child=\> \[radio#1\] radio#1-option#1 radio#1-option#2 radio#1-option#3

child=\> \[radio#2\] radio#2-option#1 radio#2-option#2

child=\> \[radio#3\] radio#3-option#1 radio#3-option#2 radio#3-option#3 radio#3-option#4

**What I am trying to achieve is allowing no more than one option to be selected across all the lists of radio buttons.**

So, if I select **radio#1-option#1** under **parent=\>radio#1** and I happen to change my mind and select **radio#3=\>option#4** under **parent=\>radio#3**, I want **radio#1-option#1** to be automatically deselected/unset.

# Answer
> 1 votes
Try Webform Conditional module, this has some extended conditional rule on radio button and other form elements:

> Webform already has support for conditional fields on multi-page forms. For example Field C on Page 2 can be dependent on Field A on Page 1. This module adds the ability to have conditional fields on the same page. This module adds the ability to have Field B on page 1 be dependent on Field A also on Page 1.

---
Tags: 7, webforms
---


# Question
Title: Connecting multiple data entities to the user object
I need to create a simple order system in Drupal 7. This will be a site for a meat wholesaler so I don't need a webshop. Users are able to register and fill in a webform to order products. However I'll need to handle different shipping addresses for the users, and let them choose a shipping address upon ordering. What I have in mind is connecting the shipping addresses to the user object (billing address is already on the user form).

Which method is better?

1. Create a field collection entity for the shipping addresses and add it to the user form
2. Leave the user form alone and create a new content type that can be added/edited by users and use the UID to decide which address belongs to which user

I'd like to let users edit their shipping addresses anytime on their user page, preferably independently from the other datas.

If anyone done something like this before, please share some ideas.

# Answer
You would probably be best to create a Shipping Address content type. You should also look at the Address Field module to collect the addresses rather than field collection.

Then you can create a simple view to list the shipping addresses (Node Tile not linked) using a contextual filter on uid. Then set up a node reference field in your webform using the view to provide the values. The user can then select which shipping address to use for his order.

On the user page you mav use the same view (separate display listing titles as edit links) to let them edit their shipping addresses, and give them a link to add new addresses if necessary.
> 2 votes

---
Tags: users, entities
---


title: login block has disappeared from /user

text:
# Question
Title: login block has disappeared from /user
The content region throughout the site seems to have disappeared. I believe this might be a result of some mishandling of the default settings in Omega.

As a result the login prompt is gone from /user and I'm currently logged out without a way to log back in and fix it.

Any idea how I can login to the site without going to /user or how I would go about editing Omega/delta so that I can bring back the content region without logging in? This site is still local/on my development server. So I can still access the files.

Attached is a screenshot of what I'm looking at for those who are confused.

# Answer
> 3 votes
you could print the login block programmatically in (the top of ..) your page.tpl.php like

```
<?php
 $block = module_invoke('user', 'block_view', 'login');
 print render($block['content']);
?>

```

clear caches through drush if possible

```
drush cc all

```

---
Tags: nodes, users, theming
---


title: Italicizing content pane titles

text:
# Question
Title: Italicizing content pane titles
A few of our content pane titles need to be italicized because they contain book titles.

I've added an "italicize-title" class to the content pane in Panelizer \> Content \> Content Pane \> CSS properties. This has some drawbacks. The main disadvantages are that the whole title is italicized and I have to manually add the class to each piece of content needing its title italicized.

I've tried the HTML Title module, but that didn't work.

Is there a way for me to allow content editors to use a limited number of html tags in a content pane's title field?

Thank you for looking...

# Answer
> 0 votes
This is untested but I would try implementing a `template_preprocess_panels_pane()`:

```
function mytheme_preprocess_panels_pane(&$vars) {
  $content = &$vars['content'];

  $title = !empty($content->title) ? $content->title : '';
  $title = preg_replace("/\*\*(.*?)\*\*/", "<b>$1</b>", $title);
  $title = preg_replace("/\*(.*?)\*/", "<i>$1</i>", $title);

  $vars['title'] = $title;
}

```

Adapted from this answer, and would allow some simple markdown in the titles.

---
Tags: 7, panels
---


title: Redirect if URL does not match

text:
# Question
Title: Redirect if URL does not match
I am using D7.

I am attempting to create a redirect in my .htaccess file that will redirect the page **if** the path **doesn't match a pattern**.

```
# only if a particular domain
RewriteCond %{HTTP_HOST} ^mysite\.domain\.org$ [NC]
# only if URI contains "library"
RewriteCond %{REQUEST_URI} !^/Library$ [NC]
# rewrite the URL
RewriteRule ^(.*)$ http://otherdomain.org/$1 [R=301,L]

```

This works fine for most of the site (e.g. http://mysite.domain.org/blogs is redirected to http://otherdomain.org/blogs

However, http://mysite.domain.org/Library?id=1234 is being redirected but to http://otherdomain.org?id=1234 ("library" in URI is missing but this shouldn't redirect at all)

What am I missing? Am I running into Drupal URL rewriting rules?

# Answer
> 1 votes
Try this:

```
# only if a particular domain
RewriteCond %{HTTP_HOST} ^mysite\.domain\.org$ [NC]
# rewrite the URL
RewriteRule ^((?!Library).*)$ http://otherdomain.org/$1 [R=301,L]

```

The (?!Library) should look ahead, and the match should fail if "Library" is present. Hope this works for you.

---
Tags: 7, .htaccess
---


# Question
Title: What is the best way, programmatically, to iterate through a view's results?
Given a view, named 'Children' (with two fields: child\_node\_id and a birth\_order\_value) what is the best way, programmatically, to iterate through the views results set given a display\_id of 'default' and an argument that contains the parent node id?

Previously, I have used the View in a block using code similar to the following:

```
if ( arg(0) == 'node' && is_numeric(arg(1)) && ! arg(2)) {
   $node = node_load(arg(1));
   $args = array($node->nid);
   $view = views_get_view('Children');
   print $view->preview('default', $args);
}

```

However, in another block I want to perform some logic based on the values found in the view. You might be able guess that business logic based on my final requirement: I want the block of code supporting the view ('Children') be called multiple times. As I iterate through the view dataset results, I want to recursively iterate through the children nodes querying for their children.

# Answer
Playing around with Views a bit I seem to have worked out an approach. However, I'd like to leave my question open to other answers and better solutions.

```
<?php
if ( arg(0) == 'node' && is_numeric(arg(1)) && ! arg(2) ) {
   $node = node_load(arg(1));
   $args = array($node->nid );
   unset($view);
   $view = views_get_view('Children');
   $view->set_display('default');
   $view->set_arguments($args);
   $view->set_items_per_page(20);
   $view->execute();
   $newarg = array();
   for ($i=0; $i<sizeof($view->result); $i++) {
      $newarg[$i] = $view->render_field('nid_1', $i);
   }
   for ($i=0; $i<sizeof($newarg); $i++) {
      unset($view);
      $view = views_get_view('Children');
      $view->set_display('default');
      $view->set_arguments($newarg[$i]);
      $view->set_items_per_page(20);
      $view->execute();
      ....
   }
}
?>

```

The key to executing the view multiple times was for me to unset($view) when I was done with the result set.
> 2 votes

# Answer
I've gotten good mileage out of the following function. The return value is an array of all the view records. Calling dsm($return\_value) will give you a good idea of the structure of your particular view.

```
function _get_view_data($view_name, $args, $page = NULL, $page_size = 0 ) {
    $view = views_get_view($view_name);
    $view->pager['items_per_page'] = $page_size;
    $view->set_arguments($args);
    if ($page) {
        $view->build($page);
        $view->execute($page);
    }
    else {
        $view->execute();
    }
    return $view->result;
}

```
> 1 votes

# Answer
Here is a helper function already built in to the Drupal API. (I spent a while flailing around in the Drupal Docs, and eventually found it. It seems many others have also produced solutions that don't use this helper, and also that this helper does one interesting step that other solutions don't... to call pre\_render on the $view object before execute).

I can't vouch for whether it works well or not, but at least it's a specific place to call out issues with these approaches.

For D6 http://api.drupal.org/api/views/views.module/function/views\_get\_view\_result/6

And for D7 http://api.drupal.org/api/views/views.module/function/views\_get\_view\_result/7
> 1 votes

---
Tags: views, 6
---


title: Submitting a form added using ajax

text:
# Question
Title: Submitting a form added using ajax
I am adding content to my page using `file_get_contents` (I'm rendering the content to strip all template html as in this example: https://stackoverflow.com/questions/247991/displaying-a-drupal-view-without-a-page-template-around-it).

Some of the pages have forms which should be submitted normally, as in the page should be validated and redirected after submission. However submission is not working. For example, if the page is at http://mysite.com/myform and pressing the cancel button should call myform\_cancel() and redirect me to http://mysite.com/, I instead get redirected to http://mysite.com/myform?response\_type=embed and no submit methods are called.

What do I need to so to make my form submit as expected?

**Edit:**
A similar thing happens when I instead render the form using `menu_get_item` to get the callback and arguments, then render the html using: `drupal_render(call_user_func_array($menu_item['page_callback'], $menu_item['page_arguments']))`. This time I am redirected to my 'http://mysite.com/ajax-form' which is my menu url to the ajax call used to return the html.

# Answer
I was able to solve this using the following code:

```
function bikebike_ajax_form()
{
    if (isset($_POST['url']))
    {
        $url = $_POST['url'];
        $menu_item = menu_get_item($url);
        $form = call_user_func_array($menu_item['page_callback'], $menu_item['page_arguments']);
        if (isset($form['#action']))
        {
            $form['#action'] = url($url);
        }
        $html = drupal_render($form);
        die($html);
    }
    die('');
}

```

As you can see, instead of rendering the page using `file_get_contents`, I simply grabbed the elements from the function defined in hook\_menu. I needed to change the 'action' parameter of the resulting form structure.

If anyone has a better solution to this problem, I'll happily give you the answer.
> 0 votes

---
Tags: 7, forms
---


# Question
Title: Show PDF/print icons inside a template file
I am using a template file to render a content type. So I print variables as with the following code.

```
print $node->body

```

I have installed the Print module, and I have selected the option to display print icons for this content type to, but the icons are not getting printed.

How can the icons be printed inside a template file?

# Answer
> 2 votes
As the README.txt says

> Administration \> Structure \> Content types (admin/structure/types)
> For each content type it is possible to enable or disable the PF link via the "Show printer-friendly version link" checkbox. (default: enabled) It is also possible to enable or disable the PF link in individual comments via the "Show printer-friendly version link in individual comments" checkbox. (default: disabled)

API

```
print_insert_link(), print_mail_insert_link(), print_pdf_insert_link()

```

> The \*_insert\_link functions are available to content developers that prefer to place the printer-friendly link in a custom location. It is advisable to disable the regular Printer-friendly link so that it is not shown in both locations.

Take a look at THEMEABLE FUNCTIONS

**It is a best Practice to read modules README.txt.**

---
Tags: theming
---


title: theme_username($object) in Drupal 7?

text:
# Question
Title: theme_username($object) in Drupal 7?
In my author\_pane template, I get my user´s names trimmed as it was back then in Drupal 6. So I went to the api page (as I did in my D6 installation) and I see that the code that used to work in Drupal 6 isn´t there anymore in Drupal 7.

This was the code I´m looking for:

```
function theme_username($object) {

  if ($object->uid && $object->name) {
    // Shorten the name when it is too long or it will break many tables.
    if (drupal_strlen($object->name) > 20) {
      $name = drupal_substr($object->name, 0, 15) . '...';
    }
    else {
      $name = $object->name;
    }

```

How may I ensure in D7 that my username´s names aren´t being trimmered at 20 character´s length?

# Answer
> 3 votes
That code has been moved in template\_preprocess\_username(), which is called before the theme function.

```
// Set the name to a formatted name that is safe for printing and
// that won't break tables by being too long. Keep an unshortened,
// unsanitized version, in case other preprocess functions want to implement
// their own shortening logic or add markup. If they do so, they must ensure
// that $variables['name'] is safe for printing.
$name = $variables['name_raw'] = format_username($account);
if (drupal_strlen($name) > 20) {
  $name = drupal_substr($name, 0, 15) . '...';
}

```

If you need to use the full-length name, you should use `$variables['name_raw']` in your implementation of `theme_username()`, remembering that the value has not been passed to any sanitization function.

---
Tags: 7, theming
---


# Question
Title: In a manually created menu, when a taxonomy term is a parent with children, the children never display. Bug?
I manually created a menu where each parent term is a taxonomy. so:

Menu name:cars

Path: cars

Note that 'cars' is a path auto generated url for taxonomy/term/3. I thought you could only put nodes here, but this saves instead of giving the usual error when the path is not available.

Each one of these parent items has 1 level of children. Or, should at least.

In the Structure \> Menu view, you can easily see the menu structure with parent and children.

however, when this is rendered as a menu block, only the parents are displayed. Is this because the Parent is a taxonomy term and not a node?

One of the reasons I think it may be a bug is that if you look at the source code the html shows 'collapsed' as an li class, indicating that it knows it needs to have children here. The second reason I think this is a bug is that if I change this to node/(number) then everything works fine. Anyone know a solution to get this working?

# Answer
> 0 votes
Have you tried editing the parent menu item and enabling the 'Expanded' checkbox? This module may also come in handy: http://drupal.org/project/menu\_expanded

Keep in mind that in many themes, the stock menu for primary links / secondary links is not a multi-level menu and so even if expanded renders the child items in HTML, they may not render properly in the actual menu. If this is the case, you may wish to look at implementing a menu block with one of the menu modules such as: http://drupal.org/project/superfish

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


# Question
Title: How can I paginate the Views page itself where all views are listed?
At the url admin/structure/views how can I paginate this list of results?

# Answer
> 2 votes
If you have many views I would suggest you go to Views settings (`admin/structure/views/settings`) and enable **`Show filters on the list of views`**. This gives you the possibility to search and filter the list of views in various ways.

---
Tags: 7, views
---


# Question
Title: Need to change the subdomain URL structure - D7
Need to change the subdomain URL structure from:

```
sub1.example.com
sub2.example.com

```

To:

```
www.example.com/sub1
www.example.com/sub2

```

Is there any module to do this in Drupal 7

If there is no other module in the text I need to rewrite the module for D7 version which is available in D6 in the below link. But before doing that I would like to confirm is there any modules ?

**Below text is taken from the link**:

> Of course this could quite easily be achieved using a redirect / RewriteRule in an htaccess file – but in this case we wanted to to achieve the URL re-routing without actually using a redirect. In other words, the URL in the browser’s address bar should always show URLs like this

# Answer
> 0 votes
I believe you will still need some mod\_rewrite redirection rules (RewriteRule), but only after the fact; it can be used used to ensure users accessing subX.example.com get redirected appropriately to the new content URL instead of mod\_rewrite being the solution to the problem (which, as you mentioned, is not what you wanted).

Have you tried using pathauto to set a URL pattern and then using views\_bulk\_operations to mass update node aliases? I recall VBO will overwrite any existing alias, but if it doesn't simply make a database backup for good measure and then drop your existing node path aliases from the database directly as they will be regenerated anyways using VBO.

If you need to create redirects from the old node aliases to the new ones (ignoring the hostname component), the redirect module will automatically create 301s.

Here is a quick guide on pathauto + VBO: http://drupal.org/node/1326928

---
Tags: 7, uri, .htaccess, subsites
---


# Question
Title: how to add data to custom content type using node with codeing
i have drupal site with custom content type called donation and i have 4 step registration form which contains the data for the custom content type,i want to add forms data in to custom content type node how can i do that i try way like this

```
$nid = 1;
$node = node_load($nid);
$node->donationname = '.$data1.';
$node->donationitem = '.$data2.';
node_save($node);

```

# Answer
The proper method is

```
  $body_text = 'Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.';

  $node = new stdClass();
  $node->type = 'article';
  node_object_prepare($node);

  $node->title    = 'Node Created Programmatically on ' . date('c');
  $node->language = LANGUAGE_NONE;

  $node->body[$node->language][0]['value']   = $body_text;
  $node->body[$node->language][0]['summary'] = text_summary($body_text);
  $node->body[$node->language][0]['format']  = 'filtered_html';

  $path = 'content/my-lipsum-' . date('YmdHis');
  $node->path = array('alias' => $path);

  node_save($node);

```

**To Add custom fields**

```
// Let's add some CCK/Fields API field. This is pretty similar to the body example
$node->field_custom_name[$node->language][0]['value'] = 'This is a custom field value';
// If your custom field has a format, don't forget to define it here
$node->field_custom_name[$node->language][0]['format'] = 'This is a custom field value';

```

How to programmatically create/manage node in drupal 7
> 1 votes

---
Tags: 7, forms, nodes
---


title: Feed import not creating new nodes

text:
# Question
Title: Feed import not creating new nodes
I've got a feed import set up using the **HTTP Fetcher**. It creates nodes of a certain type. I need it to import repeatedly so I've got **Periodic Import** set to **As often as possible**. I've got **Import on Submission** and **Update existing Nodes** checked.

However, the feed imports and creates only **25 nodes** on my first manual import. After that it does not create any new nodes either when doing so manually or when the cron run triggers it.

This is a **youtube feed** pulling videos of a certain publisher and parsing the data with the Feeds youtube module. I also have a field that I am using as **Unique**.

Any idea what might be going on??

**NOTE:** There are no error messages in any of the logs.

# Answer
According to the specs, you can set the `max-results` parameter up to 50. For succeeding searches the `start-index` can be increased. I guess you will have to do this manually to fill the database for the first time, or you can try to use the Feeds Crawler.
> 0 votes

---
Tags: feeds
---


# Question
Title: creating a custom entity which stores multiple bundles as per user input?
I want to create an custom entity(Lets say payroll entity) which has the following fields 1. Basic salary 2. Earnings 3. Deductions

It is possible by Entities

But now I would like to add some new feature

1. Basic salary(field)
2. Earnings(Bundle) contains (bun1, bun2, bun3 fields)
3. Deduction(Bundle ded1,ded2 and ded3 fields )

If a user wants to set his employee's Earnings and other details he can manual sets it .For an example if a user needs to set his/her employee's salary like daily allowance, travel allowance, bonus etc) he/she can do it from their own choice . And there should not be any restrictions for the no. of fields to add either bundles or fields . A user add custom bundles as well as custom fields.

# Answer
Satyabrata,

Not sure i got the requirement correct. Have you considered using entity reference + inline entity form? You can attach bundles to the main bundle and can create them (sub bundles) from the main bundle using inline entity form .

Hope it helps.
> 0 votes

---
Tags: 7, entities
---


title: How to redirect the user after login

text:
# Question
Title: How to redirect the user after login
I have created a custom form for login page. When a user logs in, I want to redirect the user to some other page, different from `user/<user_name>`.

How can I perform such redirect?

# Answer
> 2 votes
You can use the Rules module.

> Example use cases
>
> Build flexible content publishing workflows changes Send customized mails to notify your users about important Create custom redirections, system messages, breadcrumbs, ... And many more...

To use that go to `admin/config/workflow/rules/reaction/import` and import this it will redirect user to `admin/dashboard` path after user logged in :

```
{ "rules_redirect_after_login" : {
    "LABEL" : "redirect after login",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "user_login" : [] },
    "DO" : [ { "redirect" : { "url" : "admin\/dashboard" } } ]
  }
}

```

You may also build a custom module and use hook\_user\_login and do something on the lines of :

```
function hook_user_login(&$edit, $account) {
     $_GET['destination'] = 'node/25';
 }

```

# Answer
> 1 votes
You and also use the Login Destination module and in the config set the redirect.

> The Login Destination module allows you to customize the destination that a user is redirected to after logging in, registering to the site (7.x), using a one-time login link or logging out (7.x). The destination can be an internal page or an external URL. It is possible to specify certain conditions like referring pages or user roles and make the destination depend upon them. You may use PHP snippets to provide custom conditions and destinations. It is also possible to keep users on the currently visited page after logging in or out.

---
Tags: 6, redirection
---


# Question
Title: How do I add classes to form elements in the theme layer?
I want to do it in template.php. The form ID is page\_node\_form, and there are six form text fields. The default class is "form-text."

I want to add "text1," "text2," etc after "form-text" to each input text class. How can I do it?

This is the HTML:

```
<input gtbfieldid="10" id="edit-field-14sq-und-0-value" name="field_14sq[und][0][value]" value="" size="12" maxlength="10" class="form-text" type="text">
<input gtbfieldid="10" id="edit-field-14sq-und-0-value" name="field_15sq[und][0][value]" value="" size="12" maxlength="10" class="form-text" type="text"> ....

```

# Answer
> 6 votes
This is an ideal situation for a preprocess function.

I don't have Drupal 7 working to test at the moment, but something like this in your template.php should do the trick.

```
function mytheme_preprocess_textfield(&$vars) {
  static $counter = 0;
  $counter++;
  $vars['element']['#attributes']['class'][] = 'test' . $counter;
}

```

# Answer
> 0 votes
If you wish to do it in your module, in your hook\_form\_alter for the node form add :

```
$form['field_14sq'][und][0][value]['#attributes'] ['class'][] = text1;

```

---
Tags: theming, forms
---


# Question
Title: How to theming and deploy custom blocks which created in admin UI?
I've created some custom blocks in my development environment and export them with `Features` \+ `FE Block` with given machine names. And then deploy and enable them in my staging environment.

Just like the sample below, the blocks with same machine name have different block ids in different environments, but I want the `guide` block has a special layout than other blocks.

```
development
    block-block-1 (guide)
    block-block-2 (case_links)

staging
    block-block-1 (case_links)
    block-block-2 (guide)

```

Because in different environments the `guide` block has different `block_id`, I can't just use the block id as the identifier to apply these css rules.

What should I do to solve this problem?

# Answer
> 1 votes
You can add custom classes or id's to your blocks. If you don't feel to code it yourself your best bet would be to use the Block class module, and perhaps also along with the Block Class Styles module which provides custom templates for your blocks.

--update--

The new version (7.x-2.0) of Block Class module has just changed it database structure, removed the `block_class` table and add a field `css_class` into `block` table. The current version of Block Class Styles module work well with Block Class 7.x-1.2.

---
Tags: 7, theming, blocks, features, deployment
---


# Question
Title: Listing all entries of a specific content type within a panel
I've been tasked with adding a page to an existing Drupal (version 7.15) site. I know next to nothing about Drupal or PHP so I've been struggling a bit.

I've created a page with 2 panels and am trying to use the "custom content" option to display the title field for each entry of a specific content type in one panel. And in the other panel, I would like to display all the fields for each entry.

For instance, the first panel thus far contains:

```
<div class="open-positions">
  <h2>Open Positions:</h2>
  <ul>
    <li></li>
  </ul>
</div>

```

And I'd like to know what PHP code I'd need to use to make each `<li>` tag contain the titles for my content type. The other panel would be somewhat similarly formatted in that there would be markup enclosing each field, but I do not know how to get the entries from the database, and then display specific fields from that entry.

Thanks.

# Answer
If you can at all avoid it, the direction you've started in is not the solution you want. Panels is *not* for handling content, but *context*.

What you want instead is a Views content pane. Explaining Views in detail is beyond the scope of this post, but here's the general outline.

1. Install Views and Ctools.
2. Enable "Views UI" and "Views content panes".
3. Create a new View
4. Add a filter on node type so you get only the right content type.
5. Add title as field. Then repeat the View creation above but add the rest of the fields.
6. Go into Panels and add both Views in their respective regions.

Much much more info about Views in Taming the Beast: Learn Views with NodeOne.
> 3 votes

# Answer
Read about Views. You can easily create a Views blocks with nodes list and put it inside panel.
> 1 votes

# Answer
Aperture,

I think you should create 2 views one which lists just the title and the other one displaying the rest of the fields. After creating the 2 views you can call them in panels page.

You will need to download and enable ctools (Views content panes), views and panels modules.

Create a new view at admin/structure/views with type content pane.

Once done with views, it will appear in panel pane to add to the page.

Deepak
> 1 votes

---
Tags: nodes, panels
---


title: Taxonomy-term based block display

text:
# Question
Title: Taxonomy-term based block display
I'm trying to display certain blocks in taxonomy term pages and the nodes associated based on the taxonomy term itself.

Let's say I have 3 taxonomy terms: Bologna, Milan and Rome.

When I'm in Bologna taxonomy-term page I would like to display a block that show the map of Bologna, when I'm in Milan taxonomy-term page the Milan map and so on.

Context module seems to work with node associated to a particular taxonomy term (for example, I'm able to display Milan map block in every node associated with Milan taxonomy term), but doesn't work for the taxonomy page itself.

I think the trick is in Panels. I've enabled the taxonomy-term page override but I do not know how to display blocks based on arguments.

I've used views and panels many times before but never faced this particular problem: It's a bit different that filtering with arguments particular nodes or content types.

# Answer
> 0 votes
Kropot,

Have you tried views contextual filters?

1. Create a block view.
2. Add a Contextual filters with Content: Has taxonomy term ID.
3. defalt value: Taxonomy Term ID from URL
4. Add the fields to display.
5. Add the filters.

Deepak

---
Tags: taxonomy-terms, blocks, panels
---


# Question
Title: Create a view to show users who flagged other users
I have created a User flag as Report Abuse. Users may flag other users with this flag. Now i want to create a view where the users who are flagged along with the flagging user are shown. However i am unable to show the flagging user (though i am getting the user id of the flagging user). It should have been quite simple. I have added, i think, the required relationships. Here's a screen shot of the view settings.

# Answer
Well it was quite easy actually. I just added a field in User:Name and added the relationship as Flag User as the required relationship
> 1 votes

---
Tags: 7, views, users, flags
---


title: CSS grid for custom theming in Omega?

text:
# Question
Title: CSS grid for custom theming in Omega?
I cant find the answer to my question by googeling or in the documentation for the theme but im sure ive heard it exists. Does the Omega theme give you a CSS grid to work with?

So if you wanted to customize a tpl file and have 2 colums, one twice the width of the other, could you just write some CSS a bit like this?

```
<div class="1of3">content here</div>
<div class="2of3">more content here</div>

```

Im happy to use standard classes but Im trying to avoid adding additional CSS, I would have thought the theme (as a grid based layout) would have classes I could use? Thanks

# Answer
> 0 votes
Absolutely, one might argue that's one of the reasons to use Omega in the first place; as per the first two features listed on the project page:

* Fully Responsive Grid layouts based on 960.gs standards.
* 12, 16, 24 Column Layouts built in.

Have a look in the CSS files with names like `alpha-default-normal-12.css` under omega/alpha/css/grid/alpha\_default/\* to discover what classes are available for you to use.

Those files should make it fairly obvious what conventions Alpha/Omega use for naming those classes too, so you should be able to predict what you need to use easily.

---
Tags: theming
---


title: #ajax response handler function

text:
# Question
Title: #ajax response handler function
Hi I am using #ajax in my custom form. I need a response handler function for my form in jquery. How can i acheive this goal?

For example:

```
$form['changethis'] = array(
'#type' => 'select',
'#options' => array(
  'one' => 'one',
  'two' => 'two',
  'three' => 'three',
),
'#ajax' => array(
  'callback' => 'ajax_example_simplest_callback',
  'wrapper' => 'replace_textfield_div',
 ),
);

```

Here i have the ajax\_example\_simplest\_callback in php. I need a response handler in js.

# Answer
> 1 votes
Try this

```
(function($) {

  Drupal.YOUR_MODULE_NAME = {
    form_id: 'FORM_ID'
  };

  Drupal.behaviors.YOUR_MODULE_NAME = {
   attach: function(context, settings) {

    for (ajax_el in settings.ajax) {
      if (Drupal.ajax[ajax_el].element.form) {
        if (Drupal.ajax[ajax_el].element.form.id === Drupal.YOUR_MODULE_NAME.form_id) {
          Drupal.ajax[ajax_el].success = Drupal.YOUR_MODULE_NAME.success;
       }
      }
     }
    }
   };

 Drupal.YOUR_MODULE_NAME.success = function (response, status) {
    // HERE YOU GET THE response
 }

 });

```

# Answer
> 0 votes
You should look into examples modules. ajax\_example module has a number of examples.

eg. dependent dropdown

# Answer
> 0 votes
This is not the cleanest way of doing things but does the job none the less...

```
'#ajax' => array(
  'progress' => array(
    'type' => 'throbber',
    'message' => '<script>YOUR_CUSTOM_HANDLER(); </script>',
  ),

```

---
Tags: 7, ajax
---


title: How to update a feature

text:
# Question
Title: How to update a feature
I have a feature which contains fields for the user profile page. This is currently working in PROD.

In the dev site, I've updated the feature to include a new field, updated the version, and download a new TAR file.

In PROD, when I go to Update Module, and try to update the feature, an error message appears saying the feature is already installed.

Am I missing something here? Are features only expected to be installed once? Or do I need to manually remove the feature before updating?

Would it be better practice to create a brand new feature containing the one field?

# Answer
when it's structure only, you will have to upload your dev feature, replace it with the production one and revert the production feature.
> 1 votes

# Answer
Drush is invaluable for managing features.

1. Install drush - drush manual page.
2. Copy files over existing feature.
3. Run "drush fr myfeature" on the command line.

That is put a feature back (features-revert) to the way it was before you experimented making changes in the user interface.

Drush can also be useful to update the feature (features-update):

```
drush fu myfeature

```

Create a "diff" between what has been changed using the user interface and what is stored in the feature:

```
drush fd myfeature

```
> 1 votes

---
Tags: entities, users, features
---


# Question
Title: using an existing token as a variable in a custom token
I am using simplenews to send out a newsletter. I have a custom module. It has a table that relates a user code to the user's email.

```
email_address                  user_code
bob.loblaw@lawblogs.com        37XylT12

```

In the simplenews email I will send, the idea is that each user will receive a link with their usercode in it (i.e., http://www.domain.com/?q=go&c=37XylT12).

I've been attempting to create a custom token to place in the text of the newsletter and replaced with my custom link prior to send. However, I have two issues: 1) I cannot find an example of a token that includes a db\_select query to return data and 2) I cannot find a way to access the simplenews email token (\[simplenews-subscriber:mail\]) in my custom module -- I need this value to lookup the code.

If someone could point me in the right direction, I would appreciate it. KMT

# Answer
> 1 votes
Accessing the database to set a token is not different from accessing the database in other cases.

```
function mymodule_tokens($type, $tokens, array $data = array(), array $options = array()) {
  $sanitize = !empty($options['sanitize']);

  $replacements = array();

  if ($type == 'YOUR TOKEN TYPE') {
    foreach ($tokens as $name => $original) {
      switch ($name) {
        case 'YOUR TOKEN':
          $replacements[$original] = /* CODE TO QUERY THE DATABASE */;
          break;
      }
    }
  }

  return $replacements;
}

```

As for accessing the value of a token defined from a module, when you know the token you are looking for, you can call token\_replace() passing the token for which you want to know the value as first parameter. Keep in mind that your implementation of `hook_tokens()` is going to be called again; be careful of not causing a loop.

---
Tags: database, tokens, emails
---


# Question
Title: Listing module under one custom module heading
I have created Menu type called Form submission. Under this I want to list all the Form submitted values. There are two forms one is Contact form and help form. I want to display these two as Contact and help form under the menu type Form submission.

Example: When I click Contact it has to show the contact list.

How to list the Contact and help form under the Form submission in admin page. I build it as custom module.

# Answer
I believe your question actually relates to adding new custom entries to the admin menu, in which case this article may help: http://drupalst.com/blog/add-menu-block-administrator-configuration-page (it's specifically about the config menu but any part of the admin menu can be customized in a similar manner).
> 0 votes

# Answer
You can print any form using drupal\_get\_form

```
drupal_get_form($form_id)

```

And to print a form

```
<?php print drupal_render(drupal_get_form($form_id)); ?>

```

You can find form id using hook\_form\_alter

Eg :

```
function YOURMODULENAME_form_alter(&$form, &$form_state, $form_id) {
  echo $form_id;
}

```

To redirect users after submission you can use drupal\_redirect\_form

> Redirects the user to a URL after a form has been processed.

To get all modules list you can use module\_list

> Returns a list of currently active modules.
> 0 votes

---
Tags: routes
---


# Question
Title: How to edit/extend/remove pager in the admin back-end?
For example I just applied Mollom for antispam and everything, because the site got like 500 spam comments and 500 spam users. Now I can delete them only by selecting 50 users per page in the admin/people list and that is taking up really lots of time. I will have to remove comments and forum threads like that too page by page, 50 at the time? Would be nice to somehow extend those admin back-end pagers for various lists, like amdin/people or admin/content so I could select them all at once, or select at least 100 per each or something like that.

Maybe there's a module or something?

# Answer
> 1 votes
Also take a look at http://drupal.org/project/admin\_views which gives you a drop-in replacement for the user management page with views bulk operations integrated, which because it is implemented as a view can be made to work however you like.

# Answer
> 1 votes
Views Bulk Operations was written to handle such situations:

> This module augments Views by allowing bulk operations to be executed on the displayed rows. It does so by showing a checkbox in front of each node, and adding a select box containing operations that can be applied. Drupal Core or Rules actions can be used.

You can build a View to filter users by whatever criteria makes sense, and use VBO to delete them all (not just those on the current page) in one go.

# Answer
> 1 votes
When you are cancelling accounts, you are given the option to either block or delete them. You are also given the option to delete all content associated with that account. There is no reason to use separate operations for user and content. Do it all at once as you delete the accounts.

---
Tags: 7, paging
---


# Question
Title: What is causing /user/*/taxonomy/term/* to redirect to /taxonomy/term/*?
I got a view with contextual filters set up as the following:

* Global: Null (Fixed value "user")
* Content: Author uid (User ID from URL)
* Global: Null (Fixed value "taxonomy")
* Global: Null (Fixed value "term")
* Content: Has taxonomy term ID (Taxonomy term ID from URL)

When I go to `mysite.com/user/*/taxonomy/term/*` I'm being redirected to `mysite.com/taxonomy/term/*`.

How can I prevent this?

I also got Pathauto to change the URLs to `[user:name]` for `user/*` and `tags/[term:name]`for `taxonomy/term/*`.

Edit: If I disable the URL alias for the taxonomy terms it still redirects to `mysite.com/taxonomy/term/*`.

# Answer
> 5 votes
The source of the redirect could be essentially any module you have, and several modules allow for configuration that will cause redirects as well. You will need find the source of the redirect on for your particular situation.

Suggestions:

1. Deactivate modules in a 50 / 50 manner. This allows you to quickly narrow down which module is providing the redirect, and hopefully that will help you to work it out. Using drush to disable/enable modules will make this much faster.
2. Install Devel. It has a settings called "Display redirection page", and implements `devel_drupal_goto_alter` halting the redirection.

The primary purpose of this is to gather up debug information that would otherwise go lost due to the redirect. In this particular case, I suggest you add a `dpm(debug_backtrace());` into the hook so you can trace the call to the source of the redirect.
3. Everything else failing, fire up a full debugger, and trace the call, ideally with help from the information provided by the `debug_backtrace()` above.

# Answer
> 2 votes
Implement hook\_drupal\_goto\_alter() in a module and

a) put a breakpoint on code in this function and view the call-stack to determine which function is setting the redirect in the first place.

b) change the path.

path is passed by reference so this can be changed directly. Assuming you create a module name ungoto:

```
ungoto_drupal_goto_alter(&$path, &$options, &$http_response_code) {
   // regular expression can be tightened
   if (preg_match('#^taxonomy/term/', $path)) {
     // Guessing that you are trying to 'display profiles' not display current
     // users details, so global $user is not useful.
     // Contextual filters says is is on the path.
     // OP to do work to extract only the information needed.
     $user_details = $_GET[q];

     // Reset the path
     $path = $user_details . $path;
   }
}

```

# Answer
> -1 votes
You could use hook\_exit($destination) to change the redirect.

* Create a new module. I use the Netbeans drupal-7 plugin to create .install, .info and .module files.
* Fill out the .info template.
* Implement hook\_exit($destination). Call another drupal\_goto(). Be careful that it can't create a redirect loop.

Hook Exit passes the destination address, and if you put a debugger on it you may be able to trace the call-stack to find another drupal\_goto() that is causing the redirect.

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


# Question
Title: 2 Drupal Multisites, Separate Databases, Changing 1 Also Changes the Other
I have a very weird issue. Been doing Multisites in Drupal 7 for a while now without any hitches... until last week. I have 2 multisites both with separate databases, however when I change content on 1 of them it also changes content on the other.

I have *Multisite01 pointing to Database01* and *Multisite02 pointing to Database02* (copy of 01). I should be able to change 1 multisite and not have it effect the other. I'm not sharing databases or anything. This has always worked for me before.

What I did different in this instance was when I copied Database01, Database01-Copy, to create 02. I was in a hurry and meant to click on 01-Copy to rename but instead, I clicked on 01. No matter, or so I thought... I just renamed *Database01 to Database02* and then I renamed *Database01-Copy to Database01*.

Now Drupal has them permanetly linked... even if I link Multisite01 or 02 to another database (ie Database03 or 04, etc). So I know that the change is outside of each Multisite's database. Wondering if this can be fixed without reinstalling Drupal...

```
/*Misc. Info
Multisite01 Settings.PHP (Multisite02 is same but connects to database02)*/

$databases = array (
  'default' =>
  array (
    'default' =>
    array (
      'database' => 'database01',
      'username' => 'username',
      'password' => 'password',
      'host' => 'localhost',
      'port' => '',
      'driver' => 'mysql',
      'prefix' => '',
    ),
  ),
);

```

# Answer
> 0 votes
You've been doing Multisites for awhile now, so this seems like an obvious question -- but did you clear the drupal cache?

... and after doing so, restart Apache. Many of my "unexplainable" errors have come down to that.

---
Tags: database, multi-sites, configuration
---


# Question
Title: PHP - If a field has a certain text value then print something
The following PHP in a node tpl file:

```
check_plain($node->field_room[$node->language][0]['value'])

```

Will print this in the page: Value1

What I want however is if the field has a value of 'Value1' then I want to print something else on the page. Ive tried the following but I think I have a syntax error:

```
if ( check_plain($node->field_room[$node->language][0]['value']) == "Value1" ) {
                        echo "<p>Print something else </p>";
                    }

```

# Answer
> 2 votes
There's no syntax error in the second code sample, if you're getting a syntax error it's not coming from those lines.

The best way to get values from an entity is with field\_get\_items():

```
$items = field_get_items('node', $node, 'field_room');
if (count($items) && check_plain($items[0]['value']) == 'Value1') {
  // Do something
}

```

But unless you have some sort of multi-lingual issue the code you've got should do exactly the same thing as that, so the problem might be elsewhere.

---
Tags: nodes, theming
---


# Question
Title: very simple form in block rendering incorrect values
I have a very simple code in block :

```
if ($vocabulary = taxonomy_vocabulary_machine_name_load('caller_details')) {
  module_load_include('inc', 'taxonomy', 'taxonomy.admin');
  $output = drupal_render(drupal_get_form('taxonomy_form_term', $vocabulary));
}
echo $output;

```

the problem is that it sets the value of "name" in my form to taxonomy vocabulary name by default. Why is that?

Thanks for any suggestions!

# Answer
> 1 votes
That form expects an array representing the current term as edited as its first argument. The vocabulary is the second argument. Add an empty array as first argument and you should be OK.

# Answer
> 0 votes
You could `hook_form_alter()` this form in a custom module and set your default value to that element.

---
Tags: 7, forms, blocks
---


title: Contextual link for individual node?

text:
# Question
Title: Contextual link for individual node?
When I hover over a block on the front end, I get the Contextual Links popup to edit the block. Can I also set this so when someone with permissions to do so hovers over a node, they get a link popup to edit that story?

# Answer
> 1 votes
To set permissions for different user roles to access the contextual links: Navigate to the Permissions page (People \> Permissions tab). For each role you can enable or disable the Use contextual links permission.

# Answer
> 4 votes
To avoid hacking core, this code put in a custom module accomplishes the exact same thing as the solution by Psykoral/Clive:

```
//Implements hook_node_view_alter()
function mymodule_node_view_alter(&$build) {
  if(isset($build['#node'])) {
    $node = $build['#node'];
    if(!empty($node->nid)) {
      $build['#contextual_links']['node'] = array('node', array($node->nid));
    }
  }
}

```

# Answer
> 0 votes
There is a sandbox project for this on Drupal.org. The only caveats I found were when a theme overrides theme\_preprocess\_region() and removes markup that is needed, or it overrides theme\_menu\_local\_tasks() and it changes markup in certain ways then I didn't get the contextual links.

The only other problem I found was if my node had no content in the body, then there is nothing to hover over in order to get the contextual links. I just made sure something is always in the node content to avoid this problem, even if it is only a ` `. I did this through a DS field that is added when the node body is empty, but there could be a number of ways to deal with this issue.

# Answer
> -2 votes
Because I went looking around for this FOREVER, hopefully it'll help someone still digging up this thread. I searched for 3 days, found all kinds of 200 lines of code nonsense, custom modules that claimed to do this, yada yada, all to no avail.

Basically what I found was that the PHP that builds contextual links specifically looks for it NOT to be it's own page node, or in full view mode. Well jeebs, thanks, that's exactly where I wanted contextual links! How awesome of you to hard code it and decide not to give me them on pages I want to be able to edit without going into the Admin interface.

Anyway, bitterness aside (can you tell I've been looking for this answer for a while?)... it's time to brute force remove that so we can enable it for all full page nodes in one shot.

* Edit /modules/node/node.module
* About line 1303 you should see this line:

`if (!empty($node->nid) && !($view_mode == 'full' && node_is_page($node)))`
* Comment it out and make it this instead:

`if (!empty($node->nid))`
* Save, upload, and dance!

Basically, what this does is make contextual links available to every block, view, or node, when previously the code was specifically blocking them from 'full view mode' and if the node is being viewed as an entire page.

May not be the most 'official' way to do it via the Drupal UI, but it does what I want it to do anyway. Hope it helps someone. Going to glue my hair back to my head now.

---
Tags: 7, navigation, views
---


# Question
Title: Programmatically attach image to a content type from local system folder
I am in middle of coding creating nodes programatically. Here i have one problem. I need to programmatically attach image to the content type from local system folder. I mean my image path example 'c://xxxxx/xxxx/images/img.jpg'.

Thanks in advance for your advice.

Hi i used this code and work fine in the localhost. But it's failed when i work on the server.

```
$filepath = drupal_realpath('misc/druplicon.png');
// Create managed File object and associate with Image field.
$file = (object) array(
 'uid' => 1,
 'uri' => $filepath,
 'filemime' => file_get_mimetype($filepath),
 'status' => 1,
);

// We save the file to the root of the files directory.
$file = file_copy($file, 'public://');

$node->field_image[LANGUAGE_NONE][0] = (array)$file;

```

Reference link : attaching-files-to-nodes-programmatically-in-drupal-7

> I didn't get the solution yet. Can any one have the experience?

# Answer
> 1 votes
You can just use file\_copy or file\_move.

Here is an example: https://stackoverflow.com/questions/5129559/attaching-files-to-nodes-programmatically-in-drupal-7

# Answer
> 1 votes
I usually use a code like this:

```
$filepath = 'TheFilePath';
$file = new stdClass();
$file->filename = basename($filepath);
$file->filepath = $filepath;
$file->filemime = file_get_mimetype($filepath);
$file->filesize = filesize($filepath);
$file->uid = 1;
$file->status = FILE_STATUS_PERMANENT;
$file->uri = $filepath;
$file->display = 1;
$file->description = '';
$file = file_copy($file, 'public://news-images', FILE_EXISTS_REPLACE);

$node->field_article_picture[LANGUAGE_NONE][] = (array)$file;

```

And it works...so I hope it helps for you too!

---
Tags: 7, nodes
---


title: Blocking node creation after validation

text:
# Question
Title: Blocking node creation after validation
We have a lot of spammers (which are logged in users) creating content on our site. They are creating photo nodes without photos (which I have recently allowed as a way to catch them and ignore them, sort of a honeypot). I have also added the honeypot module but the 10 second delay doesn't seem to be working too well...

Is there a way to catch these nodes that don't have photos and block them from ever actually being created? I was thinking that it could be done in the `presave` hook, but unsetting the node didn't seem to work.

**Edit**

I could make the image required, but the bot is filling out all of the required fields so far, and it isn't hard to upload an image using a script.

I have implemented what I put in my answer and it seems to work, and I am giving the spammers 10 tries/day before they get banned. This may or may not be too lenient.

So far I have caught and banned 14 spam accounts (~1 hour of it being live).

# Answer
> 0 votes
Maybe this is the solution... doesn't create the node, sends them to a blank 403 page.

```
function _utils_photo_nodeapi(&$node, $op, $teaser = NULL, $page = NULL) {
  switch($op){
    case 'presave':
      if(empty($node->field_image[0]['fid'])){
        _utils_check_spammer($node->uid);
        //try again?
        die(header('Location: /node/add/photo', TRUE));
      }
      break;
  }
}
//meta code
function _utils_check_spammer($uid){
    if (in_spam_table && spam_count > spam_limit_for_today)
        //nice knowing you...
        ban_user($uid);
    else
        //you get some more chances
        increment_spam_count($uid)
    endif;
}

```

# Answer
> 0 votes
I think you should mark the image filed as required the bot won't be able to create the nodes without attached image.

---
Tags: 6, nodes, advertising
---


# Question
Title: I'm suddenly getting the error :EntityMetadataWrapperException
I'm running a Drupal 7.21 site that uses the Entity Reference module (v.7.x-1.0) to support reusing image nodes in other node types. After several months of smooth sailing , I'm seeing a new error when I try to view image nodes on my site. The error is:

> EntityMetadataWrapperException: Unknown data property field\_entity\_image. in EntityStructureWrapper-\>getPropertyInfo()

The property named in the error, "field\_entity\_image", is the name of an Entity Reference field that exists on other node types (article, basic page). However, those other content types don't throw the error when I try to view them. What is new is the fact that I created a new node type (bio) that also uses the existing field\_entity\_image field.

I've seen this error discussed in relation to certain modules (Commerce being one) but not as the result of creating new content type or adding entity reference fields. If anyone has insights into this, all help will be much appreciated.

# Answer
Your site has not been running on Drupal 7.21 for several months. You have recently upgraded.

There was a security fix in the drupal core image module in 7.20 which broke several contributed modules. 7.21 has a new variable to mitigate the problem, but if your issue involves images, it is probably related to the security fix. For more information read the release notes.
> 1 votes

# Answer
I have had similar weirdness with the Entity API data wrappers. The root cause of the problem in my case, and in the Commerce module, was the stable version of UUID. Upgrading the the dev version solved all of my issues. Searching for UUID in both of the issue queues will give you more insight.
> 0 votes

---
Tags: entities
---


# Question
Title: How can I get bundle of an entity from type and id?
I need to identify `bundle` of an entity from its `type` and `id`.

For example, if the `type` is 'node' and `id` is 7, I may get 'page' as `bundle`.

Thanks

# Answer
> 11 votes
Use `entity_load` to load the entity as mentioned by @Nikhil.

Then use entity\_extract\_ids, to extract the bundle. Example:

```
$entity = entity_load('node', array('7'));

list(, , $bundle) = entity_extract_ids('node', $entity);

echo "Bundle name is : " . $bundle;

```

The function `entity_extract_ids` returns a numerically indexed array (not a hash table) containing the elements:

* 0: Primary ID of the entity.
* 1: Revision ID of the entity, or NULL if $entity\_type is not versioned.
* 2: Bundle name of the entity, or NULL if $entity\_type has no bundles.

where, `0`, `1`, and `2` are array indices. However, the approach used by core and contrib modules is to use the `list()` function.

# Answer
> 8 votes
Here is the cleanest one that I got from Organic groups module code.

```
$wrapper = entity_metadata_wrapper($entity_type, $entity_id);
$bundle = $wrapper->getBundle();

```

For example I can call it like:

```
$wrapper = entity_metadata_wrapper('node', 1);
$bundle = $wrapper->getBundle();

```

Edit: As @Clive pointed out, above method depends on entity module.

Here is another method that does not depend on any extra module. It is explained here https://forrst.com/posts/Get\_the\_bundle\_of\_a\_Drupal\_7\_entity-0xW

Copy pasting that method:

```
function _entity_get_bundle($entity, $entity_type) {
  $info = entity_get_info($entity_type);
  if (empty($info['entity keys']['bundle'])) {
    return $entity_type;
  } else {
    return $entity->{$info['entity keys']['bundle']};
  }
}

```

# Answer
> 3 votes
Try entity\_load

> Load entities from the database.
>
> The entities are stored in a static memory cache, and will not require database access if loaded again during the same page request.

### Parameters

**$entity\_type**: The entity type to load, e.g. node or user.

**$ids**: An array of entity IDs, or FALSE to load all entities.

**$conditions**: (deprecated) An associative array of conditions on the base table, where the keys are the database fields and the values are the values those fields must have. Instead, it is preferable to use EntityFieldQuery to retrieve a list of entity IDs loadable by this function.

**$reset**: Whether to reset the internal cache for the requested entity type.

### Return value

An array of entity objects indexed by their ids. When no results are found, an empty array is returned.

# Answer
> 3 votes
If you want a very lightweight way, performance-wise, to get the node type from node id - you can use a single select query on the node table.

```
$type = db_query("SELECT type FROM {node} WHERE nid = :nid",
                  array(':nid' => $nid))->fetchField();

```

That way, you don't need to invoke the entire entity hook system, with entity\_load etc..

It's a single select query using the indexed node id.

---
Tags: 7, entities
---


title: How to add captcha to pdf version

text:
# Question
Title: How to add captcha to pdf version
I want to add a captcha to the PDF generator from the Print Module so that my server doesn't waste time generating a PDF for robots and to prevent DOS attacks.

There is a similar question asked, but the accepted answer doesn't actually answer my question (the PDF Version part), but rather only the E-mail part.

Since the PDF Version doesn't link to a form, there isn't a form ID I can add to the Captcha module. Is there a way to require a CaPTCHA to download/generate a PDF?

# Answer
First you should avoid captcha, their are not user friendly. But good new, in this case you don't need it :).

Print module generate the pdf once and cache it https://drupal.org/node/516466#comment-6390678. So DOS are not possible on pdf generation.

You can still have DOS by requesting a pdf thousand of time, saturating your bandwidth. If you are really worried about that you can for example configure Apache with mod\_evasive http://systembash.com/content/how-to-stop-an-apache-ddos-attack-with-mod\_evasive/

By robot I suppose you mean search engine robot. You can add that in your robot.txt (But I think is not necessary):

```
User Agent: *
Disallow: /*.pdf$

```
> 1 votes

---
Tags: captcha
---


title: Fivestar - filter by number of votes

text:
# Question
Title: Fivestar - filter by number of votes
I want to filter a view that shows nodes sorted by rating. I would like to filter it to only show nodes with at least 5 votes. I added the relationship for "vote results - number of votes". When I add the filter it doesn't give me an option for "greater than":

Any ideas how to fix that? Thanks

# Answer
> 4 votes
When i added the **Vote results: Value type** field for output. It shown like **percent** or **points** so how can we filter the varchar field type with number behavior. I think you should filter by **Vote results: Value** not **Vote results: Value type**

---
Tags: 7, views, rating
---


# Question
Title: Trouble getting block to display after module enabled
I've created a drupal module, it's info file, and a tpl.php for the block all in the same module directory. When I enable the module, I can see the block listed and assign it to a region. However when I view the page the block does not display. If I do a vardump on $content within block\_view, the dump displays at the top of the page, and firebug shows that block is wrapped with the right div tags. I would think if you did a var dump on within the block\_view function, it should display in the right region. This one is probably really simple, but it's got me stumped - any help much appreciated. Also if I title the block just to see if it shows up anywhere in the page - it's still nowhere to be seen even though admin shows it it in the region, and no filters are set to prevent it being viewed. I would think that if you gave the block a title -if it's on the page it would at least show a title even if everything else is blank.

```
module file:

function my_block_block_info() {
   $blocks['my_block'] = array(
      'info' => t('My Block')
   );
   return $blocks;
}

function my_block_block_view() {

if(arg(0) == 'node' && is_numeric(arg(1)))  {
    $id = arg(1);
}
   $query = "SELECT * FROM table WHERE id= :id AND deleted=0";
   $args = array(':id' => $id);
   $result = db_query($query,$args)->fetchAll();
   foreach($result as $item) {
     $stuff[] = array($item->stuff_url,$item->stuff_name);
   }
   $content=
      theme_render_template(drupal_get_path('module','my_module').'/'.'block--         my_block.tpl.php',array("stuff" => $stuffs));
   return $content;
   }

 block--my_block_tpl.php

<div class="wrapper">
 <?php

 foreach($stuffs as $thing) {
 for($i=0; $i < count(thing); $i++) {
       //print out result passed from module
  }
  }
 ?>
 </div>

```

# Answer
your hook\_block\_view() is implemented in a wrong way,

1. first pass in argument delta as a parameter
2. you should put the contents of your block inside the $block\['content'\] variable.
3. return $block;

heres a very good tutorial building a custom block
> 1 votes

# Answer
use your query as drupal standard like this way

```
$query = db_select('node', 'n')
    ->fields('n', array('nid', 'title', 'created'))
    ->condition('status', 1) //Published.
    ->orderBy('created', 'DESC') //Most recent first.
    ->execute();
  return $query;
}

```
> 0 votes

---
Tags: 7, blocks
---


# Question
Title: Set default value of a custom field attached to a Media file image field
I have set up a media image file field on a couple of content types, per the instructions given in the Media 2.x Quick Start Guide.

The image file field has a custom field I added (admin/structure/file-types/manage/image/fields). This field has a default value. I would like to be able to change the default value via a hook based on conditions determined at runtime.

While I have found that hook\_form\_alter *is* called when the Edit Image modal (AJAX) dialog is displayed (see diagram "Create a New Node and Upload an Image" in the above-referenced documentation page), I would also like to have the chance to alter the default value even if the user does not click on the "Edit" button. Also, information about the fields attached to the image file field are not populated when hook\_form\_alter is called for the node create form for the content type that contains the image file field.

I considered hook\_node\_save, but by the time this hook is called, the file field has already been saved, and I can't tell if the user visited the Edit Image modal dialog or not. For that matter, even changing #default\_value in hook\_form\_alter will change the displayed value, even if the user has already visited the dialog before and selected a new, non-default value for the field.

Is there an elegant way to determine in hook\_form\_alter and hook\_node\_save that the user has already changed the value for the field? Alternately, is there an earlier hook that can adjust the default value for these fields before either of these hooks are called?

**Update**: I thought of a reasonable workaround. If I set the default value for the attached field to "I don't care", then I could calculate the dynamic default value at view time. I'd rather not have an "I don't care" value, though, and would therefore still be interested in having this question answered.

**Update 2**: I am now happily running with the "I don't care" workaround deployed on my live site. I would still be interested in an answer on how to elegantly set the default value for media file fields, though.

# Answer
Drupal has the capability to dynamically set a default value for a field, but it is not exposed in the UI.

Each field instance can be set a `'default_value_function'`, which has the following signature:

```
function my_default_value_function($entity_type, $entity, $field, $instance, $langcode) {
  // Returns a standard field structure.
  return array(
    0 => array(
      // This can be different depending on the field type.
      'value' => 'myvalue',
    ),
  );
}

```

To set the default value function, either:

* Modify the field structure exported by Features to add a `'default_value_function'` in the `'field_instance'` part (and revert the feature),
* Do something like this (once):

```
$instance = field_info_instance($entity_type, $field_name, $bundle_name);
$instance['default_value_function'] = 'my_default_value_function';
field_update_instance($instance);

```
> 8 votes

---
Tags: media
---


# Question
Title: Programmatically submit form / save all nodes
After migrating all the content from a drupal 6 installation to a drupal 7 one, I ended up with empty fields in my nodes, that are displayed when viewing the node.

However if I edit the node without changing anything and save it, the empty fields are gone (at that point the save function populates the database with the proper null values).

Obviously I can't do that by hand and the solution proposed here: Load and Save nodes with script? doesn't remove the empty fields, even if I actually edit one of the fields. I would like to do this with a php script as I am not familiar at all with Python and the selenium script proposed here: How to programmatically iterate over nodes, load into form, and save the form?.

Now as far as Drupal's `form_submit` method, how does it actually populate the `$form`, `$form_state` variables since I won't be changing anything.

Thanks in advance.

# Answer
I don't think trying to fake form submissions is a good idea - there is a lot that goes on behind the scenes, and it is easy to get something wrong.

I would suggest instead you implement a script similar to the one you pointed out in Load and Save nodes with script? in which you actually set the missing values to the empty data you require. In that script, after the `node_load` (and before the `node_save`) you could do something like:

```
$empty_value = array(
  'value' => ''
);
$node->field_my_custom_field[$node->language] = array(
  0 => $empty_value
);

```

You would need to do this for each field that needs fixing. The value you need for `$empty_value` will depend on the field type. You could work it out dynamically by calling field\_info\_field ; however as your script is a one-off, it's simpler to just set the right value for each field. To know what the right empty value should be, just create a node with the right empty value and then inspect it (eg. using `var_dump`, `dpm`, etc.)
> 1 votes

---
Tags: forms, nodes
---


title: block template for node view

text:
# Question
Title: block template for node view
What should be the template for my block view if the url is

> block/manage/views/guides-block/configure?destination=node/9

I have tried `block--block--9.tpl.php` but does not work

# Answer
As per Drupal 7 Template (Theme Hook) Suggestions

**block--\[region|\[module|--delta\]\].tpl.php** *base template: block.tpl.php*

> Theme hook suggestions are made based on these factors, listed from the most specific template to the least. Drupal will use the most specific template it finds:

```
block--module--delta.tpl.php
block--module.tpl.php
block--region.tpl.php

```
> 1 votes

---
Tags: views, blocks, theming
---


title: Outputing a json file in drupal 6

text:
# Question
Title: Outputing a json file in drupal 6
I'm linking an android app with a drupal 6 server. Basically the app should be able to request information from the server to sync data and other simple functions. JSON is our preferred way of achieving this.

I've installed Service, JSON Server in drupal 6 and activated both node and view services. With views.get i'm able to get a JSON output of the default display from the view listed.

Question(s)

1. First thing I'd like to achieve is to have the JSON output in a separate file. Completely. Currently the JSON is being shown below the views.get page. I've googled solutions for this but only found for drupal 7.
2. I'd like the JSON to receive arguments from the android app using POST.

How can I achieve the two above.

Thank you very much.

# Answer
Use Services Views

After enabling that resource you would be able to do call to

```
http://example.com/<endpoint path>/<resource name>

```

After enabling "views" resource in your services endpoint you can do GET request to:

```
http://example.com/<endpoint path>/views/<view name>

```

This will execute a view and pass results.

```
Possible arguments:
- display_id: views display
- args: array of view arguments
- filters: array of view filter values
- offset: views offset
- limit: limit views number of results
- format_output: boolean whether we would like to get themed view or data

```

**Example of calls:**

```
http://example.com/rest/views/articles?limit=5&offset=2&filters[tags]=5
http://example.com/rest/views/articles?filters[tags]=5&display_id=block_1&format_output=1

```
> 0 votes

---
Tags: views, services, 8
---


# Question
Title: FBOauth: how to pass arguments to the callback function?
I am trying to create a facebook event through a drupal content type "event". I call the `hook_node_insert()` to make a POST on Facebook.

```
function fb_event_create_node_insert($node){
    if ($node->type == "event"){
        // get field values submitted when a new content type "event" is saved
        $event_name = $node->field_event_name['und'][0]['value'];
        $event_start_date = $node->field_event_start_date['und'][0]['value'];

        // get facebook app_id & secret from fboauth variables
        $app_id = isset($app_id) ? $app_id : variable_get('fboauth_id', '');
        $app_secret = isset($app_secret) ? $app_secret : variable_get('fboauth_secret', '');

        // Get the link to get the facebook code (generated by fboauth module)
        $link = fboauth_action_link_properties('fb_event_create');

        print l(t('Create event'), $link['href'], array('query' => $link['query']));
        // output a link to https://www.facebook.com/dialog/oauth?client_id=CLIENT_ID&redirect_uri=http%3A//localhost%3A8888/cs/%3Fq%3Dfboauth%252Ffb_event_create&scope=manage_pages%2Ccreate_event
        // parameters are created by the fb_oauth action (scope=permission) and some settings of the module (client_id & redirect uri).

    }
}

```

So I then have a link after having saved the node: when I click on it, it connects to facebook and gives me back a code as a parameter in my redirect uri (code has been modified):

```
http://localhost:8888/cs/?q=fboauth%2Ffb_event_create&code=AQDEvaeupRO-FE6lWaKXZFqvoSRnSuKlIdVjMDeGoy5su-hXpgCcGnBsyCzcPDl5YGGc3hj1yPAXheBjmFtGuivmM-lm5jlm5QG2UeFLPg3gQfnWM3UvB10Y-yrYPyr176dyuMI2Q3vvHGM8z-YVKpYkzPPgYUEifEDIbvADokgniNFiiwpyWZCS72GD32zWLxWCBkCThRk8o3MnO2vWXAmc#_=_

```

It goes to the callback function defined earlier:

```
function fb_event_create_fboauth_actions() {
  $actions['fb_event_create'] = array(
    'title' => t('Create events on behalf of CS'),
    'callback' => 'fb_event_create_fboauth_action_event_create',
    'permissions' => array(
      'manage_pages,create_event'),
  );
  return $actions;
}

```

And here is the callback function:

```
function fb_event_create_fboauth_action_event_create($app_id, $access_token) {
    $result = fboauth_graph_query("EVENT_ID/events", $access_token, array("name" => "test", "start_time" => "2013-04-04T19:00:00-0700"), 'POST');
}

```

**WHAT I WANT:**

Insert parameters to this callback function to be able to insert the `$event_name` and `$event_start_date` (that we find from the `node_insert()` hook above) to have the callback function like :

```
function fb_event_create_fboauth_action_event_create($app_id, $access_token, $name_fb_ev, $start_fb_ev) {
    $result = fboauth_graph_query("EVENT_ID/events", $access_token, array("name" => $name_fb_ev, "start_time" => $start_fb_ev), 'POST');
}

```

Thank you for any help guys!

# Answer
> 2 votes
I modified the `fboauth_action_menu()` to make it accept arguments:

```
function fboauth_menu() {
  $items['fboauth/%fboauth_action/%/%'] = array(
    'title' => 'Facebook connect',
    'page callback' => 'fboauth_action_page',
    'page arguments' => array(1, 'foo', 'foo'),
    'access callback' => TRUE,
    'file' => 'includes/fboauth.fboauth.inc',
    'type' => MENU_CALLBACK,
  );
  return $items;
}

```

But then I had another problem with the function `fboauth_action_page()`it executed because it called the another function to get the access token because the two redirect\_uri parameters were not the same between the code request to FB and the access token. All this, because the function to get the access token was not taking into account the parameters.

```
function fboauth_access_token($code, $action_name, $app_id = NULL, $app_secret = NULL) {
  $app_id = isset($app_id) ? $app_id : variable_get('fboauth_id', '');
  $app_secret = isset($app_secret) ? $app_secret : variable_get('fboauth_secret', '');

  // get the parameters from the redirect_uri by the drupal function arg() and includes them in the redirect_uri to get the access token.
  $query = array(
    'client_id' => $app_id,
    'client_secret' => $app_secret,
    'redirect_uri' => fboauth_action_url('fboauth/' . $action_name . "/" . arg(2) . "/" . arg(3) . "/", array('absolute' => TRUE, 'query' => !empty($_GET['destination']) ? array('destination' => $_GET['destination']) : array())),
    'code' => $code,
  );

// rest of the function

}

```

Now, both redirect\_uri are the same and my callback function defined earlier must also catch parameters from the url:

```
function fb_event_create_fboauth_action_event_create($app_id, $access_token) {
    $event_name = arg(2);
    $event_start_date = arg(3);

    $result = fboauth_graph_query("EVENT_ID/events", $access_token, array("name" => $event_name, "start_time" => $event_start_date), 'POST');

}

```

Hope this helps someone!

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