title: Disable example of shipping method

text:
# Question
Title: Disable example of shipping method
Please tell me how to remove the example shipping method. If I disable this module, my other shipping methods also don't work. There is no option to disable or delete this. The only option is 'Configure Component'. I have even tried imposing a condition on Example Shipping Method 'that it must show up only if the order is too big' but still doesn't work. All shipping methods get disabled even if I add a condition on 'Example Shipping Method. '

# Answer
> 1 votes
You can disable Shipping Method Example from the module list itself. I have never enabled that and my shipping method works. I have flat rate enabled for my shipping method. Simply disable the module. Here is the screenshot of my shipping modules tab -

---
Tags: commerce
---


# Question
Title: How to use Block Access with specific Block?
I am using `block access` module to restrict `block administration` permission. I want to give permission to a role on specific block to edit that block. When I changed the permission firstly it permits only change title and description not body. Second it gives permission on every blocks I added manually.

I only want to allow one single block should be edited by `site editors`. How to do it?

# Answer
> 0 votes
Solved this using a patch and granting input filter permission. Patch is here https://drupal.org/node/1916028#comment-7302100.

---
Tags: 7, blocks
---


# Question
Title: How to make Expose filter of Author Id from autocomplete to select list?
I added a exposed filter of `Author` and it showing me the autocomplete. How to change it in select list?

I found a solution here https://stackoverflow.com/a/3885759. Is there any other simple way to do it Because I have other filters also so I can't take a contextual filter?

# Answer
Add a custom module with the help of https://stackoverflow.com/a/16517124 on the same post and solved my issue.
> 0 votes

---
Tags: 7, views
---


# Question
Title: How to add region just above title for omega theme?
How to add region just above title for omega theme? I try to add a region just above title. But no sccessful.

# Answer
In case you're using Omega 4 you need to include your regions in two files, instead of only the `.info` file.

You also need to include them in your `layout.inc` file, which is located in the theme's folder at:

> layouts/yourlayout/yourlayout.layout.inc

and then print them at the desired spot in your HTML markup in your `layout.tpl.php` file, which is in the same folder.

Hope this helps.
> 2 votes

# Answer
A simple way might be to use the Blockify module
> 1 votes

---
Tags: theming
---


# Question
Title: Can I create two sites with a single user login?
I have two sites with loosely related content. I'd like a user to be able to create an account on one site but have that account be valid on the other site. Also have the ability so that if any changes are made on site 1 to the account, they are reflected in site 2's database. Is this possible?

# Answer
> 0 votes
The mechanism which you are talking about called SSO (Single Sign On). There are modules in Drupal to achieve SSO but it would depend upon your site setup like whether 2nd site is sub-domain of the first or both are sub-domain of some other etc..

In case one of them second level domain then you can use Bakery. I have used it successfully.

I have heard so much about CAS module too though never used it. You can go through the documentation of the module and find out whether it fulfil your need or not.

You can have a look here on comparison between all SSO modules available in Drupal.

Regarding auto update, I am not sure it can be done easily with any of them. You will have to write your own code maybe.

# Answer
> 0 votes
I also think the bakery module will do what you need. If changes are made to the user account on the master site some of the data is updated on the slave sites. It depends on how much there is that needs to be synchronized. Also, as Rajeev says, with Bakery your sites must be on the same domain.

another route you could look at would be sharing the user table: https://drupal.org/node/22267

Bakery would definitely be the safer choice, as it doesn't share any of the user related tables, allowing you to update different sites at different times while still allowing access to users. Upgrading to new versions using the second method is not an easy matter..

---
Tags: users
---


# Question
Title: Panels on the front page get invalid $user variable
I have a Drupal 7 wite where the front page is a Panel. In one of its tiles I have a custom PHP code that prints out the value of \`$user-\>name'. Now the problem is that it usually prints out a different user's name.

Cacheing and memcache is now switched off. Do you have any idea what might cause this problem..?

# Answer
> 0 votes
Ok, got is. Panels have its own caching that was switched on.

---
Tags: 7, panels, caching
---


# Question
Title: Implementing Taxonomy hierarchy in View and Search
I am working on a biology website that needs to make use of Drupal 7's Taxonomy system, for a biological taxonomy.

My goal is to allow users to tag all content with related species information, and provide the following functionality:

1. Display all nodes that are associated with a child term of the specified taxonomy term (so if they access the "Birds" term, "sparrow" would be included)
2. Include taxonomy terms in search
3. Allow for species nicknames, (synonyms), abbreviations and variations in spelling or singular/plural usage

I have installed the Hierarchical Select module, but am not sure it is working correctly. Or, I am not using it correctly. When I insert new terms deep in the hierarchy, they sometimes end up at the top level. There have also been intermittent errors showing in a red box. I'll add that to this post if it shows again.

Example taxonomy

```
Animalia
- Chordata
-- Aves
--- Passeriformes
---- Passeridae
----- Passer
------ Passer domesticus (primary species term)
------- Common sparrow   (synonym)
------- English sparrow  (synonym)
------- House sparrow    (synonym)
------- ENSP             (synonym/abbreviation)
------- House sparrows   (synonym/plural)

```

In the above example, I need users to see English Sparrow content when they view the Taxonomy page for Aves, as well as the Taxonomy page for "ENSP" if the node has been tagged with Passer domesticus or any of its child terms.

Ideally, a basic search for any of the child terms for Passer domesticus would also return a list of nodes tagged with any of the term's siblings.

I am open to configuring a View for this, if Search is not possible. All advice is appreciated.

Similar questions from others: http://drupal.org/node/1792256

How to have parent taxonomy terms include their children terms' nodes?

How to show the parent and child taxonomy term?

https://stackoverflow.com/questions/5910071/views-show-child-taxonomy-terms

# Answer
> -1 votes
I would look into using Search API for this and build up facets using the Facets API.

Once you have Search API installed you need to create a search index, choose which fields to index and what facets to create.

With the search index in place you can from Views create a Search view that uses your index as base.

Place the facets where you want them and tell them to show up at your search views url.

There is a guide that explains how to setup Search API here. In the guide they use Apache Solr as backend for the search index. That is not necessary, you can use the database as backend but I recommend using Apache Solr as backend as I've stumbled on a few bugs in the database backend which work with Solr.

You would be able to do searches such as this:

Good luck

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


# Question
Title: Intermittent hook_menu error - call_user_func_array() expects parameter 1 to be a valid callback
As the title suggests I'm getting intermittent errors when hook\_menu is called. Based on the error message it's as if the callback can not be found. Clearing the cache resolves the issue and the page works as expected. However, if the server is idle the error reappears. Any ideas as to what might be happening? Here are some details:

Error as reported in log:

> Warning: call\_user\_func\_array() expects parameter 1 to be a valid callback, function '\_protected\_download' not found or invalid function name in menu\_execute\_active\_handler() (line 517 of /var/www/drupal/includes/menu.inc).

All code is in the my\_module.module and the module is enabled:

```
function my_module_menu()
{
    $items = array();
    $items['lesson-register-for-download'] = array(
        'path' => 'download/register',
        'title' => t('Register to Download a Lesson Plan'),
        'title callback' => FALSE,
        'access callback' => TRUE,
        'type' => MENU_CALLBACK,
        'page callback' => '_protected_download',
    );
    return $items;
}

function _protected_download()
{
    // check cookies and redirect here
}

```

# Answer
You say your code is in my\_module.inc, which means you have to tell the menu system that it is in there.

By default drupal will load my\_module.module, but because the function is not in there it can't find the function.

As a side note, generally you should put hooks like hook\_menu() in the .module file.

To tell the menu system that it has to load my\_module.inc for your menu callback, do this:

```
$items['download/register'] = array(
  'title' => 'Register to Download a Lesson Plan',
  'access callback' => TRUE,
  'type' => MENU_CALLBACK,
  'page callback' => '_protected_download',
  'file' => 'my_module.inc',
);

```

Note the 'file' param.

Also, I made a couple of other changes:

1. Removed t() from the title and removed the 'title callback', because by default title callback is t().
2. Removed the 'path' param and changes the array key for the menu item. The path param was used in drupal 6 but not in drupal 7.
> 1 votes

# Answer
the callbacks are written to menu\_router.page\_callback; maybe find that record and then go look when the error occurs...
> 0 votes

---
Tags: 7, routes
---


# Question
Title: Delete hundreds of nodes by ID programmatically
I am trying to remove 700 or so nodes from my Drupal 7 system (they are duplicates) and have a big list of node IDs in a text file.

Have tried using Views Bulk Operations (VBO) but it doesn't allow me to enter a list of IDs.

Also looked at using Drush documentation, but it doesn't seem to have a node-delete command? (surely a pretty standard thing?)

So now I'm thinking of writing my own **Python** script to do the following:

* Take list of input IDs (via input file)

(note: this is just pseudo code)

```
# remove nodes
Foreach id in file_in_ids:
   SQL(DELETE FROM node WHERE nid={id});

# clean up all rows in tables containing col 'entity_id':
tables_with_entity_id = SQL(SELECT DISTINCT TABLE_NAME
FROM INFORMATION_SCHEMA.COLUMNS
WHERE COLUMN_NAME
IN (
'entity_id'
)
AND TABLE_SCHEMA = 'my_drupal_db')

foreach table_name in tables_with_entity_id:
  foreach id in file_in_ids:
    SQL(DELETE FROM {table_name} WHERE entity_id=id)

```

Does this seem like a sound approach?

# Answer
> 6 votes
You want to avoid deleting directly from the database. The node system distributes its data across a number of tables. Generally you always want to use the API. The method your after is node\_delete() which takes the nid as its single argument. This will handle deleting all the associated data and firing off any hooks that are attached to the event.

An alternative approach:

* Download and install the "Devel" module. This then gives you access to a page at /devel/php where you can run arbitrary PHP code within Drupal.
* You could write custom code to load the text file and explode the nid's into an array. Something like this:

```
$nids = file_get_contents("/path/to/file");
$nids = explode(",", $nids); // This will depend on how your nids are delimited. Could be line break "\n"
foreach ($nids as $n) {
  node_delete($n);
}

