# Question
Title: Using hook_form_alter to change from text filter to checkboxes
I'm using a custom module and `hook_form_alter` to change a Views Exposed Filter from a text field to checkboxes. When altering to a select list, the module works fine. However, when I change the form type to "checkbox", the filter renders as a single checked checkbox without a label. I thought I had solved it earlier by simply removing the #size line, but after reverting the code and trying to fix it that way again, it's no longer fixing it. Any idea what I need to change?

Working select list code:

```
function dropdown_bartab_form_views_exposed_form_alter(&$form, &$form_state) {
  $field_id = 'field_venue_bar_tab';

  // Only alter forms with the necessary field
  if (isset($form[$field_id .'_value'])) {

// Build a query to get all node ids having the specified field
$query = new EntityFieldQuery();
$results = $query->entityCondition('entity_type', 'node')
                  ->fieldCondition($field_id, 'value', 'NULL', '!=')
                  ->fieldOrderBy($field_id, 'value', 'ASC')
                  ->execute();

// Attach the field values to the nodes
$nodes = $results['node'];
field_attach_load('node', $nodes, FIELD_LOAD_CURRENT, array('field_id' => $field_id));

// Add a default so the filter is optional
$options = array(
    '' => 'Any',
    '0' => 'Drinks',
    '1' => 'Food',
    );

// Alter the field
$form[$field_id .'_value']['#type'] = 'select';
$form[$field_id .'_value']['#options'] = $options;
$form[$field_id .'_value']['#size'] = 1;
  }
}

```

# Answer
So, I changed nothing, but it suddenly started working again. Must have been some strange bug.
> 0 votes

# Answer
You probably want to use #type `checkboxES` (uppercase only for emphasis ;)), which is a list of checkboxes. checkbox is just a single checkbox that can either be checked or not, it can't have multiple options, so that property is ignored.
> 2 votes

---
Tags: views, forms
---


# Question
Title: How do you load a node inside of another node?
A node has several text links or thumbnails loaded from a view. For the purpose of this question, lets suppose they're thumbnails and the area with the thumbnails lets call it the "head" of the node.

Those thumbnails link to other nodes. To be able to understand the scenario am trying place here. Lets call the nodes that the thumbnails link to "*Subnodes*". The Area under the thumbnails, is a area where you want to load a "subnode" from the thumbnail clicked. Lets call this area the "footer".

The goal here is keep the original node with the thumbnails or text links ("Header") at the top of the page AND load the subnode in the "footer". The ideal method would involve some AJAX to keep the page load away from the end user. Although this is not required because a solution with a page load is acceptable.

*Extra consideration to anyone who purposes a solution using AJAX.*

# Answer
> 2 votes
Take a look at the Peekaboo; Ajax field formatter module.

> Provides the ability to load the contents of a field via Ajax.
>
> ### Use cases
>
> * **Field output that is heavy on resources**
> Some fields, such as the \*reference fields, can contain a tremendous amount of overhead when formatting the output for the field. This module allows the page output to load without calculating the formatted output of the field, and the field contents can be subsequently loaded into the page with Ajax.
> * **Field output that takes up too much space**
> Peekaboo can be used to initially hide certain fields that take up a lot of space, like maps or images, only to be revealed later at the user's request.
> * **Fields that reveal more information**
> Peekaboo can also be used purely for the Ajax functionality as a gimmick to reveal more information.

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


title: Get Last NID into Variable

text:
# Question
Title: Get Last NID into Variable
I need to get the previous (referrer) NID into a variable on a page. After saving new content of a certain content type a rule will redirect the visitor to a set page where I would like to have the NID of the new node to play with. Can anyone point me in the right direction? I think its possibly going to be one of those ones that you'd think is simple but ends up being awfully complex but I'm really in need of a solution and can't find anything very relevant.

Thanks in advance folks!

# Answer
> 1 votes
You might be able to create a rule based on this:

1. event: After content has been saved...
2. condition: content is new
3. condition: content is type (select type)
4. action: page redirect: fill in page here with tokens based up content above

In the page direct you can create a query variable after the ?, eg foo=\[TOKEN\], and then in your page, you can access that variable via $\_GET\['foo'\] or $\_REQUEST\['foo'\].

---
Tags: nodes
---


# Question
Title: Drupal 6 clean urls without domain name (accessing via IP Address)
Is there a way to do clean urls without a domain name; just using an IP Address. The option is disabled when using ip address.

# Answer
Clean URLs is not dependent on domain names it is disabled because your server doesnt support it. You need to enable `mod_rewrite` module in apache to get that option enabled. Check out the server configuration section here.
> 2 votes

---
Tags: uri
---


# Question
Title: Disallow specific combination of checkbox selections in term reference field?
I have a term reference field in the format of checkboxes. However, I'd like to disallow certain combinations of checkboxes. The options are:

```
[]None
[]Food
[]Drinks

```

The "None" option is not the default none, but a taxonomy term that is actually stored in the database. I'm wondering how to allow two selections, but to disallow the selection of both "Food" and "None", or "Drinks" and "None", since in practice that really doesn't make any sense. Any suggestions?

# Answer
> 0 votes
Take a look at the Field Validation module, it attaches a UI where you can set custom validation rules for each field on a content type.

I am not sure whether any of the inbuilt options will work for what you want, but you can select the PHP code option and write the rules you require. There is a short reference for the PHP validator here: http://drupal.org/node/1537028

---
Tags: entities, taxonomy-terms
---


# Question
Title: Anybody know how to create the filters to filter the content using views?
Here my critical question is how to create filters in a menu which is having some child

