# Question
Title: Modify tpl file to print the path to the image instead of the image itself?
I need to change this tpl file which generate images for a image field to print the path to image instead of the image itself.

**This code print out the images. It works fine**

```
<div class="<?php print $classes; ?> clearfix"<?php print $attributes; ?>>
  <?php if (!$label_hidden) : ?>
    <div class="field-label"<?php print $title_attributes; ?>><?php print $label ?>: </div>
  <?php endif; ?>
  <div class="field-items"<?php print $content_attributes; ?>>
    <?php foreach ($items as $delta => $item) : ?>
      <span class="<?php print $delta % 2 ? 'odd' : 'even'; ?>"><?php print render($item); ?></span>
    <?php endforeach; ?>
  </div>
</div>

```

I need to print just the path to the image (not the image). **I tried with this code but I get a error message related to line 58. (see the error message below)**

```
<div class="<?php print $classes; ?> clearfix"<?php print $attributes; ?>>
  <?php if (!$label_hidden) : ?>
    <div class="field-label"<?php print $title_attributes; ?>><?php print $label ?>: </div>
  <?php endif; ?>
  <div class="field-items"<?php print $content_attributes; ?>>
    <?php foreach ($items as $delta => $item) : ?>
      <?php dpm($item); // I uploaded a capture of this dpm

          echo $item['#item']->uri; // THIS IS LINE 58

     ?>
    <?php endforeach; ?>
  </div>
</div>

```

Error:

> Notice: Trying to get property of non-object en include() (line 58 de /Applications/MAMP/htdocs/lembassade.com/sites/all/themes/omega\_subtheme\_2/templates/field--field-im-genes-del-fondo.tpl.php).

# Answer
> 2 votes
From the looks of your devel output (and the error message), each `$item` is an array, not an object.

You should be able to fix it by changing the line inside the loop to:

```
echo $item['#item']['uri'];

```

---
Tags: theming
---


# Question
Title: Content From Another Page Displaying on Current Page
I created a piece of content called training that is supposed to display all training content offered. Instead of displaying only training content it is displaying articles, news content within the page.

Could someone steer me in the right direction in order to solve this issue? I'm a bit new to Drupal so I am still learning my way around. Thank You.

# Answer
Go to the views section in Drupal and double check your "filter" and "sort" settings. Sounds like you may have missed a step.
> 0 votes

# Answer
I think we might need a bit more detail to answer your question.

Is training really a content type or a view? Normally content is displayed inside a view unless your are viewing the actual node page. If you are really talking about a view that you could just add a content type filter.

Also, what version of drupal are you using? My above response assumes 7.
> 0 votes

---
Tags: views, nodes
---


# Question
Title: With optimized js enabled, my javascript code not working
I have a drop down list. On the change event of the drop down list I have written some javascript code. When I select an option from the drop down list a site opens in the new window.

So for this I wrote some javascript code on the change event of the drop down list.

But the problem is that when I enable the optimize js files then my drop down change event does not work and when I disable the optimize js files then the change event of the drop down works.

So what should I do for this to work in both condition?

**UPDATED:**

```
Drupal.behaviors.change = function (context) {

    $(".test").change(function(){
        var page = $(".test").val();
        window.open(''+page+'', '_blank');
    }) ;

};

```

# Answer
The reason maybe is your custom script loads first before the Jquery script.

Try this:

```
(function($) {
  $(function() {
    //your script here
  });
})(jQuery);

```

or

```
Drupal.behaviors.somethingHere = function (context) {
  //your script here
}

```
> 1 votes

# Answer
This is a shot in the dark, but when you concatenate Javascript files, the problem could actually be from another file and not the one that isn't working. I would try using

```
;Drupal.behaviors.change = function (context) {
    $(".test").change(function(){
        var page = $(".test").val();
        window.open(''+page+'', '_blank');
    }) ;
};

```

Note the semicolon at the beginning. If the previous file is missing a semi-colon, it may work on its own, but result in a syntax error when you concatenate. Out of habit, everything I declare at the top-level gets these.
> 0 votes

---
Tags: 6, javascript
---


# Question
Title: Links continue to point to live server - Drupal Live to localhost
I have inherited a Drupal 6 site to maintain.

I am new to Drupal so there is an element of learning as I go.

I have encountered a strange issue after attempting to set up a test site on my local machine.

All my links on my local site continue to point to the live server. So any menus, login buttons etc all point towards live site.

Steps I have taken:

* checked settings.php to ensure that $base\_url is set to "http://localhost:456"
* checked settings.php to ensure that MySQL settings are correct
* Taken an SQL dump of the entire local database and searched for any references to live site URL
* deleted all the local cache data from database
* Checked various blocks to ensure that there was no hard coding of links
* Disabled language support as that does use separate URLS for each language

I am at a total loss as to where to go from here. I can navigate through the site locally by replacing the url in the address bar to point to the local site, and I have even managed to change the local theme so I can see which version of teh site Im on. The fact that I could do this means that the database is set up correctly.

Totally stumped as to where to go from here. Any takers??

# Answer
> 0 votes
the issue was being caused by the default language being set from the 'variable' table. The URL associated with this language was pointing my local site to my remote server.

I had changed the URL to localhost directly in the languages table, but it turns out Drupal also stores this information in the 'variable' table.

1 thing to note if anyone decides to change a value in the variable table, be sure to change the metadata for the variable as well as the value.in my case S:22 had to be changed to S:21

i.e. the original value was a string of 22 characters, whereas the new one was a string of 21 characters

# Answer
> 0 votes
Make sure you updated the $base\_url to reflect to you local server name in settings.php. Also check if your menu system is using absolute path.

---
Tags: 6, navigation
---


title: Field collection table print row number

text:
# Question
Title: Field collection table print row number
I'd like to print a row number at the start of each table row in a field collection table.

Is this possible? Could you please explain?

thx in advance

# Answer
The field table collection module is kind enough to provide a specific theme function for tables that it outputs.

As such, you can implement a preprocess hook for the `theme_table__field_collection_table()` function and add your row numbers in there:

```
function MYMODULE_preprocess_table__field_collection_table(&$vars) {
  // Add a new (blank) header
  array_unshift($vars['header'], ' ');

  // Add an incremental count to each row
  $count = 1;
  foreach ($vars['rows'] as $key => &$row) {
    array_unshift($row['data'], $count++);
  }
}

```
> 2 votes

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


title: render hook_theme()

text:
# Question
Title: render hook_theme()
I'm developing a module which should display a tpl.php file. Check this code:

```
/**
 * Implements hook_theme().
 */
function cookiedo_theme() {
  $path = drupal_get_path('module', 'cookiedo');
  return array(
    'cookiedo_info' => array(
      'template' => '/theme/cookiedo.theme',
      'path' => $path,
    ),
  );
}

```

There are no mistakes right? So i'd like to output/render cookiedo.theme.tpl.php, how should I do this?

this is all I can come up with.. :

```
  function cookiedo_preprocess_page() {

    cookiedo_theme('cookiedo_info');

}

```

I can possibly display this in a block/region, but I prefer to display the cookie.theme.tpl.php on all pages without the use of a block. The output should take place inside the .module file, I don't want the need to put extra code in the main template file.

I hope you understand my problem and question.

Thanks in advance for your help

# Answer
> 7 votes
That's not quite how `hook_theme()` works...Drupal's theme registry will pick up the themes you define in that function, and to call them you use the central `theme()` function.