```

# Answer
> 2 votes
Use Drush Entity extension. It implements several operations on entities via drush. One of them is entity-delete:

```
drush entity-delete node 1 2 3 4

```

# Answer
> 1 votes
FWIW, here's a similar menu callback function I wrote for another developer's site which had an issue with orphaned nodes being created without a node type set:

Hat tip to MPD - I wasn't aware of node\_delete\_multiple() for D7 (but this was written for a D6 site anyway)

```
    function es_node_cleanup_callback() {
      // get all nodes without node type
      $q = 'select nid from {node} where type = ""';
      $r = db_query($q);
      if(!$r) {
        drupal_set_message('query failed');
      }
      else {
        $counter = 0;
        $message = 0;
        if(mysql_num_rows($r) > 0) {
          while($row = mysql_fetch_row($r)) {
            if(isset($row[0]) && ctype_digit($row[0])) {
              node_delete($row[0]);
              $counter ++;
            }
            else if($message == 0) {
              drupal_set_message(print_r($row, 1));
              $message = 1;
            }
          }
          drupal_set_message($counter . ' nodes deleted');
        }
        else {
          drupal_set_message('No orphanned nodes');
        }
      }

      drupal_goto('admin');
    }

```

# Answer
> 1 votes
If they are duplicates they will have the same title, so you can views bulk operation , modify the view to search by title and delete (select all, including all nodes not in current page matching the search). Very useful.

You'd probably could also tweak the view to add node id's...

---
Tags: 7, drush
---


title: Drupal for Facebook logout problem

text:
# Question
Title: Drupal for Facebook logout problem
I can connect through this module, but i can't logout. I don't know how, but it doesn't clear the cache or something else. It still remembers my account details and relogin me again everytime.

# Answer
First thing is that you should log out of your facebook account and then try the same.

It would surely work fine.
> 1 votes

# Answer
You could also add a menu there.

Drupal provides you a **user menu** which has logout link.
> 0 votes

---
Tags: social-network
---


# Question
Title: Filter Images, Audio and video from Media in Views?
I am using media selector module. I have a field collection item in my content type called media. I added a image field in field collection item. I created a view to display the images of a content. I uploaded 2 images and 1 youtube video. I dont want to show video in view result.

# Answer
> 0 votes
You may consider to use `File: Mime type` filter instead of `File: Path`.

For all video files the `Mime type` always has a pattern: `video/[video source or format]`

it might be for example:

```
video/youtube
video/vimeo
video/quicktime
video/mpeg
video/mp4

```

Applying the filter `File: Mime type` contains `video` will solve the problem for all video files, not only youtube.

---
Tags: 7, media
---


# Question
Title: How to print a date field value on a page?
In Drupal 7, I have created a node type x, with a date field D:M:Y. Here is an edited Devel tree array structure message for easy reading.

content \>\> system\_main \>\> nodes \>\> 31 \>\> field\_Mydate \>\> #items \>\> 0 \>\> value

How do I render the particular node date field value from the above extract?

# Answer
> 3 votes
You should use Drupal's 'format\_date' function.

Example: format\_date(strtotime($entity-\>field\_mydate\['und'\]\[0\]\['value2'\]) ,'custom','F j, Y');

# Answer
> 0 votes
This worked for me:

```
<?php
print format_date(strtotime($content['field_Mydate']['#items'][0]['value']), 'custom', 'F j, Y'); ?>

```

I used the format\_date function as suggested. I entered the values based on Devel info, and inserted into node.tpl.

---
Tags: entities, datetime
---


# Question
Title: Git showing every changed file not folders
Git is showing every change in every installed module folder. This makes it unusable because I can't see what I'm committing.

Previously git only showed the module folders. So if i installed Views, it would show me in `git status`, untracked files "`sites/all/modules/views`"

I used git -rm to remove a file, but somehow it managed to completely mess this up and now it shows every single changed file. Here's the bottom part of my latest `git status`, it's so long most of it is untrackable.

What have I done, how can I change this back to what I had before, because I really need to roll back a commit.

EDIT:

Context for my problem, now having the solution.

Some modules in Drupal have a huge number of files. When you add them to the index, git lists all the files in the folder rather than each individual one.

In the case of some modules, in my case the commerce and jquery\_update modules this will probably add more files than your command line shell can display, so you won't be able to see everything.

I got around this by removing the modules from my index with `git reset HEAD *filepath*`

and then adding them in separate commits.

# Answer
> 2 votes
The difference between showing the folder level for untracked files and the file level for tracked files is expected git behavior. This will always be the case. Once you add the folder (which adds all the files in it) each of the files is tracked by git and will be tracked individually. So, when you do a status, it SHOULD list each file separately. Yes, this is kind of annoying, but the general idea is that you'll add a folder and then commit that change. Once committed, you won't see each file unless is has been changed in some way.

As for fixing the situation, you probably haven't actually messed anything up; it's just tough to see that because there are so many new files in your index (a git term which you can research if you'd like more information).

If you'd like to undo it all, you can run the `git reset` command. In general, most things related to git can be demystified with a couple of Google searches. If you're new to git, I recommend the free Git Book.

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


title: Can't edit permissions

text:
# Question
Title: Can't edit permissions
Drupal 7.21 For some reason I can't edit/add permissions for certain content to ANY roles anymore. I first noticed this with one role and that had certain permissions missing. Added the missing permissions and tried to save, but it always reverted back to before save. I deleted the entire role and it doesn't take any permission. Other roles the same issue, can't add any additional permissions for create content even for r administrator (User1)

# Answer
This happened to me once not too long ago. It seems that, depending on the type of server you are using, there will be a limit when you save permissions or when you use a lot of memory at one given time. The more roles and the more modules the more check boxes in the permissions page and the larger the calculation needed to be accomplished by the server. I went through the modules and got rid of a few modules and also a role that was not necessary and that solved the problem. I have also read that under settings.php you just uncomment where it says:

```
ini_set('pcre.backtrack_limit', 200000);
ini_set('pcre.recursion_limit', 200000);

```
> 0 votes

# Answer
I experienced this under Drupal 6.x - it is possibly a similar experience on Drupal 7.x.

The Apache error log (`/var/log/httpd/error_log` or similar) may show something similar to the following:

```
... [error] [client ... ] PHP Warning:  Unknown: Input variables exceeded 1000.
    To increase the limit change max_input_vars in php.ini. in Unknown
    on line 0, referer: https://.../admin/user/permissions

```

To resolve add the following to php.ini

```
max_input_vars = 2000

```

Reload Apache per your operating system and increase setting if pain persists.
> 2 votes

# Answer
I also ran into the same problem once, I solved it by adjusting the suhosin-configuration in server.

Check suhosin enabled in your server and if enabled Change your suhosin.ini or php.ini to allow more (i.e. 1000) vars:

```
[suhosin]
suhosin.post.max_vars=1000
suhosin.request.max_vars=1000

```

or if you can't set it in your .htacces

```
php_value suhosin.post.max_vars 1000
php_value suhosin.request.max_vars 1000

```

Some other possible solutions can found in this link
> 0 votes

---
Tags: users
---


# Question
Title: Easy steps for adding the imported content on one single page for display
I have imported the data using the Feeds module from an Excel file.

But as I am new it has created multiple article nodes. I want all these articles to be shown under one article list page. Please explain step by step how can I move forward.

# Answer
You can use Views module to do it. Follow these steps, to set a page listing all articles--

* Download views & keep it in **sites/all/modules** folder.
* Enable **`Views`** & **`Views UI`** from your module list.
* Under **Structure** click **View** & **Add a new View**.
* Select **Content** under show & **Article** of type.
* Give a name to it & check **Create a page**.
* Save & continue.
* Give a path to the created view page.
* Now you can access your path like `$basth_url/(your given path)`.

Thats it.
> 1 votes

---
Tags: feeds
---


title: How can I set up free shipping?

text:
# Question
Title: How can I set up free shipping?
I am having trouble setting up free shipping on my Commerce project. I added the Free Shipping module, but when I go to configure, I don't have any options.

The shipping costs for all of our products are absorbed by the manufacturer (who also drop-ships the product, so we don't care about FedEx, UPS, etc). Therefore, I want to show a free shipping line item during checkout.

I installed the Shipping module (7.x-2.x-dev), and I don't see options to create Shipping Services or Shipping Methods.

How can I configure our store so all products are free shipping? I watched a few screencasts, but none of them seemed to apply to what I'm wanting to do.

# Answer
> 3 votes
I use Flat Rate module to do the same. You can set free shipping with help of this module very easily.

Once you enable the module, navigate to `Store->Configuration->Shipping->Shipping Method->Flat Rate`.

You will find Flat Rate under `Shipping Method` tab. Click `Add a flat rate service`.

Add something kind of Free Shipping, give it `Title`, `Display title` & `Base Rate` as 0.

Now visit **Shipping Service** tab. You will find your added flat rate service in there. Click `Configure Component` & put any condition you like e.g. `Data Comparison` to `commerce-order:commerce-order-total:amount` for any amount.

Now When ever your condition matches, this Free shipping service will apply if you have put **Shipping service** in **Shipping pane** under **Store-\>Configuration\>Checkout settings**.

---
Tags: 7, commerce
---


title: views pagination pager add | to the li

text:
# Question
Title: views pagination pager add | to the li
How do I add "|" to views pager when you are displaying numbers. See the example below

previous 1 | 2 | 3 next

# Answer
> 1 votes
There are couple of options: 1. Using the view's tempate file 2. The easiest and my favorite in that case - using css :after selector to add the '|' to the li's

Hope that helps.

---
Tags: 7, paging
---


# Question
Title: Prevent output of control code characters in Views Data Export
I've recently experienced a problem where by users have entered control code characters into Long text fields. Specifically the ASCII codes `\001, \007, \008, \021` (codes for `Start Of Heading, Bell, Backspace, Device control 1`) which are causing havoc in my XML exports since they are not allowed by the XML standard and prevent the XML file from being parsed.

Therefore I would like to cleanse the output as it goes through Views Data Export to prevent bad characters from outputting. As commented below, this sounds like a bug in VDE, however I'm wondering whether I can tackle this issue easily with my own views hooks rather than wait for a new version/patch?

# Answer
> 3 votes
Views Data Export enables you to write your own `.tpl` files for fields. So, in a template for a problematic fields, you might use

```
preg_replace('/[\x00-\x09\x0B\x0C\x0E-\x1F\x7F]/', '', $input);

