# Question
Title: How to load an OpenLayers view into the content area with an AJAX link?
I have a link in the side bar that links to a OL view.

I would like to Ajaxify it so the view is loaded into the content area without a page re-load.

I am using the Ajax link example in the Example module and saving the `$output` at `ajax_link_response()` with this code:

```
<?php
...
function ajax_link_response($type = 'ajax') {
  ...
  $view = views_get_view('view-name');
  $view->set_display('display-name');
  $view->exposed_input['myfilter'] = 'filter-value';
  $view->pre_execute();

  // $output = t("This is some content delivered via AJAX");

  $output = $view->render();
  ...

```

This solution works fine for non OL views but fails to load a OL view into the wrapper div. What am I missing?

Gist files:

# Answer
> 0 votes
This is an issue in OL being addressed by one of its maintainers at http://drupal.org/node/1895530.

He is in need of help, if you got some savvy skills on Drupal Ajax / JS framework, please check out the post above and, if possible, give him a hand.

# Answer
> 1 votes
**NOTE FROM THE QUESTION'S AUTHOR:** This solution works for non OpenLayers views. It fails to build up the wrapper when the view is an OpenLayers though.

So the question remains to be answered.

---

* You have to create a div wrapper where you are supposed to show the ajaxified view content. You have to add the div wrapper in the template file (MYTEMPLATE.tpl.php)
* Create a module that will register the ajax link in hook\_menu(). In the callback of the menu item you have to render the view content using ajax\_commands.

Sample code:

```
function MYMODULE_init() {
  // Add the Drupal AJAX library.
  // You can optionally provide a check to add AJAX library only on certain pages.
  drupal_add_library('system', 'drupal.ajax');
}

function MYMODULE_menu() {
  $items = array();

  $items['ajax-link/nojs'] = array(
    'title' => 'TITLE',
    'description' => 'DESCRIPTION',
    'page callback' => 'MYMODULE_ajax_link_callback',
    'page arguments' => array(1),
    'access callback' => PERMISSION,
    'type' => MENU_CALLBACK,
  );

  $items['ajax-link/ajax'] = array(
    'delivery callback' => 'ajax_deliver',
  ) + $items['ajax-link/nojs'];
}

function MYMODULE_ajax_link_callback($ajax) {
  // Check whether this is AJAX callback.
  $is_ajax = $ajax === 'ajax';

  if ($is_ajax) {
    // Your code to obtain view content in HTML format and store it in some variable say $ajax_content.

    $commands = array();

    $commands[] = ajax_command_replace('div.WRAPPER-YOU-ADDED-PREVIOUSLY', $ajax_content);

    return array(
      '#type' => 'ajax',
      '#commands' => $commands,
    );

  }
  else {
    drupal_set_message('Content added');
    drupal_goto();
  }
}

```

# Answer
> 1 votes
I've had to do this on a Drupal 6 site. The problem is that the settings for the view are output in the header as inline javascript, so you can't just load the div containing the view and expect it to work.

What I had to do was use an ajax call to get the page that has the OL view, grab the div from that containing the view html, then grab the inline js from the header of the page, and run that javascript, then run the OL javascript function that initialises the view.

In short it is a massive PIA.

There are some examples of this working on the individual community pages here

http://www.villagesos.org.uk/communities

..though for the life of me I can't remember which one.

Here's the js snippet that does this anyway, you should be able to work out what's going on, but like I say, it's not a great solution and prob worth looking at something other than the OpenLayers module imo.

```
// Load content from a remote url into ajax target
/*
Drupal.behaviors.vsosStateLoader.loadUrl = function(State, target) {
  $.ajax({
    type:State.data.type,
    url:State.data.url,
    data:State.data.data,
    success:function vsosAjaxLoaded(response) {
      // Load the individual elements and Drupal classes into our ajax target region
      var content = $('#main-content > *', response).not('h1, .local-tasks');
      target.find('> .content').html(content);
      // Load any Drupal settings - to set map data
      var settings = $(response).filter('script').not('[src]');
      settings.each(function() {
      //check we have a value
      if($(this).html()){
        var setting = $(this).html();
        //parse out html comments as this breaks in IE
        setting = setting.replace("<!--","");
        setting = setting.replace("-->","");
        eval(setting);
      }
      });
      // Load behaviours onto new content
      Drupal.attachBehaviors();
    }
  });
};*/

```

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


# Question
Title: Dont want to redirect after registration, possible?
I have a lightbox pop up when a link is clicked to sign up for the site but, after signing up i don't want them to redirect to their user profile page, I need them to stay on the same exact page. Is this possible?

I tried login destination but that feature only works for the login not registration.

# Answer
> 2 votes
You could also use the Rules module.

# Answer
> 1 votes
Try the LoginToboggan module. It has alot more features and community support than login destination module

# Answer
> 1 votes
Cleanest way is probably to just write a little module. In it, use hook\_user() to change the destination URL after login:

```
/**
 * Implements hook_user().
 */
function mymodule_user($op, &$edit, &$account, $category = NULL) {
  switch ($op) {
    case 'register':
      // set the redirect url to <front>
      $_REQUEST['destination'] = '<front>';
      // OR, uncomment the following to disable redirecting completely:
      // unset($_REQUEST['destination']);
      break;
}

```

# Answer
> 0 votes
If you're trying to do this in your own custom module in Drupal 7:

```
function mymodulename_form_user_register_form_alter(){
    $_REQUEST['destination'] = 'anywhere_you_want_to_go_to';
}

```

`hook_form_user_register_form_alter()` always runs on the registration form. Change **mymodulename** to your module and make sure it's on.

The second line is the line that redirects on submit (if it validates). I don't know of any way to not redirect, but you can redirect to the page you're redirecting away from for the same result. Change the **"anywhere\_you\_want\_to\_go\_to"** string to the page you want to go to. eg. *"user/register"* or *"\<front\>"*.

---
Tags: users, redirection
---


title: Change the current loggedin Domain?

text:
# Question
Title: Change the current loggedin Domain?
At D7 multi-domain site, how to simply change the current domain of the user after he logged in to another domain?

For e.g, A user fill the login form at, "false.example.com", I want to push him into "true.example.com" I believe it is the SESSION trick.

Note: I'm using the "Domain Access" module at D7.

# Answer
It depends on your settings.php `$cookie_domain` value.

```
/**
 * Drupal automatically generates a unique session cookie name for each site
 * based on on its full domain name. If you have multiple domains pointing at
 * the same Drupal site, you can either redirect them all to a single domain
 * (see comment in .htaccess), or uncomment the line below and specify their
 * shared base domain. Doing so assures that users remain logged in as they
 * cross between your various domains.
 */
# $cookie_domain = 'example.com';

```

For the session cookie, a value of:

```
$cookie_domain = '.example.com'; // Note the leading wildcard dot "."

```

will work across subdomains

Whereas a value of:

```
$cookie_domain = 'true.example.com';

```

will only work on `true.example.com`

If that session id is valid for that site database session table then the user will be logged in.
> 2 votes

---
Tags: 7, redirection, users, sessions
---


# Question
Title: Page title not displayed at the top of the Content area
The page title is displayed in the breadcrumb, but not as a page title, at the top of the content area. Is there a setting somewhere I can edit, or will I need to manually add it to node.tpl.php?

The Title field is there, in the Content type - manage fields.

The search results page however, does have the page title displayed at the top of the content...(?)

# Answer
According to your `node.tpl.php`, if the node is viewed in teaser mode, that `$title` variable will be output. (`if (!$page):`)

For the node view in full page mode (`if ($page == TRUE):`) then you need to have `print $title` in your theme `page.tpl.php`

i.e:

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

```
> 0 votes

---
Tags: 7
---


# Question
Title: How to include CSS3 Pie in my Drupal site?
I would like to use rounded corners on my Drupal site. I came across CSS3 Pie and would like to try it out. But where exactly do I include the code that I download? In the modules folder?

http://css3pie.com/download

# Answer
There is a module for that: http://drupal.org/project/css3pie

The instruction on the project page are better than what I could explain it as having to be done.
> 3 votes

---
Tags: 7, theming
---


# Question
Title: The purpose of $page in node.tpl.php and when does it become FALSE?
I noticed that there is a variable `$page` in node.tpl.php and it is usually `TRUE`.
The node title is not displayed while it is `TRUE`, but in **page.tpl.php**, the node title has been displayed as a page title. The below is the code snippet from node.tpl.php of Bartik theme.

```
  <?php if (!$page): ?>
    <h2<?php print $title_attributes; ?>>
      <a href="<?php print $node_url; ?>"><?php print $title; ?></a>
    </h2>
  <?php endif; ?>

```

When the variable is `FALSE`, the node title in **node.tpl.php** will be displayed and it seems like duplicate title being displayed. I tried this:

```
function bartik_preprocess_node(&$variables) {
  if ($variables['view_mode'] == 'full' && node_is_page($variables['node'])) {
    $variables['classes_array'][] = 'node-full';
  }
  dpm($variables);
  $variables['page'] = FALSE;
}

```

What is the purpose of this variable and when does it become `FALSE`?.

# Answer
The variable `$page` is TRUE if the node is being shown in its own full page.

If the path is "node/34", `$page` is TRUE.
If the path is "taxonomy/term/5", `$page` is FALSE.

If the node is tagged to taxonomy term 5, it will also be displayed in node listing page at "taxonomy/term/5" in teaser by default. So you do need to add the title and attributes with a link to the node.

But in the full page, title is printed at the **page.tpl.php** level so you don't need to print it again.

The variable `$teaser` is **usually** the inverse of `$page` but you can pass `$teaser` and `$page` both FALSE by making a View on content (not fields) to show full node.

Use `$page` to determine the path of the node. If it's already the node path, you don't have to make a link to node.
> 0 votes

# Answer
That variable becomes false in:

template\_preprocess\_node

with

```
$variables['page'] = $variables['view_mode'] == 'full' && node_is_page($node);

```

See also:

node\_view

For the view\_mode parameter used there.

The output of the node `$title` is controlled by `page.tpl.php` for the full page node view.
> 1 votes

---
Tags: nodes, theming, 7
---


# Question
Title: What is the purpose of the tabs div when logged out?
I am using a Bartik theme and am getting some extra padding in between the breadcrumbs and page title. Using firebug I discovered that there is an empty div which is displayed when I am logged out.

What is the purpose of this div? I thought it's only used in logged in mode... Is there a way to remove it from logged out mode?

# Answer
The tabs div will contain links even when logged out on some pages, such as the user page, where logged-out users can choose to either "Create new account" "Login" or "Request new password" by using the tabs.

Instead of removing it you can prevent it from taking up space when empty using CSS to remove the padding and margins on the div.
> 2 votes

---
Tags: theming
---


title: RSS not appearing in meta tag

text:
# Question
Title: RSS not appearing in meta tag
An RSS-feed on my site doesn't show up in the HTML `<head>` as it is supposed to, which makes it very difficult to find. Here's my situation:

* A view is displaying the latest blog posts.
* This view has two displays: a content pane and a feed. The feed is attached to the content pane.
* The content pane is shown on a page using panels and page manager.

The RSS-icon shows up at the bottom of the view, so the feed is definitely there. However, the feed doesn't show up in the the meta-tags, so the browser doesn't discover the feed like it's supposed to. Does anyone know where this goes wrong, and how I can fix it?

# Answer
> 0 votes
I had a similar issue before. As you mentioned, feed auto-discovery works through the link in the tag (see http://diveintohtml5.info/semantics.html#rel-alternate for more info).

I found that some themes and modules add it in automatically, while others don't. If yours is absent, you can auto-discover the default drupal RSS feed by adding the following to a preprocess function:

```
$element = array(
  '#tag' => 'link',
  '#attributes' => array(
    'href' => '/rss.xml',
    'rel' => 'alternate',
  ),
);
drupal_add_html_head($element, 'mymodule');