You also need one of `render element` or `variables` in there (even if you're not passing any). The path defaults to the module that the hook is defined in so there's no need to specify. So your `hook_theme()` should look like this:

```
function cookiedo_theme() {
  return array(
    'cookiedo_info' => array(
      'template' => '/theme/cookiedo.theme',
      'variables' => array()
    ),
  );
}

```

And in your preprocess function you would call that theme like so:

```
$output = theme('cookiedo_info');

```

Remember to clear the caches once you make the change to the theme function or it won't get picked up by the registry.

---
Tags: 7, theming
---


# Question
Title: Drupal Commerce: How to get payment module settings?
How to programmatically retrieve configuration of the specific payment module?

I tried

```
$settings = rules_config_load('commerce_payment_MODULE_NAME');

```

It returns very basic info (name, ID etc) and empty "settings" array.

Cant also get it directly from DB .

It is stored in serialized array that can not be fully processed with the `unserialize()` function.

# Answer
I'm using this:

```
$payment = commerce_payment_method_instance_load('foo|commerce_payment_foo');

```

where `foo` is the payment method string identifier.

The resulting array contains the `'settings'` index, with the data saved in the settings form.

---

In other words `foo|commerce_payment_foo` is instance id which consist `method_id|rule_name`.

The `method_id` can be found by executing `commerce_payment_methods()` and `rule_name` can be found in URL when editing Payment action (at `/admin/commerce/config/payment-methods`).
> 16 votes

---
Tags: 7, commerce
---


title: Openlayers map with dynamic markup

text:
# Question
Title: Openlayers map with dynamic markup
I have an open layers view that displays the numbers of reports for each country.

Can i display it other way for instance with dynamic circles markups : 3 reports : small circles , 50 reports : medium circles etc ...

example: http://reliefweb.int/

# Answer
> 1 votes
You can do that by passing a context function in Javascript that replaces the $-placeholders in your style object. I gave an example in this answer. The linked answer only changes the icon based on term rather than changing the marker size, but the principle's the same. Let me know if I can be of more help.

**Edit:** Sorry, I hadn't looked at your example when answering. That map doesn't involve clustering, so I think you can do it purely via the GUI. First you need to get the number as a field in Views and then use the appropriate placeholder (which you can see when you preview the data overlay display of the view) in the `pointRadius` field of the map's style.

**Details**

1. Make sure that the report count is a field in the *OpenLayers Data Overlay* display of your view.
2. Look at the preview of this display and note down the placeholder for the field - something like `${field_report_count}`.
3. Go to *Structure* -\> *OpenLayers* -\> *Maps* and edit the appropriate map.
4. Go to *Layers & Styles*, scroll down to *OVERLAY LAYERS* and look for the line which starts with the name of your view (it should end with *\- OpenLayers Data Overlay*). Note down the name of the style in the *STYLE* column.
5. Go to *Structure* -\> *OpenLayers* -\> *Styles* and edit the style you noted down from step 4.
6. Put the field name you noted down from step 2. in the fields `pointRadius` and `label`. (I've never used the `label` field but I assume it does what you want.) You can also change the `labelAllign`, `labelXOffset` and `labelYOffset` fields if you want.

---
Tags: javascript
---


# Question
Title: Is it possible to have a specific page.tpl.php for mobile devices?
Background is, that the "desktop-version" of the website will have some external advertisements added via javascript-tags. Due to the nature of these adverts, they don't scale down with the rest of the responsive elements. I could just hide them via CSS and Media Queries, but then they would load anyway and slow down loading times.

# Answer
> 3 votes
If these advertisements are in a block, you can put some intelligence in that block, eg:

```
if USER_AGENT == MOBILE DEVICE
   return // eg, nothing
else
   return the AD

```

This way, the ad is never delivered on the mobile device. The USER AGENT can be gleaned from `$_SERVER['HTTP_USER_AGENT']`, eg:

```
if (strpos($_SERVER['HTTP_USER_AGENT'],'iPhone')!==FALSE) {
   // I'm an iPhone
}

```

---
Tags: 7, theming
---


# Question
Title: How do you know if user_login_submit was successful in Drupal 7?
Based on the answer from this question How do I programmatically log in a user?

I know how to login in a user, but is there a way to test if user\_login\_submit was successful or not? It does not have a return value.

# Answer
You can check if user is logged in or not by using global $user variable, if user is not logged in then $user-\>uid will be 0 for anonymous users.
> 7 votes

---
Tags: 7, users
---


title: How to make a view table row clickable

text:
# Question
Title: How to make a view table row clickable
I was trying to make a row of the table I created using Views into something that was clickable. I'm really not finding anything online and everything I try doesn't give me the effect I'm looking for. I'm hoping someone here could share some insights. Thanks.

# Answer
> 3 votes
Pardon my neanderthalic jQuery skills here, but if you add a CSS class to your view via the UI, let's all it `clickable-row`, you could then do something like this in a JavaScript file that basically looks through the HTML and, if it finds a link inside your views row, it makes the surrounding div clickable to that link. So, just as long as one field in your view is a link, you'd be all set.

```
$('.clickable-row .views-row').each( function() {
  if ($(this).find('a').length) {
    $(this).click(function() {
        window.location=$(this).find('a').attr('href');
        return false;
    });
  }
});

```

---
Tags: 7, views
---


# Question
Title: Install module from URL to site directory instead of /all
At http://drupal.local/admin/modules/install, when I install modules by entering a URL, they get saved to sites/all/modules. I have a multisite setup, and I need them to go to sites/SITE/modules.

Any way to control that?

# Answer
> 2 votes
The update manager will only install modules to `sites/all/modules` unfortunately (see this page), so it looks like you'll have to FTP/SCP/whatever them to your server.

There are some advanced installation methods here, but installing modules into specific directories is not something the update manager can do.

Alternatively, you should definately try Drush if you're not using it already. There's a pretty good tutorial on how to set up Drush for a multisite here.

Drush homepage

Drush project page

Drush DO page

Drush cheatsheet

Drush guide

---
Tags: 7, installation
---


# Question
Title: Does drupal_http_request ever cache results?
Does `drupal_http_request` ever cache results?

I am making a request that looks something like:

```
$url = "http://www.example.com/some/rest/service?" . drupal_http_build_query(array(
    "id" => 1234,
));

$options = array(
    "headers" => array(
        "Pragma" => "no-cache",
        "Cache-Control" => "no-cache",
    ),
);

$response = drupal_http_request($url, $options);

```

The problem is that I am getting back some cached results. I am not looking for ways to cachebust this request; I am trying to rule out Drupal caching this internally so I can work with the far end to see why their Varnish is being weird.

# Answer
No, drupal\_http\_request() is not doing any kind of caching. If the results are cached then it's either the server or some intermediary system, e.g. a proxy.
> 3 votes

---
Tags: 7, services
---


# Question
Title: How can I target a webform results page to create a panel around?
I'm trying to set up a panel for the submitted page for a webform in order to add a sidebar and bottom section. I need help setting up the panel, specifically with how to select the submission (results) page of the webform.

The url of the submitted page looks like this - http://site.localhost/node/2136/done?sid=8

I tried -

```
String: URL path : Current path is "node/2136/*"

```

as well as -

```
String: URL path : Current path is "node/*/done"

```

both were a no go

Any ideas?

# Answer
> 5 votes
Since webform, for showing results implements a different path than the standard node/%, you need a way to tell Panels to take over this path.

The module Page manager existing pages allows you to do this.

Install and enable the module. Go to `admin/structure/pages/existing-pages/add`, find the path `/node/%webform_menu/done` and add it to the list.

Now go to `admin/structure/pages` and you should see a new "task" for results, where you can customize the result page.

As pointed out by winchendonsprings, the results are available under `Add Content >> Existing pages >> Existing page >> node overview`.

In order to do this on a webform by webform basis, one will need to add a manual node context, where you select the webform you want by nid, and then add a selection rule that compares the current context against the manually loaded one.

Normally manually loaded contexts should be avoided as "hardcoding" node id's is rarely a good idea, but this seems like a good exception from the rule, although it will still not be properly exportable.

---
Tags: webforms, panels, forms
---


# Question
Title: I can't save changes of settings of an Omega subtheme. Problem just happens in remote server
I can't save changes of settings of an Omega subtheme in **admin/appearance/settings/omega\_subtheme\_2**

I get no error message. The changes are not saved at all.

This problem just happens in remote server. In my local server works just fine.

I guess it could be a folder or file permission problem. I already set the permission of **site/all/themes/omega subtheme 2** folder and all its content to 777. But the problem persist.

# Answer
this thread may answer your question: http://drupal.org/node/1388196

for some it is a suPHP request.max\_vars and post.max\_vars issue
> 2 votes

---
Tags: theming
---


# Question
Title: How do I create a 'page' that creates and downloads a file from within a module
I have mymodule.php which contains all the logic for my site.

I need to create something like this.

```
header("Content-type: text/csv");
header("Content-Disposition: attachment; filename=file.csv");
header("Pragma: no-cache");
header("Expires: 0");

$array = array(
    array("data11", "data12", "data13"),
    array("data21", "data22", "data23"),
    array("data31", "data32", "data23"));
outputCSV($array);

function outputCSV($data) {
    $outstream = fopen("php://output", "w");
    function __outputCSV(&$vals, $key, $filehandler) {
        fputcsv($filehandler, $vals); // add parameters if you want
    }
    array_walk($data, "__outputCSV", $outstream);
    fclose($outstream);
}

```

Generally I've been adding items to `mymodule_menu()`, `mymodule_theme()`, and directing it to a `mymodule_mypage()` function, and oftentimes a `mypage.tpl.php`.

This setup doesn't really make sense for what I need to do here, though.

I need a linke like `mysite.com/mypage` to generate/download the csv.

I don't think that headers will work in a `mymodule_mypage()` function, and the template files are not appropriate because they load headers/footers etc.

I could just create the php files separately and create links to them, but I'm trying to keep things within the module and with tidy URLs.

# Answer
Don't forget anything you can do with PHP you can do with Drupal, so headers work in exactly the same way.

Adding a page callback which sets headers and exits the script (with `drupal_exit()`) is definitely the right way to do this:

```
function MYMODULE_MENU() {
  $items['mypage'] = array(
    'title' => 'CSV',
    'access arguments' => array('access content'),
    'page callback' => 'MYMODULE_deliver_csv'
  );

  return $items;
}

function MYMODULE_deliver_csv() {
  // Full complement of headers so IE behaves
  header("Cache-Control: public");
  header("Content-Type: application/octet-stream");
  header("Cache-Control: no-store, no-cache, must-revalidate");
  header("Cache-Control: post-check=0, pre-check=0");
  header("Content-Disposition: attachment; filename=\"filename.csv\";" );
  header("Content-Transfer-Encoding: binary");

  // Print your CSV data here

  // Exit the script
  drupal_exit();
}

```
> 6 votes

---
Tags: 7, files
---


# Question
Title: Hierarchy management solution(s)? (node or taxonomy)
I have a content type with a large number of nodes (70K+) and have integrated a straightforward, though custom, node hierarchy solution (node reference for the parent, sibling order using delta).

I'm implementing a custom hierarchy management tool and have started out playing with taxonomy because the hierarchy management is already present (drag & drop). However, core's default taxonomy management only goes so far, and though a good starting point, will not be suitable for a vocabulary this size (moving a large piece of the tree somewhere else isn't possible, as the vocab is paginated).

I then thought about a view combo'd with VBO, and a few custom actions, but i'm not sure drag & drop could be used with this method.

**Question:** Have you used (or seen) a drag & drop hierarchy management solution (node or taxonomy) implemented either in views or a contributed module that fits this scenario?

# Answer
Yes, the wonderful Taxonomy Manager module. I don't start a big project without it these days:

> This module provides a powerful interface for managing taxonomies. A vocabulary gets displayed in a dynamic tree view, where parent terms can be expanded to list their nested child terms or can be collapsed.

It's packed with features, there's a list of them on the module page. I think this one in particular will be of interest to you:

> Double Tree interface for moving terms in hierarchies, adding new translations and switching terms between different vocabularies
> 3 votes

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


# Question
Title: How can I display the value of an addressfield in a single line?
I modified the "Address form (country-specific)" bundled with the Addressfield module to take only a country, administrative area, and city; this works fine on the node edit form, but when the field is displayed upon viewing the node, it looks like this:

What I want to do is display it on a single line with commas like this:

> Indianapolis, Indiana, United States

I am using the Views module to display the field. How can I rewrite (using Views or custom code) the addressfield output to be a single line?

# Answer
I had to do the same thing a couple of days ago, this is what I came up with using `hook_field_formatter_info()` and `hook_field_formatter_view()`:

```
function MYMODULE_field_formatter_info() {
  return array(
    'inline_address_field' => array(
      'label' => t('Inline Address Field'),
      'field types' => array('addressfield'),
    )
  );
}

function MYMODULE_field_formatter_view($entity_type, $entity, $field, $instance, $langcode, $items, $display) {
  $build = array();

  $count = 1;
  foreach ($items as $item) {
    $inline_address = "<h3>Address $count</h3>";

    $address_parts = array();
    if (!empty($item['first_name'])) {
      $address_parts[] = $item['first_name'];
    }
    if (!empty($item['last_name'])) {
      $address_parts[] = $item['last_name'];
    }
    if (!empty($item['premise'])) {
      $address_parts[] = $item['premise'];
    }
    if (!empty($item['thoroughfare'])) {
      $address_parts[] = $item['thoroughfare'];
    }
    // And so on for all of the columns that you're interested in, in the order
    // that you want them to be displayed.

    $inline_address .= '<p>' . implode(', ', $address_parts) . '</p>';

    $build[] = array('#markup' => $inline_address);
    $count++;
  }

  return $build;
}

```

It provides a field formatter you can pick for the address field on the node's "Manage Display" form.
> 7 votes

# Answer
This can also be done with the Location Taxonomize module.

Enable Location Taxonomize and create a taxonomy term reference as described in the module's README. Then, in Views, display this term reference field instead of the addressfield.

The benefit of this approach is that the module's configuration page allows you to easily choose if you would like to display the country/administrative area abbreviations or the actual names.
> 2 votes

---
Tags: entities
---


# Question
Title: Create a list and count of users per role
Using Drupal 7 I would like to display:

A) a list of recent users per role (Limit to 10).

and

B) a total count of users per role.

I have looked for a module to do this but can't find anything. I also tried a few things in views but had no luck. This is what I tried in views:

> enable aggregation for you view, and then set the group by for you field (Content:nid for example) to Count.

Didn't give me the results I was looking for.

If there is a module that can do this that would be perfect otherwise i'm hoping to use views... lastly I guess it could be posible with PHP.

# Answer
> 2 votes
I'm going to assume Part A is the easy part, but just to be thorough:

1. Create a new view based on the Users table
2. Add the User: Name field (if it isn't already there)
3. Limit the results to 10
4. Sort by descending

As for Part B, let's begin by dissecting why Aggregation will not work right out of the box with Views 3.

The only reasonable base table that we could use to count user roles is the Users table, right? After all, Views gives us a User: Roles field right away. So, we turn on Aggregation on two copies of the User: Roles field (the first to group the results, and the second to COUNT the results). However, if you take a look at the SQL, the query is:

```
SELECT users.uid AS uid, COUNT(users_roles.rid) AS users_roles_rid
FROM {users} users
LEFT JOIN {users_roles} users_roles ON users.uid = users_roles.uid
GROUP BY uid

```

So, the query will:

* SELECT a uid and then COUNT the roles that particular uid possesses
* Perform a LEFT JOIN by comparing two uids from the users table and the users\_roles table (not very helpful)

It turns out that the COUNT does its job correctly by counting up the roles each user has... but it is not what we need. Since we chose User as the base table, the COUNT is only counting the number of *roles*. What we actually need is to COUNT how many **users** belong to each role. The **users\_roles** table will provide us the necessary information.

Here is the SQL we're after:

```
SELECT role.name, COUNT(users_roles.uid) AS users_per_role
FROM users_roles AS users_roles
INNER JOIN role AS role ON role.rid = users_roles.rid
GROUP BY role.name

```

The above query will give you a list of all of the roles in your site along with a count. Since users\_roles is not an available base table out of the box, we cannot construct this query via Views without some PHP customization.

**There are a few options to get the required results:**

* Use the Views API to describe users\_roles to Views. This requires a bit of PHP heavy lifting. Check out this answer for more information. The Data module may be of use as well.
* Cheat and run the above query through db\_query and stick the results in $view-\>attachment\_after.

Here is an example of the latter, using hook\_views\_pre\_render in a custom module (be sure to clear caches first to get this hook to work):

```
function mymodule_views_pre_render(&$view) {
  switch($view->name) {
    case 'my-view-name':
      $results = db_query('
        SELECT role.name, COUNT(users_roles.uid) AS users_per_role
        FROM users_roles AS users_roles
        INNER JOIN role AS role ON role.rid = users_roles.rid
        GROUP BY role.name
      ')->fetchAll();

      foreach($results as $result) {
        $rows[] = array($result->name, $result->users_per_role);
      }

      $view->attachment_after = theme('table',
        array(
          'header' => array('Role', 'Number of Users'),
          'rows' => $rows,
        )
      );
      break;
  }
}

```

Lastly, keep in mind that a user may have multiple roles. So, it would be incorrect to sum up all of the "Users Per Role" values and say that the result is your total number of users.

---
Tags: 7, views
---


# Question
Title: How are entities and libraries for the Apache Solr server organized?
I'm trying to understand some basics about Apache Solr server, and particularly how its entities and libraries are organized.

I've tried to read the documentation but it is hard to understand it without good knowledge of the Java language.

My goal is to integrate Solr with Drupal 7's Search API location module. I have already got working and configured Solr server but it also requires Solr to be extended with Lucene localation library, and this is actually the part that I don't clearly understand.

There is a version of Solr with an already compiled location library, but it means that the existing one should be deleted. What I was thinking about: is it possible to just copy the `apachesolr/solr` (with geo library) directory from that version into existing Solr server as new instance?

Any explanations about this?

# Answer
> 0 votes
Iv updated solr to 3.6 version, it has integrated support for spatial search.

---
Tags: search
---


title: Using the API of relations module

text:
# Question
Title: Using the API of relations module
How can I use the API and hooks of a contributed module, I am trying to use relations module to add my functionalities using that module but I could not find any documentation that help me to do that

Any help?

# Answer
Unfortunately the relation.api.php file included with the module is empty, so it doesn't appear that there's any official API documentation yet. There's the standard documentation but I don't think that covers code.

In this situation I normally head straight for the `.test` files included with the module. If they've been done properly (and it looks like they have for Relation), you should find all the code examples you need in there.

To find out what hooks (if any) the module provides, I usually just grep the module folder for `module_implements(` and see what hooks are actually invoked. If any are provided by the module you should be able to find them that way.

If that doesn't help it might be wise to re-think your question and make it more specific to what you're actually trying to accomplish in the first instance.
> 2 votes

---
Tags: entities
---


title: How to parse data field?

text:
# Question
Title: How to parse data field?
I'm using Drupal 7.14 + ulogin module (for auth. through social networks) and have following records in the database:

```
# select uid,name,data from drupal_users where uid=20041;
  uid  |               name                |
                                             data

-------+-----------------------------------+---------------------------------------------------------------------------------------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
---------------------------------------------------
 20041 | ulogin_odnoklassniki_406011483750 | a:2:{s:7:"contact";i:1;s:6:"ulogin";a:8:{s:7:"network";s:13:"odnoklassniki";s:8:"identity";s:36:"http://odnoklassniki.ru/406011483750";s:3:"uid";s:12:"4060114
83750";s:10:"first_name";s:18:"\320\220\320\273\320\265\320\272\321\201\320\260\320\275\320\264\321\200";s:3:"sex";s:1:"2";s:5:"photo";s:70:"http://i506.odnoklassniki.ru/getImage?photoId=348908356448&pho
toType=4";s:4:"city";s:0:"";s:6:"manual";s:0:"";}}
(1 row)

# select * from drupal_ulogin_identity where uid=20041;
 id |  uid  |    network    |  ulogin_uid  |
                           data

----+-------+---------------+--------------+---------------------------------------------------------------------------------------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
--------------
  2 | 20041 | odnoklassniki | 406011483750 | a:8:{s:7:"network";s:13:"odnoklassniki";s:8:"identity";s:36:"http://odnoklassniki.ru/406011483750";s:3:"uid";s:12:"406011483750";s:10:"first_name";s:18:"\320\
220\320\273\320\265\320\272\321\201\320\260\320\275\320\264\321\200";s:3:"sex";s:1:"2";s:5:"photo";s:70:"http://i506.odnoklassniki.ru/getImage?photoId=348908356448&photoType=4";s:4:"city";s:0:"";s:6:"man
ual";s:0:"";}
(1 row)

```

My question is - how to decode the `data` column in PHP? It looks like JSON, but is not JSON. I understand that `a:2` is an array with 2 items and `s:18` is a 18-chars long string... but how to parse it?

# Answer
> 2 votes
The data column is a serialized php object. Take a look at the unserialize function.

# Answer
> 4 votes
As @lenni rightly says it's a serialized PHP variable. But `data` is a property of the user entity type so you don't actually need to unserialize it yourself.

When the user object is loaded from the database it's automatically populated with the unserialized version of the `data` column. So all you need to do to access your 'user tokens' field (if such a field exists, it doesn't appear to from your screenshot) is this:

```
global $user;
$user_tokens = $user->data['user tokens'];

```

---
Tags: 7
---


# Question
Title: View Title does not filter correctly by userid
I'm very new to Drupal and trying to learn how to create a view that is filtered by userid, then by whether or not it's been published. I've created a content type of "Lists" and have a link on the home page called "My Lists." When the user clicks the link, it should open a view (and I have it set up as a page) and the title of the "page" should be "My Lists" and show each set of lists the user has. I.e., the user could have a list for their favorite movies, and another for their favorite books. Both lists should be shown UNDER the title of "My Lists" and the user would then click on which list they want to view or update.

What is happening though, is that somehow I got the Title "Booklists for " & "User" name in the title so it shows up as the main title for ALL lists instead of the correct title of "My Lists." I've gone to my Administration menu: Home » Administration » Structure » Views and under Views I have it set up as a Page. The Display name: Page - My Lists. The Title = Title: View My Lists. Now, when I scroll all the way to the bottom of the View My Lists (Content) it has a section for the Title with a little gear wheel icon that you're supposed to click on to change the Title. I've done that and the Page - My Lists: The title of this view dialog box comes up. I've changed the title in that section to "View My Lists" and set it to save for all displays. Then , it goes back to the Title and in the box showing for the title (that I just changed) it STILL shows "Booklist for Ayliea" when it SHOULD say "View My Lists."

It isn't changing the title.

# Answer
> 1 votes
Ok, i guess this is difficult to solve from here. First you should check the following settings in your view.

1. Display name (how your Page-View is named, for administrative purposes, will not affect the frontend)
2. Title (this is the name of your view at the frontend, it can be overridden with contextual filters)
3. Path (this is the URL of your view)
4. This is the Title of your menu-item.

If this is all in order, you probably have overriden your view-title with a contextual filter.

Check these settings:

---
Tags: views
---


title: Locked out of drupal

text:
# Question
Title: Locked out of drupal
I managed to lock myself out of drupal by removing the user login block. Is there any file I can modify to enable myself to get back in?

Thanks

# Answer
> 7 votes
Try: `www.example.com/?q=user`.

---
Tags: users
---


# Question
Title: How can I print something only when cck field has certain value on node.tpl.php?
I need to print something conditionally in my `node.tpl.php` depending on the cck value of a field on my content type.

For example, if `field_color` has "*red*" or "*blue*", then print "*It has color*" and if it has other values print empty text.

# Answer
> 2 votes
The following should work:

```
if (isset($node->field_color[0]['value'])) {
  //If you want the field value to be displayed
  print $node->field_color[0]['value'];
  //If you want some custom text to be displayed
  print 'It has colour';
}
else {
  print 'Empty Text';
}

```

Or with ternary operators:

```
print (!empty($node->field_color[0]['value']) ? $node->field_color[0]['value'] : 'Empty text';

```

You'll probably either want to put in some logic to make sure the field exists though, or create a `node-TYPE.tpl.php` for your specific content type.

**EDIT**

This should sort out your red or blue issue:

```
if (isset($node->field_color[0]['value'])) {

  $colour_value = $node->field_color[0]['value'];

  if ($colour_value == 'red' || $colour_value == 'blue') {
    $colour = $colour_value;
  }
}

print (isset($colour)) ? $colour : t('Empty Text');

```

I've only put the field value into a variable to save space - you don't have to do this if you don't want to :-)

---
Tags: 6, entities, theming
---


# Question
Title: How to guide user through multiple unrelated forms
I have a content type with a term reference field. I want to give user a convenient way of grouping multiple nodes of that type together. I see it like this:

1. The user creates a first node
2. When he goes to a node page, he sees a link "subjoin another document"
3. After pressing it the taxonomy term creation form is shown, user fills required fields
4. After saving the term he gets redirected to node creation form
5. Second node is created, taxonomy term fields of both nodes point to newly created taxonomy term

What puzzles me is how it's best to implement such a multiphase logic in Drupal, when we need to guide the user through several unrelated forms.

# Answer
In the end I implemented this functionality in a custom module. Together with prepopulate it allows to conveniently link nodes together without manually creating taxonomy terms.

```
function mymodule_menu() {
  $items = array();
  $items['continue_with/%/%'] = array(
    'title' => 'Continue with',
    'description' => 'Creates new story and links existent material to it',
    'page callback' => 'vidsboku_custom_continue_with',
    'page arguments' => array(1,2),
    'access callback' => true,
    'type' => MENU_CALLBACK,
  );

  return $items;
}

function my_module_continue_with($content_type, $nid) {
  $existing = node_load($nid);

  if(!is_object($existing)) {
    drupal_goto("");
  }

  if (empty($existing->field_story)) {
    if (!node_access('update', $existing)  || !(user_access('administer taxonomy') || user_access('edit terms in 4'))) {
      drupal_set_message('Insufficient permissions','error');
      drupal_goto("");
      return;
    }

    $term = new stdClass();
    $term->vid = 4; // Vocabulary ID for Story
    $term->name = $existing->title; // Term Name

    taxonomy_term_save($term);
    $tid = $term->tid;

    $existing->field_story = array('und' => array(0 => array('tid' => $tid)));
    node_save($existing);
  } else
    $tid = $existing->field_story['und'][0]['tid'];

  drupal_goto('node/add/' . $content_type, array('query' =>
                                                  array('edit[field_story][und]' => $tid)));
}

```
> 0 votes

# Answer
I'm not sure, but you might find References and Relation module useful for this.
> 1 votes

---
Tags: 7, forms
---


# Question
Title: List nodes with Views 2 module, despite nodes having restricted permissions
My nodes have individual Access Control permissions.

I need anonymous users to be able to see a View (giving them a preview essentially) of these nodes, but currently they don't have access.

Is there an easy way to override the permissions just for this View, and show the nodes anyway? Searching for a solution lists a workaround which only works in Views 3.

# Answer
> 0 votes
Is there any way to update to Views 3? Because in views 3, under the **Advanced** \> **Other** section you can change the **Query settings** options and make sure the **Disable SQL rewriting** checkbox is checked.

---
Tags: views, users
---


# Question
Title: Contextual Filters with multiple arguments
Why isn't this view filtering correctly? I have four contextual filters applied to one view:

https://i.stack.imgur.com/ANEzq.png

The view is filtering a list of projects by four properties, `Region`, `Client`, `Type`, and `State`. When the view-page is loaded, all 4 arguments will be supplied. The problem I'm having is:

The first two arguments, `Region` and `State`, filter correctly. The last two: `Type` and `State` do not affect the filter.

https://i.stack.imgur.com/qhdaE.png

The `Type` field isn't being factored into the query at all. You can see content with both Roadway and Airport values for the type field show up, but none for Asian or Military which are correctly filtered out values for the first two arguments (`Region` and `Client`).

I have tried remaking the filters, re-arranging the filters to make type first, re-entering some of the test content to make sure it wasn't corrupted.. no luck yet.

# Answer
Okay- I figured out what was going on. I'm going to answer my own question in case anyone runs into the same problem I had.

Previously I had specified some PHP Validation code to the `Type` and `State` filters. Thinking they might be causing the problem I turned off the validation for both of them, but the problem persisted and that's why I posted my question above. To solve this you need to overwrite the previous validation you set by setting it to something like `Basic validation`, thus clearing out the old code. Now it works like it should but it seems like there is a bug in Views though that doesn't properly unset validation code. Good luck!
> 1 votes

---
Tags: views
---


# Question
Title: Making geolocated latitude/longitude values available to computed field in Drupal 7
I'm working on a D7 project where I need to pass a latitude/longitude value from a Location field (acquired from geolocating during import) to a Computed field.

I found the following code in the computed field documentation, which loads the field into the computed field:

`$field_info = array_pop(field_get_items($entity_type, $entity, 'field_geo'));`

However, if I do a `dpm($field_info);` all location information is there, *EXCEPT* lat/long.

Any way around this? Thanks!

# Answer
I think I was assuming locations are geolocated on edit/changes and that's saved to DB, which appears to not be the case. At any rate, I was able to use the location ID from $field\_info to load the location, which then has the lat/long data I need:

```
$loc = location_load_location($field_info['lid']);
$longitude = $loc['longitude'];
$latitude = $loc['latitude'];

```

That was annoying...
> 0 votes

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


# Question
Title: How to remove link to profile under title, when rendering a profile as block in the module Profile2
I'm rendering a user customer profile in a form using the code:

```
$profile = profile2_load_by_user($account, 'customer');
$form['customer_profile'] = array(
    '#type' => 'item',
    '#markup' => render($profile->view('block')),
);

```

which works rather well, except that the title (in H2 tags) is rendered as a link back to the profile.

I want to get rid of that link, but as there seems to be no obvious property, to specify if you do or do not want a backlink. Not in the `$build` array parameter of hook\_entity\_view\_alter, nor in the `$elements` parameter for a '#pre\_render' callback. In a '#post\_render' callback, it's too late because the link is already inserted into html.

So, how do I get rid of it?

# Answer
This link is part of template file `profile2.tpl.php` defined as `$title` and it appear for non page display modes as described by the template code.

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

```

The short possible solution can be to unset `title` variable implementing `hook_preprocess_profile2`. But to remove whole markup you will have to overwrite theme registry implementing `hook_theme_registry_alter(&$theme_registry)` to replace template against `profile2`.

```
$theme_registry['profile2'] = array(
  'render element' => 'elements',
  'template' => 'profile2_custom',
  'path' => path_to_theme(),
);

```
> 1 votes

# Answer
Is it possible to get a more detailed explanation of your solution to this problem? I am having this exact problem. I would comment but I can not.
> 0 votes

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


title: drupal ajax message

text:
# Question
Title: drupal ajax message
Ok, i've been stuck on this for some time...

I have my own module where I alter the form to add my own button that returns a message from the server via AJAX. I'm stuck on the ajax part. When I click on the button, I see the url change to ../myforms/ajax But I get the same page returned as output instead of my ajax message

Here are my code snippets.

I click on the button that calls my getAjaxReply function:

```

function getAjaxReply(context, settings)
{
console.log("this works");
$url = this.href;
    jQuery.ajax
    (
        {
            type:'POST',
            url: '/myforms/ajax',
            dataType: 'json',
            success:voteSaved,
            data:'getAjaxReply=testingAjax',
        }
    )
    return false;
}

```

In my php file, I have

function myforms_menu()
{
    $items['myforms/ajax'] = array(
    'title' => t('myforms AJAX'),
    'type' => MENU_CALLBACK,
    'page callback' => 'myforms_ajaxCallback',
    'access arguments' => array('access content'),
     );

```
 return $items;

```

}

//the php function
function myforms_ajaxCallback()
{
    if($_POST['getAjaxReply'] == 'testingAjax')
    {
        return drupal_json(
                array(
                    'answer' => 'success'
                    )
                );
    }
    return false;
}

# Answer
> 1 votes
you also may consider using Drupal Ajax form API. This way you don't have to write any JS code or hook\_menu entries. You basically alter your form to take user input into account. Just take a look at the examples: http://drupal.org/node/752056

I recently ajaxified form by hand and after that reworked it to make use of api. And didn't regret ;)

# Answer
> 0 votes
Do not `return` when calling drupal\_json()

```
function myforms_ajaxCallback(){
    if($_POST['getAjaxReply'] == 'testingAjax'){
      drupal_json(array('answer' => 'success'));
    }else{
      drupal_json(array('answer' => 'failure'));
    }
}

```

---
Tags: ajax
---


# Question
Title: How do I switch a node's view mode for AJAX calls?
I've programmatically created a new view mode called ajax. Is there any way to force a node page to use that view mode if I'm making an AJAX call? I know how to switch page and node templates when it's an AJAX call in template.php, but it's not quite the same thing.

# Answer
If you have a custom handler for your ajax request, I suggest you to manually render the node using node\_view api function. It has a view\_mode parameter which you should set to 'ajax'.
> 1 votes

# Answer
You can make use of Services module

> A standardized solution of integrating external applications with Drupal. Service callbacks may be used with multiple interfaces like REST, XMLRPC, JSON, JSON-RPC, SOAP, AMF, etc. This allows a Drupal site to provide web services via multiple interfaces while using the same callback code.

## Features(3.x):

* Service API allow modules to create other services, including pluggable access control
* Server API allow modules to create other servers, such as SOAP
* Aliasing methods
* Integration with core Drupal functionality like files, nodes, taxonomy, users, files and more. \***you can try this option\***
* Response format API allows you to define response Formats for CONTENT-TYPE ie. application/json or application/xml. (also calls such as ENDPOINT/node/1.json work)
> 0 votes

---
Tags: ajax
---


title: Simple Drupal hook_menu

text:
# Question
Title: Simple Drupal hook_menu
I would like to pass data from Javascript to PHP using Drupal 7.14. To this end, I'm trying to follow this SO post: https://stackoverflow.com/questions/4834132/how-to-pass-jquery-variable-to-drupal-ajax.

However, |hook\_menu()\` is not working as expected.

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

  $items['example_callback/%'] = array(
    'title' => 'My Custom Callback',
    'description' => 'Description',
    'page callback' => 'my_custom_php_function',
    'page arguments' => array(1), // fill this
    // 'access arguments' => array('access content'),
    'access callback' => true,
    'type' => MENU_CALLBACK,
  );

  return $items;
}

/**
 * Function that gets called from JQuery asynchronously.
 */
function my_custom_php_function($argument) {
  // Do something with $argument...
  echo $argument;
}

```

In my understanding, going to http://mywebsite.com/example\_callback should call my\_custom\_php\_function. Instead, I get:

> The requested URL /example\_callback was not found on this server.

Are there other steps necessary to write a simple menu callback?

# Answer
Your URL is expecting an argument so your URL would have to be http://mywebsite.com/example\_callback/something. I wouldn't bother with the extra % in the path though.

So you should be doing something like and it will still pick up the arguments:

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

  $items['example_callback'] = array(
    'title' => 'My Custom Callback',
    'page callback' => 'my_custom_php_function',
    'access callback' => TRUE,
    'type' => MENU_CALLBACK,
 );

 return $items;
}

