title: URL permissions

text:
# Question
Title: URL permissions
I have some nodes which I want to hide from anonymous users when they access via a direct URL e.g. /node/1275.

However if someone accesses this via the URL alias which is an md5 hash I want to allow anonymous users to access it. This is so that the node is essentially available only to people I give the link to.

How would I achieve this? Ideally I'd like to avoid installing more modules.

---

EDIT:

Here's the complete solution that I used in my custom module. As well as the access check it contains a new filter type that generates a md5 for each node, which you can use in the URL alias patterns page.

```
 /**
 * Implements hook_menu_alter
 */
function newsletter_access_menu_alter(&$items){
  $items['node/%node']['access callback'] = 'newsletter_access_check_node_access';
}

/**
 * Custom menu access callback for node/%node
 */
function newsletter_access_check_node_access($op, $node){

  // Note $op and $node are passed in default node_menu access arguments
  if ($op == 'view' && isset($node->nid)) {
     if($node->type == "newsletter") {
            // Allow access to anon if request_uri contains specific hash
            if (!user_is_logged_in()) {
              $hash = md5(drupal_get_private_key() . $node->nid);
              // request_uri includes alias
              $request = explode('/', request_uri());
              if (in_array($hash, $request)) {
                return TRUE;
              } else {
                return FALSE;
              }
            }
        }
      }
  // Fallback to allow regular node_access checks
  return node_access($op, $node);
}

function newsletter_access_token_info() {
  $types['my_tokens'] = array(
    'name' => t("My Tokens"),
    'description' => t("My Token Category"),
  );

  $tokens['my_md5'] = array(
    'name' => t("Unique MD5 Hash"),
    'description' => t("The md5 hash unique for each node."),
  );

  return array(
    'types' => $types,
    'tokens' => array(
      'my_tokens' => $tokens,
    ),
  );

}

function newsletter_access_tokens($type, $tokens, array $data = array(), array $options = array()) {

  $replacements = array();

  if ($type == 'my_tokens') {
    foreach ($tokens as $name => $original) {
      switch ($name) {
        case 'my_md5':
          $replacements[$original] =  md5(drupal_get_private_key() . $data['node']->nid);
        break;
      }
    }
  }

  return $replacements;
}

?>

```

# Answer
You could do something like

```
/**
 * Implements hook_menu_alter
 */
function MY_MODULE_menu_alter(&$items){
  $items['node/%node']['access callback'] = 'MY_MODULE_check_node_access';
}

/**
 * Custom menu access callback for node/%node
 */
function MY_MODULE_check_node_access($op, $node){
  // Note $op and $node are passed in default node_menu access arguments
  if ($op == 'view' && isset($node->nid)) {
    // Allow access to anon if request_uri contains specific hash
    if (!user_is_logged_in()) {
      $hash = md5(drupal_get_private_key() . md5($node->nid));
      // request_uri includes alias
      $request = explode('/', request_uri());
      if (in_array($hash, $request)) {
        return TRUE;
      } else {
        return FALSE;
      }
    }
  }
  // Fallback to allow regular node_access checks
  return node_access($op, $node);
}

```
> 4 votes

# Answer
Have you tried in the template.php? what if you do something like:

```
function yourtheme_preprocess_page(&$variables, $hook){
   if((arg(0) == 'node') && (!$user->uid)){
      //redirect
   }
}

```
> 0 votes

---
Tags: uri, users
---


title: Facebook Album fetcher

text:
# Question
Title: Facebook Album fetcher
I am using facebook album fetcher module. It shows an error message

> An unknown error occurred while trying to fetch the album (empty reply).

Can anyone tell me how to resolve this issue.

# Answer
> 0 votes
The author of the module Facebook Album Fetcher has already posted a reply to a similar/identical problem that was posted in drupal.org. The general idea is that if you have followed the 10 steps that are described in the module page, you should log in to your facebook account and make sure that the album that you are trying to fetch is actually public.

---
Tags: 7
---


title: How to order a database query

text:
# Question
Title: How to order a database query
In Drupal v7.22 I'm trying to order the query below for a custom module but I cannot seem to find documentation that fits this query.

```
$sql = "SELECT field1, field2 FROM {tablename} WHERE field3 = :var1 AND field4 = :var2";
$result = db_query($sql, array(':var1' => $var1, ':var2' => $var2));
$num = $result->rowCount();
if ($num != null) {
  foreach($result as $line) {
    // Do something
  }
}

```

I've found details on 'orderBy' but only with examples as below which are not in the same format as my query. Any help would be appreciated.

```
$query->groupBy("thread.sid");
$query->having("MAX(comment.created)");
$query->orderBy("comment.created", "DESC");
$result = $query->execute();

```

# Answer
> 3 votes
Something like:

```
$query = db_select('tablename');
$query->fields('tablename', array('field1', 'field2'));
$query->condition('field3', $var1);
$query->condition('field4', $var2);
$query->orderBy('field1', 'DESC');

$result = $query->execute();

foreach($result as $row){
  // Debug
  drupal_set_message('<pre>'.print_r($row,1).'</pre>');
}

```

More info:

---
Tags: database
---


# Question
Title: Can Commerce be setup to skip Cart/Customer
Can the module Drupal Commerce (7.x-1.7) be setup so that a user can just click 'Buy' on an item and then be taken to a payment processor such as Paypal to pay? I've tried to find a way to do this but the Commerce set of modules is just a little overwhelming at the moment. I need to be able to do this as I'm selling a virtual currency to my users and they are used to a quick process and they don't wish to give out billing information.

# Answer
> 2 votes
Yes, it's possible but would need testing out and tinkering.

You could disable the checkout pages, other than payment / offsite payment redirect

Either at

You could then add a Rule

* *Event: After adding product to cart*
* *Action: Redirect to page "checkout"*

Which will hopefully take the user off to PayPal / offsite payment.

Again, needs testing, but theoretically possible.

---
Tags: commerce
---


# Question
Title: Globally rewrite broken image links in node bodies
I'm migrating my site from Drupal 6 to Drupal 7, and while most of it just worked after migration, the change from the Image module to the core image handling left a large number of broken images on the site.

Images that were inserted in the node body were not handled at all by the migration, and the links are now in an invalid format. Fortunately, fixing those links is pretty straightforward, I just need to change

```
http://mysite.com/sites/default/files/images/[image-name].[style].jpg

```

to

```
http://mysite.com/sites/default/files/styles/[style]/public/images/[image-name].jpg

```

This looks like it should be relatively straightforward to do, but I didn't find an easy way to do this replacement. I found the Search and Replace Scanner module, but that doesn't seem to allow using parts of the original match in the substitution.

How can I fix these image links all at once without having to do it manually?

# Answer
> 1 votes
Assuming MySQL, you can fix that up with a search and replace SQL query.

Perhaps easiest from the MySQL command line, though could also use db\_query.

The pattern is:

```
UPDATE tablename SET fieldname = REPLACE(fieldname, 'search', 'replace');

```

Something like:

```
UPDATE field_data_body SET body_value = REPLACE(body_value, 'sites/default/files/images/', 'sites/default/files/styles/[style]/public/images/');

UPDATE field_revision_body SET body_value = REPLACE(body_value, 'sites/default/files/images/', 'sites/default/files/styles/[style]/public/images/');

```

Backup the database first.

You may need to do it one image style at a time, or else make all the images uses a new standard style.

More info: http://dev.mysql.com/doc/refman/5.0/en/string-functions.html#function\_replace

---
Tags: media
---


title: API to localize a path?

text:
# Question
Title: API to localize a path?
I'm searching for a way to get all localized paths for one path.

For non-content pages this is quite simple:

```
foreach (language_list() as $language)
  $paths[$language->language] = url(current_path(), array('language' => $language));
}

```

For content pages (node, taxonomy, …) the path might be completely different and things like translation\_path\_get\_translations() seem more like what I need.

Is there a reliable way to get paths to all translations of a page that works whether it's a content-page or not? It feels like there has to be an API-function for that.

# Answer
I finally found out about `language_negotiation_get_switch_links($type,$path)`. The tricky part is the `$type` argument. The types are defined by implementations of `hook_language_types_info()` and at least for my setup `$type = 'language'` does the trick.
> 0 votes

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


# Question
Title: How do I add variables to a module's hook's existing render array and have them available as template variables?
As an example, the hook\_search\_execute function returns the following array:

```
$results[] = array(
      'link' => url('node/' . $item->sid, array('absolute' => TRUE)),
      'type' => check_plain(node_type_get_name($node)),
      'title' => $node->title,
      'user' => theme('username', array('account' => $node)),
      'date' => $node->changed,
      'node' => $node,
      'extra' => $extra,
      'score' => $item->calculated_score,
      'snippet' => search_excerpt($keys, $node->body),
    );

```

`'link'` and `'title'` are required and the others are optional. However, what if I wanted to add my element to the array like `'photo'` and then have that available in the $search-result.tpl.php file?

Whe I add that element to the search results array, I indeed see it when I do a dump of $variables in \_preprocess\_search\_result(). If it's available there, then how to I make it available as `<?php print $photo; ?>` in search-result.tpl.php?

# Answer
> 3 votes
According to `template_preprocess_search_result` you have the `$result` variable available, so if you've already injected your custom field into the result you can just use

```
print $result['photo'];

```

In the template file.

Or if you're absolutely set on just having a `$photo` var, you need to add it to the variables for the template:

```
function MYMODULE_preprocess_search_result(&$vars) {
  $vars['photo'] = $vars['result']['photo'];
}

```

---
Tags: theming, search
---


# Question
Title: How can I inject a taxonomy menu as the sub-menu of a standard menu item?
I have a main menu, with a top-level structure similar to the following:

```
Home - Categories - Something Else - ... - Contact

```

Each of those top-level links goes to an appropriate node page.

I have a vocabulary for Categories (multi-level), and I need to get those taxonomy terms in a sub-menu under the "Categories" item. I'd like to avoid hard-coding the items into the main menu, as the sub-menu should grow/shrink as the vocabulary does.

In the past I've written over-elaborate code to accomplish this, which hooks into taxonomy operations and manages a particular menu's sub-items based on that (very similar to what Taxonomy Menu does, but without having to have a different menu for each vocabulary).

While that method works, it's not ideal and certainly not generic. I can't just lift that code from the old project into the new one, it would require a reasonable amount of customisation.

I can't help feeling there must be a 'standard', module-based solution to this.