```

Alternatively, you could just add it into the html.tpl.php file, as mentioned in this post: http://www.webbykat.com/2012/03/adding-feedburner-rss-link-your-theme-drupal-7-omega

Regarding Views, I have found that enabling auto discovery means adding a "Feed" display then turning on the setting at `Feed Settings > Attach To > Master`, as you did. You can also set it to include other displays to get the RSS icon to display in those views.

---
Tags: 7, feeds
---


# Question
Title: Ubercart refuses to believe it is updated
I perpetualy get the "Security Update Needed" for Ubercart, even after updating.

The Update Modules page gives me: Ubercart (Security update) Installed Version: 3.0 Recommended Version: 7.x-3.3 (Release notes)

But if I actually go to the modules pages, it shows that I have installed Ubercart 7.x-3.3

Is anything actually wrong? If not, is there any way to get rid of the constant update warning?

Thanks!

As requested by responses, here are the database system tables:

'uc\_2checkout', 'sites/all/modules/ubercart/payment/uc\_2checkout/uc\_2checkout.module' 'uc\_affiliate2', 'sites/all/modules/uc\_affiliate2/uc\_affiliate2.module' 'uc\_ajax\_admin', 'sites/all/modules/ubercart/uc\_ajax\_admin/uc\_ajax\_admin.module' 'uc\_attribute', 'sites/all/modules/ubercart/uc\_attribute/uc\_attribute.module' 'uc\_authorizenet', 'sites/all/modules/ubercart/payment/uc\_authorizenet/uc\_authorizenet.module' 'uc\_cart', 'sites/all/modules/ubercart/uc\_cart/uc\_cart.module' 'uc\_cart\_links', 'sites/all/modules/ubercart/uc\_cart\_links/uc\_cart\_links.module' 'uc\_catalog', 'sites/all/modules/ubercart/uc\_catalog/uc\_catalog.module' 'uc\_credit', 'sites/all/modules/ubercart/payment/uc\_credit/uc\_credit.module' 'uc\_cybersource', 'sites/all/modules/ubercart/payment/uc\_cybersource/uc\_cybersource.module' 'uc\_file', 'sites/all/modules/ubercart/uc\_file/uc\_file.module' 'uc\_flatrate', 'sites/all/modules/ubercart/shipping/uc\_flatrate/uc\_flatrate.module' 'uc\_googleanalytics', 'sites/all/modules/ubercart/uc\_googleanalytics/uc\_googleanalytics.module' 'uc\_google\_checkout', 'sites/all/modules/ubercart/payment/uc\_google\_checkout/uc\_google\_checkout.module' 'uc\_order', 'sites/all/modules/ubercart/uc\_order/uc\_order.module' 'uc\_payment', 'sites/all/modules/ubercart/payment/uc\_payment/uc\_payment.module' 'uc\_payment\_pack', 'sites/all/modules/ubercart/payment/uc\_payment\_pack/uc\_payment\_pack.module' 'uc\_paypal', 'sites/all/modules/ubercart/payment/uc\_paypal/uc\_paypal.module' 'uc\_product', 'sites/all/modules/ubercart/uc\_product/uc\_product.module' 'uc\_product\_kit', 'sites/all/modules/ubercart/uc\_product\_kit/uc\_product\_kit.module' 'uc\_quote', 'sites/all/modules/ubercart/shipping/uc\_quote/uc\_quote.module' 'uc\_reports', 'sites/all/modules/ubercart/uc\_reports/uc\_reports.module' 'uc\_roles', 'sites/all/modules/ubercart/uc\_roles/uc\_roles.module' 'uc\_shipping', 'sites/all/modules/ubercart/shipping/uc\_shipping/uc\_shipping.module' 'uc\_stock', 'sites/all/modules/ubercart/uc\_stock/uc\_stock.module' 'uc\_store', 'sites/all/modules/ubercart/uc\_store/uc\_store.module' 'uc\_taxes', 'sites/all/modules/ubercart/uc\_taxes/uc\_taxes.module' 'uc\_tax\_report', 'sites/all/modules/ubercart/uc\_tax\_report/uc\_tax\_report.module' 'uc\_ups', 'sites/all/modules/ubercart/shipping/uc\_ups/uc\_ups.module' 'uc\_usps', 'sites/all/modules/ubercart/shipping/uc\_usps/uc\_usps.module' 'uc\_weightquote', 'sites/all/modules/ubercart/shipping/uc\_weightquote/uc\_weightquote.module'

# Answer
> 0 votes
It sounds like you may have two copies of ubercart in your drupal file system.

Check your database "system" table for the ubercart module path ( filename ).

e.g, raw SQL:

```
SELECT name, filename FROM system WHERE name LIKE 'uc_%';

```

Make sure the path matches what you expect.

If on linux, you could also run:

```
find /var/www/my-site -name 'uc_*' -type d

```

to list the uc\_ folders ( type=directory )

# Answer
> 0 votes
On the suggestion of someone in the official Drupal forums, I removed the whole ubercart module directory and re-downloaded the ubercart modules. That fixed it!

---
Tags: 7, ubercart, updating
---


# Question
Title: Is it a bad practice to use dynamically generated IDs for theming
Is it a bad practice to have styles such as these in the css files ?

```
#block-block-1, #block-block-7, #block-block-8

```

I mean, if one was to delete the block and recreate it the styles would no longer be valid.

Or is it best to modify the template and target the selectors in the template ?

# Answer
> 5 votes
It is better not to use the id.

You could use this module Block Class which allows you to add a class to the block and you can then style your css using that class.

# Answer
> 0 votes
Block names should be also propagated at same level as those id- s, so using them would be more reliable. Try inspecting with Firebug to be sure.

So after recreating a block, editor should take care that names are the same.

---
Tags: theming
---


title: Using Feeds to import data

text:
# Question
Title: Using Feeds to import data
In order to import data from a CSV file, I would like to use Feeds. I followed an example from the Drupal Cookbook, and it uses the Basic Page content type.

Because the data I would like to import has unique data, could you please confirm if I will need to create a new content type with its own fields so I can map map the source to target? I would just like to make sure what I am attempting to do is correct to avoid corrupting the database...

# Answer
If there are different data that you would like to store from your csv, you should create your own content type, add required fields there.

Then in create your feeds importer, set the required settings(like selecting your content type), set mappings and let feeds do its magic(yep, its an awesome module!)

Fees is a great module where you have to import data into nodes, users or taxonomy.
> 1 votes

---
Tags: entities, nodes, feeds
---


# Question
Title: why and how the view is putted in the sidebar first block
I am studying the distrbution OpenAID
http://drupal.org/project/openaid
---
I have a question:
in the block : **sidebar first**. there are some special view related with the url.

but in admin/struction/block. the sidebar first is none.

so question: why and how the view is putted in the sidebar first.

I get a clue : **Exposed form** , but more confuse is left.

# Answer
> 0 votes
resolved it
use **context module.**
Conditions select **view**
Reactions select **block - sidebar first**

---
Tags: views
---


# Question
Title: In a custom module, get return of hook for making it available in other hook
I had some similar questions here, but would like ultimately to know best practices and possibilities for this case.

I have my custom module, in which I use two contrib modules hooks. As I understood, hooks are self-invoked (looking from my module point of view), and as soon as I am declaring it, they get executed.

That said, how I can get return of an hook function ?

I am trying to make $foo1 available in other hook and vice versa for $hook2. I would like to avoid oop solutions if possible.

Example:

```
function mymodule_contribmodulehook1 ($parameter1, $parameter2) {
  //$foo2 here somehow ?
  $foo1 = 1;
  return $foo1;
}

function mymodule_contribmodulehook2 ($parameter1, $parameter2) {
  //$foo1 here somehow ?
  $foo2 = 1;
  return $foo2;
}

```

# Answer
This is more like coding problem..

I will create a function that will store the value, the function has two parameters hook name and value. The function will both set and return values based on certain condition. Values will be set corresponding to hook names. While calling the function if we are passing an argument blank then it will return value, if we call the function and pass both arguments then it will set value.

Here's the sample code:

```
function mymodule_contribmodulehook1 ($parameter1, $parameter2) {
  // $foo2 here somehow ?
  $foo2 = to_and_fro('', 'hook1');
  $foo1=1;
  to_and_fro($foo1, 'hook2'); // Required by hook2.
  return $foo1;
}

function mymodule_contribmodulehook2 ($parameter1, $parameter2) {
  // $foo1 here somehow ?
  $foo1 = to_and_fro('', 'hook2');
  $foo2=1;
  to_and_fro($foo2, 'hook1'); // Required by hook1.
  return $foo2;
}

/**
 * $variable
 * Check whether $variable is present. If present we set the value, otherwise
 * return value.
 *
 * $hook
 * Hook name.
 */
function to_and_fro($variable, $hook) {
  if (!isset($variable)) {
    switch ($hook) {
      case 'hook1':
        return $hook2_var;
      case 'hook2':
        return $hook1_var;
    }
  }
  else {
    switch ($hook) {
      case 'hook1':
        $hook1_var = $variable;
        break;
      case 'hook2':
        $hook2_var = $variable;
        break;
    }
  }
}

```

Also this will help you if you have more than two hooks, all you need is to increase the number of `case` and variable inside the custom function.

Hope this helps you!
> 1 votes

# Answer
Yes, if you implement a hook provided by a contrib module, it is invoked by that module function. You can declare those two variables in global scope so that they can be accessible each other in the functions.

```
<?php
// mymodule.module
global $foo1;
global $foo2;

function mymodule_contribmodulehook1 ($parameter1, $parameter2) {
  global $foo2;
  //$foo2 here
  $foo1 = 1;
}

function mymodule_contribmodulehook2 ($parameter1, $parameter2) {
  global $foo1;
  //$foo1 here
  $foo2 = 1;
}

```

If you don't want to use global scope for your variables, you can save and retrieve them alternatively in your Drupal database using variable\_set() and variable\_get().

```
function mymodule_contribmodulehook1 ($parameter1, $parameter2) {
  $foo2 = variable_get('foo2');
  $foo1 = 1;
  variable_set('foo1', $foo1);
}