/**
* Function that gets called from JQuery asynchronously.
*/
function my_custom_php_function() {
  if (arg(1)) {
    // this means there is an argument
    // Do something with $argument...
  }
  return '';
}

```
> 3 votes

---
Tags: hooks, routes
---


title: phpBB 3.0.10 to drupal 7

text:
# Question
Title: phpBB 3.0.10 to drupal 7
I have a phpBB 3.0.10 site i want to migrate all the contents of the site to drupal 7.

I want all my users to import from phpBB 3.0.10 to users of drupal 7.

All the forums should be migrated to drupal forums along with their groups and access rules in the phpBB forum.

The users groups should be mentioned.

All the posts and comments should also be imported.

I have tried modules phpbb2drupal and phpbbforum but i was not able to completely migrate it to drupal.

After the migration i will be leaving phpBB 3.0.10 and only be working on drupal 7.

Is there a solution, i have been searching but couldn't find the right solutions.

Thanks for the help...

# Answer
> 1 votes
use the module migrate, be sure you studied the example and modules like TYPO3\_migrate or Wordpress migration.

Migrate has a learning curve, but it is worth it.

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


# Question
Title: Multiple contextual filters using or statements
I have a taxonomy which defines the sections of a site. One of the terms is "Global". What I am doing is creating pages with the site section term and also creating promo boxes which use the same taxonomy. By default the "Global" term is selected wherever the term relation is used.

I would like to have a block view using contextual filters. I have set it up to use one filter which is the term id from the url. This works great but when I have a page that has a specific section but does not have any related promo boxes I would like to load the "Global" set of promo boxes.

Is there a way to create multiple contextual filters using or statements? The default sets them up as and statements which will not allow me to load the "Global" plus the related to the page. I am sorting the view by taxonomy weight and have "Global" at the bottom so if I can get an or contextual filter I'll be in business.

Does anyone know of a module to do this or will I have to hook the view using hook\_views\_query\_alter

# Answer
In case anyone wants to know, I was able to accomplish this with some views hooks and will share my solution.

First you need to register view api information

```
/**
 * Implements hook_views_api().
 */