I've seen some suggestions out there to use a bunch of different modules in combination (even some suggesting to use Views-based modules, weirdly enough). I'm open to any suggestion, but if it involves installing more than 1 or 2 modules, and a load of hard-coded, context-specific configuration, it's probably not going to help too much in this case.

# Answer
> 13 votes
Option a) Unless I am mistaken, can you not just pick where your Taxonomy Menu will be parented (Menu Location) when you create it? The only problem I think you might get with this is I *think* it requires you to rebuild the menu every time the taxonomy is updated

Option b) I have done something reasonably similar to this on my site, I used Menu Views module, to allow me to put a view into my primary menu.

If you create a new view which lists all of your taxonomy terms, as a block display, apply any additional filtering/modification in the view if necessary (you may not but in my example I wanted to). Then when you add a new link to your main menu, you can select to use a view rather than a link. From there you pick which view you want to use, select the 'Category' menu item as its parent and save (after saving you then have to enable it in the menu, which appears to be a bug with the module itself)

I can't guarantee that this is the best solution for you, but it worked when I just tested it

# Answer
> 3 votes
Menupoly has an API for custom "menu tree sources". I have never really made use of this for something other than menu links, so there might be issues we have to fix on the way. But the basic architecture is there.

If you go this route, you would

* Use your existing main menu, without any taxonomy term links beyond the "Categories" page.
* Create your taxonomy tree independent of that.
* Write a custom "menu tree source" that fetches from menu\_links as normal, but when it finds a taxonomy term, it fetches from taxonomy instead.
So, somehow you need to be able to detect that the "Categories" link is taxonomy-related.
* If a menu link is taxonomy-related and at the same time has a regular submenu, you need to somehow mix the two types of children together.

This route would be some work, but it might be useful for others, and it is probably more elegant and reusable than your site-specific logic.

Currently not even a taxonomy-only "menu tree source" exists, so maybe that would be a reasonable first step before starting with a mixed plugin.

# Answer
> 2 votes
Metro Menus will do your requirement and even it have the built in skins and can create your own which act same like nice menus. With this module you can **select any sub items** with **any depth from menu or taxonomy** and I'm not using this before.

Compatibility with touch screen (iPad, iPhone and etc.).

# Answer
> 2 votes
You can use Om Maxi menu module for the same. It will allow admin to create menus with blocks you want as attachments, modules like views, slideshow, menu, user, nice menus, quicktabs, and custom blocks with tables, lists, images, videos, etc.

You can create a separate menu using Taxonomy Menu and can attach this menu as sublinks to menu generated by om maxi menu.

Thanks

# Answer
> 2 votes
I have recently done something similar for a product category menu. This was only for 1 level deep, but could easily be modified to show further levels.

```
/**
 * Implements theme_menu_link().
 */
function THEME_menu_link__main_menu($variables) {

  $sub_menu = '';
  $element = $variables['element'];
  $menu_string = $element['#title'];

  if (module_load_include('inc','pathauto','pathauto') !== FALSE) {
    $menu_string =  pathauto_cleanstring($menu_string);
  }

  if ($menu_string == 'categories') {
    $sub_menu = get_categories_menu();
  }

  if ($sub_menu) {
    $element['#attributes']['class'][] = 'haschildren';
  }

  $output = l($element['#title'], $element['#href'], $element['#localized_options']);
  return '<li' . drupal_attributes($element['#attributes']) . '>' . $output . $sub_menu . "</li>\n";
}

function get_categories_menu() {

  $current_category = arg(2); // Get current category from path
  $volcab = taxonomy_vocabulary_machine_name_load('product-categories');
  $tree = taxonomy_get_tree($volcab->vid,0,1);

  $output = '<ul class="menu product-category">';
  foreach ($tree as $term) {
    $safe_term = pathauto_cleanstring($term->name);
    $class = ($current_category==$safe_term) ? ' class="active"' : '';
    $output .= '<li><a' . $class . ' href="/path/to/' . $safe_term . '">' . $term->name . '</a></li>';
  }
  $output .= '</ul>';

  return $output;
}

```

The get\_category\_menu function is better off as a block, but shown here as another function in the template.php for convenience.

Hope it helps or is at least a step towards a solution.

Paul

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


title: krumo()/dpm() not working

text:
# Question
Title: krumo()/dpm() not working
I have a custom module and a template to alter the appearance of my node submission forms, á la these instructions.

My module consists of three functions:

* A `hook_form_alter()` that works fine
* A `hook_theme()` that doesn't do anything but return an array, even if you enter other code before `return` (not sure if this is by design)
* A `hook_preprocess_HOOK()` that is currently empty

`dpm()` doesn't seem to do anything in `hook_preprocess_HOOK()`, although `krumo()` on the same variables *sort of* works. It sets a Drupal message that reads `Array: [n] items` but can't be expanded or inspected at all.

In my template, `print_r($form);` prints out the form array as expected. `dpm('self-aware roomba');` sets a Drupal message of "self-aware roomba" as expected. but `dpm($form)`; does nothing and throws no error.

Everything except my `hook_form_alter()` is exactly as it appears in the linked tutorial. I even tried pulling out the entire `hook_form_alter()` to see if it works without it; it doesn't.

What could be causing `dpm()`/`krumo()` to fail silently?

# Answer
> 6 votes
I have run into an issue where `dpm()` and some other messages were eaten up by a 404 request in the background.

*Explanation:*

If `dpm()` or `drupal_set_message()` is called before the messages are printed out with `theme_status_messages()`, then you get to see them on the same page.

If `dpm()` or `drupal_set_message()` is called after `theme_status_messages()`, then those messages are delayed in `$_SESSION` until the next request that does `theme_status_messages()`.

Some types of requests **do NOT** trigger `theme_status_messages()`. E.g. a form submit will only do the form processing, and then do a redirect, so the messages remain in the `$_SESSION`.

Also, it will only trigger on requests by the same visitor/client (this is why it is saved in session, which is client specific).

However, some requests that happen in the background do trigger `theme_status_messages()`, and can eat up your messages.

In my case this were requests to missing images, which resulted in full-blown html 404 pages WITH messages (and I did not get to see any of this, obviously).

**Solution:**

The solution was to activate the "fast 404" feature.

# Answer
> 1 votes
test this my friend

```
ob_start();
krumo($yourparameter);
$output = ob_get_contents();
ob_end_clean();
drupal_set_message($output);

```

---
Tags: theming, forms, debugging
---


# Question
Title: Host two ready websites with different URL using same code base
I’m pretty newbie to drupal and deploying stuffs. I’ve two separate drupal websites ready.

```
www.example.com
www.example.org

```

My directory structures on local machine for both websites are

```
wamp/www/example.com/sites/’all & default ‘ folder
wamp/www/example.org/sites/’all & default ‘ folder

```

These websites have complete different theme and database from each other. Now I want to go live for these two websites. But the problem is on hosting server they will provide me only 1 drupal installation.
I need both URL’s working. (There is a setting for URL redirection on hosting). But on hosting server, redirection via `.htaccess` is not running. (They said !!!).
So my question is how to host two complete different websites on server with two complete different URLs using same drupal code base? I’m using drupal 7. Any help or suggestion will be appreciated.

Thanks in advance…

# Answer
It looks like you are looking for Multisite approach. It's pretty easy to set up and to keep sites separate, but if one day you'll need to share anything between sites, you'll regret not using Domain Access.

If you are sure there will be no need to share data, in `<drupal root>/sites` create 2 subdirectories, like `example.org` and `example.com`, and put site-specific files (modules, themes, libraries and settings.php) into them. Point both domains to your Drupal (your provider should be able to help with that) and Drupal will take care to recognize what site is accessed.

It might be worth to consider Domain Access module.

> The Domain Access project is a suite of modules that provide tools for running a group of affiliated sites from one Drupal installation and a single shared database.
> 2 votes

---
Tags: 7, uri, redirection, multi-sites
---


# Question
Title: How do I add classes to an img tag inside the node?
I want to add classes to the image that is getting displayed only inside the node. I want to do it in the Drupal way.

Here is the img tag HTML.

```
<img typeof="foaf:Image" src="../image/imagefield_98F1iQ.png" width="220" height="78" alt="Capto cui esca" title="Damnum duis eum">

```

I want to add the classes like the below

```
<img class="medium img-polaroid" typeof="foaf:Image" src="../image/imagefield_98F1iQ.png" width="220" height="78" alt="Capto cui esca" title="Damnum duis eum">

```

I just want to add `"medium img-polaroid"` like class to the img field.

# Answer
You can do it server side by overriding theme\_image\_style

e.g, in template.php

```
/**
 * Theme override
 *
 * Add custom class to image styles
 */
function MY_THEME_image_style($variables) {
  // Determine the dimensions of the styled image.
  $dimensions = array(
    'width' => $variables['width'],
    'height' => $variables['height'],
  );

  image_style_transform_dimensions($variables['style_name'], $dimensions);

  $variables['width'] = $dimensions['width'];
  $variables['height'] = $dimensions['height'];

  // Determine the URL for the styled image.
  $variables['path'] = image_style_url($variables['style_name'], $variables['path']);

  /* Begin custom snippet */
  // Add or append custom classes, to avoid clobbering existing
  if (isset($variables['attributes']['class'])) {
    $variables['attributes']['class'] += array('my-class', $variables['style_name']);
  }else{
    $variables['attributes']['class'] = array('my-class', $variables['style_name']);
  }
  /* End custom snippet */
  return theme('image', $variables);
}

```

Note: This is just a clone of theme\_image\_style with the custom classes added at the end.

You can add some conditional logic based on style\_name for specific classes, and also do a similar thing with theme\_image if needed.
> 1 votes

# Answer
you could preprocess the content in the template, but it would be a little difficult, or you could do it via attachBehaviors in jQuery.

If you mind the jQuery way you can add this script:

```
(function($) {
  Drupal.behaviors.classadd = {
    attach: function(){
      $('.node img').addClass('class1 class2 class3');
    }
  }
}

```

This way you can easily add classes to your node with .node class. even when you load content dinamicly via ajax. the attachBehavior is a useful Drupal technic to attach actions to your content, and it's widely implemented in all the Drupal framework.
> 1 votes

---
Tags: nodes, theming
---


title: display select list as an image list

text:
# Question
Title: display select list as an image list
I want to make my site more user friendly and so I would like to replace select list with an image list. Is it possible to display ordinary select list as an image list? Is there a module that would allow me to do so or do I need a custom code for this fetaure?

# Answer
There is in fact a module that can do this. It's the Select with style module.
> 5 votes