function mymodule_contribmodulehook2 ($parameter1, $parameter2) {
  $foo1 = variable_get('foo1');
  $foo2 = 1;
  variable_set('foo2', $foo2);
}

```

Note that, for both approaches, you don't need to return each of them as long as you don't have any other purpose.
> 4 votes

# Answer
You can call a hook yourself, so you could write

```
function mymodule_contribmodulehook1 ($parameter1, $parameter2) {
  $foo2 = mymodule_contribmodulehook2($parameter1, $parameter2);
  $foo1 = 1;
  return $foo1 + $foo2;
}

function mymodule_contribmodulehook2 ($parameter1, $parameter2) {
  // don't call mymodule_contribmodulehook1 here though, it would result in an infinite loop!
  $foo2 = 1;
  return $foo2;
}

```

You might want to refactor the above though:

```
function mymodule_getFoo1($a, $b) { ... }
function mymodule_getFoo2($a, $b) { ... }

function mymodule_contribmodulehook1 ($parameter1, $parameter2) {
  $foo1 = mymodule_getFoo1($paramater1, $paramater2);
  $foo2 = mymodule_getFoo2($paramater1, $paramater2);
  ...
}

function mymodule_contribmodulehook2 ($parameter1, $parameter2) {
  $foo1 = mymodule_getFoo1($paramater1, $paramater2);
  $foo2 = mymodule_getFoo2($paramater1, $paramater2);
  ...
}

```
> 1 votes

---
Tags: hooks
---


# Question
Title: Distance / Proximity from cck location field ? not from user or node location?
I try to get a distance between cck location nodes / users but I didn't succeed at that point because the only avalaible views field to do that is "EMPLACEMENT : DISTANCE / PROXIMITY" which concerns node location or user location, not cck location field.

How to get that point ?

Regards, Yoann

# Answer
> 3 votes
Results may vary based upon your drupal version, but basically when you create a proximity filter:

the first option is "Node location" but when you click on that:

it will allow you to use a Location CCK field as well.

# Answer
> 0 votes
Here is the code I used in the "php code for latitue, longitude" origin section in the "Emplacement: Distance / Proximity field" views :

global $user;
global $databases;
$res = db\_set\_active('default');
$query1 = db\_query("SELECT field\_lien\_adresse\_utilisateur\_target\_id FROM
{field\_data\_field\_lien\_adresse\_utilisateur} WHERE entity\_id = :uid", array('uid' =\> $user-\>uid));
$results1 = $query1-\>fetchAll();
$query2 = db\_query("SELECT field\_adresse\_utilisateur\_lid FROM
{field\_data\_field\_adresse\_utilisateur} WHERE entity\_id = :entity\_id", array('entity\_id' =\> $results1\[0\]-\>field\_lien\_adresse\_utilisateur\_target\_id));
$results2 = $query2-\>fetchAll();
$query3 = db\_query("SELECT latitude, longitude FROM {location} WHERE lid = :lid",
array('lid' =\> $results2\[0\]-\>field\_adresse\_utilisateur\_lid));
$results3 = $query3-\>fetchAll();
$result\['latitude'\] = (float) $results3\[0\]-\>latitude;
$result\['longitude'\] = (float) $results3\[0\]-\>longitude;
return $result;

Then I got the latitude and longitude of the current user.

Hope it's useful.

---
Tags: entities, location
---


# Question
Title: How can I work on which particular pages a CSS rule is used?
I would like to see a list of pages where a particular style is used so I can either delete/modify it.

# Answer
You can see a list of selectors not used on a page using external tools, there is no way for drupal itself to create the list for you however.

You can find some suggestions here: https://stackoverflow.com/questions/33242/how-can-i-find-unused-images-and-css-styles-in-a-website I personally use the chrome developer tools as described in the above link.
> 4 votes

# Answer
I can say that this is not possible.

A particular style is applied on either an id, class or an element. In Drupal, a page is generated by lots of different mechanisms including templates, modules, blocks, etc... So there is no easy way to track a particular id or class and find exactly in which pages does it exist.
> 1 votes

---
Tags: theming
---


# Question
Title: D7 images not loading from css or from direct urls
I have a site that I have developed off-line and now loaded onto the production server. None of the images load on the server (despite being present in the appropriate directories). This applies to images loaded by css (for example:

```
.section-contact div#header {
background-image: url('/www.bernwodebenefice.com/images/contact_banner.png');}

```

It also applies to direct links from nodes. For example:

```
<img alt="" src="/www.bernwodebenefice.com/sites/default/files/StMaryDedication_1_20121202.jpg" style="width: 220px; height: 322px; margin-left: auto; margin-right: auto;">

```

(these samples are from the rendered code and are what I expected).

I do not have this problem with any of my other sites running on the same host. For example:

```
div#header {background-image: url(/sites/all/themes/Endurance80/css/images/e80_2013.gif); height: 263px; }

```

This works perfectly. And urls within the site work nicely using the same sort of link addresses.

I guess I have got some parameter somewhere not set right... (I copied .htaccess and php.ini from a working site to the failing site in the hopes it was a rewrite problem... nope)

Any thoughts?

Peter

# Answer
> 1 votes
Have you tried

`<img src="/sites/default/files/StMaryDedication_1_20121202.jpg">`

and

```
.section-contact div#header {
  background-image: url('../images/contact_banner.png');
}

```

where `images` is a folder in your theme dir e.g: `images/contact_banner.png` relative to css file in e.g: `css/style.css`.

# Answer
> 0 votes
Why are your ulrs in your first two examples start with a slash? If you are not intentionally doing it, it can most probably be related with your settings.php. Check and make sure that your base\_url is defined correctly.

---
Tags: media
---


# Question
Title: Getting different terms from different rows for the same node with Feeds
I have a kind of weird CSV file to import. The structure is like that:

ID| TITLE| TERMS
1 | Title1 | term1
1 | Title1 | term2
2 | Title2 | term3
2 | Title2 | term1
3 | Title2 | term5

I would like to get all the terms from different lines to the same node. In the end, the node with "Title 1" will have taxonomy terms of "term1" and "term2".

If I directly run the importer, I know that only last value will be taken to the term field.

In short, I would like to get multiple terms from different rows to the same node.

Anyone have an idea?

# Answer
In the end, I ended up with a custom php script placed inside the Drupal root. The script reads the csv line-by-line, checks the node if the term exists, if it doesnt exist, adds it to taxonomy term reference field table and taxonomy index table. Taxonomy nidex table is important because views, etc uses it to generate output.
> 0 votes

---
Tags: 7, feeds
---


title: Sub selection in db_select selectQuery

text:
# Question
Title: Sub selection in db_select selectQuery
> **Possible Duplicate:**
> Is it possible to join dynamic tables (subqueries) using db\_select()?

I have this part of a query running in drupal with db\_query.

```
LEFT JOIN (SELECT ogmk.gid, ogmk.etid, kompas.* FROM og_membership ogmk
        INNER JOIN node kompas ON kompas.nid=ogmk.etid AND kompas.type='kompas'
        INNER JOIN publication_date pd ON pd.nid=kompas.nid
        WHERE pd.published_at > :start AND pd.published_at < :end AND kompas.status = 1
        ) ogm_kompas
        ON ogm_kompas.gid=og.gid

```

The left join should give records if they are available. If not the fields will be null.

How can I transform this to the db\_select method with a selectQuery, so I can use the theme function for sorting and paging?

Thanks in advance for your answer.

# Answer
I just found out that you can add a db\_select as a table into the left join. So the solution for this will be:

```
$subselect = db_select('og_membership', 'ogmk');
$subselect->join('node', 'kompas', "kompas.nid=ogmk.etid AND kompas.type='kompas'");
$subselect->join('publication_date', 'pd', 'pd.nid=kompas.nid');
$subselect->condition('pd.published_at', $end, '<');
$subselect->condition('pd.published_at', $start, '>');
$subselect->condition('kompas.status', 1, '=');
$subselect->fields('ogmk', array('gid', 'etid'));

$select->leftJoin($subselect, 'ogm_kompas', 'ogm_kompas.gid=og.gid');

```
> 0 votes

---
Tags: database
---


# Question
Title: How do I set up default.settings.php to use it for development, testing and production sites?
I use **dev**, **tst** and **prd** environments for my Drupal 7 site set up. I use **git** for version control.

I would like to eliminate one manual step I need to do when moving site from *dev* to *tst* and from *tst* to *prd*.

Now I have to update settings.php separately for dev, tst and prd sites.

I would like to set up default.settings.php file so all the settings for dev, tst and prd are stored in one default.settings.php and. after copying to settings.php, Drupal will pick right settings depending on the environment.

I am looking for something like the pseudo code below:

```
common.settings

if environment = dev then
   ...
   dev.settings
   ...
else if environment = tst then
   ...
   tst.settings
   ...
else if environment = prd then
   ...
   prd.settings
   ...
end if

```

Do you know how to do this for Drupal 7, exactly?

# Answer
Don't use the same settings file like you are suggesting with your pseudocode. Instead, use three different settings files in three different folders, each folder corresponding to the domain name of each of your instances.

As a minimum, generally each environment is going to use a separate database host. Other settings that can differ from environment to environment can include the Apache Solr host, memcached settings, temporary folder and files folder, to name a few. You can place all of those there. When you migrate your database from PROD to TEST to DEV, it will automatically pick up the settings you specified.

Imagine that my site is called myfoobarsite.com. This is how my settings structure would look like:

```
/htdocs
../sites
..../default
....../default.settings.php
..../dev.myfoobarsite.com (DEV)
....../settings.php
..../qa.myfoobarsite.com (TEST)
....../settings.php
..../myfoobarsite.com (PROD)
....../settings.php

```

I also generally have two local instances of the site, one with the latest database snapshot from PROD and another where I keep all my changes. This is very useful when working with Features, and it allows you to test your features against the production database (locally) before committing. Here's the modified structure:

```
/htdocs
../sites
..../default
..../dev.myfoobarsite.com (DEV)
..../qa.myfoobarsite.com (TEST)
..../myfoobarsite.com (PROD)
..../mfbs.local (LOCAL ONE)
....../settings.php
..../mfbs2.local (LOCAL TWO)
....../settings.php

```

As for your local instances remember to make the appropriate entries in the `/etc/hosts` file and to modify your Apache host settings.

Just in case, I also placed a snippet from the settings.php for guidance:

```
<?php
$databases['default']['default'] = array(
    'database' => 'myfoobarsite',
    'username' => 'foo',
    'password' => 'bar',
    'host' => '127.0.0.1',
    'port' => '3306',
    'driver' => 'mysql',
    'prefix' => '',
);

/**
 * Apache Solr settings.
 * Use the acquia_identifier/acquia_key when hosting w/ Acquia.
 * Specify only the apachesolr_path key for your local instance
 * or instances that do not use Acquia.
 */