function mymodule_views_api() {
  return array(
    'api' => 3,
  );
}

```

Then you need to alter the view at pre build to include the "Global" term. I am using entity query to determine if there is any content with the Global term. If so I am adding that term as an argument.

```
/**
 * Implements hook_views_pre_build().
 */
function mymodule_views_pre_build(&$view) {
  // we were getting no results if the tid of the Global term was not 1
  // in some build instances it is not so we need to ensure that the default
  // value being passed is the actual tid of the Global term.
  if (($view->name == 'badge' || $view->name == 'promo_box' || $view->name == 'article'|| $view->name == 'tips') && $view->current_display == 'block') {
    $vocabulary = taxonomy_vocabulary_machine_name_load('site_section');

    $entityQuery = new EntityFieldQuery;
    $entityQuery->entityCondition('entity_type', 'taxonomy_term')
      ->propertyCondition('name', 'Global')
      ->propertyCondition('vid', $vocabulary->vid)
      ->range(0 ,1);

    $result = $entityQuery->execute();

    if ($result) {
      $term = array_slice($result['taxonomy_term'], 0);
      $view->argument['tid_1']->options['default_argument_options']['argument'] = $term[0]->tid;
    }
  }
}

```

And finally you need to switch the where statement to and or

```
/**
 * Implements hook_views_query_alter().
 */