# Answer
You'll have to use some jQuery help for displaying images as options in a select form element. Check out this collection of plugins.

You may also have to implement your own Form API element type using `hook_element_info()` to output the markup that your chosen jQuery plugin needs.

Lastly, you haven't said which select list you would like to change, but if it's an existing form, you might end up implementing `hook_form_alter()`.
> 0 votes

---
Tags: 7, entities
---


# Question
Title: Allowing users to create multiple "notebooks" of nodes
I'm trying to add some functionality to a site that I'm building that would allow users to create multiple "notebooks" that themselves contain links to nodes on the site, and metadata that the user can edit: a little like Evernote, but restricted to one site.

What's the best way to go about building this? I was thinking of using either Entity Reference or Flag, and would be interested on hearing thoughts regarding both of these options, and also any other ways to implement this functionality.

# Answer
We did the on a Drupal 6 site a few years ago.

If you want a single notebook, or have a fixed number of notebooks, then you can use Flags.

Our client wanted an unlimited number of notebooks, so we went the node references.

Basically, we created a "notebook" content type, with a few fields on it. One of the fields held the noderefs of everything that was saved. We may have also had some metadata for each saved item. It's a mostly straightforward approach, but it involves a decent of plumbing to add/remove things (the unlimited number of notebooks complicates some scenarios), and you also need to consider all of the use cases you want with regards to how notebooks will be managed.

If we had to do this again with Drupal 7, then I would likely still go with nodes and entity references, potentially using field collections to bundle the entityref with metadata for a saved item.
> 1 votes

---
Tags: 7, entities, flags
---


# Question
Title: When creating new view: "Base table or view not found" problem
When creating a new view and then trying to save it, I get this error:

PDOException: SQLSTATE\[42S02\]: Base table or view not found: 1146 Table 'drupal.views\_display' doesn't exist: INSERT INTO {views\_display} (vid, id, display\_title, display\_plugin, position, display\_options) VALUES (:db\_insert\_placeholder\_0, :db\_insert\_placeholder\_1, :db\_insert\_placeholder\_2, :db\_insert\_placeholder\_3, :db\_insert\_placeholder\_4, :db\_insert\_placeholder\_5); Array ( \[:db\_insert\_placeholder\_0\] =\> 11 \[:db\_insert\_placeholder\_1\] =\> default \[:db\_insert\_placeholder\_2\] =\> Master \[:db\_insert\_placeholder\_3\] =\> default \[:db\_insert\_placeholder\_4\] =\> 1 \[:db\_insert\_placeholder\_5\] =\> a:12:{s:5:"query";a:2:{s:4:"type";s:11:"views\_query";s:7:"options";a:0:{}}s:6:"access";a:1:{s:4:"type";s:4:"perm";}s:5:"cache";a:1:{s:4:"type";s:4:"none";}s:12:"exposed\_form";a:1:{s:4:"type";s:5:"basic";}s:5:"pager";a:2:{s:4:"type";s:4:"full";s:7:"options";a:1:{s:14:"items\_per\_page";s:2:"10";}}s:12:"style\_plugin";s:4:"list";s:10:"row\_plugin";s:4:"node";s:6:"fields";a:1:{s:5:"title";a:8:{s:2:"id";s:5:"title";s:5:"table";s:4:"node";s:5:"field";s:5:"title";s:5:"label";s:0:"";s:5:"alter";a:8:{s:10:"alter\_text";i:0;s:9:"make\_link";i:0;s:8:"absolute";i:0;s:4:"trim";i:0;s:13:"word\_boundary";i:0;s:8:"ellipsis";i:0;s:10:"strip\_tags";i:0;s:4:"html";i:0;}s:10:"hide\_empty";i:0;s:10:"empty\_zero";i:0;s:12:"link\_to\_node";i:1;}}s:7:"filters";a:3:{s:6:"status";a:6:{s:5:"value";i:1;s:5:"table";s:4:"node";s:5:"field";s:6:"status";s:2:"id";s:6:"status";s:6:"expose";a:1:{s:8:"operator";b:0;}s:5:"group";i:1;}s:4:"type";a:4:{s:2:"id";s:4:"type";s:5:"table";s:4:"node";s:5:"field";s:4:"type";s:5:"value";a:1:{s:7:"teznews";s:7:"teznews";}}s:3:"tid";a:5:{s:2:"id";s:3:"tid";s:5:"table";s:14:"taxonomy\_index";s:5:"field";s:3:"tid";s:5:"value";a:1:{i:0;s:1:"1";}s:10:"vocabulary";s:4:"tags";}}s:5:"sorts";a:1:{s:7:"created";a:4:{s:2:"id";s:7:"created";s:5:"table";s:4:"node";s:5:"field";s:7:"created";s:5:"order";s:4:"DESC";}}s:5:"title";s:11:"Latest News";s:11:"row\_options";a:3:{s:10:"build\_mode";s:4:"full";s:5:"links";b:1;s:8:"comments";b:0;}} ) in views\_db\_object-\>save\_row() (line 2224 of D:\xampp\htdocs\drupal\sites\all\modules\views\includes\view.inc).

I have struggled with this for a while and have used SQL snippets to create tables which were previously 'missing'. I have also googled it extensively, without seeming to find an answer, and sure that someone will understand what the problem relates to immediately. This is the first time I have come up against it. This is a fresh install of drupal 7.22 and I have never experienced this problem previously whilst building drupal sites.

I have tried updating everything and wondered if there was some way to install a clean version of 'views' in core or if this related to another problem.

Any advice from a more skilled set of eyes would be invaluable.

Thanks

Ed

# Answer
> 1 votes
```
'drupal.views_display' doesn't exist.

```

That pretty much sums up the problem. The table wasn't created in the initial setup of views. Without knowing more I can't tell you exactly what's going on but a couple of things you could try is to run update.php and check for the issue in the views queue. You may have a mysql issue as well that's not allowing the table to be created.

Good luck!

---
Tags: views, database
---


# Question
Title: My form does not show any action on clicking the submit button
I have create custom module with hook\_block , inside the block i want form but the problem ( my from does not take any action of submit ). This is my code

```
function loan_calculator_block_info() {
  // This example comes from node.module.
  $blocks['loan_calculator'] = array(
    'info' => t('Loan Calculator'),
    'cache' => DRUPAL_NO_CACHE
  );
  return $blocks;
}
function loan_calculator_block_view($delta = '') {
    switch ($delta) {
        case 'loan_calculator':
        $block['subject'] = t('Loan Calculator');
        $block['content'] = drupal_get_form('loanCalculator_form');
    return $block;
    break;
  }
}

function loanCalculator_form(){
  $month = range(1 , 12);
  $form['amount'] = array(
    '#title' => t('Amount'),
    '#required' => TRUE,
    '#type' => 'textfield'
  );
  $form['duration'] = array(
    '#title' => t('Duration (Months)'),
    '#required' => TRUE,
    '#type' => 'select',
    '#options' => $month
  );
  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Submit'),
    '#submit' => array('calculator_loan_form_submit')
  );
  return $form;
}

function loanCalculator_form_validate($form, &$form_state) {
  $amount = $form_state['values']['amount'];
  if ($amount == '') {
    form_set_error('amount', t('You must select Amount.'));
  }
  elseif (!is_numeric($amount)) {
    form_set_error('name', t('The Amount must be numeric.'));
  }
}
function calculator_loan_form_submit($form, &$form_state) {
  var_dump($form_state['values']);
  $mount = $form_state['values']['amount'];
  if(!is_numeric($form_state['values']['amount'])) {
    return '<div class="erorr">'.t('Please Enter numaric value').'</div>';
  }
  return $mount;
}

```

How I can fix this problem?

# Answer
Something like this should work:

```
/**
 * Implements hook_block_info
 */
function loan_calculator_block_info() {
  // This example comes from node.module.
  $blocks['loan_calculator'] = array(
    'info' => t('Loan Calculator'),
    'cache' => DRUPAL_NO_CACHE
  );
  return $blocks;
}

/**
 * Implements hook_block_view
 */
function loan_calculator_block_view($delta = '') {
    switch ($delta) {
      case 'loan_calculator':
        $block['subject'] = t('Loan Calculator');
        $block['content'] = drupal_get_form('loan_calculator_calculator_form');
    return $block;
    break;
  }
}

/**
 * Form builder
 */
function loan_calculator_calculator_form(){
  $month = range(1 , 12);
  $form['amount'] = array(
    '#title' => t('Amount'),
    '#required' => TRUE,
    '#type' => 'textfield',
    '#element_validate' => array('element_validate_number'),
  );
  $form['duration'] = array(
    '#title' => t('Duration (Months)'),
    '#required' => TRUE,
    '#type' => 'select',
    '#options' => $month
  );
  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Submit'),
  );
  return $form;
}

/**
 * Form submit handler
 */
function loan_calculator_calculator_form_submit($form, &$form_state) {
  drupal_set_message('<pre>'.print_r($form_state['values'],1).'</pre>');
}

```

Note, the renamed functions are per Drupal convention, (avoiding hook\_form namespace collision), including using default submit handler. Also, no need for validate handler if amount element is required and set to numeric element validator. Tidied up a bit, should be fine but needs testing.
> 2 votes

---
Tags: 7, forms
---


# Question
Title: Would disabling core modules, which I don't need, speed up my site?
Would disabling core modules which I don't need, like Color, speed up my site? If so, why?

# Answer
In theory, the answer is yes, but in practice, I doubt it. It depends entirely on on the module though.

If you have badly written module that implements hook\_boot, so it executes on even cached page requests, and it performs lots of logic in there, and you have no use for it, then sure, you would gain speed from disabling it.

Most likely though, the average module is going to be implementing logic that is only actually executed when it is used, so if you don't use it it's not going to cost much.

If it's a big module, you could see a small dent in memory usage, as all enabled modules are loaded into memory, and as pointed out by Mołot, a modules variables and menu router entries will consume some resources, but again, I think in practice, it's not going to make a big difference.

That said, if you don't use the module, why keep it enabled? It by definition doesn't provide you with any benefit if it's not used, and at least it's going to clean up the administrative pages.
> 8 votes

---
Tags: performance
---


# Question
Title: How to add a 'read more' theme link to a custom view mode?
In Drupal 7 the Teaser view mode automatically comes with a 'read more' theme link. I need to retain the Teaser view mode and then create another called 'Snippet', which is basically the same as Teaser but has a lot less content in the trimmed area.

I created a custom module and added the view mode...