//$conf["acquia_identifier"] = "ABCD-12345";
//$conf["acquia_key"] = "1234f05ab12345dc1234a1234bbc1c12";
$conf["apachesolr_path"] = "http://localhost:8983/solr";

/**
 * Filesystem settings (MAC OS X, LOCAL)
 */
$conf["file_public_path"] = "sites/default/files";
$conf["file_temporary_path"] = "/Users/amateurbarista/tmp";
$conf["file_private_path"] = "/Users/amateurbarista/Sites/tfk/private";

```

Finally, if you're hosting with Acquia, you'll need to go to `http://myfoobarsite.com/admin/config/system/acquia-agent` and click on "clear keys" every time you migrate the database. That will cause Drupal to drop the keys that came w/ the imported database and pick up the ones specified in the settings file.
> 11 votes

# Answer
You can also use Environment modules which allows you to use different modules per environment.

## Instructions

First, you need to have your dev/staging/production sites set up with their own unique settings.php (a common pattern for this is to require settings.local.php from settings.php). If you don't have this kind of set-up, then you don't need this module.

For staging/dev, add something like this to settings.php, once environment\_modules is enabled, these modules will be enabled too.

E.g.

```
$conf['environment_modules'] = array(
  'devel' => 'sites/all/modules/devel/devel.module',
);

```

You can also use one settings.php by using the following example:

```
$env = $_ENV['AH_SITE_ENVIRONMENT']; // Acquia way: environment name
$env = $_SERVER['SERVER_NAME']; // or your server name, or whatever
$envModules = array(
    'default' => array( // By default it is development environment
      'devel' => 'sites/all/modules/contrib/devel/devel.module',
      'coder_review' => 'sites/all/modules/contrib/coder/coder_review/coder_review.module',
    ),
    'dev' => array(
      'devel' => 'profiles/mp_singapore/modules/devel/devel.module',
      'coder_review' => 'sites/all/modules/contrib/coder/coder_review/coder_review.module',
    ),
    'test' => array(
      'diff' => 'sites/all/modules/contrib/diff/diff.module',
    ),
    'prod' => array(
      'diff' => 'sites/all/modules/contrib/diff/diff.module',
    ),
);
$conf['environment_modules'] = $envModules[$env] ?: $envModules['default'];

```
> 0 votes

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


title: File creation date

text:
# Question
Title: File creation date
I have a function in template.php:

```
function test_file_icon($variables) {
  $file = $variables['file'];
  $icon_directory = drupal_get_path('theme', 'test') . '/images/icons';

  $mime = check_plain($file->filemime);
  $icon_url = file_icon_url($file, $icon_directory);
  return '<div class="file-icon"><img alt="" class="file-icon" src="' . $icon_url . '" title="' . $mime . '" /></div>';

}

```

and at the end of file icon i want to show date of file create. Can anyone suggest?

# Answer
> 1 votes
Just add the `format_date($file->timestamp)` somewhere to html of the return value. To set the proper time format, see the documentation of format\_date().

```
return '<div class="file-icon"><img alt="" class="file-icon" src="' . $icon_url . '" title="' . $mime . '" /> ' . format_date($file->timestamp) . ' </div>';

```

---
Tags: files
---


# Question
Title: Where are valid password reset tokens stored?
When one submits the form on `user/password` or executes `drush uli`, a password token is generated. Where does Drupal store these?

# Answer
I do not think Drupal stores password tokens. I have used `drush uli` many times and it generates a one time login link, similar to link generated by user\_pass\_reset\_url(). You should see the functions coding
> 1 votes

---
Tags: users
---


# Question
Title: No body text saved when creating a node with I18n and specific language set
Drupal 7

I'm creating a event type nodes, using data from an external database. It's a multi-lingual site, and the primary language is english.

My code creates the node correctly, when the language is set to LANGUAGE\_NONE, but when it is set to "en", the body text is not saved in the database.

```
foreach ($results as $record) {
  echo '<br/>Creating event: ' . $record->name;

  $node = new stdClass();
  $node->type = 'event';
  $node->uid = 1;
  node_object_prepare($node);

  $node->title    = $record->name;
  $node->language = "en";
  //$node->language = LANGUAGE_NONE;

  $node->body[$node->language][0]['value'] = 'This is a body text for '.$record->name;
  $node->body[$node->language][0]['summary'] = 'Here goes a summary for '.$record->name;
  $node->body[$node->language][0]['format'] = 'raw';

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

  $instance = field_info_instance('node', 'body', 'event');
  print_r($instance);

  $node = node_submit($node);
  node_save($node);
  dpm($node);
}

```

When $node-\>language = LANGUAGE\_NONE, a record is created in the fields\_data\_body table. I can see the body text, but cannot translate it. I guess this is correct.

But when $node-\>language = "en", no record is created. This is my problem. I need this set to "en" as it's a multi-lingual site, and without it, there is no "translate" tab when editing the node (Internationalization module drupal.org/project/i18n)

There is some back history to this issue here.. No "body" when creating a node programatically, with Internationalization ..but it's not essential to read it.

# Answer
> 0 votes
It should be showing 'und' for language neutral nodes. Have you checked the value of the $node-\>language parameter?

You could also try creating one of these nodes with the user interface. Then install the devel module and use the php executor (whatever.com/devel/php) to load the node and output with dpm() to see the contents of the node. You probably have something wrong with the structure.

Example (after the sample node is created):

```
$node = node_load(21);
dpm($node);

```

That will output the node contents for you to help you better explore what you are creating.

# Answer
> 0 votes
The only solution I found was to update the language AFTER it had been saved.

```
$node = node_submit($node);
node_save($node);

// This is a hack, until a good solution is found.
// Can't successfully set language on create, so update it afterwards
$node = node_load($node->nid);
$node->language = "en";
node_save($node);

```

I know it's a hack. But it will do until a solution is found, or a bug fixed.

---
Tags: i18n-l10n
---


# Question
Title: How to show image in teaser of any content
I have created a view which displays the recent blog entries made by users...i have placed this block in sidebar...right now the view is displaying only the recent content with the teaser..however i need the view to display the recent content along with the user picture who posted it and display any image in the teaser if the user has also posted an image in the blog...i.e., if there is an image in the blog then it should be displayed in the view and if not then the teaser should be displayed

thanks

# Answer
Your sentence is not very clear but :

1. To display **user's picture**, add "author of the node" relationship to the view and "user picture" field, *with* the relationship.
2. To display **post's picture**, presuming it's in a distinct image field and not in the body, go to your *display settings* of your content type, in the *teaser* section, set the image as you want it to be displayed, it will then appear in your view.
> 1 votes

---
Tags: views, users, nodes
---


title: Drupal equivalent of Starkers

text:
# Question
Title: Drupal equivalent of Starkers
As most of you probably know when themeing in Wordpress you can use Starkers as your base theme. This clears up the view to show pure semantics so you can style and theme cleanly.

Is there an equivalent for Drupal?

# Answer
> 5 votes
If you're looking for clean and easy base themes, there's Stark (which has a contrib version, as well as the version in Drupal core)

> This contrib version of Stark is an exact copy of the one in Drupal 7 core with one exception. This version now uses a responsive design that matches a Drupal 8 proposal to make Stark use a responsive layout.

There's also Mothership, which I've never used - but it looks pretty awesome!

> The Mothership is a HTML5 base theme that offers a workaround to Drupal’s obscure love for wrapping everything in 2 divs and slapping on 3 CSS classes wherever possible.

---
Tags: 7, theming
---


# Question
Title: How to bulk/mass import/create webform components?
Apart from his module : webform\_auto\_field, is there any way to bulk import or create multiple components in a webform. Even if it is one type of component at a time.

I've already googled on, and didn't get sufficient response..

Thank you all in advance...

# Answer
Maybe the Webform Share module can solve your problem?
> 1 votes

---
Tags: 7, entities, webforms, importing-exporting
---


# Question
Title: User View List in Drupal filter by taxonomy
In a social website powered by Drupal, Users are allowed to add interest tags into a taxonomy terms by autotagging.

My problem is how to create a view page to list all users based on a certain interest in the term list.

Say, I need to display user interested on PHP.

# Answer
You can accomplish this using the views module. Its the Drupal GUI way to build queries so you will be able to crate a page that lists all users based on the field you need.

Here goes a really good reference that may help you with that:

http://nodeone.se/en/taming-the-beast-learn-views-with-nodeone

If you prefer to get your hands dirty you can use the Entity Field Query
> 1 votes

---
Tags: users, views
---


# Question
Title: webform alter default value template.php
I need to alter the default value of a webform in d6, so in my template.php I insert the following function, but it does not work; I don't like to use `$get` in webform.

```
function themename_form_alter(&$form, &$form_state, $form_id) {
  if ('webform_client_form_id' == $form_id) {
    $form['id_of_input']['#default_value'] = $node->field_cck_value[0]['value'];
    return $form;
  }
}

```

Can you help me?

# Answer
> 1 votes
Webform is a node module. So editing a node even though it contains form can be altered using hook\_nodeapi.

# Answer
> 0 votes
You should use

```
$form['submitted']['id_of_input']['#default_value'] = $node->field_cck_value[0]['value'];

```

For further details, refer http://drupal.org/node/1558246

---
Tags: 6, webforms
---


title: Use views result to send data to a rule

text:
# Question
Title: Use views result to send data to a rule
I have a custom view that display several email address. How I can use these addresses to send it an email with a rule?

# Answer
This module will help you views\_rules

From module page:

> **View loop**
>
> A view loop is similar to a regular Rules loop, but allows looping over rows of view results.
>
> **Collect view result rows (action):**
>
> This action collects each variable in all view result rows into list variables for use in Rules.
> 6 votes

# Answer
See subhojit777's answer first. views\_rules is a good module I guess but I have personally used Views Bulk Operations with Rules module and the outcome was *great*!

When Rules and Views Bulk Operations (VBO) modules are present, you will see the integrations in both ends. You can use a Rule (to be clear, a Rules Set) as an action for a VBO form. You can basically, for example, have a button and a table with a list of nodes and checkboxes so you can choose a set of nodes and click the button to run the Rules set on the chosen nodes. In other words, execute a Rules Set on a selection of items using VBO module.

You can do this from the other side as well.

Create a View, and you will see an action to execute a Rules Set on a View using Rules itself. For an example, you can promote all blog nodes made *by the current user* to the front page when the user updates his account.

This can be done by creating a Rules Set that promotes given node to the front page, and a View that lists all blog nodes from a given user ID contextual filter , and a Rule that runs when the user profile is updated.

Johan from nodeone.se has a really nice set of videos about this: http://nodeone.se/en/using-rules-components-with-vbo . You will see many videos in nodeone.se site.

Good luck!
> 5 votes

---
Tags: views, rules
---


# Question
Title: Why is hook_node_access($node, $op, $account) called with $op equal to "create"?
I am using the function `mymodule_node_access($node, $op, $account)` to intercept the operation of creating a new node type "article" by the user Advertiser.

