# Question
Title: Is jQuery interpreting it wrong? or Drupal outputting wrong?
I'm facing a peculiar problem. My Drupal website uses Jquery 1.4.4 version.

As you all know, Drupal outputs `Drupal.settings` json to Javascript as:

**when I enable `devel_themer` module**:

The following is the output

```
jQuery.extend(Drupal.settings, {
   "basePath":"\/d7\/",
   "pathPrefix":"",
   "ajaxPageState":{
      "theme":"bartik",
      "theme_token":"KC2-1Z9CN5PCxDyAq_W8FGBQBOOnwt8AyoeX1UDBoP8",
      "js":{
         "misc\/jquery.js":1,
         "misc\/jquery.once.js":1,
         "misc\/drupal.js":1,
         "misc\/ui\/jquery.ui.core.min.js":1,
         "misc\/ui\/jquery.ui.widget.min.js":1,
         "misc\/jquery.cookie.js":1,
         "misc\/jquery.form.js":1,
         "misc\/ui\/jquery.ui.mouse.min.js":1,
         "misc\/ui\/jquery.ui.draggable.min.js":1,
         "misc\/ui\/jquery.ui.resizable.min.js":1,
         "misc\/jquery.ba-bbq.js":1,
         "modules\/overlay\/overlay-parent.js":1,
         "misc\/ajax.js":1,
         "misc\/progress.js":1,
         "sites\/all\/modules\/devel_themer\/devel_themer.js":1,
         "sites\/all\/modules\/devel\/krumo\/krumo.js":1,
         "modules\/toolbar\/toolbar.js":1,
         "sites\/all\/modules\/devel\/devel_krumo_path.js":1
      },
      "css":{
         "modules\/system\/system.base.css":1,
         "modules\/system\/system.menus.css":1,
         "modules\/system\/system.messages.css":1,
         "modules\/system\/system.theme.css":1,
         "misc\/ui\/jquery.ui.core.css":1,
         "misc\/ui\/jquery.ui.theme.css":1,
         "misc\/ui\/jquery.ui.resizable.css":1,
         "modules\/overlay\/overlay-parent.css":1,
         "modules\/comment\/comment.css":1,
         "modules\/field\/theme\/field.css":1,
         "modules\/node\/node.css":1,
         "modules\/search\/search.css":1,
         "modules\/user\/user.css":1,
         "sites\/all\/modules\/devel_themer\/devel_themer.css":1,
         "sites\/all\/modules\/devel\/krumo\/skins\/default\/skin.css":1,
         "modules\/shortcut\/shortcut.css":1,
         "modules\/toolbar\/toolbar.css":1,
         "sites\/all\/modules\/devel_themer\/devel_themer_ie_fix.css":1,
         "themes\/bartik\/css\/layout.css":1,
         "themes\/bartik\/css\/style.css":1,
         "themes\/bartik\/css\/colors.css":1,
         "themes\/bartik\/css\/print.css":1,
         "themes\/bartik\/css\/ie.css":1,
         "themes\/bartik\/css\/ie6.css":1
      }
   },
   "thmrStrings":{
      "themer_info":"Themer info",
      "toggle_throbber":" \u003Cimg src=\u0022\/d7\/sites\/all\/modules\/devel_themer\/loader-little.gif\u0022 alt=\u0022loading\u0022 class=\u0022throbber\u0022 width=\u002216\u0022 height=\u002216\u0022 style=\u0022display:none\u0022 \/\u003E",
      "parents":"Parents: ",
      "function_called":"Function called: ",
      "template_called":"Template called: ",
      "candidate_files":"Candidate template files: ",
      "preprocessors":"Preprocess functions: ",
      "processors":"Process functions: ",
      "candidate_functions":"Candidate function names: ",
      "drupal_api_docs":"link to Drupal API documentation",
      "source_link_title":"link to source code",
      "function_arguments":"Function Arguments",
      "template_variables":"Template Variables",
      "file_used":"File used: ",
      "duration":"Duration: ",
      "api_site":"http:\/\/api.drupal.org\/",
      "drupal_version":"7",
      "source_link":"\/d7\/devel\/source?file="
   },
   "thmr_popup":"  \u003Cdiv id=\u0022themer-fixeder\u0022\u003E\n  \u003Cdiv id=\u0022themer-relativer\u0022\u003E\n  \u003Cdiv id=\u0022themer-popup\u0022\u003E\n      \u003Cdiv class=\u0022topper\u0022\u003E\n        \u003Cspan class=\u0022close\u0022\u003EX\u003C\/span\u003E Drupal Themer Information\n      \u003C\/div\u003E\n      \u003Cdiv id=\u0022parents\u0022 class=\u0022row\u0022\u003E\n\n      \u003C\/div\u003E\n      \u003Cdiv class=\u0022info row\u0022\u003E\n        \u003Cdiv class=\u0022starter\u0022\u003EClick on any element to see information about the Drupal theme function or template that created it.\u003C\/div\u003E\n        \u003Cdl\u003E\n          \u003Cdt class=\u0022key-type\u0022\u003E\n\n          \u003C\/dt\u003E\n          \u003Cdd class=\u0022key\u0022\u003E\n\n          \u003C\/dd\u003E\n          \u003Cdiv class=\u0022used\u0022\u003E\n          \u003C\/div\u003E\n          \u003Cdt class=\u0022candidates-type\u0022\u003E\n\n          \u003C\/dt\u003E\n          \u003Cdd class=\u0022candidates\u0022\u003E\n\n          \u003C\/dd\u003E\n\n          \u003Cdt class=\u0022preprocessors-type\u0022\u003E\n\n          \u003C\/dt\u003E\n          \u003Cdd class=\u0022preprocessors\u0022\u003E\n\n          \u003C\/dd\u003E\n          \u003Cdt class=\u0022processors-type\u0022\u003E\n\n          \u003C\/dt\u003E\n          \u003Cdd class=\u0022processors\u0022\u003E\n\n          \u003C\/dd\u003E\n          \u003Cdiv class=\u0022duration\u0022\u003E\u003C\/div\u003E\n        \u003C\/dl\u003E\n      \u003C\/div\u003E\u003C!-- \/info --\u003E\n      \u003Cdiv class=\u0022attributes row\u0022\u003E\n      \u003Cdiv class=\u0022themer-variables\u0022\u003E\u003C\/div\u003E\n      \u003C\/div\u003E\u003C!-- \/attributes --\u003E\n    \u003C\/div\u003E\u003C!-- \/themer-popup --\u003E\n    \u003C\/div\u003E\n    \u003C\/div\u003E",
   "overlay":{
      "paths":{
         "admin":"node\/*\/edit\nnode\/*\/delete\nnode\/*\/revisions\nnode\/*\/revisions\/*\/revert\nnode\/*\/revisions\/*\/delete\nnode\/add\nnode\/add\/*\noverlay\/dismiss-message\nuser\/*\/shortcuts\nadmin\nadmin\/*\nbatch\ntaxonomy\/term\/*\/edit\nuser\/*\/cancel\nuser\/*\/edit\nuser\/*\/edit\/*\ndevel\/*\nnode\/*\/devel\nnode\/*\/devel\/*\ncomment\/*\/devel\ncomment\/*\/devel\/*\nuser\/*\/devel\nuser\/*\/devel\/*\ntaxonomy\/term\/*\/devel\ntaxonomy\/term\/*\/devel\/*",
         "non_admin":"admin\/structure\/block\/demo\/*\nadmin\/reports\/status\/php"
      },
      "pathPrefixes":[

      ],
      "ajaxCallback":"overlay-ajax"
   },
   "tableHeaderOffset":"Drupal.toolbar.height"
});

```

and in the browser console, as you can see in the following screenshot `Drupal.settings` object has some strange objects.

**What is strange about this?**

When I try to output in browser console, it says undefinied. But According to Drupal.settings json, there should be a `Drupal.settings.thmrStrings` object. Instead of showing these meaningful objects, according to json it shows generated some strange objects like `Drupal.settings.thmr_1`, `Drupal.settings.thmr_2`, `Drupal.settings.thmr_3` .. `Drupal.settings.thmr_94`. Where are these `Drupal.settings.thmr_*` objects coming from? They are not in the json? Why are the objects not according to jSON?

The error that you see in the screenshot is caused because of this. The javascript file `devel_themer.js` is accessing a sub-object of `Drupal.settings.thmrStrings` but its not getting it. Thats is the main problem why I got behind this.

**when I disable `devel_themer` module**:

The following is the output:

```
<script type="text/javascript">
<!--//--><![CDATA[//><!--
jQuery.extend(Drupal.settings, {
   "basePath":"\/d7\/",
   "pathPrefix":"",
   "ajaxPageState":{
      "theme":"bartik",
      "theme_token":"KC2-1Z9CN5PCxDyAq_W8FGBQBOOnwt8AyoeX1UDBoP8",
      "js":{
         "misc\/jquery.js":1,
         "misc\/jquery.once.js":1,
         "misc\/drupal.js":1,
         "misc\/ui\/jquery.ui.core.min.js":1,
         "misc\/jquery.ba-bbq.js":1,
         "modules\/overlay\/overlay-parent.js":1,
         "modules\/contextual\/contextual.js":1,
         "misc\/jquery.cookie.js":1,
         "sites\/all\/modules\/devel\/devel_krumo_path.js":1,
         "modules\/toolbar\/toolbar.js":1
      },
      "css":{
         "modules\/system\/system.base.css":1,
         "modules\/system\/system.menus.css":1,
         "modules\/system\/system.messages.css":1,
         "modules\/system\/system.theme.css":1,
         "misc\/ui\/jquery.ui.core.css":1,
         "misc\/ui\/jquery.ui.theme.css":1,
         "modules\/overlay\/overlay-parent.css":1,
         "modules\/contextual\/contextual.css":1,
         "modules\/comment\/comment.css":1,
         "modules\/field\/theme\/field.css":1,
         "modules\/node\/node.css":1,
         "modules\/search\/search.css":1,
         "modules\/user\/user.css":1,
         "modules\/shortcut\/shortcut.css":1,
         "modules\/toolbar\/toolbar.css":1,
         "themes\/bartik\/css\/layout.css":1,
         "themes\/bartik\/css\/style.css":1,
         "themes\/bartik\/css\/colors.css":1,
         "themes\/bartik\/css\/print.css":1,
         "themes\/bartik\/css\/ie.css":1,
         "themes\/bartik\/css\/ie6.css":1
      }
   },
   "overlay":{
      "paths":{
         "admin":"node\/*\/edit\nnode\/*\/delete\nnode\/*\/revisions\nnode\/*\/revisions\/*\/revert\nnode\/*\/revisions\/*\/delete\nnode\/add\nnode\/add\/*\noverlay\/dismiss-message\nuser\/*\/shortcuts\nadmin\nadmin\/*\nbatch\ntaxonomy\/term\/*\/edit\nuser\/*\/cancel\nuser\/*\/edit\nuser\/*\/edit\/*\ndevel\/*\nnode\/*\/devel\nnode\/*\/devel\/*\ncomment\/*\/devel\ncomment\/*\/devel\/*\nuser\/*\/devel\nuser\/*\/devel\/*\ntaxonomy\/term\/*\/devel\ntaxonomy\/term\/*\/devel\/*",
         "non_admin":"admin\/structure\/block\/demo\/*\nadmin\/reports\/status\/php"
      },
      "pathPrefixes":[

      ],
      "ajaxCallback":"overlay-ajax"
   },
   "tableHeaderOffset":"Drupal.toolbar.height"
});
//--><!]]>
</script>

```