```
/**
* Implements hook_entity_info_alter().
*/
function mymodule_entity_info_alter(&$entity_info) {
    // Add a custom view mode
    $entity_info['node']['view modes']['snippet'] = array(
        'label' => t('Snippet'),
        'custom settings' => TRUE,
    );
}

```

But it doesn't activate the 'read more' link like Teaser does. Can anyone point me in the right direction with this please?

# Answer
You can use Display Suite for this. Each view mode gives you a screen like below with control over fields and pseudo-fields.
> 0 votes

# Answer
I took a look here

https://api.drupal.org/api/drupal/modules%21node%21node.module/function/node\_build\_content/7

and here

https://drupal.org/node/1844292

and came up with this

```
function YOURMODULE_node_view_alter(&$build) {
    if ($build['#view_mode'] == 'YOURVIEWMODE') {
        $node=$build['#node'];
        $links=array();
        // Read more for teas ext
        $node_title_stripped = strip_tags($node->title);
        $links['node-readmore'] = array(
            'title' => t('Read more<span class="element-invisible"> about @title</span>', array('@title' => $node_title_stripped)),
            'href' => 'node/' . $node->nid,
            'html' => TRUE,
            'attributes' => array('rel' => 'tag', 'title' => $node_title_stripped)
        );
        // Assign links
        $build['links']['node']['#links']=$links;
    }
}

```
> 6 votes

# Answer
Add a new field 'Content:link' then give it a label none and 'Read more' in text to display.
> 2 votes

# Answer
you may add content and theming options in your

```
 mymodule_node_view($node,$view_mode,$langcode){}

```

you may customize your content through $node-\>content.

if you created a custom node you may use

```
mynodemodule_view($node,$view_mode,$langcode);

```

instead of hook\_node\_view

even you may attach a new tpl file or theming function for your node by `$node->content['#theme'] = 'my_theme_item';`
> 0 votes

---
Tags: 7, entities
---


title: Drupal Commons change theme

text:
# Question
Title: Drupal Commons change theme
I'm pretty new to Drupal, I installed Drupal Commons in order to build a website where users can register and create a custom profile. Users will be split in categories.

I'm not entirely sure Drupal Commons is the best choice for me.

Anyways, now I find myself in the following situation: \- I cannot find a way to change the Commons Origins default theme, let alone find a place where I can acquire such themes.

# Answer
You can essentially download and upload a new theme to your site by following the instructions here:

https://drupal.org/getting-started/install-contrib/themes
> 3 votes

# Answer
All you need to do is download a theme from http://drupal.org/project/themes

Extract your theme in your site/all/themes folder

Go to administer -\> site building -\> themes and enable the theme(make sure to set it as the default theme), save it and you should have your new theme enabled.
> 3 votes

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


# Question
Title: How do I display fields in my product type in a product display?
I have the unique parameters for my product. Sometimes I want to display some parameters, and sometimes I don't. So, I defined them in my product type.

My question is how do I display these fields for a product display? I don't want to create a duplicate when the values are already defined in the product type.

# Answer
Fields from the referenced product entity are automatically available on the product display node.

Set the fields to visible on the product at

*admin/commerce/products/types/subscription-product/display*

Then, set the fields to display at:

*admin/structure/types/manage/product-display/display*

**Update**: As noted by vintorg below when creating your product reference field on the product display node, ensure "*Render fields from the referenced products when viewing this entity*." is checked.

That should do it.
> 2 votes

# Answer
When I created my product reference field in my product display, I did not check "Render fields from the referenced products when viewing this entity."

I checked it, and now my product fields now render in my product display.
> 0 votes

---
Tags: 7, commerce
---


title: How to open nodes in Lightbox?

text:
# Question
Title: How to open nodes in Lightbox?
Goal here is to just open my Nodes in a Lightbox. Following is what I have tried at it is not working for me, any clue would be great:

In my View, I am rewriting the node title as following:

```
<a href="/node/[nid]/lightbox2" rel="lightframe" title="Full Node View">[title]</a>

```

All I see that the title is output as a link to the node. Clicking on the title just opens the new node.

I followed the instructions at https://drupal.org/node/252260

> Basic example: Search google

I am using Drupal 6! (D6 Version: 6.22 & lightbox2 Version: 6.x-1.11)

Update: I tested this works in my D7 installation - but not in my D6 site. :S

# Answer
> 1 votes
I found the solution - had a silly error. In lightbox2 module configuration page, under Page Specific Lightbox2 Settings, I was telling it to not load on any page.

---
Tags: 6, nodes, javascript
---


title: Simple hit counter (as block)?

text:
# Question
Title: Simple hit counter (as block)?
I need to implement kind of a hit counter for the entire page (so how often the site was visited) in D7.

For D6 we got the Counter module, but is there any simple way to do it? Perhaps with a custom block and some PHP code?

# Answer
You could use the core Statistics module as described here.

You could use Visitors module.

I use Google Analytics but this might be too heavy if you need a basic solution.
> 7 votes

# Answer
You could use the mostpopular module for this.

> The module is pre-packaged with several services including:
>
> 1. Drupal - Most Viewed pages (using Statistics module)
> 2. Drupal - Most Commented pages (from simple database query)
> 3. Google Analytics - Most Viewed pages
> 4. AddThis.com - Most Shared pages
> 5. Disqus.com - Most Commented pages The system defines Drupal hooks to allow new services to be created, which can pull data from third party providers or internally from Drupal.
>
> The system also provides an API to help service plugins normalize their results and exclude certain pages, as configured by the administrator.

For more detail about the module you could visit this.
> 0 votes

---
Tags: 7
---


title: How can I reorder meta tags?

text:
# Question
Title: How can I reorder meta tags?
According to my client's requirement, I need to change the order of meta tags. The requirements are also to hide some of the meta tags.

The order requested is similar to the following one.

```
<Title>
<Description>
<keywords>

```

Is there a module to achieve this easily, do I need to edit the files of the Metatag module?

# Answer
To alter the order of specific meta tags, a `hook_html_head_alter()` implementation in your theme's template.php file would be your best bet:

```
function MYTHEME_html_head_alter(&$head_elements) {
  // Combined with the devel module this line will tell you what elements you have to work with
  dpm($head_elements);

  // Any you can just alter the weight like this
  $head_elements['module:key']['#weight'] = -1000;
  $head_elements['another_module:another_key']['#weight'] = -999;
}

```
> 10 votes

# Answer
HTML head elements are defined in 2 places.

## First one, easiest to access, is your theme's `html.tpl.php`.

In Professional Theme relevant part looks like that:
```
<head>
<meta http-equiv="X-UA-Compatible" content="IE=Edge" />
<?php print $head; ?>
<title><?php print $head_title; ?></title>
<?php print $styles; ?>
<?php print $scripts; ?>
<!--[if lt IE 9]><script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script><![endif]-->
</head>

```

So, here you can put title before other headers. It's wise to leave CSS and JS parts at the end, in the order specified.

## If you feel you need to reorder what's in `$head` variable,

it gets more tricky. This variable is generated by Drupal core, and then altered by modules and themes. Good thing, your theme will be the last accessing it.

For Drupal 6, in `template.php` define THEMENAME\__preprocess\_page(&$variables), and alter or reorder `$variables['header']` as you please. Keep in mind that it may break other modules, especially if you will remove things. Reordering is relatively safe, adding is usually safe, removal is risky.

For Drupal 7 see answer by Clive. THEMENAME\__preprocess\_page(&$variables) would still work, but 7 provides more direct solution to your problem.
> 6 votes

---
Tags: 7, meta-tags
---


# Question
Title: drupal 6: passing multiple arguments to a view using code
I have a template file that uses execute\_display to pass arguments to a view and this works great for single arguments. However, one of my arguments is a taxonomy id and the form allows the user to choose multiple term ids.

I've set the view to accept multiple arguments in the form 1+2+3 etc. But when i pass execute\_display an array array containing arguments in the form of term1+term2 it doesn't work.

Any ideas how to pass multiple ids as one argument using code

# Answer
the array must be array in "execute" then this array in array - in "preview", e.g

```
$args = array($arg1, $arg2, $arg3);
$view2->execute('block_1', $args);
print  $view2->preview('block_1', array($args));

```
> 1 votes

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


# Question
Title: How do I mark a database query with a tag?
How do I mark a database query with a tag so that I may alter it via hook\_query\_alter? I get the concept, but does anyone know what the syntax is? A working example would be helpful. Thanks.

# Answer
In case you're struggling to find the documentation, the class is called `SelectQuery`, and you're looking for the `addTag` function.

```
$query = db_select('table', 't')->fields('t')->addTag('my_tag');

```

Then in your query alter:

```
function MYMODULE_query_alter(QueryAlterableInterface $query) {
  if ($query->hasTag('my_tag')) {
    // Do something...
  }
}

```
> 2 votes

---
Tags: database
---


# Question
Title: How can I get a field value of a node using PHP?
I have created a field in a Basic Page with the label of User Name and the field name of `field_user_name`.

How can I get it's value using PHP?

# Answer
The easiest non Entity API way of doing it is to use field\_get\_items():

```
// Assuming you have the node object and assuming it is a single value
// field or you just want the first value of a multi value field.
$username_value = '';
if ($items = field_get_items('node', $node, 'field_user_name')) {
  $username_value = $items[0]['value'];
}

```
> 10 votes

# Answer
Not sure what you mean by global PHP, but here goes anyway.

I'd use the `entity_metadata_wrapper`(). For further reference, there's the handbook page here, but you're looking at something like the following:

```
// Assuming the NID if your Basic Page node is 123
$node = node_load(123);
$wrapper = entity_metadata_wrapper('node', $node);

$field_value = $wrapper->FIELD_NAME->value();

```

You'd need the Entity API installed, but if you're running D7 then it's a pretty safe bet that *something* will have required it in the past as a dependency.
> 7 votes

---
Tags: entities
---


title: Close Lightbox on Custom Form Submit

text:
# Question
Title: Close Lightbox on Custom Form Submit
I am using form Api to create a custom form. My form is below.

```
function myform_form() {
  $form = array();
  $form['name'] = array(
    '#type'          => 'textfield',
    '#title'         => t(''),
    '#required'      => FALSE,
    '#weight'        => 2,
  );
   $form['telephone'] = array(
    '#type'          => 'textfield',
    '#title'         => t(''),
    '#weight' => 3,
    );
     $form['submit'] = array(
      '#type' => 'submit',
      '#value' => t('submit'),
     );
  return $form;
}

function myform_submit($form, &$form_state) {
  drupal_set_message(t('Your form has been submitted successfully.'));
  $form_state['redirect'] = 'thankyou';
}

```