* I created a new user "Advertiser"
* The new user "Advertiser" has all permissions enabled on the node type "article"
* The user "Advertiser" can use the admin bar
* I created a custom module to control access to the node by the user "Advertiser"
* In `mymodule_node_access($node, $op, $account)`, I displays the values of `$node` and `$op`

When the user logs into the system, the function `mymodule_node_access($node, $op, $account)` displays:

> Type of node: article Operation: create

Why does that happen?

The user "Advetiser" has not yet created a new node type article.

Besides, if I disable the use of the admin bar by the user "Advertiser", the situation does not occur.

How can I fix?

# Answer
> 1 votes
The admin menu contains links to create new content, and menu items also go through an access check to make sure the current user has access to the path. If they don't, the menu item is hidden.

The access callback for the path `node/add/*` is `node_access()`, which invokes `hook_node_access()`, which is why your access hook is being invoked when the admin menu is present.

You can either remove the admin menu altogether, or remove the links to create new content from it and your hook won't be invoked any more.

---
Tags: users
---


# Question
Title: Need to add a condition between two fields in a view
I am a Drupal 7 novice. I have two fields of two different contents in a view. The first field is a boolean and the second is text (configured to an external link). Now, I want to make a condition like "If the first field is `Yes`, then the second field should be hidden."

# Answer
This can be accomplished through the Form API. However, if you are a PHP novice, you would probably be better off using the Conditional Fields module. Although this is still in dev (no official release) for Drupal 7, it does work. (If you have security-related requirements, you should use Form API instead though.)

Basically, the module provides you with a UI for adding conditions to fields. The example you give is the same given on the module's page, so this is one solution to your problem.
> 7 votes

# Answer
I guess your question is about views, whether displaying a field or not, not in the node form.

Then my advice, without using views PhP, would be to use **no-result behaviour** in your view :

1. Add your text field, and hide it
2. Add your boolean field, and use **rewrite the output**, and in it set your text field with the given token
3. Use **no result behaviour** on that field, and put either nothing, either what you want to be displayed when your boolean field is set to no.

Hint : for your *no result behaviour* to be triggered when your boolean field is set to no, you have to ensure the key of the "no" is either "0" or empty. To be sure, check the option **Count the number 0 as empty** .
> 0 votes

---
Tags: entities
---


# Question
Title: Override Search module's textfield CSS ID
this is what I am using to override the Search module's submit button's CSS ID:

```
function hook_form_alter(&$form, &$form_state, $form_id) {
    if ($form_id == 'search_block_form') {
        $form['actions']['submit']['#attributes']['id'][] = 'custom_css_id';
    }
}

```

Now I want same thing for the textfield input.

# Answer
It is the same thing as you did above

```
$form['search_block_form']['#attributes']['id'][] = 'custom_css_id';

```
> 2 votes

---
Tags: theming, search, forms
---


# Question
Title: Delete nodes if URL is called via Wget Command
How can I delete the `nodes` if i am calling my `URL` via `wget` command. Because the `anonymous` user haven't permission to `edit/delete`.

# Answer
> 0 votes
I did it using following code :

```
global $user;
$owner_account = user_load(array('uid' => UID));
$temp_user = $user;
$user = $owner_account;
node_delete(NID);
$user = $temp_user;

```

# Answer
> 3 votes
**Services module** is great for this job. Here are the steps how you can make it work:

* Download Services, Chaos tools and Libraries. Enable the **REST Server** module (shipped with Services), it will make you enable all dependencies as well.
* Go to *Structure » Services*, add a new endpoint.
* Choose a machine-readable name, e.g.: `node_remove`.
* Select *REST* as a server.
* Define a path to your endpoint, e.g.: `node-remove`.
* Enable debug mode, it's handy while you are experimenting, Services will write useful information to the log.
* Enable session authentication, this will ensure security.
* After saving your endpoint, edit its resources.
* Enable the *delete* operation in the *node* group and the *login* operation in the *user* group.
* Go to the *Server* tab, select the response formatters and request parsing options that you want.