filters too. Filters are taken from views based on (Year,and in child - dates,and in

sub-child - category's which we provide in taxonomy),so that while selecting the particular

fields in the child filters ,the result of contents should display. the filters should not be

a select list ,dropdown,or auto compete field.It should shown in a menu and filters are in

its child menu one by one.

anyone know how to do this Kindly reply for this shortly .Thanks in advance

# Answer
When you are creating any filter in views then see the query string in the address bar. It gives you array. You can use these query strings to create your custom menu links. Use "AND", "OR" operators in filters. Then do little custom code. Also use $\_GET to get filter values from filters.
> 0 votes

# Answer
Lets say your view path is `dhinesh/news` and you have a contextual filter for year, the URL will be `dhinesh/news/2012` for 2012 filtered news.

Then go to your menu and add the filter menu items in (you can also pragmatically create the menu items, but that is another question)
> 0 votes

# Answer
Thanks rishi and Duncanmoo ,

i have created categories using taxonomy and filtered the content in views using taxonomy term id.

Then i displayed the taxonomy exposed filters as menu .and did some custom code to show the menu as parent and child.
> 0 votes

---
Tags: views
---


title: Help theming hook_theme in Drupal 7

text:
# Question
Title: Help theming hook_theme in Drupal 7
I created a module with a hook\_theme(). It works fine but when I copy my-custom-template.tpl.php file into my theme folder to customize the override doesn't work. I don't understand what I am doing wrong.

```
function foo_bar_theme() {
  return array(
    'something' => array(
      'template' => 'my-custom-template',
      'variables' => array(
        'zone' => null,
        'location' => null,
        'class' => null),
    ),
  );
}

```

Can someone help me please? I've checked everything, cleared the cache, checked the spelling, made sure the names are original to not have name clashes.

# Answer
The file outside your module should be named (in your example) something.tpl.php.
> 1 votes

# Answer
you can try

```
function foo_bar_theme() {
  return array(
    'something' => array(
      'template' => 'my-custom-template',
      'arguments' => array(),
    ),
  );
}

```
> 1 votes

# Answer
Your template file must be placed in your modules directory or you can use file option see return values for hook\_theme here

```
function foo_bar_theme() {
  return array(
    'something' => array(
      'template' => 'my-custom-template',
      'file'=>drupal_get_path('theme','my_default_theme').'my_custom_template.tpl.php',

      'variables' => array(
        'zone' => null,
        'location' => null,
        'class' => null),
    ),
  );
}

```

you may override theme suggestions in your default theme's template.php you have to write overriding functions like this

function MYTHEME\_something($variables){}

you can do this for all theme registry elements(use devel module to see all theme registry) drupal looks for theme implications like let's say that you use grayscale theme:

* grayscale\_something()
* sites/all/themes/grayscale/something.tpl.php
* theme\_something()

the last theme something assumed that you wrote a theme\_something function in your module
> 0 votes

---
Tags: theming, hooks
---


# Question
Title: Renders my safe_value instead of the value
When I'm displaying the contentfield of a node, Drupal only shows the safe\_value. I want to use the full HTML from my WYSIWYG. I know this because, when I change `$items[$id][$delta]['safe_value']` into $`items[$id][$delta]['value']` (in modules/field/modules/text/text.module line 159 in the text\_field\_load hook implementation), it displays the correct HTML from my WYSIWYG.

How can I change this, so that Drupal shows the value with the HTML?

# Answer
> 1 votes
I needed to change the filter of the field. That fixed the problem.

---
Tags: entities
---


# Question
Title: Cannot see user_stats module logs in drupal site
I have used User Stats Module for the purpose to find the users login count till date. I am able to see the data in database but can't find the logs in my drupal site.

I have checked in "Reports" but can't see. Please help.

# Answer
> 0 votes
Apart from some pages available under admin/reports/ip\_tracking, which are visible when the Views module is enabled, and the "Track IP addresses" option is enabled on admin/settings/user\_stats, the module doesn't show those values. You need to do one of the following:

* Install the Advanced Forum module
* Use user\_stats\_get\_stats() in a template file

### Reference

---
Tags: 7
---


title: Auto Fill Content Fields

text:
# Question
Title: Auto Fill Content Fields
I want to have a content type named **person** with fields like *first name, last name, phone number ....*

In another content type named **account**, it will also contain the fields belong to **person**, but I want to have a drop down list for the *field person* in **account** to select from existing person content, and auto populate the rest of the fields in account.

Also, is it possible to auto populate a field based on the value in previous field? For example, two fields of the same content type, user id and user email, while user input the user id sunnyside, user email would automatically generate sunnyside@gmail.com.

Thanks

# Answer
you have to write alter function for your form then you may attach fields from another entity by using field attach form function here is a example for loading profile2 fields form elements

```
 global $user;
         $profile = profile2_load_by_user($user,'profile');
        field_attach_form('profile2',$profile,$form,$form_state,'und');

```
> 1 votes

---
Tags: entities, nodes, ajax
---


# Question
Title: Change published status directly in database
I want to change published status of nodes according certain criteria. So I directly modified 'status' column of 'node' table. But it seems to be not reflected when nodes are viewed or edited (I want to avoid using `node_lodad()` and `node_save()`)

That is, if I change 'status' column value of a row in 'node' table, it does not reflected in when corresponding node opened in browser.

So, from where it takes the 'status' (publihed/unpublihed) value other than 'node' table?

# Answer
> 5 votes
You also need to change the `status` column in the `node_revision` table:

```
foreach (array('node', 'node_revision') as $table) {
  db_update($table)
    ->fields(array('status' => 0))
    ->condition('nid', $nid)
    ->execute();
}

```

Notwithstanding any aggressive caching you might have in place, the effect should be immediate once you've run both those queries.

Drupal has plenty of these little nuances, which is why it's highly recommended to use the API functions rather than manipulating the database directly. Yes there's extra overhead, but you don't need to give things like the revisions table/caching a second thought as they're handled for you.

---
Tags: 7, database
---


# Question
Title: Views: how to add rel attribute to multivalue image thumbnail
I know about lightbox module, but I need a universal solution working with more than one jQuery plugin.

There is a view with image field displayed as a thumbnail and I'd like to link it to the normal image, and the link should have "rel" attribute.

How to implement it in the simplest way?

In the View-\>Fields-\>myfield properties, the first option (Link image to File) won't work because there is no option to insert "rel" attribute.

The second option is to REWRITE RESULTS and "Output this field as a link" and insert "lightbox" as a rel text. But what to write in the "Link path" textbox??

The path to image is: `/sites/example.com/files/gallery/img1.jpg`

1. How to obtain the "/sites/example.com/files/" path other than just hardcode typing it? (it's a public:// stream)
2. How to obtain the "img1.jpg" image name? I tried \[field-image\] replacement token but didn't work and there seem to be no fields that look like the file name.

# Answer
> 0 votes
You can install Image URL Formatter module. This will give you "Image URL" as a formatter option on Views.

So what to do is:

1. Add the image field, and Exclude from display. Set the formatter as Image URL
2. Add the same image field again. This one should be outputted as a thumbnail with Image Styles (perhaps), and have the normal "Image" formatter. Rewrite -\> Output this image as a link, put the field added in step 1 to the link path.

---
Tags: 7, views
---


# Question
Title: I want to write the logs for users info, page navigation in drupal 7
I want to write the logs for users info, page navigation in drupal 7. For example: from the time the user log in what actions he has performed, pages visited

Is there any module available? Please help.

# Answer
User log in/out is always logged. Switch on the statistics core module for page view statistics. If you need more details google analytics is very handy (or Piwik if you don't trust google).
> 2 votes

---
Tags: nodes
---


title: Set defaults for new content types

text:
# Question
Title: Set defaults for new content types
I have to make a lot of different new content types. It will save me some time if the defaults (promote to frontpage etc) are set to my preferences. How can I do this?

I hope you get my question

# Answer
It's quite simple, if you want to change a content type default setting, just change it in :

> Administration » Structure » Content types » Edit a content type

Everything you change in the "global" content type settings will be default when you add a new node of this content type.

In the case of a Basic page, it will be this page (admin/structure/types/manage/page) :
> 1 votes

---
Tags: nodes
---


# Question
Title: How do I override the taxonomy default content?
I'm coding a way to display the taxonomy terms, and I don't want some of the term pages to report "There is currently no content classified with this term." I need to remove that message form the term pages with no content, but let the content be listed like normal when there is content associated with that term.

# Answer
> 2 votes
This information is added in taxonomy\_term\_page(). As you can see there, the page callback returns a renderable array, which means that you can easily replace it in a custom module by implementing hook\_page\_alter().

In that hook, check that you are on a taxonomy term page, look if the 'no\_content' block exists, and if yes, override the #markup.

I suggest to use dpm() from devel.module to print $page so that you can more easily figure out where exactly the page content is in that huge render array. Somewhere in system\_main, if I remember correctly.

# Answer
> 1 votes
Another way of doing this is to add a class to the message using your template.php

```
function YOURTHEMENAME_process_page(&$variables) {

  if(isset($variables['page']['content']['system_main']['no_content'])) {
    $variables['page']['content']['system_main']['no_content']['#prefix'] = '<p class="empty-term">' ;
  }
}

```

Then you can hide it, style it etc

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


# Question
Title: Log profile 2 user info a separate log file
When a user logs in, I want to log the user information from the Profile2 module in a separate file.

How can I achieve this?

# Answer
> 1 votes
The profiles2 docs state:

Thanks to the foundational entity API the module integrates well with Rules as well as Features.

Install the rules module (http://drupal.org/project/rules) and you should be able to access the profile data after he user login event. To log to the system watchdog with rules you need this patch: http://drupal.org/node/1349882#comment-6190164

This does not write to a separate file, but it would be trivial to extract your entries from the watchdog db table using phpMyAdmin.

And finally it does not require any coding.

---
Tags: users
---


# Question
Title: What may cause Column not found (nid) in on clause?
I'm using Drupal 7.14 and Entity API and Reference 1.0-rc3.

And I'm also using i18n, entityreference (not References) and field\_sql\_storage.

I get this error when saving a node that has some custom fields using references.

> PDOException: SQLSTATE\[42S22\]: Column not found: 1054 Unknown column 'field\_data\_body0.nid' in 'on clause': SELECT field\_data\_body0.entity\_type AS entity\_type, field\_data\_body0.entity\_id AS entity\_id, field\_data\_body0.revision\_id AS revision\_id, field\_data\_body0.bundle AS bundle FROM {field\_data\_body} field\_data\_body0 INNER JOIN {node} node ON field\_data\_body0.nid = node.nid WHERE (field\_data\_body0.deleted = :db\_condition\_placeholder\_0) AND (field\_data\_body0.entity\_type = :db\_condition\_placeholder\_1) AND (field\_data\_body0.bundle IN (:db\_condition\_placeholder\_2, :db\_condition\_placeholder\_3)) AND (field\_data\_body0.entity\_id IN (:db\_condition\_placeholder\_4)) AND (node.language IN (:db\_condition\_placeholder\_5, :db\_condition\_placeholder\_6)) ORDER BY field\_data\_body0.body\_value ASC; Array ( \[:db\_condition\_placeholder\_0\] =\> 0 \[:db\_condition\_placeholder\_1\] =\> node \[:db\_condition\_placeholder\_2\] =\> news \[:db\_condition\_placeholder\_3\] =\> page \[:db\_condition\_placeholder\_4\] =\> 25 \[:db\_condition\_placeholder\_5\] =\> it \[:db\_condition\_placeholder\_6\] =\> und ) in field\_sql\_storage\_field\_storage\_query() (linea 577 di /home/morpheu5/web/xdatanet/modules/field/modules/field\_sql\_storage/field\_sql\_storage.module).

What bothers me is that, first of all there's a zero appended to the name of the table, and second, if I add that nid column to that table, Drupal is happy and everything seems to work.

I suspect there must have been some update gone horribly wrong, since maintenance is not under my control, and I had to implement some new features working on my local copy which at that time was already completely out of sync with the client's staging and production servers.

I tried a number of patches, and I've gone through the code myself but I'm not **this** familiar with Drupal.

**EDIT**

It seems the nid column is getting added at some point in `function preExecute` in `includes/database/select.inc` specifically at row 1236

```
drupal_alter($hooks, $query);

```

the hooks acting here are

* `query`
* `query_entity_field_access`
* `query_node_access`
* `query_entityreference`

but after a hour long investigation I only came up with a huge headache, and I'm still not sure if I actually found and debugged all of those hooks. As far as I could see, the `nid` column is not present before the drupal\_alter call while it is after, but it's there at the beginning of each hook\_query\_TAG\_alter I was able to find.

I must be missing something.

**EDIT 2**

The culprit seems to be `i18n`, specifically `i18n_select`, more specifically at row 137 of `i18n_select.module` where it adds the `nid` column.

**EDIT 3**

There, I opened a bug: https://drupal.org/node/1679646

# Answer
The body field should definitively NOT have a `nid` column in the table. The `field_data_body` table provided by core will contain an `entity_id` column which is the reference to the node entity.

2 things I can think of that might be causing this:

1. You have custom code that's making an erroneous database query in a `hook_node_load()` function or similar (either directly or using an `EntityFieldQuery`)
2. (more likely I think) Core/contributed modules or files have been edited and the changes are only now causing problems.

The best advice I can give is to install the Hacked! module and determine whether or not core/contributed modules have indeed been hacked. If that comes back all clear then you're just looking at an error in some custom code somewhere which will be easy to track down.

If it doesn't come back clear, at least you know what the problem is and you can then decide how best to proceed with getting Drupal back into a proper un-hacked state.

Incidentally, don't worry about the table being referred to as `field_data_body0`...if you look further down in the query that's just an alias that's being used for `field_data_body`:

```
FROM {field_data_body} field_data_body0

```
> 0 votes

---
Tags: 7, entities, i18n-l10n, database
---


# Question
Title: How do I iterate through views result with pagination in a template file?
I am using Drupal 7.8, built a custom cck type, populated it with content, and created a view with full pager of 10 items per page.

I'm modifying the views theme Row Style Output - views-view-fields.tpl.php to do something, but every-time I try to collect the entire views result set, I only get the first 10.

ie. foreach($view-\>result as $id =\> $data) { // track $data-\>field }

How do I bypass the pagination limits so that in my views template I have access to all the results (which is over 20+)?

Here is an example layout of my cck type -

CCK TYPE: Videos; CCK FIELDs: title, body, url, date\_recorded

date\_recorded is a custom date format which only has Month, Year.

The view filters and groups these fields by date\_recorded, and uses full pager for 10 items like so :

```
Feb 2012
- Video 1
- Video 2

Dec 2011
- Video 3
- VIdeo 4

```

...

PS - This is the 2nd part of a question that began here - Alternative ways to group results of a view by CCK field?

# Answer
Set up a second display on your view or a new view that has no pagination or limit on the number of items displayed and use views\_get\_view\_result to retrieve the object.
> 0 votes

---
Tags: paging
---


title: Replace Page Title with Image

text:
# Question
Title: Replace Page Title with Image
I'm attempting to replace the titles on my pages with images. I've added an image field to my content type and have created a view that displays the image for the selected page with a contextual filter.

I am embedding the view in my page.tpl.php page with `views_embed_view()`.

I'm having a problem with the conditional statement. If no image exists for the selected page, I want to show the regular page title. Currently, my code will print an empty `<h1>` tag on pages with no mages. Can I get some help with this?

I am using Drupal 7 and the Views module version 7.3.3.

```
<?php $TitleImage = views_embed_view('title_image', 'block'); //Embed View ?>

<?php if (!empty($TitleImage)): //Check to see of View is empty ?>
    <h1 class="title" id="page-title"><?php print $TitleImage; ?> </h1>
<?php else: //Display regular title ?>
    <?php print render($title_prefix); ?>
    <?php if ($title): ?>
        <h1 class="title" id="page-title"><?php print $title; ?></h1>
    <?php endif; ?>
    <?php print render($title_suffix); ?>
<?php endif; ?>

```

---

I need to replace the page title in the page.tpl.php file. There are 3 content types that have the field\_title\_image field. I thought that creating a view with a contextual filter would be the best approach, to not display on content types that do not have the field\_title\_image field.

I came across this comment that helped me with displaying the image.

Below is my revised code. Is there a better solution?

```
<?php if (isset($node->field_title_image['und']['0']['filename'])): ?>
<h1 class="title" id="page-title"><img src="/sites/default/files/images/<?php print $node->field_title_image['und']['0']['filename']; ?>" alt="<?php print $node->field_title_image['und']['0']['alt']; ?>"></h1>
<?php else: ?>
<?php print render($title_prefix); ?>
<?php if ($title): ?>
    <h1 class="title" id="page-title"><?php print $title; ?></h1>
<?php endif; ?>
<?php print render($title_suffix); ?>
<?php endif; ?>

```

# Answer
To answer your specific question; clearly $TitleImage is not empty, views\_embed\_view is returning wrapper elements or a space. in the view settings make sure "no results" returns nothing using the no results behavior of the field and the view (under advanced).

**Why use a view?** If that image is on that piece of content then there is no need for a view at all, just use the field:

```
<?php hide($content['field_title_image']); // So it does not render elsewhere ?>
<?php if (!empty($content['field_title_image'])): ?>
  <h1 class="title" id="page-title">
      <?php print render($content['field_title_image']); ?>
  </h1>
<?php else: //Display regular title ?>
  <?php print render($title_prefix); ?>
  <?php if ($title): ?>
    <h1 class="title" id="page-title"><?php print $title; ?></h1>
  <?php endif; ?>
  <?php print render($title_suffix); ?>
<?php endif; ?>

```

(if you are on node.tpl.php the filed will be as above, if you are on page.tpl.php it will be inside $page\['content'\] array)
> 2 votes

# Answer
As already said from Duncanmoo, using a view to show the content of a field is a bit excessive. The purpose of the Views module is to show a list of entities, and using a view for getting the information of a single node is not using the module for the purpose it is thought.

You second snippet can be written in a better way.

The template file should just contain the code to show values, not the code to compute those values. You should also avoid to hard code the file path into the template file.

I would rather use the following code, if you need it in a theme.

### template.php

```
function mytheme_preprocess_node(&$variables) {
  if (!empty($variables['node'])) {
    $images = field_get_items('node', $variables['node'], 'field_title_image');
    if (!empty($images)) {
      $image = array_shift($images);

      if ($wrapper = file_stream_wrapper_get_instance_by_uri($image['uri'])) {
        $variables['image_title_url'] = $wrapper->getExternalUrl();
        $variables['image_title_alt_text'] = $image['alt'];
      }
    }
  }
}

```

### page.tpl.php

```
<?php if (!empty($image_title_url)): ?>
  <h1 class="title" id="page-title"><img src="<?php print $image_title_url; ?>" alt="<?php print $image_title_alt_text; ?>"></h1>
<?php else: ?>
  <?php print render($title_prefix); ?>
  <?php if ($title): ?>
    <h1 class="title" id="page-title"><?php print $title; ?></h1>
  <?php endif; ?>
  <?php print render($title_suffix); ?>
<?php endif; ?>

```

If you need it in a module, then the module should contain the following code.

```
function mymodule_preprocess_node(&$variables) {
  if (!empty($variables['node'])) {
    $images = field_get_items('node', $variables['node'], 'field_title_image');
    if (!empty($images)) {
      $image = array_shift($images);

      if ($wrapper = file_stream_wrapper_get_instance_by_uri($image['uri'])) {
        $variables['image_title_url'] = $wrapper->getExternalUrl();
        $variables['image_title_alt_text'] = $image['alt'];
      }
    }
  }
}

```

The template file being used should contain the following code.

```
<?php if (!empty($image_title_url)): ?>
  <h1 class="title" id="page-title"><img src="<?php print $image_title_url; ?>" alt="<?php print $image_title_alt_text; ?>"></h1>
<?php else: ?>
  <?php print render($title_prefix); ?>
  <?php if ($title): ?>
    <h1 class="title" id="page-title"><?php print $title; ?></h1>
  <?php endif; ?>
  <?php print render($title_suffix); ?>
<?php endif; ?>

```

I am using `$wrapper->getExternalUrl()` because it doesn't take the assumption the file is local to the server, and it works also in the case stream wrappers are used to support remote file storage. See the documentation for drupal\_realpath().
> 0 votes

---
Tags: views, theming
---


title: Drupal homepage customization

text:
# Question
Title: Drupal homepage customization
i want to add some feature in drupal home page, like: 1) All new posts will be arranged greed 2) A thumbnail will appear from post photos 3) Text of content will be minimized to 150 words so, how to do it? Thanks

# Answer
> 0 votes
What @Kantu already said. Take a look at this tutorial: Panels 3: Creating a new front page with Views and Panels 3.

---
Tags: 7, nodes
---


title: Adding javascript in html.tpl

text:
# Question
Title: Adding javascript in html.tpl
I am trying to add JavaScript in footer with `drupal_add_js(drupal_get_path('theme', 'mytheme') .'/js/libs/jquery-1.7.1.min.js', array('type' => 'file', 'scope' => 'footer'));`, but for some reasons, it is not getting loaded.

What is wrong in my code?

# Answer
Consider what's at the top of the html.tpl.php file...a call to `<?php print $scripts; ?>`.

This would logically mean that all scripts added by `drupal_add_js()` in the current page call have already been rendered down into the `$scripts` variable, and printed to the page.

Thus, when you call `drupal_add_js()` inside html.tpl.php, it's too late to add new scripts with `drupal_add_js()`.

This sort of code should never really be inside a template file anyway to be honest, it should be inside a preprocess function inside your theme's template.php file.

On another note, it looks like you're trying to insert jQuery 1.7 into the current page. This may cause you all sorts of problems as Drupal already loads its own version of jQuery into the page...you'll probably get conflicts.

The better way would be to install the development version of the \[jQuery update\]\[1\] module, which has the option to use jQuery 1.7 throughout the site. I don't know the current state of this; the last time I checked (a couple of months ago) there were still some core JS elements that break using 1.7.

You can find a bit more info here: How do I update jQuery to the latest version I can download?
> 3 votes

# Answer
Another option to get the latest jQuery version is the jQuery Multi module.
> 2 votes

---
Tags: javascript
---


# Question
Title: What does "Use aggregation" option under Other in the Views UI do?
It looks like it might be a function that can reduce duplicates rather than using the Distinct option.

# Answer
Technical what it does it allows you to add "GROUP BY field" and "count(field)" to the sql query. This might be able to reduce duplicates but in general if you have duplicates it's most often a problem by design/your choosen view type(node, user, terms etc.)
> 2 votes

# Answer
Among other things it also allows you to create "representative node" displays. i.e. latest post per content type, or latest post per taxonomy term etc.
> -1 votes

---
Tags: views, css-js-aggregation
---


title: create ftp connection using drupal

text:
# Question
Title: create ftp connection using drupal
I have made my own module, that has a form where the user can upload a file. Once the file has been collected, Drupal should open an FTP connection to a server and upload the file into it. I have found "Storage API" and "Media Move" modules that seems to have this kind of functionality, but I have no clue on how use those modules with my custom code. How do I make an FTP connection from Drupal to an external server and upload the file?

# Answer
> 1 votes
cURL ist the perfect library for this. It's available on most PHP servers. Check this for an example.

---
Tags: files
---


# Question
Title: How to find the entity specific named id?
How do I map entity type to the entity specific named id, like this:

```
node => nid
taxonomy_term => tid
comment => cid

```

so that I can turn code like

```
 $entity->nid

```

into something like

```
$entity->{$label}

```

and correctly handle non-node entities.

# Answer
This should do it (definitely works for all core entities, I don't have any custom entities to play with on my sandbox site I'm afraid):

```
$type = 'taxonomy_term';

// Get the entity type info
$info = entity_get_info($type);

// Grab the id key
$key = $info['entity keys']['id'];

// $key contains 'tid'

```

I'm pretty positive this will work across any entity type though, according to `hook_entity_info()` the `id` property of `entity keys` is required:

> Every entity object passed to the Field API must have this property and its value must be numeric.
> 1 votes

---
Tags: entities
---


title: Create a view of nodes by taxonomy id

text:
# Question
Title: Create a view of nodes by taxonomy id
On my website, the user first fills out a questionnaire. Based on the answers given, I want to generate a view. The answers correspond to taxonomy ids. The problem is that I can't seem to find any option to filter by taxonomy id, which I am passing to my view as an argument.

Is there any way to do this? Preferably through the GUI, but code is no problem.

There was an option in drupal 6 that could do this on a regular page (taxonomy\_render\_nodes), but this has disappeared in drupal 7, which is why I'm looking to create a view now.

# Answer
If you want to filter by taxonomy term in your view you can do this by adding a contextual filter (arguments in D6).

If you can pass the term id then you can do the following:

When adding a contextual filter choose "Content:Has taxonomy term ID".
Under "MORE" there is an option "Allow multiple values".

You can play around with these options as I never get it right on the first go.
> 2 votes

# Answer
You should try Taxonomy\_select\_nodes. Not sure how the implementation would be via views but this appears to what your looking for.
> 0 votes

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


# Question
Title: How do you retrieve the node IDs of the nodes using a a taxonomy term?
When you tag a content type with a taxonomy term, if you click on the term itself, Drupal will display a list of content tagged with that term. I have reviewed taxonomy\_select\_nodes(), but I wasn't able to get a working piece of code. I'm not sure this is the correct function to use when looking for the node IDs of the nodes tagged with a taxonomy term.

How do you retrieve the IDs of the nodes using a specific taxonomy term?

# Answer
> 2 votes
`EntityFieldQuery` to the rescue:

```
$query = new EntityFieldQuery;
$query->entityCondition('entity_type', 'node')
  ->fieldCondition('field_name_of_term_reference_field', 'tid', $term_id);

$result = $query->execute();
if ($result) {
  $nids = array_keys($result['node']);
}

```

# Answer
> 1 votes
taxonomy\_select\_nodes() works only if the field storage is the default one (field\_sql\_storage); with other field storages, or when the "taxonomy\_maintain\_index\_table" Drupal variable is not set to `TRUE`, the function doesn't return any value.

In the first case, the "taxonomy\_index" table used by the function will not be populated; in the second case, the function returns an empty array.

```
  if (!variable_get('taxonomy_maintain_index_table', TRUE)) {
    return array();
  }

```

The only way to get the list of nodes using a specific taxonomy term is using the EntityFieldQuery class, taking in consideration the following notes. I assume `$query` is an instance of the `EntityFieldQuery` class requiring a list of nodes; this means the following lines are being used.

```
$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'node');

```
* If you are interested in getting all the published nodes, you should add the following line:

```
$query->propertyCondition('status', 1);

```

Differently, you will get also the nodes that are unpublished.

* The `EntityFieldQuery` class verifies the currently logged in user has access to the fields being checked by the query. To avoid this, if it is not desired, you should add the following line:

```
$query->addMetaData('account', user_load(1));

```

For more information about how to use the `EntityFieldQuery` class see How to use EntityFieldQuery.

---
Tags: taxonomy-terms
---


# Question
Title: How do I clean up image uploading by removing the additional upload fields?
I am running a Drupal 6 site, and I have a content type in which the user can upload a maximum of 6 images. The problem I am having is that I don't like the fact that Drupal displays all 6 file upload slots. I would prefer that it would just display one upload slot and then display the add additional image button like it does when it is configured to upload unlimited images.

Is it possible to configure Drupal to do this? I have searched high and low, and I can't find anything.

Can anyone point me to a module or to some code to accomplish this?

# Answer
> 0 votes
You can do this. Although it may not be what you exactly want. I'm not going to write all the code for you, but can push you in the right direction:

1. Make the field accept unlimited values. That will add your "Add another" button, and will only show 1 image upload field initially.
2. Make a small module which implements hook\_form\_alter and modify the node\_form of the content type which has the image. You need to add an extra validation function.
3. Write the validation function to check the number of values supplied in the image field. And set form error if more than 6 images uploaded.

---
Tags: 6, media, files
---


# Question
Title: How to do you modify the URL created by a module?
I have a module that creates a list of taxonomy terms. This is the module.

```
    function theme_jl_custom_category_list($vars) {
      $items = array();
      foreach (taxonomy_get_tree($vars['vid']) as $term) {
        $attributes = array();

       $query = new EntityFieldQuery;
       $query->entityCondition('entity_type', 'node')
         ->fieldCondition('taxonomy_catalog', 'tid', $term->tid);

       if ($result = $query->execute()) {
         $nids = array_keys($result['node']);
       }
       if (isset($_GET['category']) && $_GET['category'] == $term->tid && $_GET['q'] == 'list-product') {
         $attributes['class'] = array('active-category');
       }

       /** How can I append &product=[$nid][0] to this? **/
       $items[] = l($term->name, 'list-product', array('query' => array('category' => $term->tid), 'attributes' => $attributes));
      }

      return theme('item_list', array('items' => $items, 'attributes' => array('class' => array('jl-custom-category-list'))));
    }

```

In my template.php file, I have the following code.

```
function [THEME]_preprocess_page(&$vars) {
  $vars['category_list'] = theme('jl_custom_category_list', array('vid' => 3));
  // …
}

```

In my page.tpl.php file I display the list with the following code.

```
<?php print ($category_list);  ?>

```

Combined, they create a list of links like the following ones:

I'm trying to modify these two pieces of code so that in the URL of each category I can append something like '&product=(ID OF FIRST NODE IN EACH CATEGORY)' in the URL to change the links to the following ones:

How can I modify the URL created by that module?

# Answer
> 0 votes
I was able to append the url with "product=" + first node id of the taxonomy term by modifying the line show in bold below.

```
// Before
$items[] = l($term->name, 'list-product', array('query' => array('category' => $term->tid), 'attributes' => $attributes));

// After
$items[] = l($term->name, 'list-product', array('query' => array('category' => $term->tid, 'product' => $nids[0]), 'attributes' => $attributes));

```

I assume Drupal creates the query string with `array('query' => array('variable' => "whatever"))`.

# Answer
> 0 votes
These are just hints to help yourself:

* Take the Theme developer module, and check what functions are involved in putting the URL together.
* Set a break point inside the l() function just before `theme('jl_custom_category_list', array('vid' => 3))` gets executed. The stack should show you the code building the URL.

---
Tags: 7, taxonomy-terms, hooks, theming
---


title: Put a node submit form in a block

text:
# Question
Title: Put a node submit form in a block
In Drupal 7, I have defined a block called `mycontenttype_block`. I would like the output of the block to be the node submit form for an existing content type, like this:

```
function mymodule_block_view($delta = '')
{
    switch ($delta)
    {
        case 'mycontenttype_block':
            $block['subject'] = t('Mycontenttype submission form');
            $block['content'] .= $something;
            return $block;
            break;
    }
}

```

Where `$something` is the form output. I tried setting `$something` to `drupal_get_form('mycontenttype_form)` but I can't get any output...

# Answer
> 0 votes
Here in drupalsixlandia, I wanted to have this on a different page and did something along the lines of this to get it to work:

```
global $user;

module_load_include('inc','node','node.pages');
$type = 'TYPEOFNODE';
$node = array('uid' => $user->uid, 'name' => $user->name, 'type' => $type, 'language' => '');

return drupal_get_form($type .'_node_form', $node);

```

so perhaps D7 needs a similar `$node` argument as well.

ADDITION: a quick look suggests D7 wants $node to be an object, not an array and does it by just doing:

```
$node = (object) array('uid' => $user->uid, ...

```

You might be able to grab its code directly and use it. Looking back, I don't know why I just didn't grab this from `node.pages.inc` directly myself:

```
/**
 * Returns a node submission form.
 */
function node_add($type) {
  global $user;

  $types = node_type_get_types();
  $node = (object) array('uid' => $user->uid, 'name' => (isset($user->name) ? $user->name : ''), 'type' => $type, 'language' => LANGUAGE_NONE);
  drupal_set_title(t('Create @name', array('@name' => $types[$type]->name)), PASS_THROUGH);
  $output = drupal_get_form($type . '_node_form', $node);

  return $output;
}

```

Ah...here's why. I didn't like the title, and I doubt you want that if you are stuffing this in a block :)

---
Tags: hooks
---


# Question
Title: How to fetch a field's values from a lot of nodes?
I need to create a list of all submitted values from a field named field\_telephone from thousands of nodes from a specific content type. using the `node_load()` function takes long time.

What is the fastest way to fetch the field's values?

# Answer
> 2 votes
The fastest (but not sanctioned/recommended) way would be to go directly in the database table to get the data:

```
// db_query() is quicker than db_select() so if you're going for performance,
// build up an SQL string
$sql = '
  SELECT f.entity_id, f.field_telephone_value
  FROM {field_revision_field_telephone} f
  WHERE f.entity_type = :entity_type
  AND f.bundle = :bundle';

// Set some args up for your query
$args = array(':entity_type' => 'node', ':bundle' => 'content_type');

// Extract the query results into an array keyed by nid
$data = db_query($sql, $args)->fetchAllKeyed();

```

There are many good reasons not to do this kind of thing directly (no support for translations, it will only work if the field storage engine is MySQL, etc.)

Any other method I can think of would involve a call to `node_load()` or `node_load_multiple()` at some point.

# Answer
> 3 votes
You can also use field\_attach\_load, I believe you can pass it just 1 field you want and a set of entity ids and you can get back all the values. The below example is taken from this blog post and I take no credit for the code:

```
$query = new EntityFieldQuery();
 $query->entityCondition('entity_type', 'node')
   ->entityCondition('bundle', 'article')
   ->propertyCondition('status', 1)
   ->fieldCondition('field_image', 'fid', 'NULL', '!=');
 $results = $query->execute();
 $articles = $results['node'];
 $fields = field_info_instances('node', 'article');
 $field_id = $fields['field_image']['field_id'];
 field_attach_load('node', $articles, FIELD_LOAD_CURRENT, array('field_id' => $field_id));

```

---
Tags: 7, entities
---


# Question
Title: How to customize the url of a field in views?
I have a view that displays product images using a jcarousel. In the view, I have a jCarousel format and it displays fields. In the Fields section, I'm displaying Content: Image. I want to link the image to a specific url. I can modify it using Rewrite Results and selecting Output this field as a link.

According to the answer I got from how to make a field in a view be the link destination to another field? & http://64sqft.danapellerin.com/2011/06/07/drupal-custom-cck-field-tokens-in-views. Views takes into consideration the order in which your fields are in the view. The taxonomy field that you want to use as a token needs to be reordered above the field you want to use the token in the url.

**Things I've tried**:

* I tried content:category (which is my taxonomy field), and hid it so it wouldn't display. In the field's replacement patterns it gave me \[taxonomy\_catalog\] & \[taxonomy\_catalog-tid\]. I tried \[taxonomy\_catalog\] but the replacement gave me the text from taxonomy description.
* I tried Content: All taxonomy terms, but it gave me the name of the term instead of the ID.

How can I modify the rewrite to include the taxonomy term id associated with the node?

# Answer
> 0 votes
The problem was the way that Content: All taxonomy terms required a rewrite to \[term\_node\_tid-tid\]. Otherwise it would display the term name instead of the tid.

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


# Question
Title: Show the latest post titles for posts using a specific category
I want to get the latest post titles for posts using a specific category, in Drupal 6.

How can I achieve this?

# Answer
> 0 votes
Drupal shows those nodes in http://example.com/taxonomy/term/$tid. If all you want is getting a page listing the nodes using a taxonomy term, that is the page to look at.

If you want to obtain the list of nodes using a taxonomy term with code, you can use the following one, based on taxonomy\_select\_nodes().

```
function mymodule_get_node_titles($tid, $order = 'n.sticky DESC, n.created DESC', $limit = 10) {
  $term = taxonomy_get_term($tid);
  $tree = taxonomy_get_tree($term->vid, $tid, -1);
  $descendant_tids[] = array_merge(array($tid), array_map('_taxonomy_get_tid_from_term', $tree));

  $args = call_user_func_array('array_merge', $descendant_tids);
  $placeholders = db_placeholders($args, 'int');
  $sql = 'SELECT DISTINCT(n.nid), n.title, n.created FROM {node} n INNER JOIN {term_node} tn ON n.vid = tn.vid WHERE tn.tid IN (' . $placeholders . ') AND n.status = 1 ORDER BY ' . $order;

  $sql = db_rewrite_sql($sql);

  return db_query_range($sql, $args, 0, $limit);
}

```

The code to call that function is similar to the following one.

```
$result = mymodule_get_node_titles($tid);
$items = array();
while ($row = db_fetch_object($result)) {
  $items[$row->nid] = $row->title;
}

```

`$tid` is the taxonomy term ID.

---
Tags: taxonomy-terms
---


# Question
Title: Code comments in template file show on page
Im using page--front.tpl.php to override my front page. Ive commented out the content with the code below, however this '--\>' is shown on the page.

```
<!-- <?php print render($page['content']); ?> -->

```

How can I stop this. Thanks

# Answer
> 0 votes
Try

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

```

---
Tags: 7, theming
---


# Question
Title: How do I add image captions using a custom style?
I am not a programmer.

However, I need to know how to use css to add a caption for an image field in a node.

# Answer
One way would be to create your own theme\_image() in your theme's template.php file. It would be pretty straightforward, just grab drupal's default theme\_image() from theme.inc and add a span to it:

If Drupal 6:

```
function YOURTHEMENAME_image($path, $alt = '', $title = '', $attributes = NULL, $getsize = TRUE) {
  if (!$getsize || (is_file($path) && (list($width, $height, $type, $image_attributes) = @getimagesize($path)))) {
    $attributes = drupal_attributes($attributes);
    $url = (url($path) == $path) ? $path : (base_path() . $path);
    return '<img src="'. check_url($url) .'" alt="'. check_plain($alt) .'" title="'. check_plain($title) .'" '. (isset($image_attributes) ? $image_attributes : '') . $attributes .' /><span class="caption">' . check_plain($title) . '</span>';
  }
}

```

If Drupal 7:

```
function YOURTHEMENAME_image($variables) {
  $attributes = $variables['attributes'];
  $attributes['src'] = file_create_url($variables['path']);

  foreach (array('width', 'height', 'alt', 'title') as $key) {

    if (isset($variables[$key])) {
      $attributes[$key] = $variables[$key];
    }
  }

  return '<img' . drupal_attributes($attributes) . ' /><span class="caption">' . (isset($variables['title']) ? $variables['title'] : '') . '</span>';
}

```

Clear caches/theme registry and now every image will have a span with class `caption` after it with the image's title in it (or blank if none obviously). If you want to get fancier with wrappers and so forth, just put whatever html you want/need in the return's above.

Then CSS this however you want.
> 3 votes

---
Tags: media
---


title: Get node id of saved node

text:
# Question
Title: Get node id of saved node
I want a function/hook to be called at a point just when my custom node type is saved, I want to get the generated node id in that function, as I have to perform some operations based on nid.

I know one solution is which form alter hook is defined and I give a custom submit function to it and that function is called just when form is submitted, but in that case node is not yet saved at that point so there is no nid.

# Answer
> 1 votes
You can use hook\_node\_update().

In Drupal 6, you can easily get the last node ID by calling db\_last\_insert\_id().

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


# Question
Title: Use text field value on another text field on same node on save
I have two fields on a Content Type called Property that requires the same information and I am trying to have it so that it only needs to be inputted one time be the user.

I am using the module Address Field and Locations and need to fill out the zip codes with the same zip code. I need to get it so I only have to input the zip code one time and it fills both. I have tried a hook form alter (my example below) but the second field does not get the text unless I save the node again. I understand why but I am not sure how to go about fixing this.

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

```

switch($form\_id) {

```
  case 'property_node_form':

$form['locations'][0]['#default_value']['postal_code'] = $form['field_address']['und'][0]['#address']['postal_code'];

  break;

```

} }