function mymodule_views_query_alter(&$view, &$query) {
  //  Let's find out if we are attempting to load either the badge or promo box
  //  view. If so we need to alter the where clause to include an or statement
  //  in the conditional filter to also look for the global term in the site secttion
  //  taxonomy. I was not able to find a way to create an OR condition filter via a
  //  module so for now this is the best to do it.
  if (($view->name == 'badge' || $view->name == 'promo_box' || $view->name == 'article'|| $view->name == 'tips') && $view->current_display == 'block') {
    if (isset($query->where[0]) && isset($query->where[1])) {
      $query->where[0]['type'] = 'OR';
    }
  }
}

```
> 0 votes

---
Tags: 7, views
---


title: Create control panel for drupal 7 site

text:
# Question
Title: Create control panel for drupal 7 site
When i use drupal 6, i install control panel module and change panels and authenticated users can goes to control\_panel page and manage contents,pages and site. but this module is not available for drupal 7.

my question is how do you create a management page for your site in drupal 7 ?

Do you use another module or add some php code to page and create this page manually?

# Answer
> 1 votes
Another possibility: You could create a taxonomy (vocabulary) for your administrative features and use that with Taxonomy Menu. Add an image field to your terms with icon. Or, just use Views to create your custom menu -- you'll be able to use your taxonomy term images there.

# Answer
> 0 votes
In Drupal 7 you can set an administration theme. By default this is set to Seven, one of the core themes, but you can make it anything you want. Looking at the Control Panel module, it strikes me as very similar to the Root Candy theme. Give that a shot. 1. Download and install Root Candy 2. On the Appearance admin page scroll to the bottom and set Root Candy as your admin theme.

Or if Root Candy doesn't fit your needs, create a custom theme and use that for your admin theme.

There is also the new dashboard module that users with appropriate permissions can add links to pages they frequently use. The dashboard is then displayed at the top of the screen much like the admin menu.

# Answer
> 0 votes
The module you've provided an example actually has a 7 version in he git repo. Although, there isn't really any idea how it currently works.

Although from the screenshot, one could set an administration theme and simply include a menu block on a particular upon login.

**Administrative modules**

I've also provided a list of administrative modules. Here are some tools that significantly improve administrative user experience:

* Contextual admin provides you lots of abilities to create rich user interfaces for administrating a Drupal website. The maintainer also provides lots of helpful videos and tutorials. He recently did a very good demonstration of this for in drupalcamp austin
* Admin menu creates a dropdown toolbar to allow administrators ease and access to many different parts of the administrative site.
* Toolbar,can also provide a great user menu for non-developers. Often admin\_menu is very intimidating and has superfluous links thus i often set roles and assign a toolbar to a particular role. This allows you to create links centered on a role.

---
Tags: 7
---


title: User proximity search?

text:
# Question
Title: User proximity search?
I'm running D7. I'm trying to figure out how to a) tag users with a location (ZIP, address, city, state, etc.) when they register an account, and b) set up a search where the visitor inputs their location (via ZIP, address, etc.), and it returns a list of every registered user sorted by their proximity to the inputted location in the search. I'm more interested in an answer to part b) since it seems more complicated, but honestly any help at this point would be very appreciated. I've been stuck for a few weeks now.

Thanks, Edward Sapp

# Answer
> 3 votes
There are two basic approaches for doing locations in D7:

According to Karen Stevenson's presentation at Do It With Drupal 2011, only location/gmap currently has location proximity search working in D7... but not very well.

Based on this presentation and the book *Mapping with Drupal*, I set up proximity search on my own site using the location module. It works, but it's not terribly user friendly, it's a pain to theme, and it's still clearly under development. However, it's a far better solution than I would have been able to arrive at rolling my own.

# Answer
> 2 votes
I found this website that may assist you with your proximity search (b). I substituted OpenLayers for GMAP and was still able to get my proximity search working. http://torontowebsitedeveloper.com/drupal-video-tutorials/creating-drupal-7-proximity-search

# Answer
> 1 votes
I think, that one of possible solutions is http://drupal.org/project/location. It has location\_user module, which allows you to store such data.

What is quite nice about that module, is a fact, that it also supports geolocation, based on user input (zip, state, country, etc). It has two backends for geolocation (zip database is required, see: http://drupal.org/node/1038010 for more information) or google maps api.

With properly geolocated users, you can create view (location module has views integration) with proximity as sort criteria.

I played with such solution on D6 and it worked for me. I see that location has D7 dev version, so it should be doable on D7 as well.

# Answer
> 1 votes
I was able to setup a user proximity search for D7 with the following combo of geo modules on drupal.org.

openlayers

addressfield

geofield

geocoder

The last one is on github ...(The existing module on drupal.org does not cover users yet).

https://github.com/FeyP/proximity

Using that combo and views make it relatively easy to set up a user proximity search.

To get it to work you will have to add an address field and a geofield to the user profile. Set the geofield to "Geocode from another field" and it will automatically store the correct geo location info from the address field. Then in a user view you can use the Proximity filters supplied by the github module for filtering proximity on address,zip-codes etc etc. Within a certain distance.

There is also a features module that has great views example for a regular node proximity search. This module uses the same module recipe from above except for the proximity module but the github code will work as well because it forked from the original and just adds entity support for user locations.

http://drupal.org/project/ol\_locator

---
Tags: 7, views, location, users
---


# Question
Title: how to set up a user field that the only the administrator can access?
I would like to have a STATUS field for certified and uncertified for all users under a certain role preferably, but it could be for all users

how would i go about implementing this? thanks!

# Answer
> 4 votes
You can use the Field Permissions module:

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

Once installed you'll be able to set CRUD permissions on each field's settings form.

---
Tags: users
---


# Question
Title: Problems with Contextual Filters & Menu Tabs
I have created a collection of views (base) that collects identifies a category of articles and a second single view (tabs) that creates tabs to filter the content into sub categories for all base views using contextual filters.

* I have created two vocabularies to contain terms for Section and part.
* A sample base uses the path /division/SectionTerm.
* The path for the tabs view is /division/%1/part.
* Each page of the tabs view has a filter to a specific part term.

The idea is to have a series of menu tabs that display different related content related to a section. This works fine in a test without the contextual filter, but the tabs do not show when I change to contextual filters for the tabs view although the preview is showing correct results.

I am having a similar problem having a view block using relations appear. See separate question post.

# Answer
I am doing something similar, I think, but it is driven by Taxonomy Menu. For what it is worth (for any other researchers), I have set a contextual filter and a relationship:

Contextual filter settings:

And my relationship (see 1st screenshot) setting is just default:
> 1 votes

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


# Question
Title: pecl uploadprogress installed, but I don't see it anywhere
I've successfully installed the PECL uploadprogress extension and restarted my server. Here's an exerpt from phpinfo():

However, when I add a piece of content and I choose to upload a photo or a video or a generic file, all I see is the normal ajax spinner but I don't see any kind of upload progress UI that I see on the drupal site (Install PECL uploadprogress), which looks like this:

What am I missing?

# Answer
Ah, I stumbled upon it right after posting. It needs to be configured on each Field in particular. I edited my Content Type and changed this setting:
> 7 votes

---
Tags: 7, files
---


# Question
Title: How do I print a taxonomy term in node.tpl.php? (D7)
I have a custom content type that I can select a vocab term for when editing the page (category more or less). How do I print this term to my page via node.tpl.php?

I've tried several different ways, but to no avail so far. Any ideas?

# Answer
> 2 votes
This works for me:

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

```