and in the browser console as you can see the following picture `Drupal.settings` object is interpreted properly. I mean, objects are as per json. There are no strange objects like in the above case.

**Question:** What is causing this strange behaviour? How to rectify it?

# Answer
> 5 votes
Those objects are coming from the Theme Developer module.

The module relies on data attributes on HTML elements to do it's thing. It either attaches to the element directly, or it will inject a `<span>`. All of the data elements are of the form `data-thmr="thmr_XXX"`. The data value matches up with an entry in `Drupal.settings`, and contains all of the theme information for that particular element, and is used to build the fancy box that appears when you click on something.

When I do a view-source on a site where I have Theme Developer enabled, I see the data attributes in the code, and I see the data elements in the DOM, and I see the objects in `Drupal.settings`. I also see the `Drupal.settings.thmrStrings` object.

However, if you poke through the issue queue and search for "thmrStrings", you will run across this issue, which talks about incompatibilities with the 2.x branch of simplehtmldom. The simplehtmldom module has this warning on it page:

> **If you're using Theme developer please note that it's currently incompatible with simplehtmldom 7.x-2.x. Use 7.x-1.12 instead. More details #2199439: Incompatible with simplehtmldom 7.x-2.x**

So, I would disable Theme Developer, then disable an uninstall simpledom API, download and enable simplehtmldom-7.x-1.12, and then enable Theme Developer again.

# Answer
> 1 votes
They come from Drupal.settings. When devel\_themer is enabled, there is a second block `jQuery.extend(Drupal.settings` that defines those objects.

---
Tags: 7, javascript
---


# Question
Title: Send a mail from my custom module after custom form submit by user
I have made a custom form from a custom module. I need to send an email to the admin when user clicks submit. How can I achieve this. Can I use entities here? Say like send mail to `[site:mail]` or something like that. Also, its pretty odd to see that Rules module does provide an event for this.

Here's my .module file:

```
<?php

global $user;

function my_module_help($path, $arg) {
  switch ($path) {
    case "admin/help#formtest":
      return '<p>' . t("Test form for accept challenge") . '</p>';
      break;
  }
}

function my_module_menu() {
  $items = array();
  $items['my_module/form'] = array(
    'title' => t('My form'),
    'page callback' => 'my_module_form',
    'access arguments' => array('access content'),
    'description' => t('My form'),
    'type' => MENU_CALLBACK,
  );
  return $items;
}

function my_module_form() {

 return drupal_get_form('my_module_my_form');

}

function my_module_my_form($form_state) {

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

  return $form;
}

function my_module_action($form, &$form_state) {
  drupal_set_message(t('Challenge Accepted'));
  $query = db_insert('challenges')
    ->fields(array(
    'cid' => '$node->nid',
    'uid' => '$user->uid'
    ))
    ->execute();
}

```

As you may have noticed there's no text field, well that is by purpose. So any suggestions would be really appreciated. One more thing, `drupal_mail`, or any other, say for example, mail chimp, notify etc would be of interest. What I need is just a mail to be send to admin after submit from the code itself.

Thanks

# Answer
> 4 votes
You surely can send an email on the submit.

See the code below.

```
function my_module_action($form, &$form_state) {
  drupal_set_message(t('Challenge Accepted'));
  $query = db_insert('challenges')
    ->fields(array(
    'cid' => '$node->nid',
    'uid' => '$user->uid'
    ))
    ->execute();
  $message = array('A new entry has been submitted');
  $to = 'example@example.com';
  $params = array(
    'body' => $body,
     'subject' => 'Website Information Request',
  );
  if (drupal_mail('my_module', 'some_mail_key', $to, language_default(), $params)) {
        drupal_set_message('Thanks, email sent.');
    } else {
        drupal_set_message('Email not sent.');
    }
}

```

You also need this function.

```
function my_module_mail($key, &$message, $params) {
  $message['subject'] = $params['subject'];
  $message['body'] = $params['body'];
}

```

in `drupal_mail()`, we pass `$params` array which contains parameters to build the email. If your module sends multiple emails, you can differentiate them using the `$key` variable. But in this example, we simple assign message's variables from the direct `$params` variables. Note that `$message` (in your submit handler) needs to be an array of text that you need to send. For example,

```
$body = array();
$body[] = 'Hello,';
$body[] = 'There is a new submission...';

```

This is because when the email gets sent, body content will be imploded by a new line character. Each value in the `$body` array will appear in a new line.

Also, as a fine tuning, you won't need `my_module_form` function if you format your hook\_menu function like this:

```
function my_module_menu() {
  $items = array();
  $items['my_module/form'] = array(
    'title' => 'My form', // We don't t() menu titles.
    'page callback' => 'drupal_get_form', // Directly call drupal_get_form...
    'page arguments' => array('my_module_my_form'), // ...with this argument.
    'access arguments' => array('access content'),
    'description' => t('My form'),
    'type' => MENU_CALLBACK,
  );
  return $items;
}

```

# Answer
> 0 votes
@ayesh's answer is accurate and is the recommended process for production sites (ie, use drupal\_mail()), but if you only want a quick email for debugging, just use php's mail() function:

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

  drupal_set_message(t('Challenge Accepted'));

  $query = db_insert('challenges')
    ->fields(array(
      'cid' => '$node->nid',
      'uid' => '$user->uid'
    ))
    ->execute();

  mail('you@email.com', 'form was submitted', 'someone submitted the form!');

}

```

---
Tags: 7, forms, emails
---


# Question
Title: Drupal 7 Private Files - How to override security in custom module
Is there a hook to override access to images stored in the private file system when theme\_image\_style is used to output the image?

# Answer
Image styles are served from the public file system, and there's no hook to control access to public files, so unfortunately not.

There's no simple solution, but there *is* a working solution: Image Style Access

> Allows granular access control to images and image style derivatives.

I've had a quick look through the code and you won't find a better starting point than that module. Quite a straightforward idea actually, it introduces a menu router item for each `./styles/[image-style]` folder, controlled by an access callback.

It does mean you now have the overhead of a full bootstrap for all image styles, but since you want to check access based on the DB there's no other way to do it.
> 2 votes

# Answer
@Clive Thanks for the suggestion, in the end I did find an answer to this and it was quite easy.

hook\_file\_download($uri) https://api.drupal.org/api/drupal/modules%21system%21system.api.php/function/hook\_file\_download/7

For what I needed this worked just great. It is called everytime a private file is accessed through the drupal system.

I can easily do the checks on the user logged in when this hook is called and just return 1 if the user should be allowed access to the file or -1 if I want to deny access.
> 0 votes

---
Tags: hooks, media, theming, security
---


title: How to print login form on page

text:
# Question
Title: How to print login form on page
How to print login form with destination url on a page using code in drupal 7 ?

# Answer
You can use below code to print login form block

```
<?php
print(drupal_render(drupal_get_form('user_login_block')));
?>

```

For login redirect to destination you can use Login Destination module

Project page says

> 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.
> 2 votes

# Answer
Outputting the form:

https://stackoverflow.com/questions/11995551/drupal-render-login-form-programatically

Redirecting after submit:

https://drupal.org/node/290462
> 1 votes

---
Tags: forms, users
---


# Question
Title: Generate hyperlink on each row for html table that contains database data
I created Ajax based dependent dropdown list and based on the selected item I selected table from database and displayed html table as output.

Now I want to generate hyperlink for each row of html table .This hyperlink is used to access public files based on the fid

I think i cannot use views because i am generating html table based on selected item from dropdownlist

I would be more thank full if anyone can share some ideas

# Answer
> 0 votes
If you have custom code that generates the table then it should be easy to output the link to files as well.

I assume you are looking for info on how to get the link to the file having your file id from the database.

You will need this: Given a File ID (fid) how can I get the HTML that represents that fid?

EDIT: After you provided some sample code I was able to figure out what you need:

You need a slash in front of drupal.

```
<a href=\"/drupal/sites/default/files/" . $data->FileName . "\">

```

---
Tags: theming, forms
---


title: Customize Rendered File markup?

text:
# Question
Title: Customize Rendered File markup?
Wondering how i can control the markup returned for a Rendered file view mode?

This is within a view, i have a field which is a media file image. I set it to use the Rendered File formatter and provide a view mode i created. But i don't see where i can customize the view mode markup.

```
<div id="file-28" class="file file-image file-image-jpeg contextual-links-region">

    <h2 class="element-invisible"><a href="/file/msvujpg" class="views-ajax-processed-processed">msvu.jpg</a></h2>

<div class="content">
  <img typeof="foaf:Image" src="http://localhost/sites/default/files/styles/featured_university/public/msvu.jpg?itok=8s4993Zo" width="352" height="240" alt="">  </div>

</div>

```

The only markup I want returned is

```
 <img typeof="foaf:Image" src="http://localhost/sites/default/files/styles/featured_university/public/msvu.jpg?itok=8s4993Zo" width="352" height="240" alt="">

```

I want to get rid of the div's and the whole h2 element.

# Answer
> 1 votes
You can create a variation of file\_entity.tpl.php from the File Entity module using the following pattern.

```
file__{file type}__{view mode}.tpl.php

```

e.g.

```
file__image__teaser.tpl.php

```

---
Tags: views, theming, media
---


# Question
Title: Is there a standard way to control which node or entity links appear in which view modes?
My module adds a link to the node view, from within `hook_node_view`. Is there a "Drupal" way to let the site builder control which view modes should show that link?

Right now, I'm using a multiselect control on the module's admin settings page.

# Answer
> 1 votes
If you are adding fields in hook\_node\_view then the most polite thing you can do is add them to the 'manage display' tabs for that content type. Do this using hook\_field\_extra\_fields(). This way people can: hide or show them per content type, per view mode and also position them amongst other fields, just like any field API field.

Here is a code example where I have added the print links to the node using hook\_node\_view().

```
/**
 * Implements hook_node_view().
 */
function zest_general_node_view($node, $view_mode, $langcode) {

    // Add print and email links as pseudo field.
    $node->content['print_links'] = array(
      '#markup'=> print_insert_link() . print_mail_insert_link(),
      '#view_mode' => $view_mode,
      '#prefix' => '<div class="links inline print-mail">',
      '#suffix' => '</div>',
      '#weight' => 20,
    );

}

```

Then I add them as a 'pseudo field' using hook\_field\_extra\_fields().

```
/**
 * Implements hook_field_extra_fields().
 *
 * Adds the print and email links as a pseudo field.
 */
function zest_general_field_extra_fields() {
  $extra = array();

  $extra['node']['product'] = array(
    'display' => array(
      'print_links' => array(
        'label' => t('Print Links'),
        'description' => t('Links provided by the print module.'),
        'weight' => 20,
      ),
    ),
  );

  return $extra;
}

```

hook\_field\_extra\_fields()

# Answer
> 0 votes
In your theme's template.php, you can invoke hook\_preprocess\_node() and modify the links array there. Something like the following:

```
function YOUR_THEME_preprocess_node(&$vars) {
  switch ($vars['view_mode']) {
    case 'teaser':
//    change $vars['content']['links'] here.
      break;
  }
}