Suggestions welcome. Thanks!

# Answer
> 0 votes
What you are doing is happening in the browser, so drupal, or anything else on the server, obviously doesn't know what's going on until you hit submit.

So you have to use jQuery that is running there in the client, and one way would be along the lines of:

```
$('#IDOFYOURFIRSTZIPCODE').live('change', function() {
  $('#IDOFYOURSECONDZIPCODE').val($('#IDOFYOURFIRSTZIPCODE').val());
});

```

The #IDs will look something like `#edit-field-FIELDNAME-0-value` but basically what it is doing is changing the second value to the first when the first changes.

Put that in a module's or theme's js and you should be set. (I suppose you could \[should?\] add it with a drupal\_add\_js() right from your form\_alter().)

(For those jQuery experts out there, I suppose I should have used on() or delegate() instead of live() but this works on both D6 and D7 with stock jQuery)

---
Tags: hooks, location, entities
---


# Question
Title: db_query not returning expected results - updated
I'm using raw SQL in a custom module (please don't tell me to use the query builder; this is a single static query that will never need to take params.) If I run the query directly in phpMyAdmin, it returns two records. When I run the module, it doesn't display anything.

```
function speaker_carousel_get_data() {
  error_log("calling get data");
  $query = db_query("SELECT
                    node.title AS node_title,
                    node.nid AS nid,
                    field_speaker_node.title AS field_speaker_node_title,
                    field_speaker_node.nid AS field_speaker_node_nid,
                    'node' AS field_data_field_job_title_node_entity_type,
                    'node' AS field_data_field_company_node_entity_type
                    FROM
                    {node} node
LEFT JOIN {field_data_field_speaker} field_data_field_speaker ON node.nid = field_data_field_speaker.field_speaker_target_id
LEFT JOIN {node} field_speaker_node ON field_data_field_speaker.entity_id = field_speaker_node.nid
WHERE ((node.status = ':status') AND (node.type = ':type') AND (node.title = ':title'))
ORDER BY node_title ASC", array(':status' => '1', ':type' => 'speaker', ':title' => 'April Carlisle'));
  print "<pre"> .print_r($query). "</pre>";
  return $query;
}

```