---
Tags: taxonomy-terms, nodes
---


title: Array value operators

text:
# Question
Title: Array value operators
I'm trying to get the select field below only to show only when the value of the platform field is 4 or greater. Is it possible to nest an operator within the array statement? The code below works if I change `>=` to `=> 4` however that only works when the platform value is 4 and I need to to be any time it's 4 or greater.

```
$form['model'] = array(
  '#type' => 'select',
  '#title' => t('Select a Model'),
  '#options' => array(0 => t('- Select -')) + $options,
  '#default_value' => 0,
  '#states' => array(
    'visible' => array(':input[name=platform]' => array('value' >= 4)),
    'required' => array(':input[name=platform]' => array('value' >= 4)),
  ),
);

```

# Answer
> 0 votes
`array('value' >= 4)` is not the correct syntax to define an array containing the index `value`.

Basing on Fixed conditionals to allow OR and XOR constructions, you can use the following code.

```
$form['model'] = array(
  '#type' => 'select',
  '#title' => t('Select a Model'),
  '#options' => array(0 => t('- Select -')) + $options,
  '#default_value' => 0,
  '#states' => array(
    'visible' => array(
      array(
        array(':input[name=platform]' => array('value' => 4)),
        array(':input[name=platform]' => array('value' => 5)),
        array(':input[name=platform]' => array('value' => 6)),
        array(':input[name=platform]' => array('value' => 7)),
      ),
    ),
    'required' => array(
      array(
        array(':input[name=platform]' => array('value' => 4)),
        array(':input[name=platform]' => array('value' => 5)),
        array(':input[name=platform]' => array('value' => 6)),
        array(':input[name=platform]' => array('value' => 7)),
      ),
    ),
  ),
);

```

Using this code, the form field will be visible when the other form field value is one of the following values: 4, 5, 6, 7. It works with Drupal 7.14, or higher.

---
Tags: javascript
---


title: About Corolla Theme Logo

text:
# Question
Title: About Corolla Theme Logo
I am using my logo with the Corolla theme but its give me the following error:

> No setting detected for Mobile first or Desktop first. Please review "Settings \> Mobile first or Desktop first" and select an option.

What do I have to do? How can I resolve this error?

# Answer
You're using the 3.x-dev version of Corolla, which is not quite ready for release. You should consider using the stable 2.x release instead.

To fix the error, you will need to go the Corolla theme administration page (/admin/appearance/settings/corolla) and choose either "mobile first" or "desktop first" under "CSS Global Settings."

P.S. In the future, this type of theme-specific question should be filed as a "Support request" in the Corolla issue queue.
> 3 votes

---
Tags: 7, media
---


# Question
Title: How to translate my drupal site in other language.
My drupal site is in default English language and I have added Spanish and German languages using Internationalization and Locale Modules. When I switch to other language using Language Switcher block placed in header of my site, It translated Drupal Interface like admin menu and other core displays, but does not translate nodes or module pages which I have added. I have used t() function to display page contents or titles and its not translating them using t function.

The code for the page which I have added is as:

```
function MY_MODULE_menu() {
     $items['fee/per'] = array(
    'title callback' => 'attendance_og_get_title',
    'title arguments' => array('calendar'),
    'description' => t('Shows attendance percentage recorded per day for a group in a calendar.'),
    'page callback' => 'attendance_og_calendar_page',
    'file' => 'fee_management.pages.inc'
  );

    return $items;
}

function attendance_og_get_title($c) {
    return t('!entity_type Attendance Report (Aggregated)',  array('!entity_type' => ucfirst('Some Name ' . $c)));
}

```

File fee\_managemen.pages.inc.

```
 function attendance_og_calendar_page($entity_type, $etid) {
       return array(
        '#prefix' => '<div class="alert-message block-message info offsetfull2 bottomonly">' .
        t('This view shows the percentage attendance recorded per attendance day in this group. An attendance day is a calendar day in which attendance was taken.') . '</div>',
        '#markup' => '<div id="loading">' . t('Loading.. I am loading here') . '</div><div id="calendar"></div>',
      );
}

```

Please help me to get this working.

# Answer
> 6 votes
As your module is not hosted on drupal.org, the strings it uses are not available on localize.drupal.org, where they can be translated in any language available there.

As such, you need to enable the Locale module, and translate the strings on your site.

With Drupal 7, you visit the page at admin/config/regional/translate/translate, and you get a list of untranslated strings you can translate.

In Drupal 6, a similar page is available on admin/build/translate/search.

# Answer
> 2 votes
Go to Language and Translation configuration , select the language and check all un translated strings , you will get all the text written in t("here"), then save the translations of each word and string . This is how it will work :) Thanks

---
Tags: nodes, i18n-l10n
---


# Question
Title: "Undefined index: #parameters" and other error in custom module
Original question at the bottom. Quick summary, I needed a way to remove the comma character from views exposed filter queries. Below, I was given an example of custom module to do this using validation, which I used and barely modified. However, I'm getting the errors:

`Notice: Undefined index: #parameters in search_helper_form_alter() (line 6 of /Applications/MAMP/htdocs/drupal-7.12_old/sites/all/modules/search_helper/search_helper.module).`

`Notice: Trying to get property of non-object in search_helper_form_alter() (line 6 of /Applications/MAMP/htdocs/drupal-7.12_old/sites/all/modules/search_helper/search_helper.module).`

Since I've never written a module before, I'm not sure how to interpret these errors. I'd really appreciate any suggestions. Here's the code.

```
<?php
function search_helper_form_alter(&$form, $form_state, $form_id) {
    switch($form_id) {
        case 'views_exposed_form':

        if ($form['#parameters'][1]['view']->name == 'views_exposed_form_address_search_page') { // name of the view
            // display array, you have to enable devel module
            //$output .= dsm($form);

        $form['#validate'][] = 'no_commas';
   }
  break;
 }
}
function no_commas($form, &$form_state) {
  $form_state['values']['d'] = preg_replace(",", ' ', $form_state['values']['d']);
}
?>

```

Original question: I've been trying to set up a location search using views exposed filters and various methods of storing information. The problem inevitably arises that users obviously will want to search for a location using a comma (San Diego, CA or Portland, OR), but the comma isn't stored with the locations anywhere. So, if they search for San Diego or they search for California it works fine, but when they search for both using comma separation, they query returns no results. Is there a way to remedy this? The best way to do this, it seems, would be to ignore the comma within the query somehow. It's been driving me crazy for quite some time now how to get this working. Any help would be appreciated.

# Answer
Basically, just got rid of unnecessary parts of the code that I didn't know I didn't need. Now, I think that this is going to apply to all views exposed filters, but at this point I don't mind. Here's the working code if anybody cares:

```
<?php
function search_helper_form_alter(&$form, $form_state, $form_id) {
    switch($form_id) {
       case 'views_exposed_form':

       $form['#validate'][] = 'no_commas';

  break;
 }
}

function no_commas($form, &$form_state) {
  $form_state['values'] = preg_replace("/,/", '', $form_state['values']);
}

```
> 0 votes

# Answer
You could write a small custom module that -

1. Form alters views exposed filter form of the particular view in question
2. Add a new validate function to the form above (validate function is called before the actual form submit function is called and allows you to manipulate values)
3. Then in the validate function you could edit the particular exposed filter form field replacing commas with nothing.

Here is a sample code that I found on Googling around - http://drupal.org/node/716420#comment-2634540

Hope this helps.
> 1 votes

---
Tags: views
---


# Question
Title: Ouput Node Reference Field Title in Drupal 7
When creating templates in Drupal 6 I can output just the title for the value of a node reference field like so:

```
echo $node->field_example[0]['safe']['title'];

```

I'm trying to do the same thing in Drupal 7 - I've tried many variations like the examples below but the output is always blank or throws an error:

```
print $content->field_example['und']['0']['node']['title'];

print $content['field_example']['#object']['field_example']['und']['0']['node']['title'];

```

Any help on how to grab the 'title' value is much appreciated.

# Answer
```
print $field_example[0]['node']->title;

```

This ended up being the syntax needed to pull just the title from the value of a node reference field.
> 1 votes

---
Tags: theming, nodes
---


title: Compare specific content type with tags

text:
# Question
Title: Compare specific content type with tags
I have a content type called 'message' which has tags. The idea is that when viewing a message, the sidebar shows a block that lists titles of other messages who have the same tags as the one the user is currently viewing. I reckon this can be done with a view, though I have no idea how to work this out.

# Answer
I managed to get it to work with a context filter.
> 0 votes

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


# Question
Title: Hide a CCK fieldgroup using #states in hook_form_alter()?
I have a custom module, and I am trying to hide a CCK fieldgroup using "#states" when a certain item is selected in a drop-down select list.

I have tried using states from within hook\_form\_alter(), like so:

```
$form['group_mygroup']['#states']['invisible'] = array(
  ':input[name="field_trigger[' . LANGUAGE_NONE. ']"]' => array( 'value' => 'hide' ),
);

```

This doesn't seem to do anything.

I have looked at changing the weight of my module as per various sites like http://proofgroup.com/blog/2008/dec/modifying\_cck\_fieldgroups\_hook\_form\_alter.

but still to no avail. I can hide all the form elements within the fieldgroup using states but not the field group itself. Does anyone have any idea?

# Answer
```
/**
 * Implements hook_field_group_build_pre_render_alter.
 */
function mymodule_field_group_build_pre_render_alter(&$element) {
  if (isset($element['#form_id'])) {
    if ($element['#form_id'] == 'mynodetype_node_form') {
      $element['group_myfieldgroup']['#states'] = array(
        'visible' => array(
          ':input[name="field_myfield[und]"]' => array('checked' => TRUE),
        )
      );
      $element['group_myfieldgroup']['#id'] = 'group_myfieldgroup';
    }
  }
}

```

I use this hook to hide my field group. It's visible only if the checkbox `field_myfield` is checked.

To explore `$element` variable in this hook I used

```
die('<pre>'.print_r($element, 1).'</pre>');

```

instead of `dpm()`.

Hope it helped :)
> 11 votes