```

You can invoke that hook from your module, as well. In fact, hook\_node\_view takes the view\_mode as a parameter, so you should be able to set it using that already.

# Answer
> 0 votes
use DisplaySuite and give the ability to allow the site manager to edit the layout for a given view mode (the same thing could be done with allowing the site manager control over `Content Types` but this is slightly more dangerous).

You can also try something with the Context module, I believe you can have a context value per node for the `view_mode` setting -- but your site architecture would have to support using Context(s).

---
Tags: 7, navigation, entities
---


title: How to center footer block?

text:
# Question
Title: How to center footer block?
Using Drupal 7 with custom zen subtheme. I created a footer block to hold standard copyright information. But this block is left aligned, how do I center my footer block?

**UPDATE**

Below is the HTML for my footer. What CSS selector should I use to identify my footer block?

```
<div class="region region-footer">
 <div id="block-block-1" class="block block-block contextual-links-region first last odd">
  <div class="contextual-links-wrapper contextual-links-processed">
   <div class="content"> © Copyright 2011 example.com </div>
  </div>
 </div>
</div>

```

# Answer
You could either:

* Add {text-align: center} to your footer region or block.
* You could specify a width for your block and add {margin: 0 auto}.
> 2 votes

# Answer
Select the class for the element containing the footer block; then add the following CSS properties:

```
.class {
  margin: 0 auto;
  text-align: center;
  width: 10%;
}

```

(Replace *.class* with the class of the container.)
> 1 votes

# Answer
just use the footer tag which is part of the default Zen theme to centralise your footer.

```
#footer {
    text-align: center;
}

```
> 0 votes

---
Tags: 7, blocks
---


title: How to Compute fields on the fly

text:
# Question
Title: How to Compute fields on the fly
I have content type having fields as follows.

first

second

third

Sum1 (first + second +third) - computed filed

xxxx

yyyy

zzzz

Sum2 (xxxx+yyyy+zzzz) - computed field

Grand Total (sum1 + sum2) - computed field

I could achieve this by using **computed field** module. When I save node, I could able to find sums and Grand Total.

My problem is client wants to see **sum1** filed in edit/create form and also wants to update sum1/sum2/Grand Total fields on the fly (dynamically). There are couple of content types having the same requirement.

Before start to write a custom module, I would like to know alternates for this.Any suggestions?

# Answer
> 3 votes
This sounds like cashier functionality. There has been some effort for D6, see Drupal POS (Point of Sales) System. I haven't used this.

Ideally, this would be done with JavaScript (I have once done it for a non-Drupal system).

A cheap workaround would be the Save & Edit module, where you just save the node and continue editing it, effectively updating the calculations. On demand, not automatically.

A smoother workaround would be updating (on demand) the form with ajax. Ajax module has no D7 version, but in the issue queue is mentioned this sandbox project which supposedly can ajaxify the node edit form: Asaf (ajax submit for any form).

You need one extra module for actually displaying Computed field on node *edit* form: Field extra widgets. Select the widget "read only".

---
Tags: 7, ajax, entities
---


title: Add a Region for Slideshow in Zen

text:
# Question
Title: Add a Region for Slideshow in Zen
I want to create a region for a slideshow using the Zen Theme. The problem is, I don't know where to place the code in the page.tpl.php file. I want the navigation to be ontop, followed by the slideshow, followed by the rest of the website. I've tried placing the following code everywhere in the page.tpl.php file, but have not been able to yield the desired result.

Here is the code I'm using:

```
  <?php if ($page['featured_slider']): ?>
    <div id="featured-slider">
      <?php print render($page['featured_slider']); ?>
    </div> <!-- End Featured Slider-->
  <?php endif; ?>

```

Here is the page.tpl.php file WITHOUT the above code:

```
?>

<div id="page-wrapper"><div id="page">

  <div id="header"><div class="section clearfix">

    <?php if ($logo): ?>
      <a href="<?php print $front_page; ?>" title="<?php print t('Home'); ?>" rel="home" id="logo"><img src="<?php print $logo; ?>" alt="<?php print t('Home'); ?>" /></a>
    <?php endif; ?>

    <?php if ($site_name || $site_slogan): ?>
      <div id="name-and-slogan">
        <?php if ($site_name): ?>
          <?php if ($title): ?>
            <div id="site-name"><strong>
              <a href="<?php print $front_page; ?>" title="<?php print t('Home'); ?>" rel="home"><span><?php print $site_name; ?></span></a>
            </strong></div>
          <?php else: /* Use h1 when the content title is empty */ ?>
            <h1 id="site-name">
              <a href="<?php print $front_page; ?>" title="<?php print t('Home'); ?>" rel="home"><span><?php print $site_name; ?></span></a>
            </h1>
          <?php endif; ?>
        <?php endif; ?>

        <?php if ($site_slogan): ?>
          <div id="site-slogan"><?php print $site_slogan; ?></div>
        <?php endif; ?>
      </div><!-- /#name-and-slogan -->
    <?php endif; ?>

    <?php print theme('links__system_secondary_menu', array(
      'links' => $secondary_menu,
      'attributes' => array(
        'id' => 'secondary-menu',
        'class' => array('links', 'inline', 'clearfix'),
      ),
      'heading' => array(
        'text' => $secondary_menu_heading,
        'level' => 'h2',
        'class' => array('element-invisible'),
      ),
    )); ?>

    <?php print render($page['header']); ?>

  </div></div><!-- /.section, /#header -->

  <div id="main-wrapper"><div id="main" class="clearfix<?php if ($main_menu || $page['navigation']) { print ' with-navigation'; } ?>">

    <div id="content" class="column"><div class="section">
      <?php print render($page['highlighted']); ?>
      <?php print $breadcrumb; ?>
      <a id="main-content"></a>
      <?php print render($title_prefix); ?>
      <?php if ($title): ?>
        <h1 class="title" id="page-title"><?php print $title; ?></h1>
      <?php endif; ?>
      <?php print render($title_suffix); ?>
      <?php print $messages; ?>
      <?php if ($tabs = render($tabs)): ?>
        <div class="tabs"><?php print $tabs; ?></div>
      <?php endif; ?>
      <?php print render($page['help']); ?>
      <?php if ($action_links): ?>
        <ul class="action-links"><?php print render($action_links); ?></ul>
      <?php endif; ?>
      <?php print render($page['content']); ?>
      <?php print $feed_icons; ?>
    </div></div><!-- /.section, /#content -->

    <?php if ($page['navigation'] || $main_menu): ?>
      <div id="navigation"><div class="section clearfix">

        <?php print theme('links__system_main_menu', array(
          'links' => $main_menu,
          'attributes' => array(
            'id' => 'main-menu',
            'class' => array('links', 'inline', 'clearfix'),
          ),
          'heading' => array(
            'text' => t('Main menu'),
            'level' => 'h2',
            'class' => array('element-invisible'),
          ),
        )); ?>

        <?php print render($page['navigation']); ?>

      </div></div><!-- /.section, /#navigation -->
    <?php endif; ?>

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

    <?php print render($page['sidebar_second']); ?>

  </div></div><!-- /#main, /#main-wrapper -->

  <?php print render($page['footer']); ?>

</div></div><!-- /#page, /#page-wrapper -->

<?php print render($page['bottom']); ?>

```

# Answer
> 1 votes
Try removing `if($page['featured_slider']):`

Make sure you have placed your slideshow block in featured\_slider region.

# Answer
> 1 votes
Make sure you are assigning the block with your slideshow to the correct region, and make sure your slideshow has content.

# Answer
> 1 votes
To add a custom region to your theme:

1. in your **subtheme.info** file (or zen.info if you don't have a subtheme...), **declare the new region** in the regions list : `regions[featured_slider] = Featured slider`.
2. in your `page.tpl.php`, render the region content

```
<?php if ($page['featured_slider']): ?>
  <div id="featured-slider">
    <?php print render($page['featured_slider']); ?>
  </div> <!-- End Featured Slider-->
<?php endif; ?>

```

Don't forget to **empty your cache**.
3. Last step : assign your block to the new region, from `admin/structure/block` admin menu, or with

```
$block = module_invoke('views', 'block_view', 'SLIDESHOW_VIEWBLOCK_NAME');
print render($block);

```

(I would personnally not create a region just for a slideshow and put it in the header region, but it's up to you of course.)

# Answer
> 0 votes
You can alternatively not change any php and just assign your slideshow block to the Content region (at the top) so its above your normal page content, and therefore below your navigation (menu).

---
Tags: theming, javascript
---


# Question
Title: Menu Block disappear when changed the access control permission
I have "Menu Block" and "Content Access" modules installed. The menu button of that page disappear when I set that page not to view by "anonymous user". How can I show the Menu Block to everyone but not the page content?

PS: I don't wanna create another menu block

Thanks!

# Answer
Drupal will show / remove pages from the menu depending on whether or not a specific role has access to it. If you want to show the page in the menu but not the content to a specific role such as anonymous there are a couple of different routes you can go.

There is a module called field permissions which would allow you to set the page itself to be visible by everyone but you could hide specific fields from visitors. From drupal.org

```
The Field Permissions module allows site administrators to set field-level permissions to edit, view and create fields on any entity.

```

You could also achieve something similar if you were to use the panels module. You could set visibility based on role, thus hiding sections of content but still having your menu items visible.
> 0 votes

---
Tags: routes
---


# Question
Title: Entity Metadata Wrapper Save VS Node Save when invoked from hook_node_insert
Can somebody shine a light into the difference of the two, in terms of their interaction with database when `hook_node_insert()` is invoked? The documentation explains that

> Note that when this hook is invoked, the changes have not yet been written to the database, because a database transaction is still in progress. The transaction is not finalized until the save operation is entirely completed and node\_save() goes out of scope.

In fact, when I tried doing `node_save($node)`, it will give me an error.

However, if I was doing it this way,

```
$nodeWrapper = entity_metadata_wrapper('node', node_load($node->nid));
$nodeWrapper->title->set(t("Saved by Entity Save"));
$nodeWrapper->save();