I had expected the `print_r()` to return an array of results, but instead it gives me this:

```
DatabaseStatementBase Object
(
    [dbh] => DatabaseConnection_mysql Object
        (
            [shutdownRegistered:protected] =>
            [target:protected] => default
            [key:protected] => default
            [logger:protected] =>
            [transactionLayers:protected] => Array
                (
                )

            [driverClasses:protected] => Array
                (
                    [SelectQuery] => SelectQuery
                    [MergeQuery] => MergeQuery
                    [DatabaseTransaction] => DatabaseTransaction
                    [InsertQuery] => InsertQuery_mysql
                    [DeleteQuery] => DeleteQuery
                    [DatabaseSchema] => DatabaseSchema_mysql
                )

            [statementClass:protected] => DatabaseStatementBase
            [transactionSupport:protected] => 1
            [transactionalDDLSupport:protected] =>
            [temporaryNameIndex:protected] => 0
            [connectionOptions:protected] => Array
                (
                    [database] => expo
                    [username] => myuser
                    [password] => mypassword
                    [host] => localhost
                    [port] =>
                    [driver] => mysql
                    [prefix] => Array
                        (
                            [default] =>
                        )

                )

            [schema:protected] => DatabaseSchema_mysql Object
                (
                    [connection:protected] => DatabaseConnection_mysql Object
 *RECURSION*
                    [placeholder:protected] => 0
                    [defaultSchema:protected] => public
                    [uniqueIdentifier:protected] => 4ffc5cb56dca11.89303530
                )

            [prefixes:protected] => Array
                (
                    [default] =>
                )

            [prefixSearch:protected] => Array
                (
                    [0] => {
                    [1] => }
                )

            [prefixReplace:protected] => Array
                (
                    [0] =>
                    [1] =>
                )

        )

    [queryString] => SELECT
                    node.title AS node_title,
                    node.nid AS nid,
                    field_speaker_node.title AS field_speaker_node_title,
                    field_speaker_node.nid AS field_speaker_node_nid,
                    'node' AS field_data_field_job_title_node_entity_type,
                    'node' AS field_data_field_company_node_entity_type
                    FROM
                    node node
LEFT JOIN field_data_field_speaker field_data_field_speaker ON node.nid = field_data_field_speaker.field_speaker_target_id
LEFT JOIN node field_speaker_node ON field_data_field_speaker.entity_id = field_speaker_node.nid
WHERE ((node.status = ':status') AND (node.type = ':type') AND (node.title = ':title'))
ORDER BY node_title ASC
)
<pre>1</pre>

```