Your endpoint is ready to use. First you need to post a username and password to `http://example.com/node-remove/user/login`. (It's recommended to create a user with a strong password and permissions for only deleting nodes.) You will get a session ID (among others) in the response. Then you need to perform a *DELETE* request to `http://example.com/node-remove/node/{nid}`. You can write a script for these actions and execute that as a cronjob.

# Answer
> 0 votes
Create a file with the following content and simply drop in the Drupal root directory.
Let's say anonymous-node-delete.php. You could add this URL with your cron command, for example, http://example.com/anonymous-node-delete.php?nids=1,2,3

```
<?php
error_reporting(E_ALL);
define('DRUPAL_ROOT', getcwd());
require_once './includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);

if( isset($_GET['nids'])) {
    $nids = explode(',', $_GET['nids']);
    node_delete($nids);
}

```

I hope this will work. As everyone is accessible to this URL if s/he knows it, **use this as your own risk as this is lack of security.**

---
Tags: nodes, cron
---


title: New "type" of node?

text:
# Question
Title: New "type" of node?
Not sure how to phrase this question but basically I'm creating an non-profit's internal portal within Drupal.

They deal with school sponsorship of children and we want to manage this database in Drupal. Within administration the staff should be able to add/edit/delete a Child from sponsorship much in the same way you would deal with a content node.

I don't want to add Content Type 'Child' as it's not directly for the front-facing website. But would prefer to create a "new node type" (does this make sense?)....in the same way that the Commerce module allows for addition of Products, separate from content.

How would I go about this? (I think I'm missing a key technical word for "Node type"...)

# Answer
I think the technical term you're looking for is 'entity type'. A node is an 'entity' in Drupal, as is a User, Taxonomy Term, Commerce Product etc.

The simplest way to create a new entity type is with the Entity Construction Kit:

> The Entity Construction Kit builds upon the entity system to create a flexible and extensible data modeling system both with a UI for site builders, and with useful abstractions (classes, plugins, etc) to help developers use entities with ease.

But you can of course do it manually too. The Examples module contains a fully working module that defines a custom entity type, if you wanted to code your own solution that would be the best place to start.
> 8 votes

# Answer
I'm not sure why you don't want to use a node.

When you want a node to refer to another node, use Entityreference or maybe Relation.
> 0 votes

---
Tags: 7, nodes
---


# Question
Title: Fusion Accelerator Skins windows are blank after core upgrade to Drupal 7.1.9
I just upgraded my Drupal core to 7.1.9, and now my Fusion Accelerator settings are not being applied. When I try to edit a skin (for a block), the pop-up window is empty except for the "save" button. Also, the front-end "Edit Skin" link (under the gear icon) is missing. Does anyone know what might cause this kind of issue, and how I can get my settings back so I can reapply those skin settings?

# Answer
> 0 votes
It was a cache issue. I cleared my cache and that fixed the issue.

---
Tags: theming
---


# Question
Title: Entity Reference auto complete user name with different field
I'm using the entity reference module to associate users with a particular content type. I'm using the auto-complete widget (tag-style). By default, it uses the user name when auto-completing users. However, I want to change the field it's searching on. I have a field, **field\_complete\_name** that I want to use instead of the **name** field.

My question is, is the Entity Reference module capable of doing this? If so, how do I do it?

# Answer
You can either use the solution mentioned by Clive in the comment above, or build your own CTools plugin for entityreference\_selection. That may take some trial and error but could give you even better control over the queries and logic behind the autocomplete feature.
> 1 votes

# Answer
I took Mikey's suggestion and made a ctools plugin. Here's what I came up with:

I'm using a custom module to house the plugin, but technically you could put the plugin into the entity-reference module itself. This would be ok because this method doesn't replace any module code (which would break updates).

Assuming you make a custom module you will need to put this hook into your .module file:

```
/*
 * Implements hook_ctools_plugin_directory
 */
function custom_module_ctools_plugin_directory($module, $plugin) {
  if ($module == 'entityreference') {
    return 'plugins/' . $plugin;
  }
}

```

Then you will make a file thats located within your module's ctools plugin directory: `.../modules/custom_module/plugins/selection/realname.inc`

The file can be called whatever you want but the file path matters. You could also make the file in `.../modules/entityreference/plugins/selection/` as well (as mentioned above).

Contents of realname.inc:

```
<?php

$plugin = array(
  'title' => t('Use realname'),
  'class' => 'EntityReferenceSelectRealname',
  'weight' => 10,
);

```

You will then make another file in the same directory as this one. The file uses the name of the class provided above then `.class.php` so it will be `EntityReferenceSelectRealname.class.php` for this one.

Contents of EntityReferenceSelectRealname.class.php:

```
<?php

class EntityReferenceSelectRealname extends EntityReference_SelectionHandler_Generic {

  /**
   * Implements EntityReferenceHandler::getInstance().
   */
  public static function getInstance($field, $instance = NULL, $entity_type = NULL, $entity = NULL) {
    $target_entity_type = $field['settings']['target_type'];

    // Check if the entity type does exist and has a base table.
    $entity_info = entity_get_info($target_entity_type);
    if (empty($entity_info['base table'])) {
      return EntityReference_SelectionHandler_Broken::getInstance($field, $instance);
    }

    if (class_exists($class_name = 'EntityReferenceSelectRealname_' . $target_entity_type)) {
      return new $class_name($field, $instance, $entity_type, $entity);
    }
    else {
      return new EntityReferenceSelectRealname($field, $instance, $entity_type, $entity);
    }
  }
}

/**
 * Override for the User type.
 *
 * This only exists to workaround core bugs.
 */
class EntityReferenceSelectRealname_user extends EntityReferenceSelectRealname {
  public function buildEntityFieldQuery($match = NULL, $match_operator = 'CONTAINS') {
    $query = parent::buildEntityFieldQuery($match, $match_operator);

    // The user entity doesn't have a label column.
    if (isset($match)) {
      //This line uses the regular username:
      //$query->propertyCondition('name', $match, $match_operator);

      //This was added to use the "realname" field instead of the regular username:
      //CHANGE THIS:
      $query->fieldCondition('field_er_realname', 'value', $match, $match_operator);
    }

    // Adding the 'user_access' tag is sadly insufficient for users: core
    // requires us to also know about the concept of 'blocked' and
    // 'active'.
    if (!user_access('administer users')) {
      $query->propertyCondition('status', 1);
    }
    return $query;
  }

  //Not sure if this is necessary, but I'll add it in to be safe.
  public function entityFieldQueryAlter(SelectQueryInterface $query) {
    if (user_access('administer users')) {
      // In addition, if the user is administrator, we need to make sure to
      // match the anonymous user, that doesn't actually have a name in the
      // database.
      $conditions = &$query->conditions();
      foreach ($conditions as $key => $condition) {
        if ($key !== '#conjunction' && is_string($condition['field']) && $condition['field'] === 'users.name') {
          // Remove the condition.
          unset($conditions[$key]);

          // Re-add the condition and a condition on uid = 0 so that we end up
          // with a query in the form:
          //    WHERE (name LIKE :name) OR (:anonymous_name LIKE :name AND uid = 0)
          $or = db_or();
          $or->condition($condition['field'], $condition['value'], $condition['operator']);
          // Sadly, the Database layer doesn't allow us to build a condition
          // in the form ':placeholder = :placeholder2', because the 'field'
          // part of a condition is always escaped.
          // As a (cheap) workaround, we separately build a condition with no
          // field, and concatenate the field and the condition separately.
          $value_part = db_and();
          $value_part->condition('anonymous_name', $condition['value'], $condition['operator']);
          $value_part->compile(Database::getConnection(), $query);
          $or->condition(db_and()
            ->where(str_replace('anonymous_name', ':anonymous_name', (string) $value_part), $value_part->arguments() + array(':anonymous_name' => format_username(user_load(0))))
            ->condition('users.uid', 0)
          );
          $query->condition($or);
        }
      }
    }
  }
}

```

You will want to go in and change `field_er_realname` to your field's name. Which is `field_complete_name` in your case. Btw, I used the Computed Field module to generate my "realname" field based on the first and last name provided.
> 7 votes

# Answer
The simplest way of doing that is providing a view for entity selection mode. You can follow the simple instructions on this comment:

https://drupal.stackexchange.com/a/39076/10176
> 0 votes

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


# Question
Title: Deny Access (instead of 404) for non-existant user accounts
For a particular project I'm working on, I'd like to return access denied instead of a 404 for non-existant user accounts. I've tried setting a custom 404 page callback and access callback in hook\_menu(), and then returning FALSE when paths like `user/` are visited, but that doesn't help. I've also tried calling `drupal_access_denied()` directly in the callback, but that just results in a server error.

I've also tried overriding the `user/%user` menu item in hook\_menu\_alter(), but that has no effect on 404 not found pages.

Is there any way to get paths like `user/239841239` (any non-existent user ID) to show an access denied page instead of a 404?

\[**Update**: I simply moved the code I was using in the custom 404 page access callback (see below) to the page callback, and now the access denied page is being served correctly.\]

```
// If visiting a non-existent user page, redirect to access denied.
if (strpos(request_path(), 'user/') !== FALSE) {
  drupal_access_denied();
  drupal_exit();
}

```

# Answer
> 2 votes
I would try setting up a conditional redirect from your 404 page to your custom users-specific error page, that only fires if the path of the referrer is user/\*.

I would try to do this using Rules.

---
Tags: routes, users
---


# Question
Title: math operators for text fields in views filters
I have a field of type text that contains a number like 10. I want to create a search form with views exposed filters. Since the field is a text, I can't use greater than and less than operators on the field. Is there any way to have such operators for a text field?

# Answer
> 0 votes
You'll want to create a different field of type "number" for that.

You might be able to do something like creating using Computed Field to create a new field that takes the value of your original field and changes it to an integer with `$num = (int)$str;`

---
Tags: 7, views
---


# Question
Title: Enable Password and Confirm Password fields in Registration form
i want to have registration form in my drupal site, but that is limited to the fields email and username.

I also want to have fields "Password" and "Confirm Password" in the registration form, so that the user does not need to check his email for his password and can login to the site directly after registration.

How can i achieve this?

# Answer
I think the LoginToboggan module can do everything you need.

> The LoginToboggan module offers several modifications of the Drupal login system in an external module by offering the following features and usability improvements:
>
> 1. Allow users to login using either their username OR their e-mail address.
> 2. Allow users to login immediately. Provide a login form on Access Denied pages for non-logged-in (anonymous) users.
> 3. The module provides two login block options: One uses JavaScript to display the form within the block immediately upon clicking "log in". The other brings the user to a separate page, but returns the user to their original page upon login.
> 4. Customize the registration form with two e-mail fields to ensure accuracy.
> 5. Optionally redirect the user to a specific page when using the 'immediate login' feature.
> 6. Optionally redirect the user to a specific page upon validation of their e-mail address.
> 7. Optionally display a user message indicating a successful login.
> 8. Optionally combine both the login and registration form on one page.
> 9. Optionally have unvalidated users purged from the system at a pre-defined interval (please read the CAVEATS section of INSTALL.txt for important information on configuring this feature!).
> 10. Integrates with Rules module to do various tasks when a user validates via email validation process (see http://drupal.org/node/880904 for an example)
> 8 votes

# Answer
I got it: I needed to de-select the checkbox that allows to enable the email confirmation of the users, which is listed under "User settings."

In Drupal 7, in admin panel, under Configuration \> People \> Account Settings \> Registration and cancellation \> deselect the checkbox: Require e-mail verification when a visitor creates an account.
> 8 votes

# Answer
User registration password module does exactly what you want.

> Let users register with a password on the registration form when verification mail is required.
>
> By default, users can create accounts directly on the registration form, set their password and be immediately logged in, or they can create their account, wait for a verification e-mail, and then create their password. With this module, users are able to create their account along with their password and simply activate their account when receiving the verification email.
> 1 votes

---
Tags: users
---


# Question
Title: Is there a way to quickly copy the same ordering and layout from manage fields to manage displays?
I have a content type I made in Drupal that has over 50+ fields and all sorts of fieldsets, divs, and horizontal tabs. I got the Manage Fields ordering and look to be what I want, but the manage display is all out of order and missing some field groups like the divs, fieldsets, and horizontal tabs. I would need to add them all back in one-by-one! Is there a quick way I can just click a button that would automatically take the existing layout from "Manage Fields" and use that for "Manage Display" for a content type?

# Answer
Since this has been posted for more than a week and nobody has responded, then I am going to assume that there is no quick and easy way. I just ended up recreating the display by hand. Oh well.
> 0 votes

---
Tags: 7, entities
---


# Question
Title: Check to see if two nodes are translations of each other
What is the *easiest* way to check to see if two nodes are indeed part of the same translation set? Is there a function or some property that can be used? I am using the i18n suite of modules to perform node translation.

# Answer
> 0 votes
You can use translation\_node\_get\_translations($tnid) function :

```
// $node is the node which translation set is needed
// this function returns an array of two node objects
translation_node_get_translations($node->tnid);

```

If you want to test it you need to put it somewhere (a wise place) in the code, clear your cache, and then show it with devel module.

Wish helps,

cheers,

jramby.

---
Tags: i18n-l10n
---


# Question
Title: Node template suggestion stopped to work for new content types
I experience the simmilar issue as asked here

I already have several template suggestions that are working properly following structure:

node--type.tpl.php

But for newly added content types, it does not work, whatever i do. I cleared cache, recreated content type, checked spelling.

How can i track in devel or in other way what is source of this error ?

# Answer
> 0 votes
This was due to the strange Caching issue, source of which is yet unknown to me. It may me somehow connected to APC caching, or to nodeaccess cache. I am not yet sure.

After nervous session of clearing different layers of cache, i somehow get it to work.

---
Tags: nodes
---


# Question
Title: How would you migrate a large list of (taxonomy) vocabulary list?
I'm moving a large series of vocabulary lists to a new D7 install. I used features to copy over taxonomy groups. However, I only copied over the taxonomy not the vocabulary lists. Is there an extension to features to handle this?

# Answer
It looks like Taxonomy CSV import/export did the trick. Here is a quote about it (from the module's project page):

> ... allows you to import or export taxonomy from or to a CSV (comma-separated values) file or with a copy-and-paste text.
>
> It helps you to quick import a non-standardized vocabulary, for example an old thesaurus, a hierarchical taxonomy or a simple list of children, synonyms, descriptions, weights or related terms to terms. It can be used as a module or as an API with a plug-in mechanism. It can manage internationalized vocabularies with i18n\_taxonomy, a submodule of i18n module \[Drupal 7 only\].
> 0 votes

# Answer
I have never used it quite for this purpose, but the Feeds module will import from CSV files and can create taxonomy terms. The Drupal 7 version still says it is alpha status, but I have been using it for a while now without any real problems with CSV files.

Just make sure your CSV is UTF-8 clean, otherwise you may get some obscure SQL errors if your data has characters with diacriticals, etc.
> 1 votes

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


# Question
Title: Pass variables from custom module to its template?
I'm trying to query my DB, and return those values as variables, then print those variables on my custom module's custom template and I can't get it to work.

If I put this into my theme layer it works fine.

```
$name=db_result(db_query('SELECT name FROM {users} WHERE id = %d', 2));
print $name;

```

I'd rather keep my queries in the .module file and only have to print the variable on my template. So far I haven't been successful. Also, since I'm planning on having many variables used in many places (like display tables, or as values in calculations) I'd rather be able to print variables where I need them, and not tie them to an `$output`, or `$content` variable.

I referenced this post but I couldn't get the example to work.

I'm really new at this, my experience so far as only to take form info and save it to the DB, not bringing it back. so I'd appreciate any help.

# Answer
> 1 votes
To use the theme API it requires three portions: the template file, the theme hook, and then displaying the defined theme. The below examples are for Drupal 7.

```
<?php
  // defines the theme hook - should follow the naming format "_theme()"
  function mymodule_theme(){
    return array(
      'example_template1' => array(
        'template' => 'mytemplatefile1', // mytemplatefile1.tpl.php
      ),
      'example_template2' => array(
        'template' => 'mytemplatefile2', // mytemplatefile2.tpl.php
      ),
    );
  }

  // in this function is where you would do your DB queries,
  // and pass to the theme function as shown
  function mymodule_customfunction(){
    $calculation = 1+1;
    return theme('example_template1', array(
      'example_variable1' => $calculation,
      'example_variable2' => '123',
    ));
  }
?>

```

The mytemplatefile1.tpl.php file could look something like this:

```
<div class="example-markup"><?php echo $example_variable1; ?></div>

```

To display your output, you could then just execute the following and it would print your value, wrapped in the "example-markup" div.

```
<?php echo mymodule_customfunction(); ?>

```

---
Tags: 6, theming
---


# Question
Title: How do I embed a view of comments within a view of nodes using Entity Views Attach (EVA)
I have one view of nodes. My row style is field. Originally I was trying to create a view that displayed all of the nodes, and all of the comments on those nodes.

I run into trouble using a relationship, because then I get duplicate records for every node. So I'm now trying to make a separate comments view and use entity views attach to attach the comment view as a field to the node.

The problem I am running into is that it seems like there is no way to do this using the fields row style. The only place I can add the comments view is in the displays option. how can I display a view of my comments within a view of my nodes.

# Answer
> 0 votes
It's not really practical to intercalate the rows of one view into another view. Instead, what I would do, would be to create a view with node as its base table, include comments via a relationship, and select "distinct" under query settings in the advanced Views settings column.

---
Tags: views, entities, nodes
---


title: Turning/unloading off jquery?

text:
# Question
Title: Turning/unloading off jquery?
I'm working on themeing a single site of a multi-site Drupal install. The organization that set up the site has jquery 1.2.6 installed which is fine for most things... but as I'm planning on using a few other javascript libraries and maybe a few $.ajax calls, I was hoping for a more up to date jquery for the sake of compatibility.

Is there a way I can write a javascript call to remove the:

```
<script type="text/javascript" src="/misc/jquery.js?K"></script>

```

and then call my own?

# Answer
> 0 votes
It's a lot simpler than you thought my friend, You can simply add your new jQuery version, add it after the older version, the older version and it's plugins will be overridden.

```
<script type="text/javascript" src="/misc/jquery.js?K"></script>
...
...
<script type="text/javascript" src="/misc/jquery-BRAND-NEW-jQuery.js"></script>

```

# Answer
> 3 votes
You cannot just push a newer version jQuery by adding/replacing the tag. Drupal and some modules bundles their own JavaScript that rely on that specific version of jQuery, updating jQuery may break these JavaScript. Most of these script require the jQuery object (from jQuery 1.2.6) to be binded to `$`.

If really needed, you can load an newer version of jQuery in noConflict mode, treating the old jQuery as a an *other library*. So `$` will still be the old jQuery object for the existing script. Andyou can use newer jQuery version using `jQuery` in your script. Properly written plugins and libraries should access the jQuery object using `jQuery` instead of `$` and so should be loadable (after calling the noConflict() method). IF not, you may need to fix them.

# Answer
> 1 votes
You might want to take a look at the JQuery Update module. That will take Drupal 6 to JQuery 1.3.2. It also will show you which Drupal core JS files need modified to work with newer versions of JQuery.

# Answer
> 0 votes
Actually, upon further research, I found an answer here:

http://drupal.org/node/1058168

I used the last solution, unset the old jquery from the $script array and put in 1.8.3 which seems to work so far.

---
Tags: javascript
---


title: Echoing admin menu child items

text:
# Question
Title: Echoing admin menu child items
When you click 'Structure' in Drupal admin the page displayed is a print of the child items of the 'Structure' menu item.

I imagine this behaviour is relatively simple to achieve? I have a custom menu item using hook\_menu but what do I need to do in page\_callback in order to achieve the same results?

# Answer
> 1 votes
```
$items['admin/sponsorship'] = array(

    'title' => 'Sponsorship',
    'page callback' => 'system_admin_menu_block_page',
    'file path' => drupal_get_path('module', 'system'),
    'file' => 'system.admin.inc',
);

```

Seems to have done the trick.

---
Tags: 7, routes
---


title: Speeding up page loading of custom view

text:
# Question
Title: Speeding up page loading of custom view
Right now I have a custom view template created where I have a left sidebar and a main content area.

In the left sidebar I have taxonomy menu running to show my taxonomy terms.

I then have a custom view in my main content region filtering the nodes related to the taxonomy term. When I click on each term, the whole page has to load. It's just a bit too slow.

I've turned Ajax ON for my view, but it's not working (probably because I am not using it right).

Would using exposed filters be my answer to this? Or is there any way to keep my format and somehow pass the information to the views without having to load the entire page?

An example of a site doing what I would like can be found here.

# Answer
> 0 votes
Using Panels you can put a view in one area of the page and allow it to accept arguments given by clicking other elements on the page. NodeOne's tutorial videos on Panels may be helpful.

# Answer
> 0 votes
You're going to have to attach view filter "actions" to your menu items. That way your view results will load with ajax.

this is probably the fastest way to do this, though I've never done it I think it's possible (theoretically).

Of course you could also just create Ajax functions that queried your view with the arguments when you click a menu item.

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


# Question
Title: Version numbers of dependencies in testing
If I'm submitting a test to the qa.drupal.org testbot, and my module requires a dev version of another module in order to function properly, is it adequate to declare the version in my module's .info file, or do I need to also specify version numbers in the test `DrupalWebTestCase::setUp()` where dependencies are declared for the test itself?

# Answer
From the **module.info** file docs: ( quite long, but informative )

## dependencies

An array of other modules that your module requires. If these modules are not present, your module cannot be enabled. If these modules are present but not enabled, the administrator will be prompted with a list of additional modules to enable and may choose to enable the required modules as well, or cancel at that point.

The string value of each dependency must be the module filename (excluding ".module") and should be written in lowercase like the examples below. Spaces are not allowed.

```
dependencies[] = taxonomy
dependencies[] = comment

```

In addition, `test_dependencies[]` can be used to indicate dependencies which are optional but recommended. At this writing they are supported only by Drupal.org's automated testing system. *They cause the testbots to check out the projects suggested*.

`test_dependencies[] = autoload`

If you need to specify that a certain module's version number is required Drupal 7 provides a way for this in the dependencies\[\] field. Version numbers are optional and only necessary if the module absolutely requires another module's specific version or branch.

The syntax for the dependencies\[\] field(s) is:

`dependencies[] = modulename (major.minor)`

Where major is the numeric major version number and minor is the numeric or alphanumeric minor version number. x can be used to denote any minor version. Some examples follow.

```
name = Really Neat Widget
description = An example module
dependencies[] = exampleapi (1.x)

test_dependencies[] = autoload (>7.x-1.5)
...

```

In the above .info code, the "Example" module requires an "Example API" module with the major version of 1 and any minor version.

`dependencies[] = exampleapi (1.0)`

This means that the module requires the 1.0 (and only the 1.0) version of the Example API module.

`dependencies[] = exampleapi (1.x)`

The above module requires any minor version of the module in the 1.x branch (1.0, 1.1, 1.2-beta4, etc.)

The `dependencies[]` property in the .info file can also optionally specify versions:

```
= or == equals (optional: equals is the default)
> greater than
< lesser than
>= greater than or equal to
<= lesser than or equal to
!= not equal to

```

`dependencies[] = exampleapi (>1.0)`

The above module requires any version greater than version 1.0.

You can optionally specify the core version number as well:

`dependencies[] = exampleapi (>7.x-1.5)`

The above module requires a 7.x version compatible version of the module and a version greater than 1.5.

Additionally, multiple version dependencies can be specified as comma-separated values within the parentheses:

`dependencies[] = exampleapi (>1.0, <=3.2, !=3.0)`

This facility can be used to specify a minimal core version by using system as the module name:

`dependencies[] = system (>=7.53)`

This makes the module require at least Drupal 7.53.

More info: http://drupal.org/node/542202#dependencies
> 6 votes

---
Tags: community-official-site, .info, testing
---


# Question
Title: How to unset CSS class for menus in the template.php?
Lets say I have a menu block in my header region. And by default Drupal gives *.active* class for links that are active. I need to get rid of that *.active* class, because the CSS/HTML version of the theme (which I am porting to Drupal 7) doesn't have *.active* class and its not just *.active*, there are many more.

I need this because now default Drupal rules like *a.active* overrides my themes CSS of a simple *a* rule.

Please, do not recommend *!important*.

# Answer
If you want to override a core stylesheet, add it to your theme .info file.

That way, the `.active` class need have no CSS rules

e.g: `themename.info`

```
stylesheets[all][] = system-menus.css

```

> To override a core or contributed module style sheet, it must be specified in your theme's .info file. Drupal overrides are cascading and your theme's stylesheets override any that were previously declared. For example, system-menus.css is located at "modules/system/system-menus.css". If you place a file with the same name in your theme's folder and add the following entry to the .info file, the original system-menus.css file will be ignored and your version will be loaded in its place.

More info here: http://drupal.org/node/263967

See also hook\_css\_alter for a code-based solution to remove stylesheets.
> 1 votes

---
Tags: theming
---


# Question
Title: To know what theme functions are available
I wonder if there is any method to obtain all available options for `theme()` function in Drupal installation? (I mean those one that are declared through `HOOK_theme()`). Or at least a resource where the most common uses are noted.

P.S. This is not trivial question for me, because almost every module introduces its own hooks for theming and if I don't know about them I can not leverage from theming opportunities. For example if I don't know about `theme('table', ....)` or `theme('fieldset', ....)` I have to write my own hooks that, e.g., another developer in his turn will not be heard of, etc.

Thank you.

# Answer
> 3 votes
The default theme implementations for Drupal core can be found listed here:

http://api.drupal.org/api/drupal/modules%21system%21theme.api.php/group/themeable/7

If you want the theme functions for contrib as well, you could use hook\_theme\_registry\_alter on your install and dump out the theme registry with devel to list all the theme implementations.

e.g

```
/**
 * Implements hook_theme_registry_alter
 */
function mymodule_theme_registry_alter(&$registry){
  dpm($registry); // requires devel module
}

```

# Answer
> 3 votes
There are over 200 theme hooks in Drupal 7 core, you should not need to know all of them, since most of them will never need to be called, or overridden.

Think about the markup you would like to produce, and then either search the drupal API for a function that provides that markup, or look at a module that already produces something similar, and use the function they use.

---
Tags: theming
---


# Question
Title: Add a hyperlink underneath the table of a Page View?
I have a Page View that is being displayed as a table. Underneath that table I want to add a simple hyperlink.

I was looking into `hook_views_pre_render` but I do not see any way to do add this. I also tried `hook_preprocess_node`. In order to add an anchor tag underneath the table, I really don't know if I should be looking at view hooks or page hooks, or ?

Question: How do I add a hyperlink underneath the table of a Page View?

# Answer
There's a few ways to do that.

1. Edit View
2. Click "Footer \> Add"
3. Add your footer HTML as "Global: Text Area"

Another way is to add a block on that page under the view.

1. admin/structure/block/add
2. Set page visibility to only your View page path
3. Set region to "Content" below "Main page content"

If you want more control or placement, you can theme the View page

1. Edit the View
2. Click "Advanced \> Theme \> Information"
3. You would override the page level "views-view.tpl.php" template renamed to match your View (e.g views-view--my-view.tpl.php ) in your theme dir.
> 3 votes

---
Tags: views, hooks, 7
---


# Question
Title: Replace menu's ul li.first a text link with image  link
Drupal 7.

For example no matter what menu block would be added to the header region, how can I make it replace first link (which has .first class) with image link?

So Drupal generates links as `<li class=first><a href="#">Home</a></li>` and then apply some function from template.php which would replace it with something like `<li class=first><a href="#"><img src='../link.png'></img></a></li>`

I found some code which kind of does that, but it needs to enter path to image via Add link under Title field and I don't really need that, the users of the theme won't understand how that works. And it also applies to any links. While I need to switch the very first text link with image link whose path would be given inside template.php

```
<?php
/**
* Allows for images as menu items.
* Just supply the an image path in the title. The image path will be replaced
* with an img tag. The description is used as alt text and title.
* Implements theme_menu_link().
* Reference: http://chrisshattuck.com/blog/how-use-images-menu-items-drupal-simple-preprocessing-function
*/
function YOUR_THEME_menu_link($variables) {
  $element = &$variables['element'];

  $pattern = '/\S+\.(png|gif|jpg)\b/i';
  if (preg_match($pattern, $element['#title'], $matches) > 0) {
    $element['#title'] = preg_replace($pattern,
      '<img alt = "' . $element['#localized_options']['attributes']['title'] . '" src = "' . url($matches[0]) . '" />',
      $element['#title']);
    $element['#localized_options']['html'] = TRUE;
  }

  return theme_menu_link($variables);
}
?>

```

I can do that with CSS, but I prefer not (client side reasons).

# Answer
> 3 votes
You can override theme\_menu\_tree. All it does is output UL tags, so you could squeeze in an LI at the beginning, like this:

```
    function mycustomtheme_menu_tree($variables) {
      $path = drupal_get_path('theme', 'mycustomtheme') . '/images/home.png';
      $image = theme('image', array('path' => $path, 'alt' => t('Home'), 'title' => t('Home')));
      $home_link = l($image, '', array('html' => TRUE));
      $home_li = '<li class="home">' . $home_link . '</li>';
      return '<ul class="menu">' . $home_li . $variables['tree'] . '</ul>';
    }

```

I've done this exact thing on several sites (but I use nice\_menus), here's the code I added to my template.php file in my custom theme:

```
    function mycustomtheme_nice_menus_tree($variables) {
      $menu_name = $variables['menu_name'];
      $mlid = $variables['mlid'];
      $depth = $variables['depth'];
      $menu = $variables['menu'];
      // Load the full menu array.
      $menu = isset($menu) ? $menu : menu_tree_all_data($menu_name);
      if (isset($menu)) {
        $page_menu = menu_tree_page_data($menu_name);
        $trail = nice_menus_build_page_trail($page_menu);
        unset($page_menu);
      }

      // Allow i18n module to translate strings where available.
      if (module_exists('i18n_menu')) {
        $menu = i18n_menu_localize_tree($menu);
      }

      // Assume depth == 0 by default, overriden if mlid is specified.
      $parent_depth = 0;

      // For custom $menus and menus built all the way from the top-level we
      // don't need to "create" the specific sub-menu and we need to get the title
      // from the $menu_name since there is no "parent item" array.

      // Create the specific menu if we have a mlid.
      if (!empty($mlid)) {
        // Load the parent menu item.
        $item = menu_link_load($mlid);
        // The depth for our parent item, if it exists.
        $parent_depth = ($item['depth']) ? $item['depth'] : 0;

        // Narrow down the full menu to the specific sub-tree we need.
        for ($p = 1; $p < 10; $p++) {
          if ($sub_mlid = $item["p$p"]) {
            $subitem = menu_link_load($sub_mlid);
            // Menu sets these ghetto-ass keys in _menu_tree_check_access().
            $menu = $menu[(50000 + $subitem['weight']) . ' ' . $subitem['title'] . ' ' . $subitem['mlid']]['below'];
          }
        }
      }

      $output['content'] = '';

      if ($menu) {
        // Set the total menu depth counting from this parent if we need it.
        $depth =  ($depth > 0) ? ($parent_depth + $depth) : $depth;
        $output['content'] .= theme('nice_menus_build', array('menu' => $menu, 'depth' => $depth, 'trail' => $trail));
      }

      /* my changes */
      $path = drupal_get_path('theme', 'mycustomtheme') . '/images/home.png';
      $image = theme('image', array('path' => $path, 'alt' => t('Home'), 'title' => t('Home')));
      $home_link = l($image, '', array('html' => TRUE));
      $home_li = '<li class="home">' . $home_link . '</li>';

      $output['content'] = $home_li . $output['content'];
      $output['subject'] = '';

      return $output;
    }

```

---
Tags: theming
---


# Question
Title: How to programmatically update node title?
I would like to programmatically update some fields including the title of a node, when this node is saved. To do so I am using a hook

```
function MY_MODULE_node_update($node) {
    $node->title = "Something new an beautiful";
    $node->filed_what_ever = "Something";
    field_attach_update('node', $node);
}

```

The problem is, that the title is not updated, I assume, that's because of the fact it isn't a field an the Drupal sense. But I can not use

```
node_save($node);

```

instead, because that brings me in an infinite loop: the function hook\_node\_update() is called by the function node\_save()... So what would be a clean why to do this?

# Answer
> 6 votes
To do this, you have to use hook\_node\_presave().

It's called before saving the node to the database. (both new nodes and edits). Note that you must make sure that you are saving sanitized and formatted data.

---
Tags: nodes
---


title: Next free value field

text:
# Question
Title: Next free value field
I need a custom field whose default value will be a "next free" value calculated using a user-defined scope (selection of content types). But before I even try to bother coding, maybe someone knows of such a contributed module? My searches returned nothing.

*I'd be reluctant to using Computed Field as I feel somewhat uncomfortable storing PHP code in database.*

# Answer
> 1 votes
Perhaps you could just use a Serial field

> This module provides an auto-increment (serial) field.
>
> Unlike Drupal's built-in auto-increment node ID, which is global and shared by nodes belonging to all content types, serial fields are managed per content type (D6) / entity (D7). For example, the serial field of an Invoice instance will generate a unique sequential number (starting at 1, then 2, etc.) exclusively for Invoice instances.
>
> The allocation of serial numbers by this module is atomic. In other words, the serial values are unique even when multiple instances of the same content type / entity are created simultaneously.

---
Tags: 7, entities
---


# Question
Title: Is it ok to move the page-title outside of the content div? Or is there a better way?
I've got a couple of blocks which I would like to appear above the main content area on one particular page... These two blocks are sitting above 'Main page content' blocks in admin/structure/block.

After enabling the page titles to be displayed, I realised that this isn't going to work, because I still want the page title to be displayed ABOVE these two blocks. So in between these two blocks and the main page content.

Is it ok for me to modify the template so that the page-title is outside of the content div? Or is there a better way to solve this problem?

# Answer
> 0 votes
Use the Blockify module. It will create block for a lot of common drupal elements (including page title), so you can easily place them on a page with a UI, rather than hacking templates.

---
Tags: theming
---


title: Drupal 6 querying multiple tables

text:
# Question
Title: Drupal 6 querying multiple tables
Having some trouble with the Drupal 6 query syntax. My query works fine on its own:

```
SELECT term_node.tid, term_data.name FROM term_node, term_data WHERE nid = 22640

```

Below is what I have when I convert it for use with drupal 6:

```
$currentTIDs = db_query("SELECT {term_node}.tid, {term_data}.name FROM {term_node}, {term_data} WHERE nid = 22640");

while ($cTids = db_fetch_object ($currentTIDs)) {
array_push($currentTIDsArray, $cTids);
}

drupal_set_message('<pre>' . print_r($currentTIDsArray, TRUE) . '</pre>');

```

This results in an empty query / array? Any Ideas?

# Answer
I think you need a proper inner join.

Tweaking your snippet to:

```
$currentTIDs = db_query("SELECT tn.tid, td.name
                         FROM {term_node} tn
                         INNER JOIN {term_data} td
                         ON tn.tid = td.tid
                         WHERE tn.nid = 22640");

while ($cTids = db_fetch_object ($currentTIDs)) {
   array_push($currentTIDsArray, $cTids);
}

drupal_set_message('<pre>' . print_r($currentTIDsArray, TRUE) . '</pre>');

```

I digress, but worth mentioning Drupal coding conventions on variable names etc.. can be found here: http://drupal.org/coding-standards#naming
> 0 votes

---
Tags: 6, database
---


# Question
Title: Add a link on to /cart on /cart/checkout, using uc_cart_checkout_form. necessary or not?
I am trying to add a link or button from the checkout page http://dev.hearst.gotpantheon.com/cart/checkout

To the update cart page http://dev.hearst.gotpantheon.com/cart/

Right now there are only two buttons showing up, "review cart" and "cancel"

strangely enough if I press "enter" on my keypad I get redirected to the desired update cart page. http://dev.hearst.gotpantheon.com/cart/

I am thinking of using

```
function MyThemeName_uc_cart_checkout_form($form) {

}

```

To add a simple link to 'update cart' into the html or as a form element, I am new to Drupal. How would I do this using the form API? Or is there simply a setting I can set to make the "update cart button" appear http://dev.hearst.gotpantheon.com/cart/

# Answer
The cancel button will take the user back to the cart page, which is why you are redirected there when you hit enter on the form.

You could indeed add the link by theming the checkout form.

The alternative would be by modifying the form itself, and adding a new markup type element:

```
$form['cart_link'] = array('#value' => l('Cart', 'cart'));

```

You can modify the form using hook\_form\_alter

But using the theme hook is fine too!
> 1 votes

---
Tags: 6, ubercart
---


# Question
Title: How to embed a custom content type in a Drupal 7 theme?
How can I make a custom content type automatically available when a specific template is used? e.g.: "Standard Page" is the custom content type I made with Drupal, going to structures--\>content type etc. Now, it will be seen among the default content types, i.e. basic page and article. I want to make that custom content type, Standard Page, available without any effort when the template is enabled, i.e. without editing it: it must be embedded in the theme. How could it be done? p.s. I'm new to drupal theming. Any suggestion will be really appreciated.

# Answer
That's correct (answer below) -- you can't embed content types in your theme, however, you can create custom modules that users can install to have a content type you've created available.

If you are new to Drupal, and do not write your own modules yet, you can use the Features module to create custom content types on your site, export them to a feature via the Features module, and import them to any number of sites.

Using the features module can be a little confusing at first, but there's lots of additional documentation and tutorials online. I'd start with the module's documentation page first: http://drupal.org/node/580026. :-)
> 1 votes

# Answer
Content types and themes are completely different things, and you cannot simply embed a content type in a theme.
> 0 votes

---
Tags: theming, nodes
---


# Question
Title: How to convert Rules 'text' data type to 'text_formatted' type?
I am working with Rules to set a node's body. Based on the data selector, the node body requires a text\_formatted type as input.

Currently, my custom event only provides a plain 'text' Rules data type. Is there a way I can programmatically convert the plain text to text\_formatted? And when and where should it happen?

# Answer
> 1 votes
I tried fixing this myself but I'm not sure if this is the best.

I took a peek at entity/includes/entity.property.inc and found the definition of entity\_property\_text\_formatted\_info() enough for me to define it properly.

I simply wrapped the plain 'text' with an array definition of a

```
    $text_formatted = array('value' => $text_plain,
                            'summary' => $text_plain,
                            'format' => 'full_html');
```

And fed $text\_formatted to the event invoke call.

---
Tags: rules
---


# Question
Title: Switch between two views by clicking on a menu tab without any page refresh
I have created two views on my custom content type as two different blocks. I want to place them in a new page say /node/47. In node/47 there are two tabs...on clicking one of them view 1 appears and on clicking another on of them view 2 appears while view1 goes away...by default any of the view can appear on the page when its first visited..i do not want any page refresh to take place

Thanks

# Answer
You can try the Quick Tabs module.

> The Quick Tabs module allows you to create blocks of tabbed content, specifically views, blocks, nodes\* and other quicktabs\*. You can create a block on your site containing multiple tabs with corresponding content. Clicking on the tabs makes the corresponding content display instantly, using jQuery. With the 6.x-2.x branch, this can be done in either ajax or non-ajax mode:
> 5 votes

---
Tags: views, 7
---