```

It works just fine. Has the new node being committed into the database after the `$nodeWrapper->save()` was executed?

# Answer
> 2 votes
Essentially, there really isn't much difference between `node_save()` and the `save()` method of the entity metadata wrapper. Neither should however be used to save the node passed in as the argument to `hook_node_insert()`.

The argument is passed by reference (since it's an object and all objects are passed by reference in later PHP versions), and any changes you make to it will be included when the node is saved by Drupal just after it's done calling the hook implementation.

Trying to manually save the same node again could trigger endless recursion into your `hook_node_insert()` implementation.

Just alter the node object as you see fit (setting the title in this case, though that is not a translatable string, so replace `t()` with `check_plain()`) and do nothing more.

If you need to do more complex alterations, the entity metadata wrapper could come in handy, but you must remember that any alterations you want to have saved must be performed on the node instance passed as a reference to `hook_node_insert()`. This means you can't `node_load($node->nid)` here first, since that would actually just create a new node object with data that's already in the database. If you do manage to save that node copy without ending up in a recursion loop, it would either mean that the node save already in progress - the reason `hook_node_insert()` was originally called - overwrites any changes you made, or fails because the new node to be saved already exists.

Instead, pass the `$node` argument to `entity_metadata_wrapper()` directly and the wrapper will be able to alter the correct node object for you, but remember to not call `save()` on the wrapper!

# Answer
> 1 votes
Calling `node_save()` from inside a `hook_node_insert()` implementation is error prone and should only be done with sufficient condition checks as to not provoke function nesting.

When you call `node_save()` coming from an insert operation and saving the `$node` object that already has an `nid`, then this call of `node_save` probably creates an update operation, which might result in strange errors. I don't fully follow the information flow here, but I would guess that one of the two calls to `node_save()` can easily run into a problem.

The correct way in a scenario where you want to alter node properties (e.g. status, promote, title, ...) prior to inserting, is to use `hook_node_presave()`. If you want to update field values inside a `hook_node_insert()`, that should be done by calling `field_attach_update('node', $node)`.

Using the `save()` method of `entity_metadata_wrapper` doesn't exactly feel good either. Looking at the code in EntityDrupalWrapper::save, which I suppose is the wrapper class that is responsible, it looks like `node_save()` is going to be called in the end too. But I have never really used Entity Wrapper, so I'm a bit short here.

**Edit:** Regarding entity\_metadata:\_wrapper, looking again at the code of `entity_save()` I realize that it's not `node_save()` that is called in the end, but that this is entirely handled by the Entity module. At the end it will end up here if I'm not mistaken: EntityAPIController::save. I'm not sure though how that explains the behavior described in the comment.

# Answer
> 0 votes
The reason why `node_save($node->nid)` gives you an error is because node\_save takes node object to be saved, not a node id. Just change it to `node_save($node)` and it will work just fine.

In simple terms, node save is just a specific kind of entity save and just makes your life easier by doing things that you would have to do yourself (like in your case, node\_save is one line, saving the entity does the same thing but you have to deal with metadata wrapper unnecessarily).

---
Tags: entities, nodes
---


# Question
Title: Can I use the prepopulate module on an entityreference field in an entityform?
It may be wishful dreaming, but it would be sweet if I could pull this off. I've been banging my head against it for a while now.

Has anyone done this before?

# Answer
> 4 votes
I actually did this on a project recently.

You can use Entity Reference Prepopulate. It's nice because you can make the field disabled if it's populated, all handled through the UI.

The alternative would be to just write a little bit of JS that disables the field on the node edit form if the value isn't empty.

# Answer
> 1 votes
I agree with @KyleTaylored. I've done this many times using Entity Reference Prepopulate but the url for pre-populating in that case is:

http://example.com/node/add/mynodetype?field\_to\_populate=11

# Answer
> 0 votes
Of course - 4 minutes after I post that I hit on the answer:

```
http://example.com/eform/submit/form-name?edit[field_entity_ref_name][und]=11

```

Now I need to figure out how to set this field as read-only and I'm golden.

---
Tags: 7, forms, entities
---


# Question
Title: Filtering on a field from field collection in a view
I have several node types (merchandise vendor, food vendor, festival vendor) which all have an embedded field collection called equipment, which can contain multiple values. The field collection has a taxonomy field called event and some others.

For example, a merchandise vendor can have equipment for event 1 (a taxonomy term), and different equipment for event 2 (a different taxonomy term).

My view can sort out the vendors for event 1 just fine. I can include the equipment for the events in the view, but I can't seem to filter it to just event 1.

I want to be able to visit the view page for event 1, and have it show all the vendors for event 1, and the equipment each vendor needs for event 1. Right now, it shows all the equipment for the vendor for all the events.

Is there a way to filter a field collection in a view?

# Answer
You can create a Relationship to the field collection, and then you'll have access to all the field collection's fields within the collection from both "Fields" and "Filters".
> 4 votes

---
Tags: views, entities
---


title: Export user profile fields in pdf

text:
# Question
Title: Export user profile fields in pdf
I\`m using Drupal 7 and i have added some extra fields in People \> Account Settings.

What I\`m trying to accomplish is to give logged in user link ( in sidebar block ) to export those fields into .pdf

I created a view with all user fields and i found module called Views Data Export

But unfortunately it does not support PDF. Is there any other way/module to do this?

# Answer
> 1 votes
To answer myself here.

There is a module Views PDF that does the job. Not sure how i missed it earlier...

---
Tags: 7, views, importing-exporting
---


# Question
Title: How to hide a sub level menu from being expanded?
When a menu is active, drupal displays the sub-menus of the active menu, but because I use the sub-menus in a separate block via the "menu block" module, I don't want the sub-menu to be shown. How can I do it on server side?

Is there an easy drupal way to do it without touching the theme\_menu\_link? If not, Is there a way to do it in a module rather in template.php? beside, can some one show me how to write the code?

# Answer
> 1 votes
In the Add/Edit menu\_block options, you can specify the `Maximum depth` of the menu tree to `1`.

---
Tags: theming, routes
---


# Question
Title: Getting Files to show up on new submitted Module page
I have a module that is ready for public use, and I have created a Drupal Account and created a development sandbox, and even uploaded the files via git. Now, I am very much a newb regarding git, so perhaps I have done something wrong. I have attached 2 screenshots of my module page screens (public facing page and the edit page).

Now I am pretty sure that the reason I cannot promote to a full project as seen on this page is because I need to create an issue so that the Drupal team can review the module. This page says to create an issue with specific details included. However, for Component, I am supposed to select either 'Module', 'Theme', or 'Feature'. I would like to select Module, but the only options that are provided at this time are 'Code', 'Documentation', 'Miscellaneous', and 'User Interface'. What am I missing? What additional steps do I need to follow to get this module publicly published?

# Answer
> 0 votes
Found answer. Apparently I missed the part where sandboxes do not have download buttons on the project pages. And I was trying to add an issue for MY project, rather than submit an issue to Drupal.org.

---
Tags: 7, version-control
---


# Question
Title: Using custom ranking for some searches and not others in D7
I want to define a custom search ranking, and only use it on a special page, without affecting the regular search feature.

Looking at the code in node.module, I see how I could hook MODULE\_ranking() in a custom module, however it won't be applied to the query unless global variable node\_rank\_X setting is enabled in the global config.

I could munge the global $conf for my one specific page, but this seems ugly. Is there a more sensible way to approach this?

# Answer
Search API was built to give a great deal of flexibility to searches. You can create separate search indexes to meet different criteria, weight individual fields differently per index and keep all of your configuration managed in the UI, versus trying to write custom logic into MODULE\_ranking().

Download Search API, install and configure your indexes at: /admin/config/search/search\_api
> 0 votes

---
Tags: search, 7
---


title: Multiple textfield values

text:
# Question
Title: Multiple textfield values
im using form api and im trying to get to make a group of fields under one type, like for example a phone number, you would have 3 fields 1 being the area code and the other 2 fields being the number

I would think it would be something like this..

```
$form['phone'] = array(

    '#title' => 'Phone Number',
    '#tree' => TRUE
);

$form['phone']['areacode'] = array(
    '#type' => 'textfield',
    '#maxlength' => 3,
    '#size' => 3,
);

$form['phone']['number1'] = array(
    '#type' => 'textfield',
    '#maxlength' => 3,
    '#size' => 3,
);

    $form['phone']['number2'] = array(
    '#type' => 'textfield',
    '#maxlength' => 4,
    '#size' => 4,
);

```

or even something with options like this for example

```
$form['phone'] = array(
    '#type' => 'textfield',
    '#title' => 'Phone Number',
    '#tree' => TRUE,
    '#options' => array(
        array(
        '#value' => t('areacode'),
        '#maxlength' => 3,
        'size' => 3,
        ),
        array(
        '#value' => t('number1'),
        '#maxlength' => 3,
        'size' => 3,
        ),
        array(
        '#value' => t('number2'),
        '#maxlength' => 4,
        'size' => 4,
        ),

    )
);

```

Either way I want to have multiple textfield values under one form type.

Thanks

# Answer
I know there are some parent and tree properties in the form API, but to be honest I have never use it. In a case like your I will create 3 text fields with a limit number of characters depending on the part of the phone number I am collecting ( 3 (for area code) - 3 (for the exchange) - 4 (for the number) ) and then on the submit function of the form I will concatenated them together.

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

// If you edit the data using the same form then
// get the previously store phone number
$phone = $phone_from_db;

$form['area-code'] = array(
  '#type' => 'textfield',
  '#title' => t('Area Code'),
  '#default_value' => substr($phone, 0, 3),
  '#size' => 3,
  '#maxlength' => 3,
  '#required' => TRUE,
);

$form['exchange'] = array(
  '#type' => 'textfield',
  '#title' => t('Exchange'),
  '#default_value' => substr($phone, 3, 3),
  '#size' => 3,
  '#maxlength' => 3,
  '#required' => TRUE,
);

$form['number'] = array(
  '#type' => 'textfield',
  '#title' => t('Number'),
  '#default_value' => substr($phone, 6, 4),
  '#size' => 4,
  '#maxlength' => 4,
  '#required' => TRUE,
);

  return $form;
}

function my_module_example_form_submit($form, &$form_state) {
  // Submission logic.
  $phone = $form_state['values']['area-code']+$form_state['values']['exchange']+$form_state['values']['number'];
  // Save the $phone variable
}

```

There are also a couple of modules with the ability to add phone fields and they even offer validation of the phone number depending on the country.

1. http://drupal.org/project/phone
2. http://drupal.org/project/cck\_phone
3. http://drupal.org/project/location
> 1 votes

# Answer
It is an ideal case to use `#tree`. `#tree` is used to force the `$form_state['values']` values to be a multidimensional array of values. See the example below:

```
  $form['phone'] = array(
    '#type' => 'fieldset',
    '#title' => t('Phone numbers'),
    '#tree' => TRUE,
  );
  $form['phone'][1] => array(
    '#type' => 'fieldset',
    '#title' => t('Phone number - @index', array('@index' => 1)),
    '#tree' => TRUE,
  );
  $form['phone'][1]['area'] => array(
    '#type' => 'textfield',
    '#title' => t('Area code'),
  );
  $form['phone'][1]['number'] => array(
    '#type' => 'textfield',
    '#title' => t('Phone number'),
  );
  // Start repeat.
  $form['phone'][2] => array(
    '#type' => 'fieldset',
    '#title' => t('Phone number - @index', array('@index' => 3)),
    '#tree' => TRUE,
  );
  $form['phone'][2]['area'] => array(
    '#type' => 'textfield',
    '#title' => t('Area code'),
  );
  $form['phone'][2]['number'] => array(
    '#type' => 'textfield',
    '#title' => t('Phone number'),
  );
  // End repeat. Ideally use a for loop here. Duplicated just to demonstrate it to you.

  return $form;

```

Now, you will receive the values in a deeper structured array: $form\_state\['values'\]\['phone'\] would contain an array like this, as if it was created using array():

```
  array(
    1 => array(
      'area' => 123,
      'phone' => 456789,
    ),
    2 => array(
      'area' => 000,
      'phone' => 9876543,
    ),
  );

```

To style the form, just add some floating and a width to the form based on the maxlength. You will find a bunch of fieldset tags and wrapping divs to use an effective yet safe CSS selector. To attach CSS to the form, use `$form['#attached']`.
> 0 votes

# Answer
I think for this particular question there is good example in examples module which exactly explains the same areacode functionality with element features. You can take a look on this one by downloading and installing the https://drupal.org/project/examples. And enable the module form example. Go to this path- 'site-name'/examples/form\_example/element\_example. This might provide a good help to you.
> 0 votes