What's going on? How do I get the results of the query?

**EDITED AFTER SOME EXPERIMENTING**

I've narrowed it down to the WHERE clause - if I set the query to the following, it works.

```
$sql = db_query("SELECT node.title AS node_title,
                  node.nid AS nid,
                  field_speaker_node.title AS field_speaker_node_title,
                    field_speaker_node.nid AS field_speaker_node_nid,
                    'node' AS field_data_field_job_title_node_entity_type,
                    'node' AS field_data_field_company_node_entity_type
                    FROM
                    node node
LEFT JOIN field_data_field_speaker field_data_field_speaker ON node.nid = field_data_field_speaker.field_speaker_target_id
LEFT JOIN node field_speaker_node ON field_data_field_speaker.entity_id = field_speaker_node.nid
                  ORDER BY node_title ASC")->fetchAll();

```

I don't know if the issue is with the where clause itself, or with the placeholders. Did I not format it correctly?

# Answer
I did figure out the issue; the placeholders should not be in quotes (in the query, not the args array.) An example I was working from showed them formatted in single quotes, so that's what I did. I just assumed somehow Drupal was replacing things, but if they're in single quotes they're being passed my mysql as literal strings and obviously there are no results that match.

The Database abstraction layer says:

> Note that placeholders should be a "complete" value. For example, when running a LIKE query the SQL wildcard character, %, should be part of the value, not the query itself. Thus, the following is incorrect:
>
> ```
>     SELECT nid, title FROM {node} WHERE title LIKE :title%;
>
> ```
>
> It should instead read:
>
> ```
>     SELECT nid, title FROM {node} WHERE title LIKE :title;
>
> ```
>
> and the value for :title should include a % as appropriate. Again, note the lack of quotation marks around :title. Because the value is not inserted into the query as one big string but as an explicitly separate value, the database server knows where the query ends and a value begins.
> 2 votes

# Answer
```
$result = db_query('SELECT id, ...');

foreach ($result as $row) {
  // do something with $row->id;
}

```
> 0 votes

---
Tags: database
---


# Question
Title: Template Suggestions Causing Undefined Variable
I am developing a Drupal theme from scratch, and I have run into some trouble with template suggestions. Using the solutions discussed on Drupal support, I created a template.php file and included this code:

```
function stronger_preprocess_page(&$vars) {

  if (isset($vars['node'])) {

    $vars['theme_hook_suggestion'] = 'page__'.$vars['node']->type; //
  }
}

```

This has allowed me to successfully use page--nodetype.tpl.php template files, but I am also randomly seeing errors such as:

> Notice: Undefined variable: node in include() (line 24 of /Applications/MAMP/htdocs/strong-local-final/sites/all/themes/stronger/page.tpl.php).