I used to show this form in lightbox as this :

```
<a href="/myform" rel="lightframe"> Form </a>

```

Form is correctly showing in lighbox. But when i submit the form it opens the `thankyou` page in popup.

I used

`<a href="/myform" rel="lightmodal"> Form </a>`

It closes the popup event if form validation returns false. I don't want to close the popup if there is any validation error. I added this to `myform_submit` function :

```
parent.Lightbox.end();

```

But `drupal_add_js` is not working in `myform_submit` function.

Updated :

I send a parameter to thank you page and added this on the page load.

```
<?php if($_GET['redirect']) { ?>
  <script>
      window.parent.location = "quick_request_quote";
  </script>
<?php } ?>

```

Its redirecting but it shows content in popup for few seconds and redirect after that. I don't want to display popup for a second also after submitting the form.

# Answer
Solved this by creating a Menu showing processing message and redirect it using :

```
      window.parent.location = "thankyoupage";

```
> 0 votes

# Answer
Hope this will help you,

For forms validation on modal dialog you can user **Chaos tool suite** module.

Steps

* Download and enable Chaos tools and Chaos Tools (CTools) AJAX Example
* Go to the URL **your\_site/ctools\_ajax\_sample**
* You can refer ctools dialog form examples using sites/all/modules/contrib/ctools/ctools\_ajax\_sample
    + Where **contrib** is the folder where I keep all my contributed modules.
> -2 votes

---
Tags: 6, javascript
---


# Question
Title: How do I control if an ajax webform has errors?
I have a webform that sends an email upon submission. Ajax is enabled so when I hit submit and there are errors on the form they will show instantly. However if there are no errors I would like to hide the form along with the success message.

Some pseudo code (sort of):

```
Drupal.behaviors.sendMail = {
  attach: function (context) {

    $('#webform-client-form-340', context).ajaxComplete(function(event, xhr, settings) {
      if ($('.alert-errors').length == 1) {
        thisForm.highLight()
      } else {
        thisForm.hide();
      }
    });

  }
};

```

This doesn't work because the .alert-errors div is not yet there on ajaxComplete. So how do I check for errors, highlight the form if they are present and otherwise hide the form?

# Answer
I when I normally have to debug this I use

Debugging ajax with FIREPHP

> Explaines how you can debug ajax with FIREPHP
> 0 votes

---
Tags: 7, ajax, webforms
---


# Question
Title: User cannot view their Orders in Ubercart
For Drupal (v7.22) I have a basic install of Ubercart (v7.x-3.4) and have set the permissions to allow an authenticated user to 'View own orders' and View own invoices'. But if an authenticated user visits an order page (for an order they made) they get the error:

page: example.com/user/user\_name/orders/1

> Access denied
>
> You are not authorized to access this page.

I've been though all of the settings and googled this but cannot see what I've missed. Does anyone know if I've missed a permission/setting somewhere?

# Answer
Enable the **Allow customers to view order invoices from their order history** in Order settings, see the below image may be this will be the problem for you and i am not sure because i have drupal 6 installation only.
> 1 votes

---
Tags: ubercart
---


title: Php error views template

text:
# Question
Title: Php error views template
I am trying to implement this function in my code, to handle language fallback, but it doesn't really work: The content is not in the correct language. I am trying to use `field_language('node', $node, 'field_exhibition_event_image')` without success.

My original views template contains the following code.

```
<img src="<?php print image_style_url('550x250', $row->_field_data['nid']['entity']->field_exhibition_event_image['en'][0]['uri']);?>" alt="Images"/>

```

I want to change the code to something similar to the following one.

```
<img src="<?php print image_style_url('550x250', $row->_field_data['nid']['entity']->field_exhibition_event_image[field_language('node', $node, 'field_exhibition_event_image')][0]['uri']);?>" alt="Images"/>

```

What would the problem be?

# Answer
The correct solution for my problem can be found here if anyone else is interested:

https://drupal.org/node/2020785
> 0 votes

# Answer
Normally, you should not directly call `field_language()` to get the value of a field in the language that should be used to render it; for that there is the field\_get\_items() function, which in fact calls `field_language()`.

```
function field_get_items($entity_type, $entity, $field_name, $langcode = NULL) {
  $langcode = field_language($entity_type, $entity, $field_name, $langcode);
  return isset($entity->{$field_name}[$langcode]) ? $entity->{$field_name}[$langcode] : FALSE;
}

```

`field_language()` is directly called (for example) from comment\_tokens(), since it needs to pass the language code to \_text\_sanitize().

```
if ($items = field_get_items('comment', $comment, 'comment_body', $language_code)) {
  $instance = field_info_instance('comment', 'body', 'comment_body');
  $field_langcode = field_language('comment', $comment, 'comment_body', $language_code);
  $replacements[$original] = $sanitize ? _text_sanitize($instance, $field_langcode, $items[0], 'value') : $items[0]['value'];
}

```
> 0 votes

---
Tags: views, theming, i18n-l10n
---


# Question
Title: How can I have a page title different from the name of its menu link?
I have the following implementation of hook\_menu in a custom module:

```
/**
 * Implements hook_menu().
 */
function employee_list_menu() {
    $items['employee-list'] = array(
        'title' => 'Employee list',
        'page callback' => 'employee_list_render',
        'access arguments' => array('view employee list'),
        'type' => MENU_CALLBACK,
    );
    return $items;
}

```

I also have a custom menu in which a menu item link is 'Staff' and the path is 'employee-list'. When I click on the 'Staff' link the page opens and the page title is 'Staff', but I want it to be 'Employee list'. How can I fix this?

Thanks

# Answer
You can set the page title with drupal\_set\_title() in your page callback.
> 4 votes

---
Tags: routes
---


# Question
Title: Make new content [typeA] out of existing content [typeB]
I have an event management site I am trying to build (which is using the COD framework) but I am trying to work my way around a functionality setup.

The basic principle is that an Event will be created, this will be published to the main page of my site and invite delegates to submit an Abstract for the Event in order to present their topic. The Abstracts will be scored internally and the selected ones will be marked to become actual presentations. The Event information will contain a Programme page, which is just a list of the presentations. Once the event has taken place, they want to be able to sell the video of the presentation.

What I wanted to achieve is outlined in steps:

* Event is setup by admin, but has no programme information
* Users submit an abstract (which has an entity reference to that Event)
* When an abstract is chosen to be presented, the important information is copied into an 'empty' product, ie: Status is set to unavailable and price to 0, but the product display for that product becomes the Presentation
* Programme is a list of all Presentations (product displays) for that Event
* After the Event has finished, a price and an asset are added to the product, which is then set to available, so that it shows up in the shop

This process is already in place in my site as it is, but the client is wondering if they can effectively remove another step from this process. They are looking to automate the process so that they don't have to copy information from the Abstract, into the empty Product

My approach to this was to add a 'selected' checkbox to the Abstract content type, then create a rule which would then check every time the content was saved to see if this checkbox is set to 'approved', \*then create a new product from the information already within the Abstract

My problem is I am getting stuck when it comes to where my * is, I don't even know if it's possible to copy all of the information from one content type into a new one of another. Can this be done, or am I going to have to find another way around or custom code it etc?

Kind regards

# Answer
It is possible all right. In your custom module use node\_load and node\_save:

```
$abstract = node_load($abstract_id);
$event = new stdClass();
$event->type = 'event';
node_object_prepare($event);

$event->title = $abstract->title; // and so on

node_save($event);

$event_id = $event->nid;

```

Just wrap it in a function and expose it to the framework you are using - most of them provide good examples in their documentation.
> 0 votes

---
Tags: 7, rules, nodes
---


# Question
Title: Drupal Apache solr does not return "no results founds"
I'm using Apache Solr 7.x-1.1 with Drupal. It was working fine but something happened and when I search for dummy data that I'm sure that is not found in my site, the search result will be all nodes in my site instead of returning "your search yielded no results". It was working perfect before but I don't know what I did so this occurred.

# Answer
> 1 votes
I met the same issue, and the main reason was the solr 'bias' settings in admin/config/search/apachesolr/settings/solr\_search/bias

I changed some of its configuration. the solution is clicking 'reset to default' button.

---
Tags: 7, search
---


# Question
Title: Why anonymous users can only see 1 link in navigation menu?
I'm trying to show navigation links to anonymous users/ visitors of my site. However, they can only see 1 of the many links while the administrator can see all links just fine.

I'm using Drupal 7 and Zen theme.

My settings : https://i.stack.imgur.com/ASOxB.png

This is what anonymous users/ visitors see: https://i.stack.imgur.com/2jYb8.png

# Answer
> 0 votes
That is because they do not have the necessary permission. So for example they do not have permission to create contents of type (article, blog, basic page and product) in your case. And I want to believe you don't want anonymous users to create products, pages, e.t.c.

To assign anonymous users new permissions, go to admin/people/permissions

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


# Question
Title: Passing arguments from Panel to View without url or using contextual filter from panel to field of taxomony term within view
Using Drupal 7, Panels 7.x-3.3, & Views 7.x-3.5.

I'm unsure the best way to approach what I'm trying to accomplish.

I have taxonomy vocabularies classifying people in my department. One example would be fellowships. Within fellowships there are terms 'Surgical Pathology', 'Transfusion Medicine', etc and within those terms there are terms such as 'Director', 'Faculty', Coordinator, etc with which people are associated. Each fellowship page will be a panel with various content and a view listing the people within that taxonomy.

We have numerous fellowships and would like to create a view that could be used for all via contextual filters or argument from the panel. The issue I'm running into is that I'm not going to use the full taxonomy term name in the url. For example 'Surgical Pathology' might be mysite/education/fellowships/surgical or 'Transfusion Medicine' might be mysite/education/fellowships/transmed. I can't use the full term name or term id as my hands are tied with keeping those urls.

I'm not sure if its possible to send an argument that is set in the panel (not from url) using 'Input on pane config' or 'From panel argument' in views but I haven't been able to figure it out or find any tutorials on how to.

The other method I tried was to add a field to the taxonomy called Manuel\_Context which I put in 'transmed' or whatever the url argument actually is. So I have the Contextual Filter set in the view to '(Parent) Taxonomy term: Manuel\_Context'. When I use the preview, the view works how I would like however I haven't been able to figure out the panel settings to get this to work. When I'm in the panel Settings\>Arguments I can only select for the 'Context Assigned' Taxonomy Term: ID. I don't know how to get the panel to look for the field Manuel\_Context of the Taxonomy Term.