```

to strip all potentially problematic characters. Of course cut list of chars for your specific need and if they are in any way meaningful to your users, consider replacing them with some mark instead of eradicating them entirely. It's a bit clumsy solution, but as far as I remember it works, ant it's fast to get up and running.

You can also use preprocess hook instead of tpl:

```
/**
 * Implements hook_preprocess_views_view_field().
 */
function mymodule_preprocess_views_view_field(&$vars) {
  if ($vars['view']->name == 'myview' && $vars['view']->plugin_name = 'views_data_export_xml') {
    $vars['output'] = preg_replace('/[\x00-\x09\x0B\x0C\x0E-\x1F\x7F]/', '', $vars['output']);
  }
}

```

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


title: Collection per content type

text:
# Question
Title: Collection per content type
I just started experimenting with the mongodb module and its fields storage module on a clean drupal install and it all seems to work fine. But what I noticed is that the content of the 2 custom content types is stored in the same collections (fields\_current.node and fields\_revision.node).

Wouldn't it make sense to have a separate collection for each content type? As queries are often per content type, it should reduce the scope of your query? Is there a possibility to do that with the current version of the module, or am I just not getting it?

# Answer
> 2 votes
My question got answered on drupal.org:

> Posted by marcingy on August 16, 2013 at 7:03pm:
>
> > This is mirroring how core storage works. fields\_current.node contains the data for the current revision. There is a collection per entity type which is the smallest division in core in terms of storage.

I guess I will have to build in the flexibility myself :-)

---
Tags: entities, database
---


# Question
Title: Access denied to login to original node id
Scenario is this:

* User sent a link to a website where they must be authenticated to view content.
* User clicks link.
* They have an account but their session has expired so they get 403 access denied page.
* They login.
* The ideal outcome is they are redirected to the original link they tried to access.

I can get a login form to show on the 403 page but can't redirect to the node.

Has anyone any experience of this?

# Answer
Login Destination claims to do what you need:

> It is also possible to keep users on the currently visited page after logging in or out.
> 1 votes

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


# Question
Title: unable to add configure field to drupal view
I added a new field to an existing content type. But when I try to add same field or any other field to the view, I don't find it in the list except few.

Eg: I added image field to content type. Then I clicked on 'edit view' for which I want to add this image field. Then I click on add field under fields section. I don't find the fields of image body or anything, except title field others.

Can anybody help me sort out this issue?

# Answer
> 0 votes
Your view is not a Content view. Create a "Content" relationship on the view, and all the content type fields configured on your site will become available to add to the view.

---
Tags: views, entities
---


# Question
Title: Generate only parent taxonomy terms in a block
I need to generate a menu for parent taxonomy terms.

How would I go about doing this? I'm also looking to generate these terms in a block.

I have a views set up right now that displays just all taxonomy terms. I can't figure out how to filter out child terms. Is there a filter for this, or do I just have to manually create each category item?

# Answer
In Drupal 7 to only show parent terms you add a “Contextual Filter” and add “Taxonomy term: Parent term,” then set “Provide default value” to a “fixed value” of 0.

That will filter out the child terms.
> 19 votes

# Answer
You can just add a normal filter, set the "Parent term" filter to "0", that does the same as the contextual filter with "provide default value" as mentioned above. Turns out the root terms have a parent of 0 which I only just found out thanks to this post :)
> 8 votes

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


title: How to add additional logo in drupal 6

text:
# Question
Title: How to add additional logo in drupal 6
While configuring my theme, I am able to configure my Logo on *Logo image settings*, but I need to configure one more logo, which will be shown in a different region.

Is there any module available or guide on how this can be achieved?

# Answer
> 2 votes
I'm *certain* this question has been answered before, but I can't seem to find it, so here goes.

If you need more than one logo, just avoid using the normal theme settings, as they are easy to get started with, but rather limited in flexibility.

Instead create a separate storage for the logos, say a 'Logo' content type, and upload each logo as an image. This will easily give you the flexibility you need.

---
Tags: 6
---


# Question
Title: Facebook comments and drupal user accounts
Okay, so here is a very theoretical and community wiki like question:

I would like to have Facebook comments on my site but I need that anyone who has an account on my site gets referenced in the Facebook comment he/she posts.

Is there any way to achieve this? Or is this just not possible as Facebook comments are rendered in a iframe and are not at all related to my database?

# Answer
> 2 votes
The various comment widgets Facebook provides are really just premade wrappers FB has created to keep a certain look and feel across the www. If you want to create your own, you can certainly do so. Broad documentation can be found on their Developer Site with key documentation about creating comments here:

https://developers.facebook.com/docs/reference/api/using-comments/#creating

---
Tags: comments, social-network
---


# Question
Title: Language switcher does not display the correct link to the default language path
I maintain a bilingual English/French website and the `Language Switcher` block is available on every page to allow the user to switch language. It works except on one particular taxonomy term page and all it's descendants:

When the language is set to English (default), the `Language Switcher` displays the correct links. English links to the EN page and French links to the FR page.

But when the language is set to French (i.e the user has clicked on French), both English and French options link to the french page (with `/fr/rest-of-the-path/`).

Any idea where the cause of this behaviour lies in?

# Answer
I think this happens because the term itself have no multilanguage path. From my experience the only way to have mulitlanguage path to a term is to create them by hand with an URL-Alias or by installing the `[Pathauto i18n Taxonomy][1]` Module. This helped me a lot
> 0 votes

---
Tags: i18n-l10n, path-aliases
---


# Question
Title: How to capture URL from a webform without using token value?
I have a Webform as a block. Set to show on a certain content type with a hidden field returning the token value `%get[q]` to let the admins know from which page the form was submitted from.

Unfortunately it has intermittent errors that I've not been able to duplicate. Is there a better way to capture the URL?

# Answer
> 0 votes
What about `$_SERVER['REQUEST_URI']`?

# Answer
> 0 votes
What about Drupal official way? https://api.drupal.org/api/drupal/includes!path.inc/function/current\_path/7

---
Tags: 7, webforms
---


# Question
Title: Cannot Upload Image or Cannot Display Image
I am new in using Drupal.

First, I downloaded and installed a Drupal free template on my localhost. Everything works fine.

However, when I duplicated the site from localhost to sharedhost for testing, the image cannot be uploaded nor displayed in the test site when I am adding or editing contents. I went to check with the sharedhost provider, so far, it concludes that "safe mode off", and no error notice nor message is shown in the report.

I copy the reply:

"I am not sure if the paths set are the problem. I noticed your temporary directoy was set to C:/xampp/tmp and I have changed this to simply tmp for you as well as created the directory on the server with complete read/write permissions. It does not appear to have corrected the issue but will be good to have set down the road.

I beleive the issue is with the way Drupal handles image uploads. Unfortunately, it does not appear their are any error messages being generated or logged when an image is uploaded. This leads me to beleive Drupal is not attempting to generate the thumbnail instead of trying and failing.

I recommend creating a post in the Drupal forums regarding the issue. I am going to continue to investigate form here but perhaps someone on the Drupal team will have more insight into what could be causing this."

I just try to upload an image in a new content type and change an image in an existing content. The error log shows:

"\[Mon Aug 19 04:44:09 2013\] \[error\] \[client 218.102.131.79\] File does not exist: /home/jwbb26i2/public\_html/favicon.ico"

We have no idea about this problem. Can everyone help me know or solve this problem?

Thank you very much.

# Answer
> 3 votes
Make sure the directory exists and write permissions are set to 777 (probably 775 on production).

Check the permissions on site/default/files . You might have to ask your shared host admin for this. If you have ssh you can do chmod 777 site/default/files.

# Answer
> 2 votes
Go to Configuration-\>File System and change your files directory from the localhost diectory to sites/default/files or similar. Your theme is trying to load the file from a directory that does not exist.

---
Tags: media
---


# Question
Title: Rules - Page redirect not working on "after saving new content"
Using Drupal 7.7 and Rules 7.x-2.0-beta3

The rule set up is:

* Event: After saving new content
* Conditions: Content is of type news
* Actions: redirect to url news

When adding a news story and clicking submit, the redirect does not happen and I get left with a 'Connection was reset' error in the browser.

Had anyone else this issue? Any ideas how to overcome this?

# Answer
There are a couple of serious bugs in the Rules 7.x beta (frequent 503 errors). Release candidate just came out that fixes these bugs. Try an update to the latest module version and see if the error goes away.
> 1 votes

# Answer
Hope this will help you,

* In Drupal 7, once you created a rule
* For your reference I have created a rule to redirect to some page when ever the **article** is created.
* Check the weight of the rule. If it is 0 then increase the rule weight. Refer above image
* In rule action, make sure to check **Force redirect** option
> 1 votes

# Answer
you could forget rules and try

```
function my_module_node_update($node) {
if ($node->type == 'news'){
drupal_goto('your_news_path');
}
}

```
> 1 votes

# Answer
Update to the current version of rules currently 7.x-2.2

Many of the bugs from beta have been fixed.
> 0 votes

---
Tags: 7, rules
---


title: Reverse order of view sort

text:
# Question
Title: Reverse order of view sort
Ok so I've got this view, and it has a few dozen items. I want the last 3.

Sort ascending seems to work, however the events are in the opposite order than I want.

Sort descending pulls events back from June.

Is there any way to pull the events, but order them differently with views?

# Answer
> 3 votes
It seems you need to have pages ordered ascending, but inside a page descending. To do that, you need to query database in ascending order. Then reverse order of one page in template that renders it.

```
<?php