---
Tags: forms
---


# Question
Title: db_affected_rows gives fatal error in drupal 7
How can i get the number of affected rows in drupal 7? db\_affected\_rows which i was used in d6 is not working in d7. It shows an error

```
 $bool = db_query("SELECT * FROM {template_config} WHERE user_role = ':d'",array(':d'=> $id));
        $num = db_affected_rows();
        if ($num != 0) {
            $result = db_fetch_array($bool);
            $custom_theme = $result['theme_name'];
        }

```

i want to check if there is any affected rows.db\_num\_rows also is not working in d7
How can i do this in d7?

# Answer
There is no `db_affected_rows()` in Drupal 7 I'm afraid. Also you don't need include the quotes in your variable placeholder. Your code might look a little more like this:

```
$results = db_query("SELECT * FROM {template_config} WHERE user_role = :role", array(':role' => 'the_role'))->fetchAll();

if (count($results) > 0) {
  $first_result = $results[0];

  $custom_theme = $first_result->theme_name;
}

```

It could be even simpler though:

```
if ($result = db_query("SELECT * FROM {template_config} WHERE user_role = :role", array(':role' => 'the_role'))->fetchObject()) {
  $custom_theme = $result->theme_name;
}

```
> 3 votes

# Answer
Drupal 7 is based on PDO as database abstraction layer. That's why a lot of functions have changed compared to D6. To get the number of affected rows, you can use the rowCount method.

By the way, in Drupal 7 you can simply foreach() over a database query result. When using foreach, you don't even need to check if the result has more than 0 rows. See db\_query documentation for more info. The following example comes from that page:

```
<?php
$uid = 1;
$result = db_query('SELECT n.nid, n.title, n.created FROM {node} n WHERE n.uid = :uid', array(':uid' => $uid));
// Result is returned as a iterable object that returns a stdClass object on each iteration
foreach ($result as $record) {
  // Perform operations on $record->title, etc. here.
  // in this example the available data would be mapped to object properties:
  // $record->nid, $record->title, $record->created
}
?>

```
> 3 votes

# Answer
```
$bool = db_query("SELECT * FROM {template_config} WHERE user_role = ':d'",array(':d'=> $id));
        $num = db_affected_rows($bool);

```

OR

```
$num = db_num_rows($bool);

    if ($num != 0) {
        $result = db_fetch_array($bool);
        $custom_theme = $result['theme_name'];
    }

```

Try this you have forgot passing the argument.
> 2 votes

# Answer
In drupal 7 use $pdos-\>rowCount(); to get the affected rows count.

```
$result = db_query('<your query>');
$affected_rows = $result->rowCount();

```
> 1 votes

---
Tags: 7
---


# Question
Title: How to skip client side validation for draft node?
I am using clientside validation module for drupal 7.I have two button for submit node one is for save as draft and other submit so Now my scenario is that if i click on save as draft then it should not display client side validation error.

# Answer
> 0 votes
You can add a 'cancel' class to your draft button and it will skip clientside\_validation, we do this out-of-the-box for the delete button, code can be found in clientside\_validation.module, line 278

---
Tags: nodes, forms
---


title: Drupal 7 - theme default node view

text:
# Question
Title: Drupal 7 - theme default node view
I would like to know the recommended way to re-theme the default node view for a certain content type.

E.g. http://dev.mysite/en/node/6547, now shows a 'list' of content fields. We would like to change this to a more clean layout.

Would using a node.tpl.php in the theme folder and then create a node--\[TYPE\].tpl.php for the specific node type solve this problem in the correct way?

Regards, Wouter

# Answer
> 1 votes
Using .tpl.php files would indeed give you more control over the HTML Drupal will create in the end. Also using a module like Display Suite (DS - drupal.org/project/ds) will give you more control over the fields in a certain display so that some settings about that field on that display are stored in database instead of in code.

# Answer
> 0 votes
Yes , You are on the right track...

For more information on templates please see Drupal 7 Template (Theme Hook) Suggestions

You can override specific nodes of a type using below tpl file name

```
node--type.tpl.php

```

To print fields in node tpl you can use below code

```
<?php print render($content['your_field_name']); ?>

```

---
Tags: nodes, theming
---


# Question
Title: Show Filename of uploaded files in "Field Collection" Field
I have a requirement where I have to show files uploaded within a category.. I used Field Collection Module of Drupal for it and made fields in the following way, where each category is a field collection item which has a title field and a multi value file field:-

Now, my end result is to show it in a Search Results Page. When someone searches for a keyword, and it matches the uploaded filename, the file should show in the Search.

I tried views, etc, but I can't output it. Any help please on how to output the file names for the search keyword through Search Results in Drupal ?

# Answer
You can create a search display using Display Suite (https://drupal.org/project/ds). By enabling DS and DS Search you will get some search options done through DS.
> 1 votes

---
Tags: search, entities, views
---


# Question
Title: When is it appropriate to run a drupal_bootstrap?
I have a static site with a drupal blog in a subfolder and I want to bring the latest posts into the homepage. I can run a drupal\_bootstrap and then load the nodes I want. Is this an ok strategy? When is it appropriate to use drupal\_bootstrap?

# Answer
> 1 votes
Check the doc of drupal bootrstrap: In order to bootstrap Drupal from another PHP script, you can use the following code:

```
define('DRUPAL_ROOT', '/path/to/drupal');
require_once DRUPAL_ROOT . '/includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);

```

> **drupal\_bootstrap($phase = NULL, $new\_phase = TRUE)**

**Parameters**

$phase: A constant telling which phase to bootstrap to. When you bootstrap to a particular phase, all earlier phases are run automatically. Possible values:

```
DRUPAL_BOOTSTRAP_CONFIGURATION: Initializes configuration.
DRUPAL_BOOTSTRAP_PAGE_CACHE: Tries to serve a cached page.
DRUPAL_BOOTSTRAP_DATABASE: Initializes the database layer.
DRUPAL_BOOTSTRAP_VARIABLES: Initializes the variable system.
DRUPAL_BOOTSTRAP_SESSION: Initializes session handling.
DRUPAL_BOOTSTRAP_PAGE_HEADER: Sets up the page header.
DRUPAL_BOOTSTRAP_LANGUAGE: Finds out the language of the page.
DRUPAL_BOOTSTRAP_FULL: Fully loads Drupal. Validates and fixes input data.

```

$new\_phase: A boolean, set to FALSE if calling drupal\_bootstrap from inside a function called from drupal\_bootstrap (recursion).

**Return value**

The most recently completed phase.

Also check this: How to call drupal\_bootstrap from custom file in subfolder?

# Answer
> 2 votes
In order to bootstrap Drupal from another PHP script, you can use below code:

```
 define('DRUPAL_ROOT', '/path/to/drupal');
  require_once DRUPAL_ROOT . '/includes/bootstrap.inc';
  drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);

```

When ever you would like to call Drupal Functions or features outside of Drupal root you can use above code..

# Answer
> 1 votes
Yes, when using Drupal functionality make sure you run the bootstrap. It's more risky to create/alter/query the database native as dependencies might get corrupt/lost.

---
Tags: bootstrapping
---


# Question
Title: Form processing issue while generating a dynamic form and preparing via API calls directly
How can I fix the processing and submission of forms that I am preparing and rendering dynamically via API calls.

```
function drupal_set_confirmation($message, array $options, array $escape=array(), $type='warning', $details=NULL){
    $form = array();

    $form['title'] = array(
    '#markup' => '<h3>' . t($message) . '</h3>'
    );

    if (!empty($details)) {
        switch(gettype($details))   {
            case 'string':
                $form['details'] = array(
                    '#markup' => $details,
                );
            break;
            case 'array':
                $form['details'] = $details;
            break;
        }
    }

    if (!empty($options)) {
        $form['options'] = array(
            '#type' => 'container',
            '#attributes' => array('class' => array('user-confirmation-options')),
        );

        foreach($options as $key => $option) {
            $form['options'][$key] = array(
                '#submit' => array($option['callback']),
                '#type' => 'submit',
                '#value' => $option['title'],
                '#attributes' => $option['attributes'],
            );
        }

        if (!empty($escape)) {
            $form['options']['escape'] = array(
                '#markup' => l($escape['title'], $escape['path']),
            );
        } else {
            $form['options']['escape'] = array(
                '#markup' => l(t('Cancel'), current_path()),
            );
        }
    }

    $form_state = form_state_defaults();
    $form_id = 'form_user_confirmation';

    drupal_prepare_form($form_id, $form, $form_state);
    // I do not see any reason to call drupal_process_form while serving the form.
    //drupal_process_form($form_id, $form, $form_state);
    $rendered_form = drupal_render($form);
    return drupal_set_message($rendered_form, $type);
}

```

And it works greatly to show a dialog form of my own choice by calling.

```
drupal_set_confirmation(t('Do you really want to suicide?'), array(
        'okay' => array(
        'callback' => '_yes_kill_me',
        'title' => t('Yes'),
        'attributes' => array('class' => array('button', 'tiny')),
    ),
    ), array(
        'title' => t('No'),
        'path' => current_path(),
    ));

```

And callback function as #submit handler for a particular element is not invoked.

**How can I fix the form processing and submission issue using this approach to work?**

# Answer
> 0 votes
I fixed it this way, it started to invoke form submit handlers.

```
function MODULE_init() {
    if (!empty($_POST) && $_POST['form_id'] == 'form_user_confirmation') {
        $form_state = form_state_defaults();
        $form_id = 'form_user_confirmation';
        drupal_build_form($form_id, $form_state);
    }
}

```

---
Tags: forms
---


# Question
Title: Modify Reference on Taxonomy Field Output
I want to modify the output of a 'Reference on Taxonomy Field'. I created a 'Reference on Taxonomy Field' in a content type that relates to terms in a vocabulary that have a title and a picture. The content type is displayed by a view that outputs the fields of the content type. I added the field and created the template file **views-view-field--kategorieseiten--page--field-produkteigenschaften.tpl.php** and it works.

It should be displayed like this:

```
<a rel="tooltip" data-placement="bottom" target="_blank" data-original-title="TERM_TITLE">OUTPUT_OF_THE_TERM_PICTURE</a>

```

The problem is that I don't know how to address the fields from the taxonomy term, since they are not directly stored in the node.

Thanks for your help!

# Answer
I managed to load the fields of the taxonomy term with this code:

```
<?php

/**
 * @file
 * This template is used to print a single field in a view.
 *
 * It is not actually used in default Views, as this is registered as a theme
 * function which has better performance. For single overrides, the template is
 * perfectly okay.
 *
 * Variables available:
 * - $view: The view object
 * - $field: The field handler object that can process the input
 * - $row: The raw SQL result that can be used
 * - $output: The processed output that will normally be used.
 *
 * When fetching output from the $row, this construct should be used:
 * $data = $row->{$field->field_alias}
 *
 * The above will guarantee that you'll always get the correct data,
 * regardless of any changes in the aliasing that might happen if
 * the view is modified.
 */
?>

<?php $taxonomy_term = taxonomy_term_load(54); ?>
<a rel="tooltip" data-placement="bottom" target="_blank" data-original-title="<?php print $taxonomy_term->name; ?>"><img src="<?php print $taxonomy_term->field_icon['und'][0]['filename']; ?>"></a>

```

But I want to load the terms dynamically from the tid stored in this field:

The field 'field\_produkteigenschaften' is part of the content type and is stored in the node object.

**How do I now address the tid stored in the field 'field\_produkteigenschaften' in this template?**
> 0 votes

# Answer
I could get the output with:

```
$row->_field_data['nid']['entity']->field_produkteigenschaften['und'][0]['tid']

```

Complete code:

```
<?php if ($row->_field_data['nid']['entity']->field_produkteigenschaften) { ?>
<?php foreach ($row->_field_data['nid']['entity']->field_produkteigenschaften['und'] as &$eigenschaft) { ?>
<?php $taxonomy_term = taxonomy_term_load($eigenschaft['tid']); ?>
<a rel="tooltip" data-placement="bottom" target="_blank" data-original-title="<?php print $taxonomy_term->name; ?>"><img src="<?php print image_style_url("icon", $taxonomy_term->field_icon['und'][0]['uri']); ?>"></a>
<?php } ?>
<?php } else { print " "; } ?>

```
> 0 votes

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


title: Krumo output with debug()

text:
# Question
Title: Krumo output with debug()
When debugging I prefer using the Devel module because of the clickable Krumo output.

However when disabling the Devel module on production unremoved calls to e.g. `dsm()` can cause a WSOD because of calls to undefined functions.

By using the built-in debug function this does not happen but it will miss the nice krumo output.

Is it possible to get krumo output with the debug() function / or otherwise prevent the WSOD on production sites when using devel functions?

# Answer
> 2 votes
Use a custom code and define your own debug function that uses dsm if available or debug if not:

```
function my_debug($data, $label = NULL, $print_r = FALSE) {
  if (function_exists('dsm')) {
    dsm($data, $label);
  }
  else {
    debug($data, $label, $print_r);
  }
}

```

But keep in mind that you should avoid any debug code in production.

---
Tags: debugging
---


title: PHP code to check for required fiels

text:
# Question
Title: PHP code to check for required fiels
I'm using the Rules module in my Drupal site to do the following:

* when an existing user logs in
* check if there are required fields of the user account that have no value yet
* redirect to the user page and show a message

This is necessary, because we have added required fields to the user account. My problem is with the second step. I can add a check for every required field, but would like to use a more generic approach.

What I'm looking for is PHP code to check if the current logged in user has required fields that are empty.

I am a developer but in .NET and have no PHP knowledge, though I'm willing to learn and I'm confident I'll pick up quickly.

# Answer
> 0 votes
Turns out there is a module that handles this perfectly: Complete Profile. That's the one I use, but there's also Profile Fields Force Filling.

# Answer
> 0 votes
Here is how its done:

First create a new rule then,

```
**Events**
-User has logged in

```

```
**Condition**
-Data Value is empty

```

you have to enter the value u want to check, something like site:current-user:field-skills make sure to change field-skills to the field name you want to check.

```
**Actions**
-Show a message on the site
"enter the message you want"
-page redirect
"enter uri to redirect to"

```

here is an export of the rule:

```
{ "rules_check_required_fields" : {
"LABEL" : "Check required fields",
"PLUGIN" : "reaction rule",
"REQUIRES" : [ "rules" ],
"ON" : [ "user_login" ],
"IF" : [
  { "data_is_empty" : { "data" : [ "site:current-user:field-skills" ] } }
],
"DO" : [
  { "drupal_message" : { "message" : "Field skills is empty", "type" : "warning" } },
  { "redirect" : { "url" : "\u003Cfront\u003E" } }
]

```

} }