# Answer
Fieldgroups aren't defined in the root of `$form`. It seems you should use not `$form['group_mygroup']`, but `$form['#fieldgroups']['group_mygroup']`.
> 1 votes

# Answer
You can look at the example module to see how they hide fieldsets. Based on that I think your code should be:

```
$form['group_mygroup']['#states'] = array(
  'invisible' => array(
    ':input[name="field_trigger"]' => array('value' => 'hide'),
  ),
),

```
> 0 votes

---
Tags: 7, javascript
---


# Question
Title: How to find in a node template file that node is loaded directly or from 'node_load' function?
I want to check, in a node template file (node-node-type.tpl.php), that code is executing because of a direct request from a user visiting a node page or from calling node\_load function in somewhere else?

**EDIT**:

the problem was `'Number of posts on main page'` option in `'Post settings'`. its value was 30 (I don't remember why I set it to its maximum value but I'm sure there was a reason that wasn't related to it's true functionality I think it triggers something else).

now that we know problem is from `'Number of posts on main page'` option how I can I fix it? why this option invokes node template file despite the fact that I use a custom `page.tpl.php` which doesn't call `node_view` at all?

# Answer
**Edit:** I realise after writing the answer that I sound rather negative. Sorry about that, but I can't phrase this in a positive fashion.

**Answer:** First, and foremost, you are mixing logic, with output. The template should *not* have logic in it, and should absolutely *not* care about *why* it was called.

When a user visits `node/1`, core will call `node_load(1)`. This is in no way different from calling `node_load(1)` anywhere else.

A node template does also *not* execute as a direct result of loading a node. Templates are used when the theme layer *renders* a node, which is the completely other end of the response.

You *can, in theory,* call debug\_backtrace() to get the call stack, and from there figure out more information about from where node\_load was called, but there is almost certainly exactly **0** valid use-cases for this. I guarantee that you do not want to go down that path, and even considering it means that something is seriously wrong.

I have built Drupal-sites professionaly for years now, and have done some *really, really* ugly hacks during that time. Neither of them would come anywhere near analysing the stacktrace, **in the theme layer**.
> 5 votes

# Answer
node will displayed after creating renderable array via `node_view(node_load($nid))`. so if there is somewhere where you render node yourself, you can pass extra variable to node\_view and catch it in `node--node-type.tpl.php`

another solution is using context module, where you can set static variable and get it in `node--node-type.tpl.php` then unset it again

```
context_set('mynamespace', 'customrender', true);

print drupal_render(node_view(node_load($nid))); //and in node--node-type.tpl.php context_get('mynamespace', 'customrender');

context_set('mynamespace', 'customrender', false);

```
> 1 votes

---
Tags: 6, nodes, theming
---


title: Remove module folder when uninstalling

text:
# Question
Title: Remove module folder when uninstalling
is there any method/module that allow removing module folder when uninstalling the module or delete the files via dashboard

# Answer
To take a different angle:

It's very possible to do this, **but you shouldn't**. Your web server user should not have the capacity to write to the web root (except for designated folders like the public files folder). You should therefore not be able to delete module folders from code. Doing so presents a security risk to your server.

This is one of the checks the Security Review module performs, and throws up a nice big red error if it find the web server *can* write to such files:

I understand this might be unavoidable if you're on shared hosting, but I think it's a good piece of information to have either way.
> 10 votes

# Answer
A module *could* implement hook\_modules\_uninstalled to do this for other modules, but I'm not aware of such a module, no.
> 2 votes

---
Tags: 7, installation
---


# Question
Title: how to find that there is a "Promoted to front page" node and load it in page.tpl.php?
because front page has no `arg(1)` (node id) I cannot load promoted node\[s\] in page.tpl.php . all I want to do is print something in one part of front page if a specific content type node in about to load in node.tpl.php. I search it alot but find no answer.

# Answer
> 1 votes
You mean a custom function?

I did a lot of this for a current project where we needed short little lists of nodes with different criterion all over. I found Views bulky and overkill in some places, so I added small functions to template.php. They're really just simple SQL SELECT statements.

For example:

```
function home_channel_list($title, $tids, $limit){

    $query = "SELECT t1.nid, MAX(t1.vid), t1.title, UNIX_TIMESTAMP(t2.field_pubdate_value) AS pubdate
                FROM {node} t1
                    JOIN field_revision_field_pubdate t2 ON t1.nid = t2.entity_id AND t1.vid = t2.revision_id
                    JOIN field_revision_field_channel t3 ON t1.nid = t3.entity_id AND t1.vid = t3.revision_id
                WHERE t3.field_channel_tid IN(".$tids.")
                    GROUP BY t1.nid ORDER BY pubdate DESC LIMIT ".$limit."";

        $result = db_query($query);

        // Container div and title
        print '<div class="home-channel-block"><h2>'.$title.'</h2>';

        // Article list
        foreach ($result as $record) {
            $mypubdate = format_date($record->pubdate, 'custom', 'F j, Y, g:iA');
            print '<div class="home-channel-title"><a href="?q=node/'.$record->nid.'">'.$record->title.'</a></div>';
            print '<div class="home-channel-pubdate pubdate">'.$mypubdate.'</div>';
        }

        // Clear and close the container div
        print '<div class="myclear"></div></div>';
}

```

# Answer
> 0 votes
Not 100% sure I understand - but I would create a block either from a view or with a custom function that pulls a list of articles where node\_revision.promote = 1. Then just have it display on the front page only.

# Answer
> 0 votes
have a look at `node_page_default()` in `modules/node/node.module` and it's output, but I think its better to use another `page.tpl.php` for those content type via suggesting new .tpl files to theme layer via this function in `template.php`:

```
function mytheme_preprocess_page(&$variables) {
  if (!empty($variables['node'])) {
    $variables['theme_hook_suggestions'][] = 'page__node__' . $variables['node']->type;
  }
}

```

so you can have `page--node--news.tpl.php` for news content type ...

---
Tags: nodes
---


# Question
Title: db_select subquery "In" condition causes PDOexception
This source should get the 4 most popular top level categories.

The result query works fine when run in phpmyadmin so I must assume the problem is in db\_select somewhere.

The resulting query should be: `SELECT tid FROM taxonomy_index,name WHERE tid IN(SELECT data.tid FROM taxonomy_term_data AS data JOIN taxonomy_term_hierarchy AS hierarchy ON data.tid=hierarchy.tid WHERE vid=2 AND parent=0) ORDER BY COUNT(nid) ASC LIMIT 0,4`

```
<?php
$vocab = 2;

$subquery = db_select('taxonomy_term_data','data')
  ->fields('data',array('tid'));
$subquery
  ->join('taxonomy_term_hierarchy', 'hierarchy', 'data.tid=hierarchy.tid');
$subquery = $subquery
  ->condition('data.vid',$vocab)      // vid of vocab we want to show
  ->condition('hierarchy.parent',0);  // tid of parent (We want toplevel terms)

$toplvlcats = db_select('taxonomy_index','index');
$toplvlcats
  ->join('taxonomy_term_data','data','index.tid=data.tid');
$toplvlcats = $toplvlcats
  ->fields('index',array('nid'))
  ->fields('data',array('name'))
  ->condition('index.tid',$subquery,'IN') // Sift through toplevel terms
  ->orderBy('COUNT(nid)','ASC')           // For the one with the most posts
  ->range(0,4)
  ->execute();
?>

```

The error message is:

`PDOException: SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'index INNER JOIN taxonomy_term_data data ON index.tid=data.tid WHERE (index.tid' at line 1: SELECT index.nid AS nid, data.name AS name FROM {taxonomy_index} index INNER JOIN {taxonomy_term_data} data ON index.tid=data.tid WHERE (index.tid IN (SELECT data.tid AS tid FROM {taxonomy_term_data} data INNER JOIN {taxonomy_term_hierarchy} hierarchy ON data.tid=hierarchy.tid WHERE (data.vid = :db_condition_placeholder_0) AND (hierarchy.parent = :db_condition_placeholder_1) )) ORDER BY COUNT(nid) ASC LIMIT 4 OFFSET 0; Array ( [:db_condition_placeholder_0] => 2 [:db_condition_placeholder_1] => 0 ) in eval() (regel 25 van /home/j/www/modules/php/php.module(80) : eval()'d code).`

# Answer
The only problem with your query is that you're using `index` as a table alias...this is a MySQL reserved word and although my instinct is that PDO should escape this, perhaps it doesn't.

The following code (with the aliases renamed) runs without error:

```
$vocab = 2;

$subquery = db_select('taxonomy_term_data','ttd')
  ->fields('ttd',array('tid'));
$subquery
  ->join('taxonomy_term_hierarchy', 'th', 'ttd.tid=th.tid');
$subquery = $subquery
  ->condition('ttd.vid',$vocab)      // vid of vocab we want to show
  ->condition('th.parent',0);  // tid of parent (We want toplevel terms)

$toplvlcats = db_select('taxonomy_index','ti');
$toplvlcats
  ->join('taxonomy_term_data','ttd','ti.tid=ttd.tid');
$toplvlcats = $toplvlcats
  ->fields('ti',array('nid'))
  ->fields('ttd',array('name'))
  ->condition('ti.tid',$subquery,'IN') // Sift through toplevel terms
  ->orderBy('COUNT(nid)','ASC')           // For the one with the most posts
  ->range(0,4)
  ->execute();

```
> 8 votes

---
Tags: database
---


title: Navigation within html.tpl

text:
# Question
Title: Navigation within html.tpl
I want to be able to put my Navigation block within the html.tpl.php, as it isn't going to change across any of the pages and it just seems like a more efficient option.

I know that I can't render a block using regular regions - so how do I go about doing this?

I'm using Nice Menus for my Navigation.

Thanks.

# Answer
> 2 votes
Basically this involves moving a region to html.tpl.php