Any suggestions on how to approach this would be greatly appreciated. Thank you

# Answer
The easier (semi-automatic) way I can think of is to

1. Override the path `/taxonomy/term/%taxonomy_term` (enable the \*term\_view\* page provided in system) in Page manager.
2. Build a page with panels for this path.
3. Now your content panes, when used in this page, can get their arguments with the 'From panel argument' option.

You can always have SEO-friendly URLs like `mysite/education/fellowships/surgical` or `mysite/education/fellowships/transmed` with path (in `/admin/config/search/path/add`).

The other way is to use the 'Input on pane config' option for your content panes. You will have to set the arguments for these panes manually in their settings dialogue. In your case, the argument should probably be the (numerical) term ID. This way your content panes don't need to be tied to a specific path pattern, and you can have some logical combinations in your contextual filters, such as `1+3+5` (term 1 OR 3 OR 5). This can get quite laborious, though.
> 0 votes

---
Tags: panels, views
---


# Question
Title: Best method for multi-page user registration form?
I am trying to set up a multi-page user registration form, and I would ideally like to use the Webform module to do so. Can webform fields be mapped to user registration or user profile fields?

Here's how I would like it to work:

1. User tries to access content page; they cannot because they are not registered, so they are prompted to create a new account.
2. They enter their name, email, password and are logged in. They are then redirected to "page 1" of the multi-page form.
3. After they go through all of the pages, they save the form. The info they entered into the pages of the form is saved in their user profile. They can go back in and edit it at a later date if they wish.

Is this possible with existing modules?

Thanks!

# Answer
The Profile2 and Profile2 Registration Path modules can help to solve your problems. You can do the following:

* You can create the profile for each role of users.
* Have the different register pages for each profiles.
* Can config the way to do after registration.
* Have the edit user information with include the extra fields from Profile2 module.
> 2 votes

---
Tags: 7, webforms, users
---


# Question
Title: Trying to get my form_alter function to be more specific
I'm hiding access to a specific fieldset within the Support Ticketing System module add a ticket page. I use a `form_alter` preprocess function to find the page's form id as such:

```
drupal_set_message($form_id);

```

I discover the ID is:

```
support_ticket_node_form

```

... perfect so I do:

```
function MYTHEME_support_ticket_node_form_form_alter(&$form,$form_state,$form_id){
  $form['subscribe']['#access'] = FALSE;
}

```

... to hide that but the fieldset does not get hidden.

However, if I do a generic `form_alter`:

```
function MYTHEME_form_alter(&$form, &$form_state, $form_id) {
    $form['subscribe']['#access'] = FALSE;
}

```

... That works, the fieldset is now hidden on the page. The only thing I could think of that I am doing wrong is that it seems odd to have `form_form_alter` as part of the string but one is from the form ID and the other is part of the function so it should be working. Not sure what i am doing wrong. I'm guessing the generic `form_alter` that works for me could be dangerous as it lacks specificity and could cause issues down the road so I'd like to get this sorted out.

# Answer
> 2 votes
The hook for specific form ID's is `hook_form_FORM_ID_alter()` (at the moment you're using something more like `hook_FORM_ID_form_alter()`). You should just need to change the name of the function to:

```
function MYTHEME_form_support_ticket_node_form_alter(&$form, &$form_state, $form_id) {
  // ...
}

```

and clear the caches.

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


# Question
Title: Commerce Product Display or just Views Display of line items?
I will be presenting the products in one view and don't need the display nodes as they wont be seen.

Do I have to create display nodes for each product or can I just use views to display the line items in a table for example?

Is there any catch with doing this?

# Answer
> 0 votes
You can't see products because the permission to see products is disabled by default. Just enable it at `/admin/people/permissions`. E.g. enable `View any product of any type` if you want to permit users to see directly entities.

But also have a look at the module Inline entity form. you can edit both node display and attached product entities in one form.

---
Tags: views, commerce
---


title: Behaviour of using drupal_add_js

text:
# Question
Title: Behaviour of using drupal_add_js
When using the drupal\_add\_js function, should I see the script I am loading appear in the list of scripts being loading in the header of the generated html page? I thought I should, but I don't - so perhaps my understanding of this function is wrong. Can someone clarify what is suppose to happen.

Just as note I have verified that the path to the script is correct so I know that isn't the issue.

Thanks.

# Answer
> 0 votes
With drupal\_add\_js() you can set the scope to either header or footer, specify the group the script is loaded into, and give the script a weight relative to that group. Scripts are loaded by scope \> group \> weight, where a lower weight will be loaded before a higher weight.

If you have aggregation turned on in /admin/config/development/performance, the script will be combined with others with the same scope & group, and ordered by weight.

---
Tags: 7, javascript
---


# Question
Title: How Do I Properly Add Custom CSS Classes And IDs To Drupal 7 Sub Menus
I'm having a theming problem with my Drupal secondary navigation. I have a two level menu set up - i.e. five parent links, two of whom have children. The problem I'm seeing is that the children have the same CSS classes and IDs. Consequently, when I click on a parent that has children, they are appearing the same as the parents.

I have tried to modify the menu via my template.php and page.tpl.php to no avail. I have the following in my template.php file and it is throwing errors saying $sub\_menu does not exist:

```
function framework_menu_link(array $variables) {

  unset($variables['element']['#attributes']['class']);
  $element = $variables['element'];
if($variables['element']['#attributes'])
$sub_menu = '';
if ($element['#below']) {
$sub_menu = drupal_render($element['#below']);
}
$output = l($element['#title'], $element['#href'], $element['#localized_options']);
return '<li' . drupal_attributes($element['#attributes']) . '>' . $output . "</li>\n";
}

```

Any help or guidance anyone could provide would be appreciated.

Thank you!

+Chris

# Answer
> 1 votes
Have you tried the Menu Attributes module? It's easy to use and has great features:

> The module currently allows you to set the following attributes for each menu item:
>
> * Id
> * Name
> * Target
> * Rel
> * Class
> * Style
> * Accesskey

# Answer
> 0 votes
Revised answer. First, there are some issues with the code

1. $sub\_menu isn't set because you have it within an if statement, which doesn't seem necessary.
2. With your current code, $sub\_menu will never be rendered, because it is no longer in the return statement
3. You are removing all classes from every menu link, not just the sub-menu items with:

unset($variables\['element'\]\['#attributes'\]\['class'\]);

You can use the following to add `.has-sub-menu` to any `li` that has a sub menu, which will save you, maybe, one level of nesting. Alternatively, you could just use css to target the sub-menu `.main-navigation ul li ul` is your sub-menu most likely.

```
function mid_america_trucking_show_menu_link(&$variables) {
  $element = $variables['element'];
  $sub_menu = '';
  if ($element['#below'] && !empty($element['#below'])) {
    // this link has children
   if (isset($element['#attributes']['class']) && !empty($element['#attributes']['class'])) {
      array_push($element['#attributes']['class'], 'has-sub-menu');
    }
    else {
      $element['#attributes']['class'] = 'has-sub-menu' ;
    }
    $sub_menu = drupal_render($element['#below']);
  }
  $output = l($element['#title'], $element['#href'], $element['#localized_options']);

  return '<li' . drupal_attributes($element['#attributes']) . '>' . $output . $sub_menu . "</li>\n";

}

```

---
Tags: theming
---


# Question
Title: JavaScript running before page fully loaded
I can not figure out why JavaScript is running before the page is loaded. The specific thing I'm waiting on is some images so that I can get their height.

The JavaScript is loaded via hook\_preprocess\_page(): `drupal_add_js(path_to_theme(). '/js/smooth-accordion.js');`.

Thanks for any help!

```
(function ($) {

Drupal.behaviors.listen_to_open = function(item) {
    // item height
    var bodyHeight = item.find('.accordion-body-inner').height();
    var imgHeight = item.find('.multi-image-wrapper li:first img');
    var targetHeight = bodyHeight > imgHeight ? bodyHeight : imgHeight;
    console.log(imgHeight.height());
    item.find('.product-showcase-open').click(
        function(){
            item.find('.multi-image-wrapper').animate({
                height: targetHeight + "px",
            })
            event.preventDefault();
        }
    )
}

Drupal.behaviors.smoothAccordion = {
    attach: function (context, settings) {
                    alert('doh'); // alerts before any text or images appear on page
        var $items = $('.accordion-item-wrapper');
        $items.each(
            function() {
                Drupal.behaviors.listen_to_open($(this));
            }
        )
    }
}
}(jQuery));

```

# Answer
Drupal attach behaviors get called from a jQuery `ready()` callback upon initial page load (it is a little more complicated than that, though). This means that the DOM is ready, but replaced elements may not be done loading. Images are considered replaced elements, so your have a loading bug.

I get around these by using something like imageloaded, or manually attaching via `$(window).bind('load', ...);`, which will run when the whole page is done loading (including images).
> 4 votes

---
Tags: 7, javascript
---


# Question
Title: In Drupal 7 Commerce, how do you change the "View Cart" link in the cart block to something else?
In the Cart Block in drupal 7 commerce. How do you change the "View Cart" link. I want to change it to Edit Cart instead.

http://img853.imageshack.us/img853/2502/8yfy.jpg

# Answer
> 2 votes
There's a couple of ways.

You could implement the Commerce hook to adjust the line item summary info

hook\_commerce\_line\_item\_summary\_link\_info\_alter

e.g:

```
/**
 * Implements hook_commerce_line_item_summary_link_info_alter
 */
function MY_MODULE_commerce_line_item_summary_link_info_alter(&$links) {
  if (!empty($links['view_cart'])) {
    $links['view_cart']['title'] = t('View the magical cart');
  }
}

```

See also commerce\_cart\_commerce\_line\_item\_summary\_link\_info for the default data.

Another way, as mentioned by 4life, is with the stringoverrides module or if you aren't using it already, you can change the text in *settings.php* without an additional module

```
$conf['locale_custom_strings_en'][''] = array(
  'View cart' => 'View the magical cart',
);

```

Either of those approaches should work there.

# Answer
> 0 votes
You can try the string override module.

> Provides a quick and easy way to replace any text on the site.

---
Tags: 7, blocks, commerce
---


# Question
Title: Bootstrap external login from subfolder isn't working
Consider the following script.