---
Tags: rules, users
---


# Question
Title: How do I write to location field in an Entity?
I am having a custom entity called Micronews which has a bundle microupdate created in it. I am able to write entity to db for all fields but I am not able to figure out how to write location (using location module). It seems to be stored in db in multiple tables. Is there any standard way to store location to db?

```
function p_save_entity($name, $issue_type, $constituency, $location){

$name = "Testing programmatically";
$issue_type = "electricity";
$constituency = '22';

$e = entity_create('micronews', array(
    'type' => 'microupdate',
    'name'=>$name,
    'created'=> time(),

));

$ew = entity_metadata_wrapper('micronews' ,$e);

$ew->field_type->set($issue_type);
$ew->field_constituency->set($constituency);

$ew->field_location[latitude]->set('65.000000');
$ew->field_location[longitude]->set('65.000000');

$fl = $ew->save();

if ($fl){
    return "";
}

else{
    return "Something went wrong";
}

```

I am using this module.

# Answer
This works, but (here's the trick), only if you enable the location\_entity module, which ships with location.

```
$location = array(
  'latitude' => $latitude,
  'street'   => $street,
  // etc, other elements added here ...
);

$ew->field_location->set($location);
$ew->save();

```

May no one else lose as much time on this ever again.
> 3 votes

# Answer
I would reference `location.test` in the modules folder. Specifically something like testCreateLocation().

That code does the following for a location field:

```
 135     $node = $this->drupalCreateNode(array(
 136       'type' => $location_type,
 137       'field_loctest' => array(
 138         array(
 139           'name' => $location1_name,
 140           'street' => '48072 289th St.',
 141           'province' => 'SD',
 142           'country' => 'us',
 143   //        'location_settings' => $settings,
 144         ),
 145       ),
 146     ));
 147     cache_clear_all();
 148
 149     // Reload the node.
 150     $node2 = node_load($node->nid, NULL, TRUE);
 151     $location = $node2->field_loctest[0];
 152
 153     $this->assertEqual($location1_name, $location['name'], t('Testing basic save/load'));

```

Using an entity wrapper it *might* be like (given that Location can be from different pieces of data, the test uses Street, your using Lat/Longs):

```
$ew->field_location->set(array(array('latitude' => 65.000000, 'longitude' => 34)));

```

I've used EntityAPI and wrappers before, but I dont do it all the time to have it all memorized. I found this other link helpful: What is the purpose of the entity\_metadata\_wrapper() function, and why should I use it?

If you follow the links on the above EntityAPI thread you see they build a `$profile_object` using nested arrays ...
> 1 votes

# Answer
Late response, but figured it'll help someone.

The "unknown data property field\_location" happens to me as well. I thought it was due to the entity not yet having been initialized. But creating the entity and resetting the wrapper had no effect. The following workaround solves the problem:

```
$entity->{$drupal_field}['und'][0] = $location;
// This seems to be necessary
$entity->locations[0] = $location;
$resp = entity_save('node', $entity);
if ($resp == false) {
    // do something
}

```
> 0 votes

---
Tags: 7, location, entities
---


title: Simultaneous Database Connections

text:
# Question
Title: Simultaneous Database Connections
I have two databases set in my settings.php file. One is used for drupal, one is for our backend which is external from the drupal installation and databases. I would like to query the backend database but cannot change the db\_active because then our site users will have issues accessing their profiles. How can I go about connecting to the two databases simultaneously?

# Answer
> 2 votes
I think you are inventing a problem that doesn't exist.

The active database will be per-request, not site wide. So if one user is accessing your backend, another user can do whatever they need against your default Drupal database.

Within a request, you can use the `db_set_active()` function to switch databases as much as you want. eg

```
$query = db_query(...);   // runs against the default database
db_set_active('backend'); // change databases
$query = db_query(...);   // runs against $databases['backend'];
db_set_active();          // change back to default databases
$query = db_query(...);   // runs against the default database

```

As PHP is single threaded w/in a single request, you don't have to worry about a query running against the wrong database.

So, in summary, just use `db_set_active()` to change databases when you need to, and then remember to switch back when you are done. If you isolate your code (which you really need to do in Drupal anyway), you shouldn't run into trouble.

I would also look into `hook_views_data()`. This works very well to being in external data into Drupal.

---
Tags: database
---


# Question
Title: Why is menu item for custom module not showing?
I'm new to Drupal and about to write my first custom module ("configurator") with help of the drupal documentation.

I've implemented the **menu hook**:

```
function configurator_menu()
{
    $items = array();
    $items['configurator'] = array(
        'title' => 'Configurator',
        'page callback' => 'configurator_init',
        'access callback' => TRUE,
        'type' => MENU_CALLBACK,
     );
     return $items;
}

function configurator_init()
{
    return "<p> Hello World </p>";
}

```

At "Administer \> Site Building \> Modules" the module is shown and activated. Cache has been cleared, but somehow the menu item for my "configurator" module is not showing up.

Why?

# Answer
You've either forgotten to set the `menu_name` key for the menu you want to add the link to:

```
$items['configurator'] = array(
  'title' => 'Configurator',
  'page callback' => 'configurator_init',
  'access callback' => TRUE,
  'type' => MENU_CALLBACK,
  'menu_name' => 'primary-links',
);

```

Or you want to use the default ('navigation'), but you're using the wrong type. It should be

```
$items['configurator'] = array(
  'title' => 'Configurator',
  'page callback' => 'configurator_init',
  'access callback' => TRUE,
  'type' => MENU_NORMAL_ITEM,
);

```

`MENU_CALLBACK` is:

> Callbacks simply register a path so that the correct function is fired when the URL is accessed. **They are not shown in the menu.**

Emphasis mine.
> 3 votes

---
Tags: 6, routes
---


# Question
Title: Responsive not working after converting html theme to Drupal theme
While trying to convert a HTML responsive theme to Drupal 7 theme, it's responsive is not working!!!

Can anyone help me with this to sort the issue? We have copied Bartik theme and removed the CSS and pasted the HTML5 theme CSS and JS that we created. changed the `index.tpl` into `page --front.tpl.php` and copied it into the template folder. In the `page-- front.tpl.php` we give all the path for CSS and JS as:

```
<?php $path="http://".$_SERVER['HTTP_HOST']; ?>
<link rel="icon" href="$path.">
<link rel="shortcut icon" href="images/favicon.ico" />
<link rel="stylesheet" href="<?php echo $path.base_path().path_to_theme()?>/css/style.css">.

```

"As specified we gave path for all CSS and JS files, but don't know where we went wrong!!"

# Answer
To create or convert a Drupal 7 responsive theme, it is *not* a good idea to start with stripping down and modifying a fully developed, non-responsive theme such as Bartik.

Instead you start out with a responsive starter theme or base theme framework, where the css is already reset for you and where the the framework is already prepared for you to add your own classes to construct whatever look and feel you're after. Basically, you install your framework, then create a sub-theme, and use that you build your own responsive theme.

Good foundations for this is IMHO Zen, Omega or AdaptiveTheme (suggested by @Kojo in a comment), but many other alternatives exist.
> 1 votes

# Answer
For converting HTML templates into Drupal templates you have to follow the given steps :

**Starting your page**

**If you're using Drupal 5:**

" xml:lang=""\>

**If you're using Drupal 6:**

language ?\>" xml:lang="language ?\>" dir="dir ?\>"\>

**If you're using Drupal 7:**

If you are using Drupal 7, your page.tpl.php file starts after the tag and end before the tag, so you do not need to worry about the doctype, html, or head tags. If you'd like to override these, copy the html.tpl.php file from your modules/system folder and make whatever changes you'd like.

The section of your site

In the above section given how we can convert HTML template into Drupal theme templates please refer this link for more info https://drupal.org/node/313510
> 0 votes

# Answer
You can probably start with whatever theme you like, certainly some require more work then others if you're looking for a sensible set of base styles and a nice grid system.

However, I suspect, your main issue is the them you're starting with is missing the meta tag to set the zoom level on a device. If you're checking this on a computer's browser then it's something in the css. What does dev tools tell you? Something has to have a fixed width applied to it if it is overflowing your desktop browser window.
> 0 votes

---
Tags: theming
---


# Question
Title: Add field to node without new content type
I need to create a field for a specific node, but I really don't want to create a new content type, for various reasons...

Is there a module that does that?

Say I wanted to create my own module that does that, how do you recommend I approach this?

# Answer
A field of the Field API is meant to be used in an entity. Nodes are specific types of entities, such as users are. Fields are attached to specific bundles of an entity. Content types for nodes are the bundles of the nodes entities. If an entity type does not support bundles, such as users, then fields are bound to the entity regardless. For more on the subject see Drupal.org: An introduction to Entities.

As such, a field is not designed to belong to a particular entity but rather to an entity type/bundle (briefly, not designed to belong, meaning that the database design and programming logic as is would not support something like that).

So to sum up, it would require some considerable coding effort to achieve something like this and it would be advised to reconsider your design to take into account those factors.
> 1 votes

---
Tags: 7, entities
---


title: Drupal 6 / No access to admin

text:
# Question
Title: Drupal 6 / No access to admin
There's a Drupal6 website I need to work on for a cliente. However, client does not have access to the admin. They don't remember their user/password.

What's the best way for me to retrieve the admin access besides the "remember password" feature?

Thanks a lot!

Johann

# Answer
> 3 votes
You can reset it directly in the db, if you have access to it?

UPDATE users SET PASS = md5('new\_pass') WHERE uid = 1

# Answer
> 1 votes
You can use drush to do so. Execute `drush upwd admin --password=YOURNEWPASSWORD` where `admin` is the username.

---
Tags: users
---


title: Associating Custom LDAP Query with View

text:
# Question
Title: Associating Custom LDAP Query with View
Versions: -\>Drupal 7.10 -\>LDAP Authentication/Authorization/Servers/Query/Views 7.x-1.0-beta5 -\>Views/Views UI 7.x-3.3

---

I'm attempting to configure a View via the Views UI module to support a custom LDAP query defined in the LDAP Query module. The example they provide depends on the existence of a query with the machine name of "ad\_users", and does function when I define a query with that name, but there doesn't seem to be a way to alter this or point a view toward an arbitrary query.

I'm wondering if I'm overlooking something. It seems illogical that the Views plugin wouldn't let one point a View toward an arbitrary LDAP Query. The question is how to do this?

# Answer
In the *Advanced* section of the view, click on *Query Settings* and choose your own LDAP Query from the select list that appears.
> 2 votes

# Answer
Assuming that you have a successful connection to an LDAP server and you have added an LDAP Query to build your view on.

Just like cafuego said first make sure to select the LDAP Query to use for the view in the view settings dialog.

Within the view add an "LDAP Query: LDAP Attribute" field and select the attribute to add from the LDAP Query Attribute Dialog.

If you are have issues then try changing the Query Settings and saving the view again. I had to do this in order for my view to start pulling correctly.
> 0 votes

---
Tags: views, authentication-authorization
---


# Question
Title: How to archive old orders in Drupal Commerce
I have a site with more than 15000 commerce orders. This is slowing down the site drastically. I have upgraded all the modules and applied the patches regarding the table locking and so on. They haven't been of much help.

I am ok with removing the order history from the site. I just want to keep an archive of that so that I can use them once I have enough resources to handle everything.

I am not able to get the site up. Hence I will have to do all the work from the command line. So is there any safe and suggested way to archive the orders?

# Answer
> 0 votes
Couldn't you just backup your database using phpmyadmin, doing a .mysql export of the whole database which would keep record of all orders in the `commerce_order` and `commerce_customer_profile` tables?

Then using phpmyadmin, just remove all rows from the `commerce_order` table, to wipe the slate clean.

In the future, if you wanted to add all orders back into the site, you could import the data from your backup.

---
Tags: commerce, views
---


title: Drupal 6 on MAMP

text:
# Question
Title: Drupal 6 on MAMP
So there's a site I need to redesign for a client. This website is currently in Drupal 6 (yes I know). I've installed a copy of this website in my computer using MAMP and I am able to run the website without problem.

However, all image files are broken. I've checked the path and they are pointing to:

```
http://localhost:8888/sites/all/themes/mytheme/images/image.jpg

```

instead of

```
http://localhost:8888/mywebsite/sites/all/themes/mytheme/images/image.jpg

```

Is there something I need to change in the Drupal admin in order to re-assign the correct image path? Some configuration I might be missing? There are a lot of images so manually doing this would be a pain.

Thanks a lot for your help!

# Answer
> 2 votes
It could potentially be solved by just adding a Virtualhost in your httpd.conf

In `/Applications/MAMP/conf/apache/httpd.conf`, add the following Virtualhost to the very bottom.

```
<VirtualHost *:80>
  ServerName mywebsite.sandbox
  DocumentRoot /path/to/mywebsite/on/Mac
  <Directory /path/to/mywebsite/on/Mac>
    Options FollowSymLinks
    Order allow,deny
    Allow from all
  </Directory>
  ErrorLog /var/log/apache2/mywebsite-error.log
  CustomLog /var/log/apache2/mywebsite-access.log combined
</VirtualHost>

```

The path, for example, would be the absolute path on your computer. So if you keep all of your sites in a Development folder in your Documents, it would look something like this.

```
/Users/USERNAME/Documents/Development/mywebsite

```

In `/etc/hosts`, add the server name.

```
127.0.0.1 mywebsite.sandbox

```

Restart MAMP and you should be good to go using `http://mywebsite.sandbox`

# Answer
> 0 votes
Thats just because every image they have referenced has an src beginning with "/sites/..." so the preceding slash before the sites will be going to the root.

I guess you have to either sit your whole site on the root of your local host, to match the src of the images, or during development, copy the image directory into a sites folder on the root.

It isn't something you can change in Drupal settings to change all image paths, as they will have probably written the img src themselves, instead of the files being in the default /sites/default/files directory.

# Answer
> 0 votes
The dirty answer is to make a `symlink` to the 'mywebsite/sites/all...' directory from the root of your MAMP install (the link called 'sites' of course). You may need to alter your Apache config to allow symlinks to be followed.

A slightly more elegant solution, but much more of a headache is to use rewrites in your Apache config to send a URL matching 'sites/all...' to 'mywebsite/sites/all...'.

You could also modify the `$base_path` global for Drupal, but you would need to do this before any other bootstrap processes, which would require a core hack (you do not want to do this), and would mean you would have to remember to change it everytime you updated and/or change it back once you finished developing. Again, you do not want to do this.

Most people using Drupal for their websites have only Drupal running their website, no static content, or images, css, js, or other files outside of the Drupal framework. It seems as though only developers need/want/have to think about these issues ... le sigh :(

---
Tags: media, path-aliases
---


title: Rules - event stopped triggering itself

text:
# Question
Title: Rules - event stopped triggering itself
I have two questions, both related to rules

1) It seems, all of a sudden and no idea why, 'When an order is first paid in full' is not triggering anything. I have a custom payment method, which worked fine till today. I can confirm that commerce\_payment\_transaction\_save works and updates the order with payment information and status changes to 1. So I don't know why 'paid in full' event stopped working. I am still able to trigger 'Completing the checkout process' event without problem.

2) Is there any module or perhaps an existing devel configuration that would allow to see rules log? Or debug by rules/events/actions?