So first you need to create a region to go in html.tpl.php which will hold your menu (unless you're using an existing region). Then create a preprocess in your template.php file:

```
function THEMENAME_preprocess_html(&$variables) {
  if ($blocks = block_get_blocks_by_region('REGION_MACHINE_NAME')) {
    $variables['REGION_MACHINE_NAME'] = $blocks;
    $variables['REGION_MACHINE_NAME']['#theme_wrappers'] = array('region');
    $variables['REGION_MACHINE_NAME']['#region'] = 'REGION_MACHINE_NAME';
  }
}

```

You need to replace `THEMENAME` with the name of your theme. Also replace all instances of `REGION_MACHINE_NAME` with the machine name of your region. The machine name can be found in your theme's .info file. Then all you need to do is put:

```
print render($REGION_MACHINE_NAME);

```

in your html.tpl.php (of course replace $REGION\_MACHINE\_NAME with the name of your region, I've only caps'd it to make it visible, it should all be lowercase otherwise)

---
Tags: routes, blocks, navigation
---


title: Views custom output into specific divs

text:
# Question
Title: Views custom output into specific divs
I am a kind of noobie so excuse me for that.

I am trying to implement this into my website.

It is a fancy looking bookshelf gallery. I am using drupal 6.x. I have already set up a view to list out the items I would like to appear in the gallery. In other posts, I saw that if I set up the view output as "fields" I can wrap individual fields into custom divs. That is kind of what I want to achieve. The code I need to alter is the following:

```
<div class="slide_animate">
<div class="products_box" id="products_box_1">
<a href="#" class="product" data-type="book" data-popup="true" data-url="images/01_large.jpg" title="The Title is Optional 1">
<img src="images/01.jpg" alt="" width="81" height="107" /></a>
<a href="#" class="product" data-type="book" data-popup="true" data-url="http://www.youtube.com/watch?v=C05pGnZQQtE" title="Youtube Video">
<img src="images/02.jpg" alt="" width="71" height="107" /></a>
</div>
</div>
<div class="slide_animate">
<div class="products_box" id="products_box_2">
<a href="#" class="product" data-type="magazine" data-popup="true" data-url="images/magazine_large.jpg" title="info"><img src="images/magazine_health.png" alt="" width="76" height="108" /></a>
<a href="#" class="product" data-type="magazine" data-popup="true" data-url="images/magazine_large.jpg" title="info"><img src="images/magazine_gourmet.png" alt="" width="71" height="100" /></a>
</div>
</div>

```

What I need to know is how to make the view output my field data (node url, img, nodetitle) in specific parts of the HTML (data-url ,img ,title); plus, based on taxonomy terms, form different categories. So my books will be under books, and my DVDs will be under dvd.

# Answer
You could alter the output in a template. Go to 'Advanced' and look at 'Theme Information'.
> 0 votes

# Answer
When editing the view, under Basic Settings -\> Style -\> Settings (the "gear" icon) you can choose to group the results by a certain field. Hope this helps.
> 0 votes

---
Tags: views
---


title: How to render youtube field?

text:
# Question
Title: How to render youtube field?
How can I render a Youtube field to get the full code for embedding?

```
field_view_field('node', $o, 'field_testvideo', $display)

```

What are the settings for $display?

# Answer
> 2 votes
$display should be one of view modes (full, teaser, rss or ...) or display setting array:

```
$display = array(
    'label' => 'hidden',
    'type' => 'file_rendered',
    'settings' => array(
        'file_view_mode' => 'media_original',
    ),
);

```

---
Tags: entities, files
---


# Question
Title: How to get change event working of a taxonomy select box on a node form?
I have a taxonomy, which I have added to a content type. Now a select box from the taxonomy appears when I want to create a node of that content type.

That content type have a cck field of type select.

In my module in the hook\_form\_alter I want to execute the js change event of the taxonomy select box, but it does not work. And when I try to execute the js change event on cck select box, it works fine.

here is my code.

```
function mymodule_form_alter(&$form, &$form_state, $form_id) {
     if($form_id == 'contenttype_node_form') {
        drupal_add_js("
            $('#taxonomy-select-box-id').change(function(){
                alert('change');
           }) ;

", "inline");
    }

```

# Answer
> 0 votes
This isn't really a Drupal question, but at a guess I'd say the problem is that you're binding the event to an element before the DOM has loaded...so the element doesn't exist yet. You should use one of the standard jQuery methods to run your code when the document is ready, e.g.:

```
$(document).ready(function() {
  $('#taxonomy-select-box-id').change(function(){
    alert('change');
  });
});

```

---
Tags: nodes, taxonomy-terms, 6, javascript
---


title: Embedding renderable forms api

text:
# Question
Title: Embedding renderable forms api
Is there any way to embed form fields (i.e. textfield) within other field (i.e. radios). I'd like to create something like radiobuttons list: first default and second (if selected) allow user to enter text value. Maybe I should create custom compound cck field?

# Answer
> 0 votes
This module may help: Select (or other)

Or maybe you want use form alter and #state attribute: http://api.drupal.org/api/drupal/developer!topics!forms\_api\_reference.html/7#states

---
Tags: 7, forms
---


title: Rendering an entity the formatter way

text:
# Question
Title: Rendering an entity the formatter way
I have written a custom formatter for taxonomy term fields. Now I would like to expand the module and add a custom entity renderer to show the entity in the very same formatter-like way, using mostly the same code.

The reason I need it is that while theming Search API Views fields, I'm not given an option to format term reference as a field, but only as entity.

I thought I'd provide a custom entity view (via `hook_entity_info_alter`). But then, how do I provide the HTML output of the entity?

# Answer
> 0 votes
You can't render an entity like a field and vice versa. These are two entirely different things. However if you in a field loaded a related entity and rendered as a way of rendering the field, there could be some common ground.

That being said, your reason for asking this question doesn't really make sense. If you have a field on an entity and want to render the field. No matter how you render it, (through views, by viewing the entity etc.) you will have to use a field formatter to render that field.

Also regarding entities there is no common way of rendering them. The module defining them can render them any way it would like to and it's up to that module to make a way to render the entity. That being said, the entity API module does create some apis for doing this in a generic way, but that is not a part of Drupal 7 core.

---
Tags: 7, entities
---


title: sibling taxonomy terms

text:
# Question
Title: sibling taxonomy terms
Drupal 7

I have a vocabulary with hierarchical terms countries and cities.

I have a view with context filter=cityA ( parent country A)

How I can display into a block all cities from country A ( siblings of cityA from vocabulary)?

Thanks

# Answer
You can try using `taxonomy_get_children($termid)` to get children of term and then `taxonomy_get_parents($termid)` and again `taxonomy_get_children()` to get the siblings . The following is the code I used in such situation :

```
<?php

if (isset($page['#views_contextual_links_info']['views_ui']['view']->args[0])){
    $termid = $page['#views_contextual_links_info']['views_ui']['view']->args[0];
    $terms = taxonomy_get_children($termid);

    if (empty($terms)) {
        $parent = taxonomy_get_parents($termid);
        $terms = taxonomy_get_children(key($parent));
    }
}

if (isset($node->field_category['und'][0]['tid'])) {
    $termid =  $node->field_category['und'][0]['tid'];
    $terms = taxonomy_get_children($termid);
}

?>

```
> 1 votes

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


# Question
Title: How can you use multiple lines in a text area?
I'm probably missing something really simple here, but I can't seem to find it at all!

I want to have a text area for lyrics in my "Songs" content type. Naturally, lyrics should be displayed one line per line, and with a space to distinguish verses, choruses etc... e.g.

> I got my head checked
> By a jumbo jet
> It wasn't easy
> But nothing is
> No
>
> Woohoo!

When I put the above in a text area, I get:

I got my head checked By a jumbo jet It wasn't easy But nothing is No Woohoo!

How do I get this to display correctly? I am using Drupal 6.

# Answer
Change the input format (just below the textarea) to Filtered HTML or Full HTML.
> 3 votes

# Answer
Use nl2br() while viewing the field.
> -1 votes

---
Tags: 6, entities
---


title: Putting headings between content fields

text:
# Question
Title: Putting headings between content fields
I am creating content and in fields i want to categorize fields, like a heading and then its related fields.For eg this is html field i m converting into drupal 7.

Now how can i get this heading `project report information` and `construction details` in creating or viewing content

# Answer
> 1 votes
Here is an example of putting heading (fieldset) on a comment form that I found a while back: click here.

Basically you need to do a hook\_form\_alter().

Start by creating a field set:

```
fucntion HOOK_form_FORM_ID_alter() {

$form['project_report_information'] = array(
    '#type' => 'fieldset',
    '#title' => t('Project Report Information'),
    '#collapsible' => FALSE,
  );

```

Next, add your fields to the field set and remove the field outside the fieldset:

```
$form['project_report_information']['subject'] = $form['your_field'];  //add to field set
unset($form['your_field']);                                            //remove field outside
$form['project_report_information']['your_field']['#weight'] = -10;    //of fieldset

```

Now repeat this for all fields and fieldsets you want.

Look over the link for a more detailed example of someone doing this. What you want is about half way down the page.

# Answer
> 0 votes
You can easily use the Field Group module for this!

> Fieldgroup will, as the name implies, group fields together. All fieldable entities will have the possibility to add groups to wrap their fields together. Fieldgroup comes with default HTML wrappers like vertical tabs, horizontal tabs, accordions, fieldsets or div wrappers.

You can put your fields into fieldsets, accordions, horizontal tabs, or vertical tabs just by dragging and dropping into created groups. Just give your field grouping the title that you want (Project Reporting Information for example) and then drag and drop the fields into the group.

---
Tags: 7
---


# Question
Title: How do I create a custom theme, or layout using images?
I would like to create a custom theme, for which I have the images for parts of the theme, such as header, footer, menu, logo. I don't understand how to start to create a layout. I have gone through "Themeing guide," but I don't know where to start.

# Answer
> 1 votes
You should download a theme such as AdaptiveTheme or Zen as a base and then create a sub-theme.

---
Tags: theming
---


# Question
Title: Rules- how can I redirect a user to view their profile only when they update their profile?
I want to redirect users to their profile (/user) after they save changes to their profile settings (/user/\[uid\]/edit).

If their accounts are updated in another manner (by rules, etc.), I do not want them to be redirected.

I made a rule like this:

* Event-\> After updating an existing account
* Actions-\> Page redirect to user/\[account:uid\]

This redirects properly; however, on my site sometimes user accounts get updated when a user adds content. Adding content then also causes this rule to get called, which I don't want. I only want the user to be redirected if they updated their account details at user/\[account:uid\]/edit.

I tried adding:

* Condition: Path has URL alias: user/\[account:uid\]/edit

However, then the redirect ceases to function.

# Answer
> 1 votes
```
{ "rules_cw_profile_redirect_user_to_profile_page_after_edit" : {
      "LABEL" : "Redirect user to profile page after editing account",
      "PLUGIN" : "reaction rule",
      "REQUIRES" : [ "rules" ],
      "ON" : [ "user_update" ],
      "IF" : [
        { "data_is" : { "data" : [ "site:current-page:url" ], "value" : [ "account:edit-url" ] } }
      ],
      "DO" : [ { "redirect" : { "url" : "user" } } ]
}

```

---
Tags: rules, redirection
---


# Question
Title: Where DHTML Menu link's title is getting printed
I would like to replace the title attribute of DHTML menu's link with a javascript tool tip. But i could not find the place where the link attributes are printed. ie. where test is mentioned.

Kindly help me.

# Answer
> 0 votes
By implementing theme\_menu\_link(), you can adjust the menu links to whatever you need.

---
Tags: routes, navigation
---