```
define('DRUPAL_ROOT', getcwd() . "/..");

require_once DRUPAL_ROOT . '/includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);

$username = "Silox";
$password = "hidden";

global $user;

$account = user_authenticate($username, $password);

// Woah, it seems like we don't know this user, let's create him!
if (!$account) {
    $userinfo = array(
        'name' => $username,
        'pass' => $password,
        'init' => $username,
        'status' => 1,
        'access' => REQUEST_TIME,
    );
    $account = user_save(drupal_anonymous_user(), $userinfo);
    $account = user_authenticate($username, $password);
}

$user = user_load($account, TRUE);
drupal_session_regenerate();
?>

```

This script logs me in or creates a new account when the username and password combination doesn't exist. When I put this script in the base directory of my Drupal installation, everything works perfectly fine.

However, when I put it in the root directory of the PhpBB subdirectory and change the `DRUPAL_ROOT` to `getcwd() . "/.."` to compensate for the extra folder, it doesn't work. If I print out my user array at the end of the function, I get a nice array with corresponding correct info but however, if I return to my Drupal site, I am not logged in.

How can this problem get solved?

# Answer
I think this is related to how you're defining the `DRUPAL_ROOT` constant.

Several times I've had to make scripts interact with Drupal from sub folders, and I've found the simplest way to make sure things work correctly is to preface my code with the following:

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

```

The key thing here is the `chdir()` call.

Also, when creating a path and you want to go up one folder, its usually `../` not `/..`, because directory paths should usually end with a `/`.
> 0 votes

---
Tags: bootstrapping
---


# Question
Title: How to pass a form field value from THEME_system_theme_settings_alter() to THEME_form_system_theme_settings_submit()
**MYTHEME/theme-settings.php:** THEME\_form\_system\_theme\_settings\_alter() builds an input form for /admin/appearance/THEME and the input (values) of the user will not be known by Drupal nor by theme\_get\_settings() before saving the user given input.

I'm kind of curious how to pass this value to THEME\_form\_system\_theme\_settings\_submit() in theme-settings.php?

In other words: I need the value from the user input of the theme settings form **BEFORE** we leave theme-settings.php - Is that possible? Or do I need another way around this?

**Test:** Let's say the value gets stored in a 'textfield', build by the THEME\_form\_system\_theme\_settings\_alter() function:

```
// theme-settings.php
function THEME_form_system_theme_settings_alter(&$form, &$form_state) {
// Test form
$form['whatever_fieldset_group']['user_input'] = array(
    '#type' => 'textfield',
    '#title' => t('Test to get value'),
    '#default_value' => theme_get_setting('user_input'),
    '#description' => t('
         Type some text in textfield
         to get shown in submit message'),
);
}

```

To test if I can pass that value to THEME\_form\_system\_theme\_settings\_submit() we try to show the value of this field in a submit message:

```
// theme-settings.php
function THEME_form_system_theme_settings_submit($form, &$form_state) {

    // the following will not work inside theme-settings.php
    // because value is not known yet by theme_get_setting()
    $data = theme_get_setting('user_input');

    drupal_set_message(
          'For testing purposes we submit that you have
           filled the textfield with the following
           mindless value: '.$data
          );
}

```

This will not work. Of course. And variable\_get() and variabel\_set() seems to be no option ether, because we can not fill any variable without knowing the value in theme-settings.php.

The reason for asking this is, I want to write css from user input in a css file while saving theme settings. Maybe there is a way to fire a function after theme-settings got saved? Not sure. Maybe I need more examples of custom themes and how they solved it there without an additional module ...

# Answer
The answer to the question is quite simple, but not easy to find in the d.o. docs. Thanks to Clive and Jack-PL who gave me the right direction. To reuse the example from the start question we need to summarize:

A form field input value needs to get splitt off (intercepted) from its usual way getting stored for a short moment. Why? For us to do our own processing while submission before theme-settings.php Party is over. Our form field:

```
// theme-settings.php
function THEME_form_system_theme_settings_alter(&$form, &$form_state) {
// Test form
$form['whatever_fieldset_group']['user_input'] = array(
    '#type' => 'textfield',
    '#title' => t('Test to get value'),
    '#default_value' => theme_get_setting('user_input'),
    '#description' => t('
         Type some text in textfield
         to get shown in submit message'),
);
}

```

Now the value will get stored when the user hits submit button. But what if we need to get in between before?

Injecting ...

```
drupal_set_message('<pre>' . print_r($form_state['input'],1));

```

... in `function THEME_form_system_theme_settings_submit` for a moment has revealed, that we were looking for `$form_state['input']['user_input']`, were our fruits are hanging. Searching the value with `drupal_set_message('<pre>' . print_r($form_state['input'],1));` gives us orientation to be able to intercept the right value for our own value processing, demonstrated here in a simple representational form with another little drupal\_set\_message() scenario:

```
// theme-settings.php
function THEME_form_system_theme_settings_submit($form, &$form_state) {

    // the following will not work inside theme-settings.php
    // because value is not known yet by theme_get_setting()
    // $data = theme_get_setting('user_input');

    // But this works!
    $data = $form_state['input']['user_input'];

    drupal_set_message(
          'For testing purposes we submit that you have
           filled the textfield with the following
           mindless value: '. $data
          );
}

```

In my case, I was able to save user input into a file now with `file_unmanaged_save_data($form_state['input']['user_input'],$filepath);` while the user hits submit.

Thanks to Clive and Jack-PL for the fast reply. It helped me a lot!
> 0 votes

---
Tags: 7, forms
---


title: drush variable-set for permission table

text:
# Question
Title: drush variable-set for permission table
I want to enable `access comments`, `post comments`, and `post comments without approval` for anonymous using drush.

Fresh install, the table entry look like this:

```
INSERT INTO `permission` VALUES (2,2,'access comments, access content, post comments, post comments without approval',0);

```

After `access comments`, `post comments`, and `post comments without approval` enabled for anonymous, it looks like this:

```
INSERT INTO `permission` VALUES (3,1,'access comments, post comments, post comments without approval, access content',0);
INSERT INTO `permission` VALUES (4,2,'access comments, post comments, post comments without approval, access content',0);

```

I can use `drush variable-set error_level "0"` to change error reporting level. But how about above case? It looks more difficult to understand

# Answer
> 3 votes
There is currently no explicit command to run in order to grant a role a certain permission. The documentation is very helpful here - http://www.drush.org/help/5

However, you can use drush to execute native SQL in order to solve the issue

e.g.

```
drush sql-query "INSERT INTO permission VALUES (4,2,'access comments, post comments, post comments without approval, access content',0)"

```

If this is something you will be doing on a regular basis after a site install, consider creating your own custom install profile (which will contain the required SQL, or features), or creating your own custom module (e.g. created using features). I imagine having to run this script over CLI is not the most maintainable solution ;)

# Answer
> 1 votes
Use the Permissions API's Drush commands.

# Answer
> 0 votes
For those coming across this post and using Drupal 7, you have two choices.

1.Using SQL, you can run the following

```
drush sql-query "INSERT INTO role_permission VALUES (<role id>,'<permission>','<module>')";

```

e.g.

```
drush sql-query "INSERT INTO role_permission VALUES (1,'access comments','comments')"

```

or

2.Using the Permissions API module, you can run the following:

```
drush -u 1 perm-grant --roles="anonymous user" --permissions="access comments"

```

---
Tags: 6, drush
---


# Question
Title: Adding a Serial (cck field) to the Page Title
I don't really know PHP or how to modify the Drupal API so it would probably have to be a solution in the Drupal interface or rather simple programming.

Is it possible to have a Serial cck field automatically combine with the page/node title? Example, Title: Update Example Task. Serial (job number): 225 -- Automatically combine to make the page/node title: 225 Update Example Task -- So it can be referenced as a autocomplete term with either the Serial field or the Title

Thanks for any input!

# Answer
> 1 votes
Checkout auto\_nodetitle, you could add the serial field as a token to the node title automatically.

The rest should then just fall into place.

---
Tags: entities, 7
---


title: SuHosin configuration for Drupal 7?

text:
# Question
Title: SuHosin configuration for Drupal 7?
My web hosting provider decided to use the suhosin php extension to protect my websites.

For some Drupal 7 sites, I am now getting tons of errors and can't login:

```
Warning: ini_set() has been disabled for security reasons in drupal_environment_initialize() (line 675 of /home/reseller1/example.com/includes/bootstrap.inc).
Warning: ini_set() has been disabled for security reasons in drupal_environment_initialize() (line 678 of /home/reseller1/example.com/includes/bootstrap.inc).
Warning: ini_set() has been disabled for security reasons in drupal_environment_initialize() (line 679 of /home/reseller1/example.com/includes/bootstrap.inc).
Warning: ini_set() has been disabled for security reasons in drupal_environment_initialize() (line 680 of /home/reseller1/example.com/includes/bootstrap.inc).
Warning: ini_set() has been disabled for security reasons in drupal_environment_initialize() (line 682 of /home/reseller1/example.com/includes/bootstrap.inc).
Warning: ini_set() has been disabled for security reasons in drupal_environment_initialize() (line 684 of /home/reseller1/example.com/includes/bootstrap.inc).
Warning: ini_set() has been disabled for security reasons in include_once() (line 300 of /home/reseller1/example.com/sites/default/settings.php).
Warning: ini_set() has been disabled for security reasons in include_once() (line 301 of /home/reseller1/example.com/sites/default/settings.php).
Warning: ini_set() has been disabled for security reasons in include_once() (line 309 of /home/reseller1/example.com/sites/default/settings.php).
Warning: ini_set() has been disabled for security reasons in include_once() (line 316 of /home/reseller1/example.com/sites/default/settings.php).
Warning: ini_set() has been disabled for security reasons in drupal_settings_initialize() (line 772 of /home/reseller1/example.com/includes/bootstrap.inc).

```

Is there an alternative bootstrap without those ini\_set statements? Can we put them on Drupal?

# Answer
> 1 votes
I imagine you could try and override the setting in a local

php.ini

file.

For example.

*/var/www/my-site/php.ini*

```
disable_functions = system

```

Adding a single function instead of the list your host is using by default.

If that works, you could add other functions there, e.g

```
disable_functions = exec,shell_exec,popen,passthru,proc_open,system,pcntl_exec

```

Otherwise, you'll need to hack Drupal to remove those ini\_set declarations and move them to the local php.ini file. ( not recommended )

You could also ask your webhost for help ( recommended )

Alternatively, find a new webhost.

---
Tags: 7
---


# Question
Title: Bootstrapping Drupal: Cannot redeclare function
I'm trying to bootstrap Drupal (I'm making a rather simple bridge that automaticly logs a user into Drupal when they sign into PhpBB). I have the following code placed in the succes scenario of a succesful PhpBB login:

```
// DrupalBridge
function drupalbridge_login($username, $password)
{
    define('DRUPAL_ROOT', getcwd() . "/..");

    require_once DRUPAL_ROOT . '/includes/bootstrap.inc';
    drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);

    global $user;

    $account = user_authenticate($username, $password);

    // Woah, it seems like we don't know this user, let's create him!
    if (!$account) {
        $userinfo = array(
            'name' => $name,
            'pass' => $pass,
            'init' => $name,
            'status' => 1,
            'access' => REQUEST_TIME,
        );
        $account = user_save(drupal_anonymous_user(), $userinfo);
        $loadme = user_authenticate($name, $pass);
    }

    $user = user_load($loadme, TRUE);
    drupal_session_regenerate();
}
//\DrupalBridge

```

This function works perfectly on its own. The problem is that this is in a giant file in the PhpBB system, where the `user_delete()` function is already defined, causing a `Fatal error: Cannot redeclare user_delete()`. The `user_delete()` function is deep inside the PhpBB core so I can't just rename that function either.

How can I solve this problem while still maintaining the functionality?

**==Update==** I managed to fix the problem with the overlapping functions by changing the user\_delete to phpbb\_user\_delete, as phpbb will also work with the phpbb\_ prefix but I've run in to another problem now: Drupal bootstrap external login from subfolder isn't working

Thanks in advance, Silox

# Answer
Instead of mashing the Drupal bootstrap into PHPBB, you could authenticate the user via an external API request to Drupal,

For example, using the Services module, with session authentication.

```
curl --data "username=test&password=pass" https://www.example.com/api/rest/user/login

```
> 1 votes

# Answer
You could perhaps work around this by renaming the functions inside your block using http://php.net/manual/en/function.rename-function.php

Just be careful, you're dealing with PECL stuff ;)
> 0 votes

# Answer
The only on-topic solution I can think of is to move to Drupal 8, which uses name spaces.

You could of course also do something like `sed s/user_delete/drupal_user_delete/g`, though that's going to be very complicated, given false positives and such.
> 0 votes

---
Tags: bootstrapping
---


title: Multisite domain path access control

text:
# Question
Title: Multisite domain path access control
E.g. My site have two subdomains : domain\_a and domain\_b.

I create a path: "custom/a".

I hope:

domain\_a can visit the path.

domain\_b visit the path, get 404.

Except according to the `golbal $domain` in the code, does anyone have other solution?

# Answer
> 2 votes
There's a few ways to do that, but an easy one is to use the Panels module to define the page, coupled with domain\_ctools

Then you can just add a selection rule or access control rule to specify the valid domains via the user interface.

Alternatively, you could do something with hook\_menu access callbacks.

---
Tags: multi-sites, domain-access
---


title: Invoke a rule upon form validation

text:
# Question
Title: Invoke a rule upon form validation
Is it possible to to invoke a rule this way?

So far I have not had any luck?

```
/* Implementation of hook_form_alter*/

function login_auth_form_alter(&$form, $form_state, $form_id) {

  if ($form_id == 'user_login') {

  $form['#validate'][] = 'ea_login';
  }
}

/* implementation of hook_form_validate */

function ea_login($form, &$form_state) {

  $response = rules_invoke('rules_my_rule', $args);
}

```

# Answer
This works

```
/* Implementation of hook_form_alter*/

function login_auth_form_alter(&$form, $form_state, $form_id) {

if ($form_id == 'user_login') {

        $form['#validate'][] = 'ea_login';
    }
}

/* implementation of hook_form_validate */
function ea_login($form, &$form_state) {

        $response = "SUCCESS message";

      rules_invoke_component('rules_display_a_message',$response);

}

```
> 1 votes

---
Tags: rules, users
---


# Question
Title: Rewrite SQL on a specific content type node on Drupal 7
I'm trying to rewrite SQL on a specific node type on Drupal 7. I found this, But it only works on Drupal 6-. What's about Drupal 7? Thank you.

https://api.drupal.org/api/drupal/includes%21database.inc/function/db\_rewrite\_sql/6

# Answer
> 0 votes
While the question is vague as to your purpose, you may be interested in

to alter queries in Drupal 7.

---
Tags: nodes, database
---


# Question
Title: Drupal.behaviors get results from function
I am struggling to understand how this works and I just can not get a grasp of if it. Basically what I am trying to do is get the results from my php function and pass it into ajax to make my page redirect to a certain area.

This is what I have for my php

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

    $entry = payday_parse($form, $form_state);

    /*if($entry['response'] == "sold"){
        print 'success';
    } else {
        print 'failed';
    }*/

    drupal_add_js(array('payday_form' => array('redirect'=>$entry)), 'settings');

}

```

And this is where I am completely lost and in the dark at.

```
(function($){
Drupal.behaviors.payday_form = {
 attach: function (context, settings) {
    $('#edit-submit', context).once('payday_form', function () {
        $(this).click(function(){

            //Response from payday_parse($form, &$form_state)
            final_redirect = Drupal.settings.payday_form.redirect;

                    //this comes back as undefined =/
            console.log(final_redirect);

            //if statement giving from the response above.
            if(final_redirect = 'success'){
                console.log('worked');
            }else{
                console.log('didnt work');
            }
        });
    });
    }
  };
})(jQuery);

```

Am I using this correctly? What am I doing wrong that it isnt picking up the function?

# Answer
Use ajax\_command\_settings. Here is the answer Drupal.settings merging when using AJAX
> 3 votes

---
Tags: 7, javascript
---


# Question
Title: Theme specific Drupal modules? Possible?
Anyone know if it is possible to have Drupal modules enabled/active only when a current theme is present?

Working on a feature where I only need one module to be enabled when the site is accessed via a specific theme controlled by the ThemeKey module in Drupal 7.

# Answer
Themes are enabled/disabled in Drupal by altering the flag in the database table system. And these settings are common for all the users irrespective of which device/ how they are accessing your page.

So in your case it is about making sure that only the files from necessary modules are loaded based on the current theme.

You can use $theme global variable to find out the current theme, and then based on that you can fetch the files from the necessary modules only. You can check the code from js module how the second part can be implemented. You need to have patience though ;)
> 1 votes