I have read elsewhere that the node variable needs to be re-declared, but I am unsure of how or where to do this. Any help or references would be greatly appreciated!

# Answer
> 4 votes
`hook_preprocess_page()` is run for any page, even non-node pages. If you're getting that error it means your trying to access `$node` in the page.tpl.php file when you're on a non-node page. As no node is available on such a page, the variable won't have been set.

Because of the delay that can happen when messages are set in template files, you might only see this message when you've left a non-node page, and navigated to a node page. So it will look like it's that particular page complaining, when in fact it was the previous one.

You should be able to fix the problem by checking the `$node` variable is available in your template file as well as in the preprocess function. e.g.

```
<?php if (isset($node)) : print $node->something; <?php endif; ?>

```

---
Tags: theming
---


# Question
Title: Need to add HTML characters to Select list
I have a form using the FAPI that has a select list of currency values as one of its inputs. I need to be able to add HTML characters such as `€ $pound; ¥`

The problem is that Drupal is filtering the input and not displaying the desired symbols, but displaying the actual html codes as displayed above.

Is there any way of having Drupal not filter my list?

# Answer
> 4 votes
You can and should put the UTF-8 characters for the symbols in your list. HTML entities are a relic from the past when it was possible that some symbols did not have a representation in the active code page. Thus simply use €, £, and ¥ in your lists.

Drupal is UTF-8 from back to front: use it.

# Answer
> 1 votes
As a solution you may use #after\_build property for your form element.

lets say you have $options variable with options for select

```
$form['myselect']['options'] = $options;
$form['myselect']['#after_build'][] = 'custom_select_formatter';

```

then you have to define your formatter function like

```
function  custom_select_formatter($form_element, $form_state){

$options = $form_element['#options'] //you can use your option values
}

```

here you may redefine your select element even you may #theme add #prefix #suffix

another probably solution is maybe that l() function in this example uses html option when creating links with images maybe select element also uses it

---
Tags: forms, theming
---


# Question
Title: Given that db_select is much slower than db_query, why would I want to use it?
For the background on this, please see http://drupal.org/node/1067802.

Given all that, what situations exists where I might want to use db\_select(), or should I be relying solely on db\_query?

# Answer
There are 5 reasons to use SelectQuery

* You are building dynamic queries with a varying number of conditions, joins, fields and so on. See field\_read\_fields() for an example.
* You want to use so called Extenders. Example extenders are PagerDefault (replaces pager\_query()) and TableSort (replaces tablesort\_sql()). These allow to add additionally functionality to SelectQuery. See also How do you make sortable tables with a pager with data from a custom table?. An example: node\_page\_default().
* You want to allow other modules to alter your queries. Then you can add so called tags and SelectQuery will automatically call a corresponding alter hook for that tag. I'm am heavily relying on this with my Privatemsg module (We already did that in D6 with a custom query builder).
* If you want/need to use the node\_access system to only show nodes the user is allowed to see. Just add the 'node\_access' tag to your $query. This replaces db\_rewrite\_sql().
* SelectQuery has a few features that help to make your code work the same across all supported databases. For example there is SelectQuery::orderRandom(). And if you have a LIKE condition, -\>condition('field', $value, 'LIKE') will make sure that it is always a case insensitive comparison. In D6, you had to use LOWER() for that which was much slower. But AFAIK, there aren't more than this two right now.

If none of these reasons apply for a specific case, use db\_query().
> 89 votes

# Answer
The documentation about `db_query()` says:

> Use this function for SELECT queries if it is just a simple query string. If the caller or other modules need to change the query, use db\_select() instead.
> 10 votes

# Answer
I always use db\_select as I prefer readability, maintainability and cross database compatibility over small performance gains. Moreover, I think the numbers given in the mentioned issue give a wrong image of the overall performance. We are talking a 300 microseconds difference on a query that, when returning more than a single column often run in the multi millisecond range. And I wouldn't be surprised if there is some 1-time only overhead (class loading) and thus that the differences for a full (page) request are far less.
> 9 votes

---
Tags: 7, performance, database
---


# Question
Title: How to switch table prefix in a module in Drupal 6?
I have multiple sites setup on a single MySQL database in Drupal 6. The sites each have their own prefix, such as site1\_, site2\_, etc. I'm wondering how I can switch the current table prefix inside of a module to check the variables on each site. For example, I want to check the preprocess\_css variable on every site by looping through each sites settings file and running variable\_get('preprocess\_css') and get the variable for each site. I can get the table prefix and get the variable using db\_query on the variables table, but I know there has to be a way to set the current table prefix inside a module so I can just run variable\_get inside a loop with each table prefix. Does anyone know how this can be done?

# Answer
> 0 votes
The problem with variable\_get() is that it doesn't read values from the database, but from a global variable, which is initialized during the Drupal bootstrap.

```
function variable_get($name, $default) {
  global $conf;

  return isset($conf[$name]) ? $conf[$name] : $default;
}

```

What you should do is use code similar to the following one.

```
$variables = array();
$old_db_prefix = $GLOBALS['db_prefix'];
$GLOBALS['db_prefix'] = 'site1_';
$result = db_query('SELECT * FROM {variable}');

while ($variable = db_fetch_object($result)) {
  $variables[$variable->name] = unserialize($variable->value);
}

$GLOBALS['db_prefix'] = $old_db_prefix;

```

Then you can read the value of, e.g., *preprocess\_css*, with `$variables['preprocess_css']`.

You could use code similar to the following one.

```
function mymodule_variable_get($db_prefix, $name, $default) {
  $old_db_prefix = $GLOBALS['db_prefix'];
  $GLOBALS['db_prefix'] = $db_prefix;
  $value = db_result(db_query("SELECT value FROM {variable} WHERE name = '%s'", array($name)));
  $GLOBALS['db_prefix'] = $old_db_prefix;

  return !empty($value) ? unserialize($value) : $default;
}

```

Bear in mind that some Drupal variables can be overridden with a value set in the settings.php file, which can contains code similar to the following one.

```
$conf = array(
  'preprocess_css' => FALSE,
);

```

What you read from the database could not be the value set for that Drupal site, for the Drupal variable you are reading.

# Answer
> 0 votes
The prefix is stored as one of the variables in the settings.php file, all of which are made `global` early on in the page build process.

That in mind, you can do something as easy as:

```
$GLOBALS['db_prefix'] = 'db1_';
print variable_get('site_name', 'default'); // Site name from first set of tables

$GLOBALS['db_prefix'] = 'db2_';
print variable_get('site_name', 'default'); // Site name from second set of tables

```

Bear in mind that this change won't persist across page loads so you'll need to do your processing in a single load, or implement some sort of system to track which prefix you should currently be using.

---
Tags: 6, database
---


# Question
Title: How do I redirect the "No Result" search page to Add node?
I would like to redirect the "No result found" page of the drupal search to Add node. Basically I want when users search for an item using the search text box they get redirected to the Add node page when the item is not found.

# Answer
> 1 votes
I was really hoping that `_preprocess_search_results(&$vars)` would work, but it only gets called when there are results, so, here are two really really I can't believe I am suggesting these but they should work ways:

Drupal 6:

In your theme's template.php file, you can retheme box, which is how drupal 6 creates the 'no results found' info:

```
function YOURTHEMENAME_box($title, $content, $region = 'main') {

  if ($title==t('Your search yielded no results')) {
    drupal_goto('node/add');
  } else {
    $output = '<h2 class="title">'. $title .'</h2><div>'. $content .'</div>';
    return $output;
  }
}

```

If Drupal 7:

Copy `search-results.tpl.php` from the search module's directory to your theme directory and change it:

```
<?php if ($search_results): ?>
  <h2><?php print t('Search results');?></h2>
  <ol class="search-results <?php print $module; ?>-results">
    <?php print $search_results; ?>
  </ol>
  <?php print $pager; ?>
<?php else: ?>
  <?php drupal_goto('node/add'); ?>
<?php endif; ?>

```

---
Tags: search, redirection
---


# Question
Title: Don't know where 404 error is coming from
Don't know where this 404 error "sites/all/modules/lightbox2/images/blank.gif" is coming from. It's on everypage on www.lostinthesmoke.com. Can't find the reference to it in the page source. I don't know if its Drupal or CloudFlare. CloudFlare says its Drupal or my server. I cleared caches everywhere. I had lightbox2 installed a couple months ago but not on this fresh install. I use this domain to learn and test on. It started showing last night.

# Answer
> 0 votes
If you go into inspector, you can see:

```
<object data="http://www.lostinthesmoke.com/sites/all/modules/lightbox2/images/blank.gif" width="0" style="position: absolute; left: -9999px; "></object>

```

is being added at the very bottom of your page. Why? I dunno, but it's there :) The fact that it doesn't show up in "view source" suggests it's being added via javascript on page load.

Why isn't it finding blank.gif? Again, I dunno. It's here in my lightbox2 directory, so, perhaps your installation has been corrupted and thinks it is still installed.

---
Tags: javascript
---


# Question
Title: Build menu based in Vocabulary (Taxonomy)?
I just follow this tutorial to build a **menu** based in the **tags** vocabulary. Everything is fine but now if I add a new term in **admin/structure/taxonomy/tags/list** the menu doesn't update, I mean that the new added term doesn't show up.

The problem is that I can't find to check: **Synchronises change to this vocabulary** because I don't have this option in **admin/structure/taxonomy/tags/edit** as showed in the tutorial. Maybe this is because I'm using D7 and the tutorial is for D6? Where are these options in D7?

# Answer
> 1 votes
Try to use the development snapshot for Drupal 7. The update is available in that version.

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


# Question
Title: How can i create theme's block width should be configured from dynamically
I want to develop a drupal theme, where

> The theme should be develop in a way that the number of the columns of the theme and the width of the columns can be configured from the Admin area.

Can anyone guide me how to approach in theme development ?

# Answer
> 1 votes
You could use a theme thats already done this...

http://drupal.org/project/adaptivetheme

http://drupal.org/project/omega/

---
Tags: theming
---


title: Run drupal website over only HTTPS

text:
# Question
Title: Run drupal website over only HTTPS
> **Possible Duplicate:**
> How to simply make the whole site https

I have my drupal 6 website running on apache. I want this site to run only on HTTPS. What should be done for this. There are lot many solutions, which are getting me confused. Please help me on this.

# Answer
> 1 votes
You can try Secure Pages and Secure Pages Hijack Prevention modules.

# Answer
> 0 votes
Redirect using the `.htaccess` file in Drupal's root directory. It should already have a couple of *rewriting* examples that you can adapt. If not, please see other examples on SE and elsewhere on the web.

---
Tags: 6
---


title: Overriding core forum function