/**
 * @file  views-view-unformatted--yourviewname.tpl.php
 * Default simple view template to display a list of rows.
 *
 * @ingroup views_templates
 */
?>
<?php if (!empty($title)): ?>
  <h3><?php print $title; ?></h3>
<?php endif; ?>
<?php /* foreach ($rows as $id => $row): // That's how it looks by default */ ?>
<?php foreach (array_reverse($rows, TRUE) as $id => $row): /* That's what you need */ ?>
  <div<?php if ($classes_array[$id]) { print ' class="' . $classes_array[$id] .'"';  } ?>
    <?php print $row; ?>
  </div>
<?php endforeach; ?>

```

# Answer
> 0 votes
To only show 3 items, change the settings in the "pager" section to "Display a specified number of items", and set the number of items to 3 in the settings (assuming you're using Drupal 7). Then you can use a filter of some sort to filter to the exact 3 you want using the post date or any other variable.

---
Tags: views
---


title: drupal commerce browsable catalog

text:
# Question
Title: drupal commerce browsable catalog
I am finding some troubles how Views works with taxonomy terms. I hope you can help me. :-)

I am building an e-commerce site with Drupal Commerce since it has all features I need for my project requirements but I don't know how I can list terms and nodes belong to concrete taxonomy on Views.

I have a product hierarchy taxonomy with all the site product categories. I use Taxonomy menu in order to show this taxonomy in a menu block allowing the user to select any term. A product display node only can be referenced to a sheet term on the taxonomy tree.

I want to use Views by listing as terms as nodes, if the user click on a non-sheet term on taxonomy menu, the view should show the subterms from clicked term. But in the other hand, if the user clicks in a sheet term then the view should show nodes referenced to the clicked term.

For instance,

Let's imagine I have the next taxonomy menu:

* products
    + term1
        - term1.1
        - term1.2
            * node1
            * node2
        - term1.3
    + term2
        - node3
        - node4

If the user clicks on term1 term the view should list term1.1, term1.2 and term1.3 but if he/she clicks on term1.2 it should list node1 and node2.

How can I do this on Views? How can I list two different types of entities depending what term is clicked?

Thanks in advance!!

# Answer
I doubt this is possible in views but you could try a combination of menu block and display suite modules, if you can't custom-code it.

You might also need a module which creates fly-out menus. Display suite is capable of pulling in various entities into your display, and there is a great set of tutorials available on Youtube that will show you how to achieve this.

This site is built with Drupal commerce, display suite and menu blocks; although I didn't add nodes to my menu blocks, it is possible.
> 0 votes

# Answer
I found a solution here. I only had to adapt a little but it worked for me! :-)

See you!
> -1 votes

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


# Question
Title: Rule running after node update shows previous content
Using Drupal 7.15. I wrote a rule containing custom PHP code that POSTs the node ID to an external system. That system accesses the Drupal REST server, retrieves the specified node, and copies its content.

Problem: It gets the version that existed **before** the current save command. The action specifically says that it is run "**After** updating existing content" so I can't understand why I consistently get the previous version.

```
0 ms Reacting on event After updating existing content.
15.618 ms Evaluating conditions of rule TEST rule on save content. [edit]
15.652 ms AND evaluated to TRUE.
    0 ms Rule TEST rule on save content fires.
    0.265 ms Evaluating the action entity_save. [edit]
    1.155 ms Saved node of type node.
        0 ms Reacting on event After updating existing content.
        0.393 ms Not evaluating reaction rule TEST rule on save content to prevent recursion. [edit]
        0.412 ms Finished reacting on event After updating existing content.
    26.716 ms Evaluating the action php_eval. [edit]
    1944.527 ms Rule TEST rule on save content has fired.
1960.253 ms Finished reacting on event After updating existing content.

```

Similar problem, but for user instead of node: Rules - After updating / saving user not working

Discussion on drupal.org: http://drupal.org/node/430274 I have tried the fixes suggested in replies #13, 14 on that page, with no success.

---

Update: I added a separate action on to run entity\_save, and set its weight at 0. The original rule's weight is 5 so it should run after the force save is complete. Same result, and it takes twice as long now.

```
0 ms Reacting on event After updating existing content.
16.051 ms Evaluating conditions of rule Force save after update. [edit]
16.083 ms AND evaluated to TRUE.
    0 ms Rule Force save after update fires.
    0.29 ms Evaluating the action entity_save. [edit]
    2.513 ms Saved node of type node.
        0 ms Reacting on event After updating existing content.
        0.386 ms Not evaluating reaction rule Force save after update to prevent recursion. [edit]
        0.431 ms Evaluating conditions of rule TEST rule on save content. [edit]
        0.448 ms AND evaluated to TRUE.
            0 ms Rule TEST rule on save content fires.
            0.161 ms Evaluating the action php_eval. [edit]
            1954.427 ms Rule TEST rule on save content has fired.
        1954.943 ms Finished reacting on event After updating existing content.
    1984.676 ms Rule Force save after update has fired.
2000.878 ms Evaluating conditions of rule TEST rule on save content. [edit]
2000.902 ms AND evaluated to TRUE.
    0 ms Rule TEST rule on save content fires.
    0.199 ms Evaluating the action php_eval. [edit]
    2422.949 ms Rule TEST rule on save content has fired.
4423.939 ms Finished reacting on event After updating existing content.

```

# Answer
> 1 votes
you can use

```
entity_get_controller('node')->resetCache(array($node->nid));