# Answer
It might be possible, with some hacks, but definitely is not built in and nothing I would encourage. Modules configuration is global. Enabling and disabling them is often slow, as no one bothers to optimize something that is meant to occur once in the lifetime anyway. So allowing this would kill your performance.

Second problem is cache. Proxies can, and often will serve responses from cache, even redirections. So your site might not be able to even know what type of browser accessed it. It might be unable to even notice it is accessed.

Last but not least, if search engine robot detects you serve it different content than you serve to it's clients, your position in result will go down the drain. They are pretty good at detecting changes in theming, but different module sets are only needed if you want to generate actual content differently, or to decide if to perform redirection. Both actions are no-go for SEO purposes.

**TL;DR** : Probably possible. Don't do it.
> 1 votes

---
Tags: 7, theming, rules
---


# Question
Title: Display a field of one content type based on another selected value
Screen Preview

I am using **DRUPAL 7.** I have created custom content types credit card detail. When adding a new card I want to select the country first and based on that loads related banks in the second drop down. I need help to resolve this issue.Thanks.

Note: country list is loading from countries module, where banks from a db table.

# Answer
You will have to use **AJAX**.

Using `hook_form_alter` you can add ID to the element which needs to be changed.

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

 //First add id to the field to be changed

  $form ['field_bank'][LANGUAGE_NONE][0]['value']['#prefix'] = '<div id="replace_textfield_div">';
  $form ['field_bank'][LANGUAGE_NONE][0]['value']['#suffix'] = '</div>';

//Then you can add AJAX to the countries field like this:

$form ['field_country'][LANGUAGE_NONE][0]['value']['#ajax'] = array(
  'callback' => 'MYMODULE_ajax_callback',
  'wrapper' => array('replace_textfield_div')
          );
 }

```

Now in your ajax callback function:

```
  function MYMODULE_ajax_callback(){
    $country = $form_state['values']['field_country'];

      if($country == 'US'){

             $options = array('Bank1'=>'Bank One', 'Bank2'=>'Bank Two');
           // and so on . You can Load Banks from DB_TABLE and place them here according to your need
             $form['field_bank']['#options'] = $options;

       }
   //AND OTHERS according to your requirement

  return  $form['field_bank'];

   }

```

Please remember to rename the fields according to your forms and requirements.
> 5 votes

---
Tags: 7, entities, nodes
---


# Question
Title: Left Join query causing 'Column not found' error
In Drupal (v7.22) I'm trying to modify a query in a module so that it checks the value of an additional field from another table while looking for a result. I've been going through the documentation but cannot seem to stop my version causing an error. The original working code was:

```
$result = db_query("SELECT nid, type FROM {node}
WHERE type IN (:type) AND LOWER(title) = LOWER(:title)",
array(':type' => $node_types, 'title' => $page_name,));

```

I've then added in a left join:

```
$result = db_query("SELECT nid, type FROM {node} AS entity_id
LEFT JOIN {field_data_field_test}
AS nid ON node.nid = field_data_field_test.entity_id
WHERE node.type IN (:type) AND LOWER(node.title) = LOWER(:title)
AND field_data_field_test.field_test_value = :test_value",
array(':type' => $node_types, 'title' => $page_name, 'test_value' => $tvalue,));

```

But it gives the error:

```
PDOException: SQLSTATE[42S22]:
Column not found: 1054 Unknown column 'node.type' in 'where clause': ...

```

Any help would be appreciated.

# Answer
You made 2 mistakes:

1. For complicated queries, use `db_select()`, not `db_query()`. That way you will use enough of built-in failsafes to know what exactly went wrong.
2. If you insist on `db_query()`, or need an UNION or something `db_select()` simply cannot create, **never** use unbracketed full table name. That's why aliasing exists.

Your query should look about like that:

```
$result = db_query("SELECT nid, type FROM {node} n
LEFT JOIN {field_data_field_test} f
ON n.nid = f.entity_id
WHERE n.type IN (:type) AND LOWER(n.title) = LOWER(:title)
AND f.field_test_value = :test_value",
array(':type' => $node_types, 'title' => $page_name, 'test_value' => $tvalue,));

```
> 3 votes

---
Tags: database
---