# Answer
> 0 votes
Rules has its own set of debugging options. Using Drupal 7? Try `/admin/config/workflow/rules/settings` and then check your recent log messages at `/admin/reports/dblog`. As a last resort, it might help to print some manual code just so you know that the rule is being triggered.

More info on debugging Rules: https://drupal.org/node/1593278

---
Tags: commerce, rules
---


# Question
Title: How to translate inline entity form nodes (or, product variations in kickstart)
My parent nodes need to be translatable - so i'm slated to use the out-of-the box internationalization module for that. However, one of the fields in this content type is an inline entity field which references another content type. Both the parent and the referenced nodes need to be translatable.

Now, is this a job for entity translate? I've tried with no success - but perhaps i'm not using the right combination. Presently if I set both the parent and child nodes to entity translate types I get an ajax error when I try to add the first child node (regardless of which fields are setup).

# Answer
> 1 votes
I'm not 100% sure on the setup, but I just finished a site that dealt with a similar circumstance. It uses String Overrides to perform targeted text changes, and if it doesn't support Internationalization by default then there's a module that provides additional tabs at `/admin/config/regional/stringoverrides` for each enabled language.

For reference, here's the translation module list currently enabled on the site:

```
Locale
String Overrides
Entity Translation
Entity Translation Upgrade
Block languages
Contact translation
Field translation
Internationalization
Menu Translation
Multilingual content
Rules Translation
Synchronize Translations
Translation Sets
Views Translation
Variable

```

Not all of these modules are required to make this happen, but perhaps you can compare your own setup to this list and find some differences. Apologies for not remembering how to set this up.

**UPDATE ::** *Process for enabling translation within String Overrides*

== Modules ==

* Internationalization :: link | download
* String Overrides :: link | download
* Variable :: link | download

1. Enable Modules:

    + Locale
        + Variable
        + Internationalization
        + String Overrides
        + String Translation
    2. Add a new language

    + /admin/config/regional/language/add
        + Select, click "Add language"
    3. Add translations for alt language strings

    + /admin/config/regional/stringoverrides, click desired language in top right
        + Add rows for each desired string, place original language text in left box and translated string in right box
        + Save, view on front end

The final interface should look something like the following cap:

---
Tags: commerce, i18n-l10n
---


title: db_query returning blank page

text:
# Question
Title: db_query returning blank page
I've been stuck on this problem for a while now. I am trying to get the results to display from the api if there are no entries in the db that match the id thats being called from the api and then store those results into the db if there is a Id that matches then pull the results from the db and display them instead of displaying the results from the db.

I keep running into this error which is causing the page to go blank when being displayed `PDOException: SQLSTATE[42S22]: Column not found: 1054 Unknown column '29f1fc0bbd3dfe65a9e0ba6e044fb8e3398967a3' in 'where clause': SELECT * FROM {places} Where {ID} = 29f1fc0bbd3dfe65a9e0ba6e044fb8e3398967a3;` I guess its because it cant find the id in the db, but it should still show the results from the api.

My logic makes sense im not sure what I am missing, Any suggestions?