```

Working for me!!

---
Tags: 7, rules
---


# Question
Title: Module (or code) to display character count?
I would like to add a simple character counter on a form textarea.

Is there a module that does this?

**I don't want to limit the number of characters that can be input; I only want to display how many characters have been input in the textarea so far.**

# Answer
> 6 votes
The Maxlength module has that functionality baked right in:

> Maxlength allows you to set maximum length of any field on any form making use of the form API. This includes fields created using the UI. (Example: any text field on a node)
>
> When the maximum length is enforced for a field, while editing content of that type some Java Script will countdown how many characters are left, also if the Javascript is turned off, it falls back to form API validation.

It works great for textfields and textareas alike. This is (roughly) what a textarea looks like after Maxlength is applied:

# Answer
> 0 votes
Checkout this simple jquery solution: https://stackoverflow.com/a/5371160/947370

You could make a tiny module, put the jQuery directly in your theme, or use https://drupal.org/project/js\_injector to add it just to the pages where you need it.

---
Tags: 7, forms
---


# Question
Title: How do I split the CCK e.g. add node form into a wizard?
I would like to split an /node/add form into multiple parts in a wizard format. Ive seen tutorials for doing this with registration but not with node/add. Any tips?

# Answer
> 0 votes
Check out multistep node form

> For each step you can define which fields should be included in this step. "Fields" includes core-fields like "Title", "Body" or "Authoring information" as well as fields defined by other modules (e.g. Date).

---
Tags: nodes, entities
---


# Question
Title: how to save uploaded file in a custom user registration webform in D7?
I implement the myModule\_webform\_submission\_insert($node, $submission) {...} function in my Module. It's a regestration webform so I want to save all the data from the webform into a the new user. The user has to upload a file during the registration. I have no idea how to save this file in the user as in $submission\[15\]\['value'\]\[0\] I only receive a integer. I have no idea how to get the path the file was actually saved.

Can somebody tell me if it's possible to save the file (uploaded with webform registration form) in the $user\_data Array which is the parameter for user\_save()?

For example I have this

```
function blabla_webform_registration_webform_submission_insert($node, $submission) {
// $node->nid will be the node id of your webform
if ($node->nid == 22) {

$submitted_data = $submission->data;
//Get data from field
$file = $submitted_data[15]['value'][0];

//Now $file has the value
// $file[value][0] = 46

}

```

What can I do with '46'? :)

Best regards, Christian

# Answer
> 2 votes
I believe `46` is the `File ID` or `FID` in Drupal. You can load it via `file_load()` and re-save, move it or attach it to a user profile however you like.

Webform has already saved the file in the system somewhere. You can find out where by inspecting the `$file` object after `$file = file_load(46);` and doing a `print_r` or `vardump` on `$file`.

---
Tags: entities, webforms, users
---


# Question
Title: Programmatically create alias using pathauto for node
Developing a site that allows users to post images (node type = my\_image) to a specific category. Basically, we create the categories and users submit images to them.

Users do not have menu or url permissions, we want to do this for them. When a user is in a category, the drupal form is displayed on that page using drupal\_render\_children().

In HOOK\_node\_insert (type == my\_image) we identify what category they were in and add it to the menu. Following this we are trying to use pathauto\_create\_alias to generate the alias (based on title) but have been unsuccessful thus far (HOOK\_node\_update would, well update the alias).

Obviously, if we grant the user permission for menu and url, the alias is created. We don't want the user to have direct access to the menu system nor aliasing.

Does anyone know the proper way to use pathauto\_create\_alias in the above scenario?

# Answer
> 5 votes
Basically to generate URL aliases in code using the *pathauto* module you would have something like this:

```
module_load_include('inc', 'pathauto'); // include the inc file for Pathauto module

/*
   pathauto_create_alias($module, $op, $source, $data, $type, $language)
   @param $module: Your module name
   @param $op: The operation (insert, update, return, bulkupdate)
   @param $source: Internal Drupal path (i.e.: node/1)
   @param $data: Addition data used to generate a pathalias, in this case the node object
   @param $type: Type of content that will be used to match a pattern, defined in the backend url alias patterns
   @param $language: If you have a multlingual website, you need to pass the language for which you want to generate the url alias
*/

pathauto_create_alias('your_module_name', 'insert', 'node/1', array('node' => $node), $node->type, $language->language); // Language is optional

```

---
Tags: 7, path-aliases, nodes
---


title: Can I store custom data in $node->data?

text:
# Question
Title: Can I store custom data in $node->data?
What is the purpose of $node-\>data? the Node object reference has $node-\>date, which used for

> Long date, including timezone data, of when the node was created.

May I use $node-\>data to store my own temporary variables?

# Answer
According to this page `$node->data` was used about Drupal 5 and is left there for legacy purposes only. It appears it's only purpose is to prevent "call to undefined property" errors. Do not use it.
> 2 votes

---
Tags: 7, nodes
---


# Question
Title: Where to start on fixing a locations module not accurately displaying on a gmap with views
I have been having problems with my locations module displaying points on a gmap using views. I have a profile 2 profile that has a locations field on it to store locations. I collect that data using a views to display it on a gmap. But this all works.

The problem I am having is the location points are in most cases not at all accurate or do not show at all. I have a list of 92 countries that are not working correctly. Some smaller countries I could care less about but ones like Barbados and Finland are not working.

I cannot figure out how to start on fixing this issue. It may be a locations.xx.inc problem, or a geocoding problem or a gmap problem. I do not know where to start.

Any suggestions?

Thanks, Greg

# Answer
> 0 votes
As we can see, pin is rendered at the good coordinates. So the bug is in the Country to coordinates relationship data. You need to look in your database and find a table with this data. Probably, to avoid name collisions, table will be prefixed with module name.

When you have it, just update it with coordinates of capital cities, for example from Wikipedia.

---
Tags: views, google-maps
---


# Question
Title: Domain Access Login Redirect for main domain and subdomain
I have created three sites namely one.example.com, two.example.com, three.example.com using domain access. Here one.example.com is the main site which can create n number of subdomains. I want to redirect the admin of one.example.com to the dashboard and the other two to their respective content listing page. I'm using rules to redirect the admin of one.example.com to the dashboard. But when i login from the two.example.com, it also redirect to the dashboard which returns a "Access denied" page. How to set login redirect separately for subdomains. Please Help. I'm struck!

# Answer
I solved this issue by creating two different roles and by adding a condition for "User has roles". So admin for one.example.com and sub-admin for two.example.com and three.example.com. Currently it works greats according to the condition. But is there any way to set the rules for same role with different actions?
> 0 votes

---
Tags: rules, users, redirection, domain-access
---


# Question
Title: How to send email using Rules from user references CCK Field?
I have 2 types of content that are: Videos and Customers.

A video can be related only by 1 customer. I want that when a video is created or edited, will send an email to the customer associated with the video.

"Videos" has a Node\_reference that is the customer reference. "Customers" have a user\_reference referencing the corresponding user.

Then, using Rules for send mail but I don't know how to get the email of the user from the field node\_reference from "Videos" to user\_reference of "Customers".

How can I do this?

# Answer
> 0 votes
In the recipient input, try to write a php code which returns the email :

```
$customer_node = node_load( $node->field_customer['und'][0]['nid'] );
$account = user_load( $customer_node->field_user['und'][0]['uid'] );
print $account->mail;

```

Note that a better way is to use a custom function in a custom module :

```
print _get_customer_email( $node );

```

and

```
function _get_customer_email( $node ){
  $customer_node = node_load( $node->field_customer['und'][0]['nid'] );
  $account = user_load( $customer_node->field_user['und'][0]['uid'] );
  return $account->mail;
}

```

---
Tags: 7, rules, nodes, emails, users
---


# Question
Title: Slideshow background images in Background
I'm building a site in Drupal 7. Using the JCarousel module I'm trying to create something similar to this:

http://dale.no/

It's simple enough to create a full width slideshow and adding text over images is not too bothersome with a few adjustments to CSS.

But is it possible to make the images into backgrond CSS images, the same as on the dale.no site? The reason is, when you resize the browser, or use a different size monitor, I would like the centre of the image to remain in the centre of the browser. At the moment, on a square monitor, the centre of the images are cropped by the right hand side of the view port.

Is this possible with this module? Are there are other modules that can achieve this?

# Answer
> 2 votes
There are few jquery library which are not using images directly. They are using images as css background.

I found one link for you - http://demo.marcofolio.net/bgimg\_slideshow/

The following tutorial might be useful for you- http://www.techerator.com/2010/11/how-to-make-a-css-background-slideshow-with-jquery/

This tutorial explains how to use css background images for slideshow.

# Answer
> 0 votes
I'm actually working on a Supersized.js module. It is not quite ready for production but I can send you a dev version if you want to test it out in it's current stage/provide feedback.

I think this will provide all of the functionality you are after. It is an addon module to the views jqfx module.

# Answer
> 0 votes
Open source contributed Drupal 7 theme is available for this purpose. Photo theme. https://drupal.org/project/photo

From the theme's project page:

> Photo is a photography and multimedia theme with a full screen slideshow. Showcase your important work, imagination with full screen photo slider. Photo is Drupal theme for photographic professionals, photo artist, amateur photographers to create photo gallery, portfolio with photos, video blogs. It is also useful for architecture, travel sites, hotels, restaurants, sculpture artist and for any purpose who want to emphasis on photos for the website.

---
Tags: theming
---


title: How to count clicks made on an image

text:
# Question
Title: How to count clicks made on an image
I created a click-able image block and posted it on the left sidebar. A click made on the image leads to an external website. How do I count the number of clicks made on that image. The Google analytics don't seem to give immediate results. Is there any module for this. Any help is much appreciated.

# Answer
> 1 votes
Look on how Advertisement module is doing it.

Simplified outline is:

1. Each image is linked to a page named like /count/*someuniqueid*
2. Module implements that page to increase counter and then sends `302 Found HTTP` header to user's browser.
3. Browser is redirected to a desired page and user don't really see what happened at all.

Actual workflow is, due to performance issues, way more complicated and involves php files that does not bootstrap Drupal, caching and all that.

# Answer
> 0 votes
----inside abc.js---------

```
Drupal.behaviors.abc = {
 attach: function (context, settings) {
var count = 1;
if (typeof(Drupal.settings.orgs.count) != 'undefined') {
    var count = Drupal.settings.orgs.count;
}
$('#imageid').mousedown(function() {
 count++;
});
 $.post(Drupal.settings.basePath + 'custom-ajax-callback',{count: count});

```

----inside module abc.module------------

```
    function custom_ajax_callback() {
    if(isset($_POST['count'] )) {
    $count = $_POST['count'];
    }
    else {
    $count = 1;
    }
    $orgs['count'] = $count;
    drupal_add_js(array('orgs' => $orgs), array('type' => setting));
    drupal_add_js(drupal_get_path('module','abc.module').'/abc.js', array('org' => $org['count']);
}

```

By using js function mousedown() you can count the number of clicks on the image

---
Tags: 7
---


title: Include CSS to module specific template

text:
# Question
Title: Include CSS to module specific template
I have a custom module which contains a template directory and a `.tpl.php`. I would like to add a specific stylesheet for this template. Right now, my tpl-file looks like:

```
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML+RDFa 1.0//EN" "http://www.w3.org/MarkUp/DTD/xhtml-rdfa-1.dtd"><html xmlns="http://www.w3.org/1999/xhtml">
<head>
  <title>My Title</title>
 <link rel="stylesheet" type="text/css" href="sites/all/themes/mytheme/css/styles.css" />
</head>
  <body>
    <div class="content-container">
        <p>My content</p>
    </div>
  </body>
</html>

```

And it works, but only partially... How can I include the css stylesheet in a more proper (read: more Drupal) way? I've tried the `drupal_add_css()`, but with no results... But maybe I did it the wrong way. Any suggestions?

# Answer
> 1 votes
In `mymodule.info` file, add following line:

```
stylesheets[all][] = css/styles.css

```

Then, in `html.tpl.php` be sure to print scripts and styles, like that:

```
  <?php print $styles; ?>
  <?php print $scripts; ?>
</head>

```

Failing to output these will break many modules, and make Drupal Core to fallback to non-javascript behavior, and you don't want this to happen.

---
Tags: 7, theming
---


title: context path and subpaths

text:
# Question
Title: context path and subpaths
I have a problem with Context path condition. I would like on the conditions region to assign something like path/\* where * indicates all its subpaths. For instance, if we have path/subpath1/subpath2 the context condition should match on path, subpath1 and subpath2.

Is it possible to do that on Context?

Thanks in advance!

# Answer
> 4 votes
I'm *pretty* sure that just checking it against `path*` should work.

So rather than `path/*` or `path/*/*` just run it against `path*`.

---
Tags: uri, 7
---


# Question
Title: How to remove ":" (colon) when displaying field name?
I created a custom content type with some text fields. In the view settings of that content type I defined both to appear and as well their titles (names of the fields) to be displayed above the content of the fields respectively.

But how can I remove the trailing colon of the titles? Is there a way of modifying the way field names are display just for certain content types? I do not want this altered site wide (e.g. for all fields of all content types).

PS: I'm already using the "views" module to define a special layout for this custom content type. Probably there is a way to carry out these changes with the help of the "views" module and a custom layout template?

**/edit/**
I did not create a view (as with the "views" module) to display that content but used Drupal's own content type view configuration (maybe called "display"). I'm working with a localized Drupal and retranslating the different words.

*Remark: Using Drupal 7.10 with Views 7.x-3.0-rc3*

# Answer
> 9 votes
Note: The OP is **not talking about Views**. (In Views you can uncheck a box that says *Place a colon after the label*).

The accepted Drupal method is by **copying** the core *field.tpl.php* file into your theme directory and manually removing the colon from the file.

```
modules/field/theme/field.tpl.php
sites/all/themes/[mytheme]/field.tpl.php

```

In Drupal 7 this is on line 55:

from:

```
<div class="field-label"<?php print $title_attributes; ?>><?php print $label ?>: </div>

```

to:

```
<div class="field-label"<?php print $title_attributes; ?>><?php print $label ?> </div>

```

In order to do this in a **specific content type** you first copy *field.tpl.php* to your theme, then duplicate it, adding the machine name of your content type, and remove the colon from the content type specific version.

```
sites/all/themes/[mytheme]/field.tpl.php
sites/all/themes/[mytheme]/field--[content-type].tpl.php

```

**Note: the double hyphen (--) is not a typ-oh.**

Read up on theme suggestions for more. Using suggestions you can target just a specific field in this content type, just the field globally, all fields in the content type, or all fields in all content types. Or handle every combination differently.

# Answer
> 4 votes
For Drupal 7 you can use the Display Suite module. After you installed this, you can enable the Display Suite Extras. Now you can set for each field "expert" values. So you can for example remove the default wrappers and classes for each field, or rename the field to something else or you also can choose to remove the ":". Very handy. If you need to know more, i can give you a more detailed explanation on how to achieve this.

# Answer
> 2 votes
I know this is a super old question, but nowadays there's also the Colonectomy module.

> This simple module allows the colon punctuation mark to be removed from field labels.

# Answer
> 0 votes
In Drupal 6 at least, you would first copy CCK's field template, content-field.tpl.php, from its theme directory into your theme, and then copy it to the specific field name you want to theme, eg, content-field-FIELDNAME.tpl.php, then edit out the hardcoded :, flush caches and see what's what. Something similar will most probably work for D7. For the exact details, check out http://api.drupal.org/api/drupal/modules--field--field.module/function/theme\_field/7.

# Answer
> 0 votes
Maybe you would like to check https://drupal.stackexchange.com/a/17770/53 . It's related with linked titles, but the issue with the colon can be corrected using the same module.

# Answer
> 0 votes
I normally use javascript to remove colons from webforms, you may be able to do the same for a node page, just by choosing a different selector.

eg.

```
$('.webform-component label').each(function() {
  var text = $(this).html();
  $(this).html( text.replace(':', '') );
});

```

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


# Question
Title: create a page view to have only one specific content type show
I'm using D7 and I am working on a blog page. I have created a content type called News, I created a view called News as well.

I want to firstly create a page, all the content that the type is News will be shown on this page, but not other content type.

I can't find where to specify content type in the view settings. Both CONTEXTUAL FILTERS and FILTER CRITERIA seem only have all the content, but how do I specify content type?

Thank you!

# Answer
> 6 votes
Under filter criteria, click on add, select **content: Type**, and then check the type you want filtered

---
Tags: views
---


# Question
Title: How to deal with /system/files references when upgrading to D7?
After migrating a site from D6 to D7 with `drush site-upgrade`, I notice that some public contents in the D6 version refered to pictures with URIs like for instance `/system/files/logo.png`, instead of the more efficient `/sites/default/files/logo.png`
There's no `system` directory on disk and no URL rewriting that I can see, so I assume the first form goes to Drupal for routing.

The problem is that with D7 post-upgrade, such references lead to a *"Page not found"* error so the pictures are broken.

As a test, if I drop `somefile.png` into `/sites/default/files/`, D6 seems to be happy to serve http://example.com/system/files/somefile.png despite the fact that the file is not known anywhere in its database. But D7 apparently doesn't do that.

Is `/system/files` a hardcoded path component that means something to D6 and not D7? In `/admin/config/media/file-system`, the download method is set to "Public local files served..."

How to solve this with Drupal 7? Is there a configuration setting somewhere that I'm missing?

# Answer
## Why it happens

In D6, the `system` module provides the following menu entry that ties `system/files` to the `file_download` callback:

In `system_menu()` function:

```
  $items['system/files'] = array(
    'title' => 'File download',
    'page callback' => 'file_download',
    'access callback' => TRUE,
    'type' => MENU_CALLBACK,
  );

```

Then in `file_download(),` if the file exists and no `hook_file_download()` objects to the download, it gets served.

On the other hand, D7 expands on that with a page argument set to `private`:

```
  $items['system/files'] = array(
    'title' => 'File download',
    'page callback' => 'file_download',
    'page arguments' => array('private'),
    'access callback' => TRUE,
    'type' => MENU_CALLBACK,
  );

```

It has the effect of preprending the `private://` scheme to the filename, which `file_download` processes by requesting the registered file stream wrapper for it.
By default (no private path set in `/admin/config/media/file-system`), this scheme is not registered, and that's why `GET /system/files/logo.png` finally fails with a 404 status.

## How to fix

Setting the private file system path to `sites/default/files` (the same as the public path) makes it work.

However it's not a good long term fix, both because routing public static files through Drupal is much heavier than direct access by httpd, and because it precludes the use of a real private space should the site need it in the future.

The long term fix is to hunt for these `/system/files/xyz` references and replace them by `/sites/default/files/xyz`.
> 1 votes

---
Tags: files, upgrading
---


title: Adding a template to a specific page

text:
# Question
Title: Adding a template to a specific page
I want to have a template for a specific page, as I want to add multiple Javascript pulled games to it.

The nid is 34, so to create this page, I would have to create `page--node--34.tpl.php`, correct?

# Answer
> 2 votes
Yes, that's correct.

Once you've added the file, clear the caches and the new template will take effect.

# Answer
> 0 votes
You do not specify the version of Drupal you're using, but if it's 7 the correct naming structure is: `node--34.tpl.php`. Ensure you clear the cache after adding it to your theme or theme/template folder.

---
Tags: theming
---


title: Assign node to one domain only

text:
# Question
Title: Assign node to one domain only
I've installed domain access module and all its submodules. I have two domains (both set already) and I would like to assign node to one of these domain only.

I set the proper domain in node edit form, but it really doesn't affect the anonymous user permissions, because ALL users can view this node from all domains.

Devel node access displays on the node page something like below:

I checked user permissions as well and everything looks pretty good there.

How do I configure this module to access node only from the right domain?

--- edit ---

after change suggested in one answer it looks like

# Answer
> 2 votes
In your screenshot above there is a "Send to all Affiliates" checkbox and then checkboxes for each individual domain. If you leave the "Send to all Affiliates" checked it overrides the individual checkboxes.

So, the solution for you is to uncheck the "Send to all Affiliates" checkbox.

---
Tags: domain-access
---


# Question
Title: How to import/sync comments from Disqus into my drupal database?
After reading the module´s homepage, I understand that there´s an easy way to get disquss comments easily imported/exported from your Drupal database in D7.

> To import/sync: You can do a one-time import at Comments-\>Disqus Import. Specify the timestamp you want to import from. You can have comments automatically import from Disqus on an interval basis. Turn this on in the import settings at Site Config -\> Disqus -\> Import. Turning on syncing will query Disqus for any comments that came in since the last import.

But how do I actually do that?

I don´t have any "Disquss import" tab or link under "admin/content/comment"

And under "/admin/config/services/disqus" I don´t have any "Import" link or tab. Maybe I´m missing something?

Thanks for your help!! Rosamunda

# Answer
Reading under the heading "Disqus Migrate Sub-module" on the module page, the import functionality/disqus migrate module seems to only be for the drupal 6 version.
> 0 votes

# Answer
here is some sandbox project for drupal 7, that import comments from disqus to drupal core comments
> 1 votes

---
Tags: 7, comments
---


# Question
Title: How do I remove the blank space that remains after removing "logo" and "site name" and "site slogan"?
I have removed the "logo", "site name", and "site slogan" from the Theme Settings menu:

Home \> Administration \> Appearance \> Settings \> MyTheme

Unchecked: \[Logo\], \[Site Name\], and \[Site Slogan\] under "Toggle Display".

For some reason, these things appear above the header and not in the header, so I am disabling them. But, there is still a small space left. It appears to be coming from a small div containing an anchor tag:

```
 <div id="skip-link">
    <a href="#main-menu" class="element-invisible element-focusable">Jump to Navigation</a>
  </div>

```

Can someone help me to remove this the "right way".. or advise me if I'm doing something wrong?

If it helps, I'm using the Zen Theme.

# Answer
You could do it in the CSS, {display:none;} or {visibility:none;}. As far as screen readers are concerned, I am not sure how they would work. I googled and found this Link.
> 0 votes

# Answer
You need to edit the CSS file that has the property:

```
<div id="skip-link">

```

Find that rule set in the CSS file and add this line to remove it from the page.

```
#skip-link {
    display: none;
}

```

That will remove it from displaying on the webpage. If there is other lines in the decleration you can remove them or not.
> 0 votes

---
Tags: theming
---


title: Adding Adsense on a CCK field

text:
# Question
Title: Adding Adsense on a CCK field
First of all I'm using drupal 6.19. I'm trying to add adsense on my site unsuccessfully. =/ I want to put my adsense on a CCK field but isn't working. When I put the code on a block everything works fine. But in a CCK field I'm in trouble. Both, block and CCK field, are set to input format FULL HTML. I don't know why doesn't work in the CCK field. Can anyone help me?

# Answer
> -1 votes
Try stripping the line breaks. Like they should be all going in one line.

---
Tags: entities, javascript
---


# Question
Title: Is it possible to change fieldset title if collapsed with #states
I'm trying to use #states in form api to change the title of a fieldset based on his collapsed states.

so far here's my code :

```
$form['advanced'] = array(
  '#type' => 'fieldset',
  '#title' => t('Advanced search'),
  '#collapsible' => TRUE,
  '#collapsed' => TRUE,
  '#attributes' => array('class' => array('search-advanced', 'clearfix')),
  '#states' => array(
    '#title' => array(
      array('fieldset#edit-advanced' => array('#collapsed' => 'Hide advanced search')),
    ),
  ),
);

```

I've tried different things, but without success.

Thanks a lot.

# Answer
> 3 votes
It is true that there were some issues with #states and fieldsets, such as #states can't hide/show fieldsets, but in your case the code doesn't work because #title is not an handled state, and #collapsed is not a handled state for the remote condition.

The list of the implemented states is given in drupal\_process\_states():

* enabled
* disabled
* required
* optional
* visible
* invisible
* checked
* unchecked
* expanded
* collapsed

The states used for the remote conditions are the following:

* empty
* filled
* checked
* unchecked
* expanded
* collapsed
* value

It would also be hard to implement that, as the state needs to be boolean, and the remove condition says the value of the state for the other form field.

For example, if *foo* is a select list, the state for a form field could be the following one.

```
'#states' => array(
  // Show the settings if 'bar' has been selected for 'foo'.
  'visible' => array(
    ':input[name="foo"]' => array('value' => 'bar'),
  ),
),

```

This state would make the form field visible when the value selected from the list is *bar*.

---
Tags: 7, javascript
---


# Question
Title: How to add a CSS class to some certain pages depending on the path alias?
I'm trying to add a CSS class to some certain pages for some certain menu styling depending on the current alias path. It works well with the following function but I'm wondering is there another way to split the current alias parts so I can use them as arguments? Here's my present function:

```
function mytheme_preprocess_html(&$vars) {

  $path = drupal_get_path_alias($_GET['q']);
  $aliases = explode('/', $path);

  if (isset($aliases[2]) && $aliases[2] === 'foo') {
    $vars['classes_array'][] = 'bar';
  }
}

```

# Answer
You should be using Drupal's arg function: https://api.drupal.org/api/drupal/includes%21bootstrap.inc/function/arg/7

Something like this should work:

```
function mytheme_preprocess_html(&$vars) {

    if (arg(2, drupal_get_path_alias()) == 'foo') {
        $vars['classes_array'][] = drupal_clean_css_identifier(arg(2, drupal_get_path_alias()));
    }
}

```

Added drupal\_get\_path\_alias() as an arguement of arg() as suggested by @koivo
> 3 votes

# Answer
There was one answer from a guy which now is deleted suggesting to use `arg(2)` instead. I commented after trying it out that `arg()` doesn't seem to work with alias paths. Well, I now found out it does and that's how by passing the Drupal alias path into the arg() function:

```
if (arg(2, drupal_get_path_alias()) === 'foo') {
  $vars['classes_array'][] = 'bar';
}

```
> 3 votes

---
Tags: 7, theming
---


# Question
Title: public:// urls being printed in source code
I have a weird issue with a Drupal website I am working on. The site has an audio player, jplayer, that plays MP3 files. Some of the files do not play. The only difference I've found between the files that play and the ones that do not is that the files that do not play have a `src` in the form of `public://audio/example.mp3`. The ones that do play have a typical url of `http://example.com/audio/example.mp3`. Is there anything that I should investigate as to why some of the urls get printed out with a `public://` url?

This is the source code that makes the jplayer work..

```
<?php

/**
 * Implementation of theme_menu_tree().
 */
function wyep_menu_tree(&$variables) {
  return '<ul class="menu">' . $variables['tree'] . '</ul>';
}

/**
 * Implementation of theme_file_link().
 */
function play_file_link($variables) {

  //watchdog('theme_file_link', '<code><pre>' . print_r($variables, TRUE) . '</pre></code>');

  global $base_path, $base_url;

  $file = $variables['file'];

  $file->url = str_replace('public:/', $base_url . '/' . variable_get('file_public_path', 'files'), $file->uri);

  switch ($file->filemime) {
case 'audio/mpeg':
    return '<script type="text/javascript">
              jQuery(document).ready(function(){
                jQuery("#jquery_jplayer_' . $file->fid . '").jPlayer({
                    ready: function (event) {
                        jQuery(this).jPlayer("setMedia", {
                            mp3:"/files/' . $file->filename . '"
                        });
                    },
                    cssSelectorAncestor: "#jp_container_' . $file->fid . '",
                    swfPath: "' . $base_url . '/sites/all/libraries/jplayer/Jplayer.swf",
                    supplied: "mp3",
                    wmode: "window"
                });
              });
            </script>

                <div id="jquery_jplayer_' . $file->fid . '" class="jp-jplayer"></div>

                <div id="jp_container_' . $file->fid . '" class="jp-audio">
                    <div class="jp-type-single">
                        <div class="jp-gui jp-interface">
                            <ul class="jp-controls">
                                <li><a href="javascript:;" class="jp-play" tabindex="1">play</a></li>
                                <li><a href="javascript:;" class="jp-pause" tabindex="1">pause</a></li>
                                <li><a href="javascript:;" class="jp-stop" tabindex="1">stop</a></li>
                            </ul>
                            <div class="jp-progress">
                                <div class="jp-seek-bar">
                                    <div class="jp-play-bar"></div>
                                </div>
                            </div>
                            <div class="jp-time-holder">
                                <div class="jp-current-time"></div>
                                <div class="jp-duration"></div>
                            </div>
                        </div>
                        <div class="jp-no-solution">
                            <span>Update Required</span>
                            To play the media you will need to either update your browser to a recent version or update your <a href="http://get.adobe.com/flashplayer/" target="_blank">Flash plugin</a>.
                        </div>
                    </div>
                </div>';
  }

}

```

# Answer
Drupal 7 uses stream wrappers instead of "file paths" to reference files in the public and private upload directories. If you want to research that more, the rabbit hole starts here - http://drupal.org/node/555118

In a "vanilla" D7 setup "public://" is equivalent to the D6 "sites//files" or "sites/default/files" directory. These directories still exist in D7 but have been moved in D8 - using a stream wrapper means the files can be moved *anywhere*, even a remote location, and still be referenced in a consistent fashion if you update the default stream wrapper.

Clive's comment referencing file\_create\_url() is a function that takes a stream uri and converts it to a url that a web browser can use.

The problem is that your server-side code delivering media to jPlayer is not sending URIs in the right format. If it's a contrib module, you should open an issue in the queue and link to it here; Clive or myself might be able to provide a patch.

I'm going to assume that the module you're using was originally released in D6 and then upgraded at some point to D7? (maybe the upgrade didn't go so well :P)

Edit:

Based on the code that was posted after I originally put this answer up I'd suggest looking into two things:

1. Shouldn't `$file->url = str_replace('public:/', $base_url . '/' . variable_get('file_public_path', 'files'), $file->uri);` be `$file->url = file_create_url($file->uri);` ?
2. The "setMedia" action for jPlayer, I can't remember off the top of my head if it needs to be a url or a file path, but if it's a url shouldn't you be using $file-\>url? if it's a file path shouldn't it be generated by drupal\_realpath()?
> 2 votes

# Answer
FROM drupal.org

https://drupal.org/node/877212

**file\_create\_url()**: Translate a filepath like public://somefile.txt into an accessible URL like http://example.com/sites/default/files/somefile.txt.

**Example:** `$url = file_create_url("public://somefile.txt");`
> 0 votes

---
Tags: 7, uri, files
---


title: taxonomy menu links change with path

text:
# Question
Title: taxonomy menu links change with path
Is there any way to change taxonomy menu links depending on path? I have a Taxonomy menu in a block with different levels and depending on path I would like to change the taxonomy level depending where the user is. Context maybe?

Thanks in advance!!

# Answer
Sounds to me like you ACTUALLY want Menu block in tandem.

> So… have you ever used the Main and Secondary menu links feature on your theme and wondered “how the hell do I display any menu items deeper than that?”

I *think* the following is what you're after, but the module is pretty configurable if I'm mistaken.

Create your taxonomy menu as you normally would, and instead of putting that menu block in the sidebar (or wherever), put a menu block generated block there. Then in the settings for the menu block click *Advanced*. Under this tab, there's now a chekbox titles *Make the starting level follow the active menu item*. If you check that box, then the top level will reflect the current page.
> 1 votes

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


# Question
Title: What is the Features specific data in a Features module's .info file
I'm not sure if this is a Features module question or simply a module construction question.

I have a module which was constructed with Features, which I have never used before. In the `.info` file of the module there are a lot of lines that read similar to `features[something][] = something`.

What is this and where is it used in the module?

# Answer
> 4 votes
Some of the documentation is sparse (still!?) https://drupal.org/node/1720098

The entries in your `.info` file tell Features that that item of your configuration is controlled by Features and not say Drupal core. You'll see stuff like `ctools` or `views` in there. In the main `features.inc` file the features info hook will require those API dependancies.

Based upon other lines in the info file such as:

```
features[ctools][] = strongarm:strongarm:1
features[ctools][] = views:views_default:3.0
features[user_permission][] = create features_test content
features[views_view][] = features_test

```

These lines would say, features uses Strongarm to read/write configuration of variables, and Ctools integration. Then there is some view `features_test` and some user permission exported `create features_test content`.

From the documentation page i linked these `.info` configuration values then:

> They are called during hook\_module\_enable/disable to fire the right stuff in the right places.

By Features itself. The info file contents tells Features what its managing. The `.inc` files include the dynamic configuration values needed per `.info` item entry (usually in terms of plain Drupal hook\_info configuration definitions that'd you basically be making in code anyways).

I recommend reading the Features API and Readme:

http://drupalcode.org/project/features.git/blob/refs/heads/7.x-1.x:/API.txt

http://drupalcode.org/project/features.git/blob/refs/heads/7.x-1.x:/README.txt

---
Tags: 7, features
---


# Question
Title: .inc files in Features - how are they being included?
Regarding the features module: I am working with a module which was created by features. I see a lot of .inc files in the module, but see very few actually included. Does this make any sense? I know that they are all being used and are creating fields etc.

# Answer
Most include files exported by features are included on-demand by the modules that define that type of component. For instance, `example.views_default.inc` is included by the views module when loading default views. This is a common pattern in Drupal, not something that is specific to Features.
> 6 votes

---
Tags: 7, features
---


# Question
Title: Allow a role to assign user roles but not to manage user permissions
on Drupal 7 how I can give to the "special" role the possibility to manage roles of other users (add a role to a user, remove, add more than a role, etc.), but not the possibility to manage all user permissions?

# Answer
> 3 votes
Use the role delegation module

> This module allows site administrators to grant some roles the authority to assign selected roles to users, without them needing the administer permissions permission.
>
> For each role, Role Delegation provides a new assign ROLE role permission to allow the assignment of that role.

---
Tags: users
---


# Question
Title: Domain Name language negotiation and mobile prefix m
I have a question regarding the domain name language negotiation.

I have 3 languages and the following domains:

* de.domain.com
* en.domain.com
* fr.domain.com

When I set this as the domains for each language and use the domain name language negotiation everything works as expected.

My problem is that I have an adaptive mobile theme and I have to use following domains for that:

* m.de.domain.com
* m.en.domain.com
* m.fr.domain.com

How can I achieve that those urls point to the correct language (de, en, fr). Now, all point to the default language (de).

Any help?

# Answer
Take a look at the Language Negotiation API, specifically hook\_language\_negotiation\_info\_alter. With this hook, you can replace the default URL based language negotiation callback function with one that respects the `m.` prefix.

Something like this should get you started.

```
function mymodule_language_negotiation_info_alter(&$negotiation_info) {
  // Replace the core function with our own function.
  module_load_include('language', 'inc', 'language.negotiation');
  $negotiation_info[LANGUAGE_NEGOTIATION_URL]['callbacks']['language'] = 'mymodule_from_url';
  $negotiation_info[LANGUAGE_NEGOTIATION_URL]['file'] = drupal_get_path('module', 'mymodule') . '/mymodule.module';
}

function mymodule_from_url($languages) {
    // Your version of locale_language_from_url() that ignores the m. prefix.
}

```

For reference, the core function that handles language negotiation based on URL is locale\_language\_from\_url.
> 1 votes

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


# Question
Title: Show term description when grouping by taxonomy term
I have one vocabulary with two terms, apples and oranges. Nodes are tagged with either one or the other. I created a view at /fruits that shows the nodes tagged with either term. I also have the field settings set to `Group by Taxonomy term` which works great.

It places the taxonomy term heading at the top of each section. Now on to my question... Is it possible to display the term description under each taxonomy heading? So it would look like below.

---

### **Oranges (Taxonomy Title)**

Oranges are probably the best fruit on earth. (Term Description)

(Results of view)

# Answer
One option for solving this is to rewrite the output of your view fields to meet your formatting requirements, which consists solely of configuration steps -- no code changes needed :).

* On your view, add the **Taxonomy: Term** field and the **Taxonomy: Term description** field. Make sure the **Term** field is above the **Term description** field.
* Next, edit the **Term** field, select **Exclude from display**, and click **Update**.
* Now, edit the **Term description** field and check **Rewrite the output of this field**. You can set this **Term description** field to include the formatting you desire of your Term name and Term description using the available tokens, which are listed in the **Replacement patterns** fieldset.

For example, try placing the following into the rewrite **Text** textarea:

```
<h1>[name]</h1>
<p>[description]</p>

```

Be sure to click **Update** after you have finished configuring the **Term description** field.

* Last, in your field settings, select **Group by Term description** and voilà, you should have all the data you want in each grouping section. As long as your term names or term descriptions are unique, this should group as expected.
> 5 votes

# Answer
A simple way is to insert a Term-id field also in your view and rewrite results with PHP in order to load the term from the tid and get its description like

```
$term = taxonomy_get_term($tid, $reset = FALSE);
echo $term->description;

```

if i remember Drupal 6 correctly anyway ..
> 0 votes

# Answer
Drupal 7 may require the use of relationships. At first I was confused about the missing Taxonomy: Term description in my view but then I read this in the Views docs.

> Drupal 7 made significant changes to Taxonomy. Because of this, many taxonomy functions Views can perform are now part of relationships. If you can't find the filter you need, add either the related taxonomy terms relationship, or a relationship on the specific taxonomy field.

Also this comment was very useful for me. https://drupal.org/node/258287#comment-6144566
> 0 votes

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


# Question
Title: What is the best practice to index remaining content with solr?
First please forgive me if this a recurrent question (I cannot find a solution otherwise). I want to avoid waiting my cron to index remaining content with solr. What is the best solution to have all the content automatically indexed??

I have done an alternative solution: I have created a cron job on my server where I run every two minutes the drush solr-index command.

What do you think about this solution? (Is it heavy to call every 2 minutes even if no content found?)

Thanks for your advices

# Answer
> 0 votes
The Apache Solr configuration page (/admin/config/search/apachesolr) provides a button under actions to index all queued content, which should send everything left in the queue. That can put a great deal of load on your server, so you should only use that option with some thought about how/if it will effect your users.

When I did a large import recently I went ahead and pushed it all the Solr as quickly as possible, but I was able to do that before the site went live. That meant that when users arrived the search index was complete. If I'd had to do it while it was in production I would have spread it out to make sure the server was very responsive when they first started to use it.

The load that comes from extra cron runs is site specific. Some sites you can't really see the effects other sites it can have a noticeable slowdown from cron runs. I have worked with sites with light cron loads (or powerful servers) that run cron once a minute to allow functions like the Solr index or external data syncs stay very close to current. The 'right' answer here depends on your site, your server, and your users.

Also remember that you do not benefit from having cron run faster than it takes for an individual cron run to complete. If you have your Solr sync setup to send lots of large files for indexing in each pass it is possible your cron runs take more than two minutes.

---
Tags: search, cron
---


title: Help with hovering field data

text:
# Question
Title: Help with hovering field data
Drupal demi-gods,

I have a scenario as follows in a "Reference data" content type

Code Description
NY New York
CA California
CO Colorado and so on

I want to have say an Address content type that references these state codes, simple enough, define a node reference for the content type, but in addition, i want to be able to hover over the drop down box of states, in the address content, and for Drupal to list the state in a hover text.

Can anyone tell me if there is any functionality that provides this, or does it require coding? If it does require coding, which file should I be modifying?

Thanks heaps, I've been struggling with this for a few days now.

Geoff

# Answer
> 0 votes
A view with an exposed filter is what you are looking for.

Create a view with the fields that you want to show, and select the state code field as an exposed filter. Then the view will display only the content related to the state code selected by the user. The view may contain only one field, or many. If the relevant fields are in different entity/content types, you will need to define a Relationship in the view to *connect* them using an entity or node reference field.

Using Views you can get almost *everything* that you want if all the data involved is related. If you give us more concrete details about what you want to achieve, I could give you precise details of how to configure the View that will solve your problem.

---
Tags: theming
---


title: MYTHEME_form_element_FORMID?

text:
# Question
Title: MYTHEME_form_element_FORMID?
I have an override for my theme called:

corporate\_form\_element()

The base hook was copied and tweaked. Multiple forms have to be modified and in some cases some individual elements did too. I typically get around this by checking conditionally whether markup is needed.

For instance I check for checkboxes and theme accordingly:

```
<?php
if($element['#type'] == 'checkbox'){
    return '<div style="width: 30%; float: left">' . $output . '</div>';
}
?>

```

However now I wish to theme two text fields quite differently than most others in forms and I have discovered there is no way to detect which form the current call is for. I have "hacked" this by adding custom '#fields' in my forms elements (either those I provided explicitly or hooked into via hook\_form\_alter) and checking for this.

This works but is a horrible hack and not very clear.

What is the preferfed drupal way of achiving this result? Can I overrivde MYTHEME\_form\_element\_FORM\_ID or something similar? I know this can be done to MYTHEME\_form\_alter but what about individual elements????

Alex

# Answer
Using custom properties is not an hack; quite the opposite, it is a perfectly fine way to achieve what you want. It allows you to identify the form elements that need to be altered, which is what you want.

In fact, custom properties are normally used from Drupal, which uses the following code for fields associated to an entity.

```
  $element = array(
    '#entity' => $entity,
    '#entity_type' => $instance['entity_type'],
    '#bundle' => $instance['bundle'],
    '#field_name' => $field_name,
    '#language' => $langcode,
    '#field_parents' => $parents,
    '#columns' => array_keys($field['columns']),
    '#title' => check_plain($instance['label']),
    '#description' => field_filter_xss($instance['description']),
    // Only the first widget should be required.
    '#required' => $delta == 0 && $instance['required'],
    '#delta' => $delta,
  );

```

Custom properties are also the Drupal 7 way to pass variables to theme functions. For example, the following code is using theme\_table() to render part of a page.

```
  $build['node_table'] = array(
    '#theme' => 'table',
    '#header' => $header,
    '#rows' => $rows,
    '#empty' => t('No content types available. <a href="@link">Add content type</a>.', array('@link' => url('admin/structure/types/add'))),
  );

```

Passing `$build` to drupal\_render() produces the same output produced by the following code.

```
$html = theme('table', array('header' => $header, 'rows' => $rows, 'empty' => t('No content types available. <a href="@link">Add content type</a>.', array('@link' => url('admin/structure/types/add')))));

```

The alternative would be adding a #after\_build or #process function to the form elements, but those functions are called before the form element is rendered, which means they can just alter the form element properties.

Those functions get access to the content of `$form_state`, and get `$form_state['input']['form_id']` or `$form_state['input']['form_build_id']`. This is what the documentation for drupal\_build\_form() says about `$form_state['complete form']`:

> A reference to the `$form` variable containing the complete form structure. #process, #after\_build, #element\_validate, and other handlers **being invoked on a form element** may use this reference to access other information in the form the element is contained in.

To add a #after\_build function (which gets `$element` and `&$form_state` as parameters), you should implement hook\_element\_info\_alter() to change the form element definition.

Notice that theme\_form\_element() is defined as theme wrapper for every form element, similarly to what done with the following code for the textfield form elements.

```
  $types['textfield'] = array(
    '#input' => TRUE,
    '#size' => 60,
    '#maxlength' => 128,
    '#autocomplete_path' => FALSE,
    '#process' => array('ajax_process_form'),
    '#theme' => 'textfield',
    '#theme_wrappers' => array('form_element'),
  );

```

As side note, every theme function has its own preprocess functions; for example, for theme\_textfield() those functions are `hook_preprocess_textfield()`. They can suggest a different theme function to be used by adding values to the `$variables['theme_hook_suggestions']` array. (`$variables` is the parameter passed as reference to the theme preprocess functions.) Unfortunately, the theme and the theme preprocess functions don't get any reference to the form being build.

### References
> 1 votes

---
Tags: theming
---