text:
# Question
Title: Overriding core forum function
is there any clean way to override \_forum\_topics\_unread function call from template\_preprocess\_forum\_list without hacking the core?

# Answer
If you want to get tricky, you can use hook\_theme\_registry\_alter(), and unset the core preprocess and replace it with your own. Advanced Forum makes use of that, if you want to see an example.
> 3 votes

# Answer
No, hardcoded function calls can not be replaced.

The only thing you can do is add your own preprocess function for "forum\_list "(`yourmodule_preprocess_forum_list()`), and then call another function to overwrite the value returned by the function.
> 5 votes

# Answer
Core Override (http://drupal.org/sandbox/gielfeldt/1546970) allows you to override individual functions in core without patching core.
> 0 votes

---
Tags: 7
---


title: php code in block - Load node

text:
# Question
Title: php code in block - Load node
I have previously used `<?php print $node->field_listing_artist[0]['taxonomy_term']->description; ?>` on page.tpl.php. What this does is prints the description of the related taxonomy term of the node being displayed.

But I am looking to use this piece of code in a Block or a Custom Content Type in Panels.

From searching around, I can see (I think?) that i need to load\_node, but cannot seem to get the code to work. Similar Drupal Answers Question

So what i am trying to achieve is create a block/'Panels custom content type' that will correctly process `<?php print $node->field_listing_artist[0]['taxonomy_term']->description; ?>` of the node currently being viewed.

# Answer
> 1 votes
You should check out What are Ctools plugin (content type, access, etc), and how does one create them?, and in addition make sure the content type has a required context on nodes so that you can't accidentally render it without a node. Check the examples on the ctools module to see how to add required contexts.

---
Tags: 7, blocks, panels, nodes
---


title: Create a master or main page

text:
# Question
Title: Create a master or main page
I want to know how to do is create a master or main page. I come from an ASP.Net background and am truly trying to learn Drupal, but I am very frustrated with finding where/how to start.

For me, the start has always been creating a main page. I use .Net as my platform but usually do all my work through HTML and CSS, as in creating a 3-column website using CSS. However, I really like the functionality of .Net in that I create this on ONE page as a master, and then just insert my content in a content holder. I know things don't work exactly the same, I don't expect them to, but I would like to know how to create a master page, or basically a template that contains the header, footer, menus and content layout.

How do I create a basic main page template?

# Answer
> 1 votes
You may need to do some research into the way the drupal system works. Here is the documentation page for how to theme drupal. http://drupal.org/documentation/theme

If you are looking to create you own theme. For a beginner, it may be easier to start with a theme framework to mold it into what you want. Here are 3 of some of the more popular frameworks; Zen, Fusion, and Adaptive Theme.

P.S. - You may want to consider doing some basic google research prior to asking questions on here without more supportive information.

# Answer
> 1 votes
Panels Everywhere allows you to create one or more "Site templates", which will usually contain things such as menues, footer, logo and similar. Then within it, you place the page specific content, which will be rendered separately.

> Panels Everywhere is an advanced method to completely do away with Drupal's restrictive blocks system and instead use the much more freeing Panels Layout system to control how your pages look. Panels Everywhere modifies the page as it is being rendered to 'wrap' the content in a display and can even take over your page theme to do away with the need for a page.tpl.php.
>
> Doing this requires that you set up a few things properly, because Drupal is not really designed for this kind of behavior. Be sure to read the README before trying to use this module.

# Answer
> 0 votes
You could try the Front Page module.

> The Front Page module allows for customised home pages dependant on role. The pages can be of the following types:
> 1. Alias (only 2.x branch) - Allows for another Drupal path to be shown as the home page without redirecting the user.
> 2. Redirect - Allows you to redirect users to a local or remote URL.
> 3. Themed - Allows you to enter some static text that will be placed into the content area of a standard Drupal page.
> 4. Full - Allows for static content to be displayed to the screen as is. This method does not pass through Drupal's theming system.

---
Tags: nodes
---


# Question
Title: How to determine where the CCK fields are stored in database?
When a **content type** is created, there is a new table for it. For example, there is a `content_type_claim` table, for content type `claim`. **Content fields** are defined within the table.

However, when a **content field** is shared (used more than once) in different **content types**, there will be another table created for this field. For example, there is a `content_field_claim_no` table for `claim no`, if `claim no` is also used in another content type.

My question is, in which table Drupal defines whether a **content type field** is stored inside the `content_type_???` table (when used once), or in its own `conten_field_???` table (when used more than once), for a particular `content type`.

# Answer
> 2 votes
You want the `content_node_field_instance` table. As that table defines each "instance" of a field on different content types. For the field configurations (global configs, independent of instance configs) you want the `content_node_field` table.

Similarly in Drupal 7 there's `field_config` table for global field configurations, and `field_config_instance` table for each instance of a field with content types.

# Answer
> 0 votes
In Drupal 7 it will create a new table for the field which is shared between two or more content type. the field "bundle" will store the content type "entity id" will store the node id of respected node "field\_fieldname\_value" will store the value of the filed..

---
Tags: 6, entities, database
---


# Question
Title: Webfrom Validation on textfiled when using default value
I am having a problem where I need to use the default value of a text field to initially populate the from visually. Unfortunately after doing this the field validates as if it has been filled out by a user. I am attempting to do a custom validation function to check against the default value of the field. So if the field has its default value to still validate as a mandatory field normally would.

The following is my attempt to do this. Am I going in the right direction?

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

    if ($form_id == 'webform_client_form_6'){
       //kpr($form);
        $form['#validate'][] = 'MY_MODULE_validate_form';
    }

```

}

```
function MY_MODULE_validate_form($form,&$form_state){
if ($form_state['submitted']['full_name']['#default_value'] == "Full Name") {
    form_set_error('full_name', t('You Must enter your full name'));
    }

}

```

Any help is much appreciated.

# Answer
Sorry that this isnt a direct answer to your question, but it seems to me to be bad practice to use a default value in an input field and then disregard it as a submission. Would a placeholder not be more appropriate for your requirements? You could even style the placeholder to look like form input via CSS
> 1 votes

---
Tags: webforms, forms
---


# Question
Title: Multilingual site page not found error on default language URL path prefix
I have a multilingual site with 3 enabled languages.
Default language is Dutch. However when going to http://MYSITE.com/nl I receive a page not found error. /fr and /en is working as usual.
How can I use /nl for my Dutch content? When using the user interface text block to display language links, on a /nl page the NL link is set to active.

# Answer
> 2 votes
On admin/config/regional/language/edit/nl Path prefix language code was set to empty. Setting the code to /nl solved the problem.

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


# Question
Title: Views regex: exclude alphabetical strings as well as those with spaces
I used the following *regular expression* on the Taxonomy term name field to exclude strings consisting solely of alphabetical names:

`[^a-zA-Z]`

Now I want to exclude those strings plus any string with a space.

What I want to do:

* Hello (no)
* Hi how are you (no)
* ハロー (ok)

I tried this:

`[^a-zA-Z\s]`

This excludes alphabetical strings but not alphabetical strings with a space:

* Hello (no)
* Hi how are you (yes-\> should be no)
* ハロー(ok)

What am I doing wrong?

# Answer
> 3 votes
The Views module uses MySQL regular expressions, and \s is not recognized in those regular expressions.

You should try with \[^a-zA-Z\[:blank:\]\], or \[^a-zA-Z\[:space:\]\]. The first excludes any whitespace character, while the second excludes any space, tab, newline, and carriage return.

In the views\_handler\_filter\_string class, the method associated with the regular expression is the following one.

```
  function op_regex($field) {
    $this->query->add_where($this->options['group'], $field, $this->value, 'RLIKE');
  }

```

```
// Add regexp support for MySQL.
if (Database::getConnection()->databaseType() == 'mysql') {
  $operators += array(
    'regular_expression' => array(
      'title' => t('Regular expression'),
      'short' => t('regex'),
      'method' => 'op_regex',
      'values' => 1,
    ),
  );
}

```

---
Tags: views
---


# Question
Title: Slow Search on Drupal 6.x site with 60.000+ nodes
We use Drupal 6 for http://www.boekwijs.nl. But when you search for something (which hasn't been searched for before, in other words; not in cache) it's very slow. At the moment there are 60.000 nodes with CCK fields and taxonomy terms.

What is the best way to optimize this? Are there any modules available? Do we need to use another search engine (SOLR?) or maybe another database structure?

# Answer
60,000 nodes in the search index is definitely a lot. Not only is it slow and suboptimal to use Drupal's default search with such a large number of nodes, but it is going to progressively put more pressure on your infrastructure as you continue adding nodes.

The solution would definitely be to offload your search to another tool. Two options:

1. Solr: 60,000 is child's play for Solr. It could suffice you for a lot more even on a commodity machine.
2. Elastic search: Another tool built on top of Apache Lucene. This one's newer and does not have as many supporting modules for it as Solr does (for Drupal). But it is faster than Solr and can handle concurrent commits much better.

In both these cases, I'd recommend installing the search tool on another server.
> 2 votes

# Answer
It is not not required to go for the other module.

I have developed site IDSA, there are 20,000+ nodes and taxonomy terms etc. Using database indexing for particular row will also affect the searching functionality.

Have you customize search module or apply any hook\_query\_alter ? This will also affect the result.
> -1 votes

---
Tags: 6, caching, search
---


# Question
Title: Complex Views / Field Collection question
Is there a way to do a subquery in a View that filters entities based on a filter value in a field collection, but also by another value attached to that field collection item?

For example, people are searching properties. Property rates are stored in a field collection that references dates, the price, and if it is available.

When a user uses the view and searches by a particular date, I only want to return the entities that have both that date **AND** an available = 1 on that field collection item. Just adding the 'available' filter on the View is not enough, because it needs to search the value attached to the field collection item id that the date is attached to.

My first thought was to use hook\_views\_query\_alter:

```
$lookup = new EntityFieldQuery;
    $lookup->entityCondition('entity_type', 'field_collection_item')
        ->entityCondition('bundle', 'field_property_booking');
    $lookup->fieldCondition('field_property_booking_basis', 'value', 'Weekly', '=');
    $lookup->fieldCondition('field_property_booking_period', 'value', 1348891200, '=');
    $lookup->fieldCondition('field_property_booking_available', 'value', 1, '=');
    $rates = $lookup->execute();

```

Okay, so, based on the timestamp from the form submission, I get 5,172 results. I am not sure where to go at this point. I want to say something like the main entity has field collection item IDs IN () with the item id's above, but I am not sure how to do that.

Can I plug in somehow with $query-\>where conditions? Or is there a better way to do this?

# Answer
After some direction from merlinofchaos, here is what I did:

* Add the field as an exposed filter
* Use form\_alter to change it to hidden
* Use javascript to set the value to 1, bound to a change event on the date select

Otherwise its like asking for a conditional filter (if filter X has value, then set these filters to Y) which is not so easy in UI.

You could also inspect $\_GET and use hook\_views\_query\_alter to add a $query-\>where, but I had better luck with Javascript.

Hope this helps others.
> 1 votes

---
Tags: 7, views, entities
---


# Question
Title: Custom template for fields in user profiles
I'd like to customize the fields in my user profiles. So far I've created `field.tpl.php` which of course applies to all fields on my whole website and not only to the fields in the user profiles.

How do I have to name the `field.tpl.php`? Is it `field--user-profiles.tpl.php`? That didn't work.

# Answer
> 1 votes
According to Drupal's theme hook suggestions for Drupal 7 the following suggested template names are available:

1. field--field-name--content-type.tpl.php
2. field--content-type.tpl.php
3. field--field-name.tpl.php
4. field--field-type.tpl.php

The `content-type` in this case is `user` (I guess it means entity type really), so to theme fields just for user profile pages, your template should be called:

```
field--user.tpl.php

```

I've just tested that on a dev site and it works perfectly.

# Answer
> 0 votes
You may write a template for whole form by altering form

I assume that you didnt use profile2 module. Your user profile(maybe account) page is at user/1/edit

first of all you need write alter function

```
function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  switch($form_id){
    case 'user_profile_form':
      //load an entity object
      $form['#theme'] = 'custom_profile_form';
    break;
}}