```
       $listings_key = 'xxxxxxx';
            $xml = file_get_contents('https://maps.googleapis.com/maps/api/place/textsearch/xml?query=loans+near+'.$city_name.'&sensor=true&type=bank&key='.$listings_key.'');
            $listings_request = simplexml_load_string($xml);

            $loans_places = '';
            $loans_places .= '<div class="city-listings-wrapper">';

            foreach($listings_request->result as $pre_list){
                $xml2 = file_get_contents('https://maps.googleapis.com/maps/api/place/details/xml?reference='.$pre_list->reference[0].'&sensor=true&key='.$listings_key.'');
                $xml2 = simplexml_load_string($xml2);
                $l_ID = reset($xml2->result->id[0]);

                $dbresult = db_query("SELECT * FROM {places} Where {ID} = ".$l_ID."");

                foreach($dbresult as $db_inlist){

                    dpr($db_inlist);

                    $places = array(
                        'Name'      => $xml2->result->name[0],
                        'Address'   => $xml2->result->adr_address[0],
                        'Phone'     => $xml2->result->formatted_phone_number[0],
                        'Website'   => $xml2->result->website[0],
                        'Ref_ID'    => $xml2->result->reference[0],
                        'ID'        => $xml2->result->id[0],
                        'City'      => ucwords(arg(2)),
                        'State'     => arg(1)
                    );

                    if($l_ID != $db_inlist->ID){
                        $loans_places .= '<div class="city-listings">';
                        $loans_places .= '<b>'.$xml2->result->name[0].'</b></br>';
                        $loans_places .= $xml2->result->adr_address[0].'</br>';
                        $loans_places .= (isset($xml2->result->formatted_phone_number[0]) ? $xml2->result->formatted_phone_number[0].'</br>' : '');
                        $loans_places .= (isset($xml2->result->website[0]) ? l('website', $xml2->result->website[0]).'</br>' : '');
                        $loans_places .= '</div>';

                        //execute store into db function
                        $nid = db_insert('places')->fields($places)->execute();

                    }else{
                        $loans_places .= '<div class="city-listingsdb city-listings">';
                        $loans_places .= '<b>'.$db_inlist->Name.'</b></br>';
                        $loans_places .= $db_inlist->Address.'</br>';
                        $loans_places .= (isset($db_inlist->Phone) ? $db_inlist->Phone.'</br>' : '');
                        $loans_places .= (isset($db_inlist->Website) ? l('website', $db_inlist->Website).'</br>' : '');
                        $loans_places .= '</div>';
                }
            }
        }

    $loans_places .= '</div>';

return $loans_places;

```

# Answer
You're currently escaping a bit too much...you only need to use the `{}` placeholders for table names. With an extra small change to protect you from SQL injection, your code should be something like:

```
$args = array(':id' => $l_ID);
$dbresult = db_query("SELECT * FROM {places} Where ID = :id", $args);

```
> 2 votes

---
Tags: 7, database
---


# Question
Title: Showing different nodes for same taxonomy terms on different URLs
I'm facing this design issue regularly.

For example I've Jobs and Company node types. Both have one common taxonomy term reference field City.

Now when we go to a City term it will show both Jobs and Companies(I don't want this mixing).

I want that it show only Jobs or Companies(in different URL's)

One solution is to duplicate City vocabulary as City Jobs and second as City Companies. Now I get what I want. But in programming it'll complicate as same city in both Vocabularies will have different term id's.

**What is the best way to achieve this?**

# Answer
> 9 votes
You can use the Views module to create two different pages:

* "Jobs in City %1" at /jobs/%
* "Companies in City %1" /companies/%

Your Views will need a filter for content type, and a contextual filter for taxonomy term. Next, use the Rabbit hole module to make the /taxonomy/term/NNN pages disappear.

# Answer
> 1 votes
1. You can create a view based on City term title

Fields : Taxonomy term: Name -\> Configure field: Taxonomy term: Name -\> REWRITE RESULT -\> Output this field as a link -\> taxonomy/term/\[tid\]/job
2. You can use the view module to create two different pages:

a. view -\> Page settings -\> path -\> taxonomy/term/%/job

b. Contextual filters add Content: Has taxonomy term ID (with depth) and Content: Has taxonomy term ID depth modifier

c. Content: Type (= job)

a1. view -\> Page settings -\> path -\> taxonomy/term/%/company

b1. b. Contextual filters add Content: Has taxonomy term ID (with depth) and Content: Has taxonomy term ID depth modifier

c1.Content: Type (= company)

when You click Taxonomy term: Name (title) based on URL like taxonomy/term/1/job that redirect to taxonomy/term/%/job view page that return group of job content.

similarly group of company list

# Answer
> 1 votes
Dylan Tack's answer is the right and the easiest way to achieve this functionality; If you don't want to use Views module you can solve this by custom module, like this (I didn't test it, correct it, if something is wrong with it):

```
function myModule_menu() {
  $items = array();

  $items['jobs/%taxonomy_term'] = array(
    'title' => 'Jobs',
    'page callback' => 'custom_page_by_jobs',
    'page arguments' => array(1),
    'access arguments' => array('access content'),
    'type' => MENU_CALLBACK,
  );

  $items['companies/%taxonomy_term'] = array(
    'title' => 'Companies',
    'page callback' => 'custom_page_by_companies',
    'page arguments' => array(1),
    'access arguments' => array('access content'),
    'type' => MENU_CALLBACK,
  );

  return $items;
}

// Mimic of taxonomy_select_nodes() function;
function taxonomy_select_nodes_by_type($tid, $type, $pager = TRUE, $limit = FALSE, $order = array('t.sticky' => 'DESC', 't.created' => 'DESC')) {
  if (!variable_get('taxonomy_maintain_index_table', TRUE)) {
    return array();
  }
  $query = db_select('taxonomy_index', 't');
  $query->join('field_data_field_city', 'fdfc', 't.tid = fdfc.field_city_tid');
  $query->addTag('node_access');
  $query->condition('t.tid', $tid);
  $query->condition('fdfc.bundle', $type, '=');
  if ($pager) {
    $count_query = clone $query;
    $count_query->addExpression('COUNT(t.nid)');

    $query = $query->extend('PagerDefault');
    if ($limit !== FALSE) {
      $query = $query->limit($limit);
    }
    $query->setCountQuery($count_query);
  }
  else {
    if ($limit !== FALSE) {
      $query->range(0, $limit);
    }
  }
  $query->addField('t', 'nid');
  $query->addField('t', 'tid');
  foreach ($order as $field => $direction) {
    $query->orderBy($field, $direction);
    list($table_alias, $name) = explode('.', $field);
    $query->addField($table_alias, $name);
  }
  return $query->execute()->fetchCol();
}

function custom_page_by_type($term, $type) {
//  drupal_set_title($term->name);
//
//  $current = (object) array(
//    'tid' => $term->tid,
//  );
//
//  $breadcrumb = array();
//  while ($parents = taxonomy_get_parents($current->tid)) {
//    $current = array_shift($parents);
//    $breadcrumb[] = l($current->name, 'taxonomy/term/' . $current->tid);
//  }
//  $breadcrumb[] = l(t('Home'), NULL);
//  $breadcrumb = array_reverse($breadcrumb);
//  drupal_set_breadcrumb($breadcrumb);
//
//  $uri = entity_uri('taxonomy_term', $term);
//  drupal_add_html_head_link(array('rel' => 'canonical', 'href' => url($uri['path'], $uri['options'])), TRUE);
//
//  drupal_add_html_head_link(array('rel' => 'shortlink', 'href' => url($uri['path'], array_merge($uri['options'], array('alias' => TRUE)))), TRUE);

  $build['term_heading'] = array(
    '#prefix' => '<div class="term-listing-heading">',
    '#suffix' => '</div>',
    'term' => taxonomy_term_view($term, 'full'),
  );

  if ($nids = taxonomy_select_nodes_by_type($term->tid, $type, TRUE, 20)) {
    $nodes = node_load_multiple($nids);
    $build += node_view_multiple($nodes);
    $build['pager'] = array(
      '#theme' => 'pager',
      '#weight' => 5,
    );
  }
  else {
    $build['no_content'] = array(
      '#prefix' => '<p>',
      '#markup' => t('There is currently no content classified with this term.'),
      '#suffix' => '</p>',
    );
  }
  return $build;
}

function custom_page_by_jobs($taxonomy_term) {
  return custom_page_by_type($taxonomy_term, 'jobs');
}

function custom_page_by_companies($taxonomy_term) {
  return custom_page_by_type($taxonomy_term, 'companies');
}

```

# Answer
> 1 votes
Simple:

* Go to Views administration page: `admin/structure/views`
* Scroll down and **clone** *Taxonomy term* view.
* Under **Page Settings** change path to: `/taxonomy/term/%/%`
* Add new contextual filter under Advanced section
* Select **Content: type** and apply default settings
* **Rearrange** contextual filters so that the order is:
    1. Content: Has taxonomy term ID (with depth)
    2. Content: Type
    3. Content: Has taxonomy term ID depth modifier
* That's it

If you visit the term page `taxonomy/term/%term`, you will still see all content types in a list. However, you can now filter this list with the name of the content type, for example:

* `taxonomy/term/%term/jobs`: will only list the jobs tagged with this term
* `taxonomy/term/%term/company`: will only list the companies tagged with this term.

---
Tags: taxonomy-terms
---


# Question
Title: Webform - Validating File Upload with PHP
How can I validate, via Webform module (using Webform file upload in Drupal 7) whether the file has been uploaded or not?

How can I handle and reference those files?

Seems that normal FAPI calls don't work (e. g. `file_save_upload('file1')` returns a non-true value if I have a file field).

I see that Webform file fields upload the file BEFORE form submission (i. e. clicking "upload to server" adjacent button).

I don't know if that's the normal file-upload behavior or it's a specific behavior.

How can I handle the files in that way? I need to validate if at least one of those fields was uploaded (assume they are named foto1, foto2, foto3, foto4), and later I need to reference those files (e.g. getting a public link to them).

# Answer
> 1 votes
Found it -.-''.

`$form_state['values']['submitted']['foto1']` returns integer 0, which is a "no file" id, instead of another value (webform for Drupal 7 currently returns a numeric string as id). File extension validation and other rules have been executed beforehand, and finally the obtained id can be loaded with `webform_get_file($form_state['values']['submitted']['foto1'])`, obtaining a `managed_file` entity (actually, as a stdClass instance).

This is the result of DPM-ing the four fields using dev tools in Drupal 7, where foto4 is not filled. The four entries correspond to calls to `webform_get_file($form_state['values']['submitted']['foto1'])` to foto4-corresponding field path.

---
Tags: 7, forms, webforms
---


# Question
Title: How to count elements grouped by an specific field?
I have a view with elements grouped by some categories, I would like to add the number of elements grouped in the same category, something like this:

## Categ A (2)

* element
* element

## Categ B (3)

* element
* element
* element

I tried with aggregations but I didn't get the result I was looking for. Is there any way to resolver this?

# Answer
You can use Views Aggregator Plus for this.
> 0 votes

---
Tags: views
---


title: Using tokens with entities?

text:
# Question
Title: Using tokens with entities?
I'd like to be able to use tokens with entities, similar to how they work for node right out of the box with core. However, for whatever reason, entity tokens are not available to me even though I have Entity API and Entity Token enabled.

Is there something that needs configuration? I see no way to configure Entity Token.

# Answer
> 0 votes
The problem was that theme\_token\_tree($variables) was being passed only a subset of available tokens. Just a gotcha to look out for if you haven't done work with the token tree before.

```
$variables = array('token_types' => array('nodes','comments'), 'global_types' => FALSE);
theme_token_tree($variables);

```

I needed to add additional token types to the token types array, like so:

```
$variables = array('token_types' => array('nodes','comments','bean'), 'global_types' => FALSE);
theme_token_tree($variables);

```

You can also go to /admin/help/token to get a list of all available tokens. Be warned though, unless you have enough memory allocated to MySQL it could consume all of it and give you a "MySQL gone away" error. I received that error and I upped mine to 500MB locally and it was fine after that.

---
Tags: tokens, entities
---