```

then you have to add own template for this form item

like

```
function MYMODULE_theme($existing, $type, $theme, $path){
  return array(
    // user profile 2 form
    'custom_profile_form'=>array(
      'render element'=>'form',
      'template'=>'custom-profile-form'
    ),

```

then you have to create custom-profile-form.tpl.php in your modules folder

in this template file you have to render some form specific variables

```
<form action="<?php print $form['#action']; ?>" method="<?php print $form['#method']; ?>"
        id="<?php print $form['#id']; ?>" accept-charset="UTF-8">
    <?php print drupal_render($form['form_build_id']); ?>
    <?php print drupal_render($form['form_token']); ?>
    <?php print drupal_render($form['form_id']); ?>
//here you have to render own elements

</form>

```

rendering fields like this will give field form elements without waste divs that core attaches

```
<?php print drupal_render($form['profile_profile']['field_status']['und'][0])?>

```

templates like field.tpl.php will effect only to field's formatter. not to widget

---
Tags: theming, users, entities
---


title: Field Label for Content Type

text:
# Question
Title: Field Label for Content Type
I need to find where the field label for a content type is stored within the database. I tried the field\_config\_instance, it's not there.

# Answer
> 1 votes
Yes it is, you just need to look a bit harder ;)

Have a look at the serialised array in the `data` column of that table. You'll find the label for the field listed in there.

If you want to extract this in code the best way is to use the field API functions, it saves you having to mess about with the serialised array directly:

```
$entity_type = 'node';
$field_name = 'body';
$bundle = 'article';

$info = field_info_instance($entity_type, $field_name, $bundle);
$label = $info['label'];

```

---
Tags: entities, nodes
---


# Question
Title: Preprocess taxonomy for a custom template file
In Drupal 6, I am customizing a view where I am trying to make the taxonomy terms work in all the page template files.

This is the code in the template.php file.

```
function getTermsName($taxonomy_id) {
  $terms = taxonomy_get_term($taxonomy_id);
  return $terms->name;
}

```

This is the code in the custom page template file.

```
$taxonomy_id = 'term id you got';
echo getTermsName($taxonomy_id);

```

Nothing happens.

I am quite bad at this; I hope in a very simple solution.

EDIT

With Boriana we found out that the mythemename\_preprocess function is *not* working *not* taking effect in my drupal. If anyone has idea why, that will be the key to this problem.

# Answer
> 1 votes
If you're trying to use this in your page template files, then you should put your template.php code inside the **yourtheme\_preprocess\_page(&$vars)** function. That's the one that will get called before your page template file, and it can "communicate" its results to the template file by putting them in the $vars variable which was passed to it by reference.

So here's an idea of how you can improve your code:

In template.php:

```
function mytheme_preprocess_page(&$vars) {
  $term = taxonomy_get_term($taxonomy_id);
  $vars['term_name'] = $terms->name;     // Store anything you want to use later in $vars
}

```

In page.tpl:

```
<?php print $term_name; ?>

```

Let me know if that helps you get closer!

============================ EDIT =============

The variables set in the hook\_preprocess\_page() function are only available in your page.tpl files. If you're trying to get to these variables in your view templates, you'll have to instead use a views pre-processing function, such as **mytheme\_preprocess\_views\_view(&$vars)**

---
Tags: taxonomy-terms, theming
---


title: Solr search page and custom filters

text:
# Question
Title: Solr search page and custom filters
I want to change the default sorting order of a pre-populated Solr search page (the option "Show enabled facets' blocks in their configured regions and first page of all available results" under "Behavior on empty search" of the Advanced Search Options). I thought the solution would be setting a custom filter but I cannot find the right syntax: I tried everything from "solrsort=ds\_created:desc" to "sort=created:desc" and all the variants between... but I failed... Anyone may help me please?

# Answer
Just a regular space seems to be working for me. Add the following to the end of your search URL: "**&solrsort=ds\_created desc**".

Just to be sure though, you can always go to the following reports page, to make sure the ds\_created field has been indexed. You can see all the fields apachesolr has in its index there: **/admin/reports/apachesolr**

Let me know if that helps!

============== EDIT ===================

Another option I've used is to create a small module that modifies my solr query and/or solr results... I actually set my default sorting in that module. Here's a snippet of my code:

```
function YOURMODULE_apachesolr_query_alter(&$query) {
  //Set the sort default options.  These are different options.  Just choose one!
  $query->setSolrsort('sort_label', 'asc');  // by title
  $query->setSolrsort('ds_created', 'desc');  // by created date
  $query->setSolrsort('score', 'desc');     // by best match
}

```

:-) Hope that helps, since the above wasn't quite what you needed...
> 4 votes

---
Tags: search
---


# Question
Title: How to specify the default installation profile
I want to specify my custom installation profile as default one, like acquia profile in acquia drupal.

For example when installing acquia drupal, acquia profile will be selected by default thus choose profile and language will be skipped. Now I need to overcome this, because I'm, writing my installation profile in the acquia drupal. So I should set my custom profile as the default one instead of acquia profile.

How can I achieve this?

# Answer
> 0 votes
oops its my mistake.

D7 by default doesn't consider standard and minimal profiles, so its selects acquia profile by default.

I had problem with my custom installation profile, that's why it doesn't showed up in the profile list.

---
Tags: 7, distributions
---


# Question
Title: Change crop focus for specific styles on certain existing images
I just migrated a 15,000 story news website and am doing some quality testing on that migration.

The site uses about 5 image styles for various things, including a REALLY wide one (~960x400px) at the top of every story. This works awesome for images with horizontal/landscape orientation, but causes some weird cropping for images with vertical/portrait orientation.

I don't want to use a solution like imagefield\_crop, which will change the cropping on all images (square thumbs are less problematic, for instance). Any idea of modules that allow me to override the default cropping focus from Image Styles for specific styles on specific images?

Thanks!

(Additionally, these images are in Field Collections, so any module suggested should work with that. Currently, it seems that imagecrop does not.)

# Answer
For my purposes, Manual Crop was the best solution.
> 1 votes

---
Tags: 7, media
---


# Question
Title: How to make a clone of a website without contents
I need to create a clone of one of my website. It will be the same (modules, views, content types, template etc...) I've already done once by coping everything and then deleting the contents and the users. Is there the right way? I will need to do 3-4 copies of the website. Is there any module that can help me(a part from backup and migrate) to do these copies? Should I create an kind of "distribution" enabling modules and creating content type, similar to the master one, from the scratch and then export the database?

If I do as I always did (clone and delete contents and users), how can I reset the content id?

Thanks in advance

# Answer
> 4 votes
I guess what your looking for is the features module http://drupal.org/project/features. When creating clones of websites, obviously all the code/themes/modules is easy to copy but the only way to get all your node types, fields, views etc... is in the database.

Features exports all this information as a module as you can just copy this to a new site along with all your other modules, enable it, and voila all your views content types etc.. In the features you can list modules as dependencies so when enabling your feature all the contrib/core modules you need are enabled aswell (they will ofcourse need to exist on your new area).

It intergrates fully with most the big contrib modules and from what I understand is exactly what your after. It can be daunting at first but dont worry its really very easy to use. The following video is for drupal 6 but the features interface is identical (as far as I remember) http://mustardseedmedia.com/podcast/episode43

There are other more complex ways to do what your after aswell using drush and creating build scripts, you can ever combine drush, build scripts and features. However I believe just normal features will do you fine.

# Answer
> 1 votes
This isn't going to answer your question fully but it might help a bit; some code to clear out all users and nodes in the system, then reset the auto-increments on the tables:

```
$uids = db_query('SELECT uid FROM {users} WHERE uid > 1')->fetchCol();
user_delete_multiple($uids);
db_query('ALTER TABLE {users} AUTO_INCREMENT = 2');

$nids = db_query('SELECT nid FROM {node}')->fetchCol();
node_delete_multiple($nids);
db_query('ALTER TABLE {node} AUTO_INCREMENT = 1');

```

You'll need to use caution running the above as it's likely to take a long time and you'll probably exceed the max execution time. You could look at splitting it into batches though (probably worth another question if you decide to go down this route).

The benefit of doing things this way is that all modules (at least those that behave themselves properly) will clear up any lingering field/custom data when the entities are deleted, so you won't have stagnant data in your db.

# Answer
> 0 votes
Couldn't you just clone the site in its entirety and then delete all the content through the content interface?

If you're going to be doing this multiple times, it might be worth your while to create an install profile.

# Answer
> -1 votes
After copying files and the DB, you can clean up the `node` and the `users` Table.

Dont forget to keep the `admin` user in the table.

---
Tags: 7, migrations
---


# Question
Title: How can I prevent certain roles from editing other roles?
I have user roles User Role 1, 2, and 3. I want a simple module that will make User Role 1 only be able to edit and administer users in User Role 2, and not User Role 3. Does anybody know of any module or other easy method to do that? It seems like there *must* have been somebody else who did something about their moderators being able to delete their admin accounts?

Please note that I'm not asking for anything about restricting the **permission** changing ability of roles.

# Answer
The userprotect module can handle that.
> 1 votes

# Answer
Administer Users by Role does that (and is now ported to Drupal 7).
> 1 votes

---
Tags: 7, users
---