# Question
Title: Taxonomy menu - link to first node associated with term?
I have a taxonomy menu block using the vocabulary 'Projects' that links to the terms: 'Bridges', 'Buildings' and 'Boats'.

Currently, each menu item links to a page that lists teasers of all the nodes associated with the menu term. For example, I click on 'Buildings' and it goes to a page with teasers of all nodes associated with 'Buildings'.

How could I have the menu term link to the latest node associated with that term directly? To continue the example, I click on 'Buildings' and it takes me to the latest 'Buildings' node.

The list of teasers is unnecessary as I will be employing elements of the teasers in an aside on each node directly.

# Answer
I figured it out; here's the solution in case anyone else needs this functionality.

Forget the Taxonomy Menu module. We'll build the functionality with a view.

1. Make a taxonomy term view (under Show when creating a view).
2. Under Advanced, add this Relationship: Taxonomy Term - Representative Node. You can leave all the settings the same, but I suggest checking 'Require this relationship' so empty terms will not get linked
3. Also Under Advanced, change Use aggregation to Yes
4. Add a filter for Taxonomy Vocabulary (with whatever vocab you want)
5. Add a Content:Path field, exclude it from display and check 'Use absolute link'
6. Add a Taxonomy Term:Name field and check Output this field as a link. For the Link Path use the Path Replacement Pattern from the Path field we just added (usually \[path\]).
> 1 votes

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


# Question
Title: Extending EntityFieldQuery. Which variables should I define?
I have been playing around with extending EntityFieldQuery, and I was wondering which variables I should define on the class. I am also a beginner in OOP so this is an experiment.

```
class nodematcher extends EntityFieldQuery
 {
  private $pathtomatch = NULL;
  private $nodestocheck = array();
  private $matchingnode = NULL;
  private $query = NULL;
  private $results = NULL;
  public $nodes = NULL;
  public $path = NULL;
  public $json = NULL;
  public function __construct()
   {
    $this->query = New entityFieldQuery;
    $this->query->entityCondition('entity_type', 'node')->fieldCondition('geoslate_slate_entry_path', 'value', '', '<>');
    $this->results = $this->query->execute();
    foreach($this->results['node'] as $result)
     {
      $this->nodestocheck[] = $result->nid;
     }
    $this->nodes = entity_load('node', $this->nodestocheck);
    return $this->nodes;
   }
  public function lookupfullpath($path)
   {
    foreach($this->nodes as $key => $value)
     {
      $wrapper = entity_metadata_wrapper('node', $value);
      $entry_path = $wrapper->geoslate_slate_entry_path->value();
      if(reset($entry_path) == $path)
       {
        $this->matchingnode[] = $wrapper->nid->value();
       }
     }
    $loadedentities = entity_load('node', $this->matchingnode);
    //$this->json = drupal_json_encode($loadedentities);
    return $loadedentities;
   }
 }

```

# Answer
> 0 votes
```
class nodematcher extends EntityFieldQuery {
  public function __construct() {
    $this->query = New entityFieldQuery;

```

This doesn't make any sense. You are either subclassing `EntityFieldQuery` or you are using a delegate pattern. Doing both makes little sense. What you wanted here is perhaps `parent::__construct` and wherever you used `$this->query` just use `$this`.

---
Tags: database
---


# Question
Title: How do I enable rich text editing on all my long text fields?
I have a node with 3 long text fields and I want to make rich text editing available on them all. So far all my experiments with Wysiwyg have only resulted in one of the long text fields getting an editor. So what editor/configuration will give me rich text editors on them all?

# Answer
Now they are all working. I think what happened is that since I have posted the question I have rebooted Apache and MySQL (as well as I may have cleared a cache or two) and that fixed the problem. I've tested a few editors, and now they all seem to work across multiple text areas.
> 0 votes

---
Tags: 7, wysiwyg
---


# Question
Title: How to add css to a form according to the user's role?
I know how to add css to individual form types using:

```
function theme_form_alter(&$form, &$form_state, $form_id) {
  switch ($form_id) {
    case 'formtype_form':
      global $theme;
      $form['#attached']['css'] = array(
        drupal_get_path('theme', 'projectname') . '/css/new.css',
      );
    break;
 }
}

```

but how can I restrict this attached css to users with a single role?

# Answer
You need to call `$user` object and compare user role with current logged in user.

```
function theme_form_alter(&$form, &$form_state, $form_id) {
  global $user, $theme;

  switch ($form_id) {
    case 'formtype_form':
      // change user_role to whatever role you want to restrict this css
      if (in_array('user_role', array_values($user->roles))) {
        $form['#attached']['css'] = array(
          drupal_get_path('theme', 'projectname') . '/css/new.css',
        );
      }
      break;
  }
}

```
> 1 votes

---
Tags: forms, theming
---


# Question
Title: Adding more fields to the registration process
In Drupal 7, is there a way to add more fields to the registration process? I was thinking along the lines of birthday, fullname, gender, twitter, etc. Also how do I access this data once it's in, so I can output it to my template files?

# Answer
Since D7, field management is included in the core. Almost every kind of content has now the ability to be managed with fields.

You can go to admin/config/people/accounts/fields to manage user fields. There is also a tab for managing the display.
> 7 votes

# Answer
Administration » Configuration » People » Account settings » Manage fields

Make sure once again by edit the new fields and its check box for Required field and Display on user registration form will be enabled.
> 0 votes

---
Tags: 7, users
---


# Question
Title: How to implement 'Starts With' for exposed filter of User ID
I have a Page based on a View with an Exposed Filter which is the User ID. So the Search form that appears shows the User ID as the standard 'lookup' of users. I don't want that. I want to be able to have the search field be a standard text field and the results be a 'starts with'.

Eg.

Enter User: \[Fra \]

Would return

Francis Frank Friend

How is this done?

# Answer
If you use the "User: Name" filter it will give you an autocomplete text field where you can start typing and it will show you a list of patching users as you type.

That field will not let you enter partial user names though, you must select a user from the autocomplete (you can have multiple comma delimited values if you like).

To match partial user names, use the "User: Name (raw)" filter.

This one allows you to have a text field that doesn't have any validation. This field can have the operator set to "Starts with".
> 1 votes

---
Tags: users, search, views
---


# Question
Title: How to make uploaded file permanent to node without node submit
My module automatically save new empty node when user create new node and redirect to edit this node. Now, is it possible to make uploaded file on \_node\_edit form without submitting form?

edit: When user visit "node/add/article" for example, my module save new node type article and redirect user to "node/NID/edit" to edit this node. In node have fields type "image" and "file". User upload image and file. Now, how to alter their (ajaxified) upload process to make this files permanent to node without click on "Save" button on node edit form?

# Answer
You could try the autosave module, which allows automatic saving of the node form via ajax while the user is editing the form.

If it doesn't do exactly what you are after it would be a great place to look for ideas on how to code it yourself.

Probably if it doesn't do exactly what you want the easiest path might be to make a patch for that module to add what you need, instead of writing something from scratch.
> 0 votes

---
Tags: 7, nodes, forms, media, files
---


# Question
Title: Recommendation On Search Form For People
We want to develop a 'Directory' of People in our organisation (a View) with search form that lets authenticated users search for one another by last name or User ID.

I'm looking for recommendations on the best way to do this as we will have literally thousands of 'People' and I don't want the standard widget with 'people' which I fear would be dreadfully slow. All I need is a text field and the SQL equivalent of...

```
Lastname LIKE('FRA%') OR UserID LIKE('FRA')

```

...where the user typed 'FRA' into the form. They would get all users (People) with a last name starting with 'Fra'.

Is there a pre-built module that someone can suggest that does this, or can someone provide some (basic) guidance on how to implement this on a View?

I looked at the default Search User tab and I didn't see a way to theme this to include various fields we will need such as the user's photo and so on.

TIA

# Answer
I would recommend using the views module.

This is kind of a duplicate of your other question How to implement 'Starts With' for exposed filter of User ID, where I explained how to do what you want with views.
> 0 votes

---
Tags: views, users, search
---


# Question
Title: Trigger 'Add another term' using javascript
Is there any way to simulate the click event of 'Add another term' using javascript? I tried like this

```
 jQuery('#edit-field-attribute-und-add-more').trigger('click');

```

but no effect

# Answer
Try this code

```
jQuery('#edit-field-attribute-und-add-more').click();

```
> 1 votes

---
Tags: forms, ajax, javascript
---


# Question
Title: Comments with Facebook Auth User and anonymous
I'm working in a site that needs some special behavior for comments.

The user will have anonymous and users connected with Facebook.

For comments, the site needs to allow anonymous comments posting but if the user is connected with Facebook the page will permit to the user make the comment with Facebook or as some anonymous user.

I been googling for a couple of hours some module that provides this functionality out of the box but I was not able to find one.

Does anyone knows some module to recommend me ?

Thanks in advance !

# Answer
You could try the disqus module, which uses the disqus service.

It is arguably better than using facebook comments because it also allows people to comment using other social network accounts, not just facebook.

It also allows guest commenting.

Depends on your requirements though as to whether or not that is an acceptable solution.
> 2 votes

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


# Question
Title: Custom php code using the site header and footer
I have a very complex page (Multiple Ajax calls and access to other three other mysql databases) that i would like to create within Drupal or find a way to embed it into Drupal. Now I do not want Drupal to manage the page, i would only like to just pull the header, navigation and footer from Drupal and manage the "content" with my own code manually. In Wordpress this is very easy to do but in Drupal it does not seem to be straightforward. What is the best way to accomplish this in Drupal.

can custom modules handle that? can views handle that? what are my best options?

Note that i just want to know if it is possible and how do i embed my own code into Drupal without having Drupal manage the code.

# Answer
Yes, you'll generally solve this by writing a custom module. In your .module file you'll probably want, as a minimum:

1. An implementation of hook\_permission to provide access control to your content
2. An implementation of hook\_menu to define the routing to your page, in other words which URLs will cause your custom code to be invoked.
3. The actual callback which generates the content.

In the callback you can use whatever PHP code you want, though if you do use Drupal's APIs and established good practice you'll be less likely to create security weaknesses and your code will work better with other modules. That's likely to save you time in the long run.
> 0 votes

---
Tags: 7
---


# Question
Title: How to access $vars['some'] variables in html.tpl.php template
In the template.php, I am using the following code for `mytheme_preprocess_page()`.

```
 // Return nid for node of type "interface_configuraitons".
    $nid_config = db_select('node', 'n')
        ->fields('n', array('nid'))
        ->fields('n', array('type'))
        ->condition('n.type', 'interface_configuraitons')
        ->execute()
        ->fetchCol();
    //load the configurations
    $configurationNode = node_load($nid_config);
    $interfaceConfig = array();
    $interfaceConfig['driver_url'] = $configurationNode->field_driver_url['und'][0]['value'];
    $interfaceConfig['driver_port'] = $configurationNode->field_driver_port['und'][0]['value'];
    $vars['interfaceConfig'] = $interfaceConfig;

```

While `$interfaceConfig` is initialized and available in any of the page templates, it is `NULL` in the html.tpl.php template. I was trying to run `mytheme_preprocess_html()` without success.

How do I get this preprocessing take place, so it is available in the html.tpl.php template file?

# Answer
> 2 votes
The general rule for any THEMEHOOK.tpl.php file (where THEMEHOOK is something like 'html', 'page', 'node' etc.) is:

1. The default variables are set in `template_preprocess_THEMEHOOK()` (eg. template\_preprocess\_html)
2. Any module can add variables using `MODULENAME_preprocess_THEMEHOOK()` (eg. toolbar\_preprocess\_html)
3. The active theme can add variables using `THEMENAME_preprocess_THEMEHOOK()` (eg. bartik\_preprocess\_html)

The `$variables` array (sometimes called `$vars`) is passed on from function to function in the above order, so each function can expand on or overwrite the variables added before.

# Answer
> 0 votes
A variable that is set from `template_preprocess_page()` or an implementation of `hook_preprocess_page()` made from a module or a theme is not available to the implementation of `hook_preprocess_html()` made from a module or a theme.

A variable is available only to specific preprocess functions, which in your case are:

* `template_preprocess()`
* `template_preprocess_html()`
* `MODULE_preprocess()`
* `MODULE_preprocess_html()`
* `ENGINE_preprocess()`
* `ENGINE_preprocess_html()`
* `THEME_preprocess()`
* `THEME_preprocess_html()`
* `template_process()`
* `template_process_html()`
* `MODULE_process()`
* `MODULE_process_html()`
* `ENGINE_process()`
* `ENGINE_process_html()`
* `THEME_process()`
* `THEME_process_html()`

MODULE is the name of any enabled module, THEME is the theme currently used to render the page, and ENGINE is the name theme engine used from the theme currently used to render the page.

Notice also that all those `*_preprocess()` and `*_process()` functions don't share the variables when called for different template files.

### Reference

---
Tags: theming
---


title: Change waiting time for new user

text:
# Question
Title: Change waiting time for new user
The registration of my website works by user email verification.

How can I change a waiting time of new user activation? I have many spam users that register at my website; they register and never activate the account.

# Answer
> 2 votes
The project LoginToboggan has a feature to auto-cancel these after a preset time. From the LoginToboggan features list:

> Optionally have unvalidated users purged from the system at a pre-defined interval (please read the CAVEATS section of INSTALL.txt for important information on configuring this feature!).

For more ideas about how to deal with spam registrations, see: How to deal with unverified users in Drupal?

# Answer
> 3 votes
In addition to what @Gisle Hannemyr said, I would recommend the spamicide module (sets hidden field that if it is filled by a bot on registration, it will not create the account) and the re-captcha module on your registration forms.

---
Tags: users
---


# Question
Title: How to link the title in a teaser to the main content?
I have created a view that provides teaser content for different nodes.

This teaser content carries a main title and some more fields. I want to make the title as a link, which when clicked, takes the user to a page that displays the full node.

I tried enabling the "Link this field to its entity" for the title field in its view, but clicking on that link takes me to a page like:

```
http://localhost:8082/node/<node id>

```

I want it to go to a prettier looking URL like:

```
http://localhost:8082/<pretty URL>

```

How can I achieve this?

# Answer
If you are using a node title field, then the "Link this field to its entity" option should definitely work.

By default it will link to

localhost:8082/node/123

where 123 is the node ID of the node.

If you want a nicer URL, like

localhost:8082/title

where title is the title of the node (or something similar), try the pathauto module, which allows you to define settings that automatically create pretty urls for nodes (and users and taxonomy terms, etc.). The pretty urls can use tokens, like \[node:title\], which will be replaced by the title of the node for example.
> 1 votes

# Answer
The PathAuto module, (already mentioned by rooby) will "prettify" URLs for you automatically.

If you *instead* wants to do this yourself, check out *Admin/Configuration/URL aliases*. This let you create aliases by hand (such as "Title" for "node/123").
> 1 votes

---
Tags: views
---


title: Show field's help text on node page

text:
# Question
Title: Show field's help text on node page
I'd like to achieve the following:

I'd like to give help text for a field in a content type, and I would like to show that help text on the node page as well.

I've looked at `$content` in `page.tpl.php` and `$variables` in `theme_field()` but these variables doesn't seem to contain these help texts.

How can I make these help texts appear?

# Answer
> 4 votes
You can get access to help by use field\_info\_instance function in Your template.php

At the beginning let's assume that You have a field called '**spagetti**' created in content type '**Article**'. Also, in this case, **mytheme** is Your default theme.

First, edit mytheme's template.php file and put into following code:

```
/**
* Implements template_preprocess_field
*/
function mytheme_preprocess_field(&$variables) {
  $field_name = $variables['element']['#field_name'];
  if($field_name == 'field_spagetti') {
    //Get help ('description' parameter) of field Spagetti
    $instance = field_info_instance('node', $field_name, 'article');
    //Add new parameter to the field
    $variables['element']['#help'] = $instance['description'];
  }
}

```

Now You can get help value from field array.

For example You may to create template for field spagetti: (field--field-spagetti.tpl.php) and render field inside:

```
$field = $variables['element'];

echo $field['#title'];
echo $field['#items'][0]['value'];
echo $field['#help'];

```

---
Tags: 7, entities
---


title: Individual account access control

text:
# Question
Title: Individual account access control
There might be a thread already with sililar question.- I am very new to drupal and looking for a module which will allow access to a user to their individual account. They should be able to see only their data and nothing else.They should not be able to manipulate site. This shouls be done just by email verification. I noticed that admin can grant access of a user after account creation but I am looking something smooth where anyone who creates account should see only their dat and later admin can change access level. Can anyone help me here.

# Answer
Drupal has only a very course access control structure for *viewing* content. For the uthenticated use role, you can set permission to 'access content' (Drupal 6) or 'view published content' (Drupal 7), but that's about it.

For more fine-grained access control, you need a node access control module. There is a page at the Drupal.org wiki giving an overview of node access modules. You may start by reading that and try to find a suitable module.

One particular module, named Flexi access, allows you to create access control lists consisting of a single user. This may be what you're looking for.

Disclosure: I am the maintainer of Flexi access.
> 1 votes

---
Tags: users
---


title: $user->uid is false even when logged in

text:
# Question
Title: $user->uid is false even when logged in
I have this code:

```
global $user;

if (!$user->uid) {
  drupal_set_message("You must log in to view this content.");
  drupal_goto('node/153', array('query'=>drupal_get_destination()));
}

```

`$user->uid` evaluates correctly when logged in as admin and editor, but users that don't have admin or editor roles have NO UID. Immediately before and after this code resolves to false, I visit site-root/user, and sure enough, I'm logged in.

What setting causes this? I've used this code many times to see if a user is logged in, and I can't find any setting that would cause this behavior.

# Answer
> 0 votes
I'm not yet clear on all the reasons, but the Secure Pages module was causing all users that weren't selected to go on https to return as null. Even `user_is_logged_in()` was returning false.

Moving a user to https upon login returned these functions' behavior back to normal.

# Answer
> 2 votes
Try using

```
global $user;

if(!$user->uid) {
  drupal_set_message("You must log in to view this content.");
  drupal_goto('node/153', array('query'=>drupal_get_destination()) );
}

```

---
Tags: users
---


# Question
Title: Unity launcher / OSX Spotlight like functionality for administration?
I'm fairly certain I've seen a module that provides a quick way of typing in, for example, the title, of an administrative page, and it would wisk you away to that page.

Much like the way Unity's launcher, OSX's spotlight or KDE's runner behaves, just inside your site instead of the desktop.

However, I can't seem to recall what it was called and google only came up with this abandoned sandbox.

# Answer
While coffee is probably the module you are looking for, i think switching on search in admin\_menu is way more productive - no roundtrip for the searches and you stay focused on the admin stuff. I bet you are using the admin\_menu anyway ? Just visit `admin/config/administration/admin_menu` and hit save - the search field should appear on the right hand side of the admin menu :)
> 4 votes

---
Tags: 7
---


# Question
Title: Views: Using Pager With Single Node, Multiple Fields
I created a node, that has multiple images on it. I want to use this node as the "source" for a views page showing a gallery of images.

I am having a few problems, the first and most major, is that the pager does not work.

I presume that is because all of the images are coming from a single node.

The second problem is more aesthetic; the images are not spaced correctly, and are not distributed across the width. I am not sure how to fix this problem either.

Any help would be greatly appreciated.

# Answer
You can use Nivo Formatter to make your image field to a slider. There is no need to build this with views.
> 0 votes

---
Tags: views
---


# Question
Title: How to allow a block on a page to load another block on same page in Drupal 7?
This is what I am looking for: On a page that has a block, I want the ability of a link within that block to load another block on the same page. (Specific case: a static page has a Views block containing a grid of team members with a 'see more' link under their picture. I want that link to load the user profile as a block, but on the same page - presumably this should use ajax).

Any help on how to do this would be supremely appreciated. Thanks.

Can't post images on Drupal.stackexchange yet but here are two screenshots to illustrate what I am looking to do: http://goo.gl/WBgcR

# Answer
As i understood from your problem, i think you can benefit from this lesson Ajax node reader in drupal http://www.youtube.com/watch?v=zyLmQtiSXgI

and there is a module called Ajax Blocks, can benefit u if u wnt to creat ur own module.

and as alternative solutions u can use http://drupal.org/project/colorbox\_node so the user profile loads in colorbox modal dialog
> 0 votes

---
Tags: views, blocks
---


title: Print a node display mode in a tpl file

text:
# Question
Title: Print a node display mode in a tpl file
I have a switch statement in my content type tpl file for 2 different view modes:

```
<?php
switch ($view_mode) {
case 'full' :
?>

//content for full view mode here

<?php break;
case 'custom-display-mode' : ?>

//content for custom display mode view mode here

<?php break;
} ?>

```

How can I print the teaser view mode within full display mode? Can I print it out in the same way you can print fileds in a tpl file?

```
<?php
switch ($view_mode) {
case 'full' :
?>

//content for full view mode here
//********* also print teaser view mode here **********

<?php break;
case 'custom-display-mode' : ?>

//content for custom display mode view mode here

<?php break;
} ?>

```

# Answer
Are you trying to print full display mode + teaser mode under full display mode? You can always render any display mode directly using node\_view as

> node\_view($node, $view\_mode = 'full', $langcode = NULL)

or with your example:

```
switch ($view_mode) {
case 'full' :

//content for full view mode here

$rendered_teaser = render(node_view(node_load($nid), 'teaser'));
print $rendered_teaser;

...

```

I would also recommend breaking your display mode templates out into separate files to simplify management. If your full mode should be the same as your teaser then using this method you can always just symbolically link the files on your server.
> 0 votes

---
Tags: 7, theming
---


title: Views slideshow without jQuery Cycle

text:
# Question
Title: Views slideshow without jQuery Cycle
I have a view slideshow that I managed to set up by following these instructions.

I want to use a responsive slider plugin instead of the jQuery Cycle plugin in *Views Style Settings*. How can I use this JavaScript code to create the slideshow.

# Answer
> 0 votes
Not sure why my question was downvoted but here is the answer.

I created a views block for my custom content type "Slider Images" and called it "Home Page Slider". I set the "Slider Images" Link and Image as Fields in the view and formatted it as an HTML list.

In my template.php file I used this function

```
function THEMENAME_preprocess_views_view(&$vars) {
   $view = $vars['view'];
   // if Home Page Slider View add the appropriate js and css
   if($view->name == 'home_page_slider') {
     // add needed javascript
     drupal_add_js(drupal_get_path('theme', 'THEMENAME') . '/js/responsiveslides.min.js');
     // add needed stylesheet
     drupal_add_css(drupal_get_path('theme', 'THEMENAME') .'/css/responsiveslides.css');
   }
}

```

to add my JS and CSS needed for the responsive slider plugin I wanted to use

# Answer
> 1 votes
This isn't exactly what you asked for, however:

I have tried a bunch of slideshows that claim various degrees of responsiveness and the best out of the box solution I have found that works as expected, is easy to set up, and is properly responsive, is the flexslider module, which can either be used by itself, or can be used with the views slideshow module.

If you haven't tried it it is definitely worth trying.

---
Tags: javascript, theming, views
---


# Question
Title: $form_state['redirect'] vs drupal_goto() in Drupal 6
What is different between $form\_state\['redirect'\] and drupal\_goto() to redirect user to a step in multi step forms in Drupal 6 ? I used $form\_state\['redirect'\] but no redirection happend so I use drupal\_goto() .

# Answer
> 2 votes
`$form_state['redirect']` is not well documented in 6, but my understanding is that when it's populated it will not always work (see the part about exceptions), so although that's documentation for 7, check that other elements of your `$form_state` are not interfering. If you are working with a multi-step form, it might be that you need to unset `$form_state['storage']` first.

`drupal_goto()` is simply a function will take the user away from the current page to whatever path you specify, and has a bunch of extra features for doing extra things (see the documentation). It is actually called anyway when your form redirects.

When a Drupal form is submitted,`$form_state['redirect']` overrides the default form redirect (which will take you to the form you've just submitted) and thus is calling `drupal_goto()` on your behalf. By putting it in a variable, you can ensure that Drupal handles, in the background, when to do the redirect, rather than you having to specify `drupal_goto()` directly and getting it wrong.

---
Tags: 6, redirection
---


# Question
Title: jQuery is not working for inserting data
I want to save data from a textbox on a button click. I am using jQuery AJAX for this task. Please note that I made this tags inside theme function.

```
function theme_user_post_block($vars) {
  $themeUserCommentInput = '';
  $themeUserCommentInput .= '<textarea id="txt_1" rows="1" cols="50"></textarea>';
  $themeUserCommentInput .= '<input type="submit" value="Post Comment" align="center" class="btnPostComment" id ="btn_1" / >';
  return $themeUserCommentInput;
}

```

This shows me the textbox and the button inside the page. This is my JavaScript code.

```
(function($) {
  Drupal.behaviors.PostComment = {
    attach: function(context, settings) {
      $('.btnPostComment', context).click(function(event) {
        var post = "&newcomment=Comment1&logid=log1";
        jQuery.ajax({
          url: 'postcomment',
          type: 'POST',
          dataType: 'json',
          data: post,
          success: function(data) {
            alert(data);
          },
          error: function(jqXHR, textStatus, errorThrown) {
            alert(textStatus + errorThrown);
          }
        });
      });
    }
  }
})(jQuery);

```

Next I create a custom page as follows.

```
function postcomment_menu() {
  $items = array();
  $items['postcomment'] = array(
      'title' => t(''),
      'type' => MENU_CALLBACK,
      'page callback' => 'user_comment_post',
      'access arguments' => array('access content'),
  );
  return $items;
}

function user_comment_post() {
  global $user;
  $cid = db_insert('user_comment')
          ->fields(array(
              'comment_user_id' => $user->uid,
              'reference_id' => $_POST['logid'],
              'comment_desc' => $_POST['newcomment'],
              'createdon' => REQUEST_TIME,
          ))
          ->execute();
  if ($cid != 0) {
    //GetUserComments($i);
    drupal_json_output("success");
  }
}

```

So I have done all things that is required for jQuery+Ajax Submit functionality. When I press "Post Comment" button it gives me error in alert says "errorundefined". The alert shows as a result of error inside the jQuery.AJAX function. Also the custom menu callback is also not getting called.

# Answer
> 0 votes
I added `'async': false` to the `jQuery.ajax` call as follows.

```
jQuery.ajax({
  url: 'postcomment',
  type: 'POST',
  dataType: 'json',
  'async': false,
  data: post,
  success: function(data) {
    alert(data);
  },
  error: function(jqXHR, textStatus, errorThrown) {
    alert(textStatus + errorThrown);
  }
});

```

The code is now working.

---
Tags: 7, forms, javascript, ajax
---


# Question
Title: Add a text field to OG subscription form
I would like to add a text field to the `og_ui_confirm_subscribe` form so that applicants can motivate their request to the owner of the group.

I don't have any problem to create the field and attach it to this form through a simple `hook_form_alter` but **I am lost once I have to link the text field to the user of the OG admin**...

I've googled but it doesn't seem to be a highly requested feature (only a - brief - mention found in OG 4.7 but this didn't led any further. It's weird since it means that admin are supposed to accept/deny only based on username...

By the way, these OG admin pages are very poor in terms of UI so I might think customizing them with Views & VBO; would this direction be a good way to go to easily get my text field?

# Answer
> 0 votes
I noticed it is possible to add this field (and others if needed) through the OG settings of the membership (cf. `admin/config/group/group-membership/manage/NAME_OF_YOUR_OG_MEMBERSHIP/fields`).

---
Tags: entities, organic-groups
---


# Question
Title: $base_path is not added to AJAX URL request in login form
I have a D7 site in a subfolder, and would like for AJAX requests to find the correct docroot folder.

When trying to login from `localhost/mysite/user`, AJAX sends a request to `localhost/system/ajax`. I've read that you can use the global variable `$base_path` for this, so I gave it a try, still the same error. I've checked in Firebug and indeed `Drupal.settings.basePath` does have the correct path. In settings.php is it written like this `$base_path = '/mysite/';`.

This made me wonder if the JS logic does not include the `$base_path` value by default and what would be a correct way to add this in. The site is tracked in Git, so I've also experimented with Apache configurations, such as ProxyPass, ProxyPassReverse, and ReWrite rules in order to prevent having to push changes that would risk breaking the site on the remote server.

I'm new to Drupal and not so experienced with Apache directives, any help here would be awesome :)

# Answer
> 0 votes
Took suggestion from Artur, problem solved by defining two domains in hosts file. One for the development environment and the other as a backup of the production environment. Then it was a case of setting up virtual hosts like this in `httpd.conf` (example for the development environment):

```
NameVirtualHost *:80
<VirtualHost *:80>
    ServerName www.project.devel
    ServerAlias project.devel *.project.devel
    DocumentRoot /www/mysite/devel/docroot/
    RewriteEngine On
    RewriteOptions inherit
</VirtualHost>

```

Login also worked even when domain was removed from the English language row in the `languages` table in the Drupal database. `$base_url` and `$base_path` also were commented out in `settings.php`, not needed with fake domains.

# Answer
> 0 votes
First off, in the settings.php file you should have an example of `http://www.example.com` and a comment there, saying that you should not append a trailing slash. Next, in your case looks like `http://localhost` would be the correct value of $base\_url, **if any** \- try hashing out $base\_url line to see if the site is fine without it - as it might be.

---
Tags: ajax, uri
---


# Question
Title: Including template footer.tpl.php within another template page.tpl.php
I am looking for simple way to include footer.tpl.php that is just html block into another template like page.tpl.php. In Grails/Groovy that is as simple as

```
<g:render template="side_menu"/>

```

Is there a same simple way(preferred no use any panels, custom modules, etc) in Drupal? Thank You

# Answer
The way to include another .tpl.php file is the `include` function.

Another idea is to add your footer as a region in the page.tpl.php and assign a region wise theme as defined in Drupal 7 Template (Theme Hook) Suggestions

> **region--\[region\].tpl.php** The region template is used when a page region has content, either from the Block system or a function like hook\_page\_build(). Possible region names are determined by the \> theme's .info file.
> 4 votes

# Answer
If your drupal site do not call for **region--\[region\].tpl.php** file, then check your template.php file and find preprocess\_region function:

```
/**
 * Override or insert variables into the region templates.
 *
 * @param $variables
 *   An array of variables to pass to the theme template.
 * @param $hook
 *   The name of the template being rendered ("region" in this case.)
 */

function YOURTHEME_preprocess_region(&$variables, $hook) {
  // add theme suggestions for blockgroup region
  if (strpos($variables['region'],'blockgroup') === 0) {
    $region_name = str_replace(array(' ','-'), '_', $variables['region']);
    $variables['theme_hook_suggestions'][] = 'region__'.$region_name;
  }
}

```

** This function should be there. If not, just place it.*

**In your region--footer.tpl.php file:**

```
/**
 * @file
 * theme implementation to display a region footer
 * variables:
 * - $content: The content for this region, typically blocks.
 * - $classes: String of classes that can be used to style contextually through CSS
 * - $region: The name of the region variable as defined in the theme's .info file.
 * - $classes_array: Array of html class attribute values. It is flattened into a string within the variable $classes.
 * - $is_admin: Flags true when the current user is an administrator.
 * - $is_front: Flags true when presented in the front page.
 * - $logged_in: Flags true when the current user is a logged-in member.
 */
?>

<?php if ($content): ?>
  <div class="your_region_class">

      <?php print $content; ?>

  </div><!-- /.region -->
<?php endif; ?>

```

** read comments*
> 2 votes

---
Tags: theming
---


# Question
Title: how to delete a node programitically in drupal 6?
I want to add delete permission for a specific node id programitically. I try calling 'node\_delete' but it doesn't work.

how can I do it ?

# Answer
> 1 votes
The node\_delete() function requires to have the delete permission for the current logged user. If you run the node\_delete() function as anon user, is probably that doesn't work

---
Tags: 6, users
---


title: Disable Clean Url in database

text:
# Question
Title: Disable Clean Url in database
I am migrating a site from Apache to IIS.

When I backed up the database Clean Urls was active, now my links do not work and I have to add **?q=** to them! Some links work well but the Admin pages are not shown and they display a white screen!

How can I disable Clean Urls?

Also, my images that are customized with ImageCache are not showing! They return a link to a broken image.

# Answer
> 9 votes
Edit settings.php and add:

```
$conf = array(
  'clean_url' => 0,
);

```

Use drush:

```
drush vset clean_url 0

```

You can also edit the database as well.

# Answer
> 4 votes
I had a similar issue where I created a site on my testing server then migrated it to a shared hosting environment and I couldn't get any inner pages to work due the the URLs being rewritten. But mod-rewrite wasn't turned on on the shared hosting environment so I kept getting a 500 Internal error. Here's what I did in settings.php for Drupal 7.

```
/*
 * Turning off clean urls
 */
$conf['clean_url'] = 0;

```

It worked like a charm

# Answer
> 0 votes
If you need deactivate the clean URL from database you can try with

```
UPDATE  `variable` SET  `value` =0 WHERE  `name` =  'clean_url'

```

---
Tags: 6, media, uri
---


# Question
Title: how to show a panel node only to authenticated users?
i am using panel nodes to display profile pages such as my profile page on facebook . i have created a menu link for it . When i logout my profile link still shows. I want that only the logged in user should see the my profile link.

# Answer
I think that Content Access module should help You because it gives You ability to grant access to content type (panel) or - after select "*Enable per content node access control settings* " option - to single node.
> 1 votes

---
Tags: 7, users, panels
---


# Question
Title: Why is a page generated by views listening to block.tpl?
I'm working on some custom templates for a page created by Views and I'm struggling to understand why it's using block.tpl (which I thought was used for blocks). Basically I'm trying to get rid of all the extra divs created for just this one particular page, and until I remove the div class content I can't get the desired style I'm looking for.

I did something similar for a block generated by views and used the template name block--view-name.tpl and got the desired effect. I ended up copying that same template file and just called it block.tpl and got the deserved effect on this Views page.

Now I'm left scratching my head as to why this Views page is listening to block.tpl when it's not a block. Also, seeing as it apparently wants a block template to do what I want, I'm trying to figure out the template naming but none of the usual tools are helping (theme developer module, the theme information under the advanced tab when editing the view).

Does anyone know why a page generated by views would be listening to block.tpl? If it helps the view content on the page is being wrapped by the following div:

```
<div id="block-system-main" class="class="block block-system"></div>

```

# Answer
That block is the main content block.

```
<div id="block-system-main" class="class="block block-system"></div>

```

It is provided by the system module and is the default content area block in the page template.

More information:

1. system\_block\_info ( delta is "main" )
2. system\_block\_view
> 1 votes

# Answer
In Drupal 7 the main page content was turned into a block that could be positioned with the block module. Problem is I don't think people have many use cases for that functionality.

You can get rid of that ugly #block-system-main div by doing the following:

1. Add a template to your theme called `block--system--main.tpl.php`
2. Print ONLY the content within that block template: `<?php print $content; ?>`
> 0 votes

---
Tags: views
---


# Question
Title: Getting the logged in username and email in a view
Im trying to get the logged in users username and email adress to display in a view is that possible?

# Answer
Yes. Just create a view with base table of (user). Then add your fields of username and email. Then add a contextual fileter of uid and set a default value for logged in user.
> 6 votes

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


# Question
Title: Is it possible to divide two columns using the the query builder?
Is it possible to divide two columns using the the query builder?

Like: `$query -> fields('A', array('valsA') / 'B', array('valsB'));`

# Answer
> 1 votes
For complex expressions you can use the `addExpression()` method, e.g.

```
$query->addExpression('A.valsA / B.valsB', 'alias');

```

---
Tags: database
---


title: Files security - files folder hacked

text:
# Question
Title: Files security - files folder hacked
For the second time in a short while my files/ folder has been hacked. Permissions are set as 755 all accross the folder. I tried to set it up as 750, 754 but it breaks the website.

What happens is that someone manages to upload files in the imagecache subfolders. The first time an html file was upload for phishing. The next time a imagecache genrated thumbnail was replaced by an other image.

Can you give me hints on where to look at to fix this?

Thanks, Chris

# Answer
> 4 votes
From the information given, it is impossible to give a full answer. For instance: Are your site on a dedicated server, or on shared hosting? What user and group "owns" the files in your Drupal installation? What is the *extension* (like `.php`) of the unwanted files somebody places in the imagecache subfolders? (Please *edit* your question and expand it with this information, it will be a great help in order to give a more precise answer.)

However, since most people use shared hosting, I'll assume that you're using that. You can read about how to set up correct *ownership* and permissions for in a shared hosting environment in this article: What are the most appropriate users and permission levels for Drupal sites on shared hosting?

However, the permissions you cite, and in particular the fact that `750` "breaks the website" indicate that you must have gotten something (probably the ownership to the files in your Drupal installation) wrong. `750`means `rwxr-x---` while `755` means `rwxr-xr-x`.

In a shared environment, the web server will either:

1. Run as the owner of the site (i.e. you). In this case your `files/` folder (upload directory) should have `700` (`rwx-----`).
2. Run as a member of the www group. In this case your `files/` folder (upload directory) should have `770` (`rwxrwx--`).

Not under *any* circumstance do you want the last triplet (permissions for others) to be anything else than zero.

However, unfortunately, wrong file permissions is probably not the *only* reason your `files/` directory has been compromised. Both `755` and `750` only gives write permission to the *owner* of the `files/` directory. You haven't told us who that owner is, but its either *you* or the *web server user*.

If it is *you*, then your shell account has been compromised, so look for Trojans with the excecute bit set (and change your shell account password). If it is the *web server user*, then you have a cross-scripting attack or a PHP-injection attack, and you need to find and fix that.

---
Tags: 6, files, security
---


# Question
Title: How to grey out fields with non editable permission upon node editing?
I need the ability to grey out fields with non editable permission i.e. to show certain field values to the user but forbid him/her to edit them, upon node editing.

How can i achieve this?

# Answer
Form elements have a `disabled` property you can set as a boolean. For example:

```
$form['test'] = array(
  '#type' => 'text',
  '#title' => t('Test'),
  '#required' => FALSE,
  '#default_value' => 0,
  '#disabled' => TRUE,
);

```

Now, you can use `hook_form_alter()` to check that you're on the right form (`$form_id`), and any other conditions you require, like for instance checking user permissions, with the `user_access()` function.
> 2 votes

# Answer
I think the fastest way to achieve what You want is to use jQuery in Your template or custom module:

```
$("#fieldName").prop("readonly",true);

```
> 0 votes

---
Tags: 7, entities, users
---


# Question
Title: Form textfield on-click remove default values
My objective is to automatically remove the default values within the form textfields upon either being selected/clicked on. Not really sure how to at the moment. Any suggestions?

# Answer
> 1 votes
The correct code for erasing the default values in a textfield, etc. is:

```
$form['Package']['FirstName'] = array(
  '#default_value' => t('First Name'),
  '#type' => 'textfield',
  '#maxlength'=> 255,
  '#required' => TRUE,
  '#attributes' => array(
    'onblur' => "if (this.value == '') {this.value = 'First Name'}",
    'onfocus' => "if (this.value == 'First Name') {this.value = ''}",
  ),
);

```

# Answer
> 2 votes
What do you mean for "default value"? Do you need to save this value or just to use it as a placeholder?

In this case you can obtain the goal without javascript:

```
$form['Package']['FirstName'] = array(
  '#type' => 'textfield',
  '#maxlength'=> 255,
  '#required' => TRUE,
  '#attributes' => array(
    'placeholder' => t('First Name'),
  ),
);

```

---
Tags: 7, forms
---


title: Remove directory name from path

text:
# Question
Title: Remove directory name from path
I am using WYSIWYG editor with IMCE for article description, the issue is that once i upload an image file with imce, its showing image path like

> /DirectoryName/sites/default/files/image.jpg

Once we hosted website from local to online server, **image is not showing** because now DirectoryName is changed to some other name.

Any suggestions?

# Answer
I think the Pathologic contributed module will do it. I have used it in the past and it's awesome. Configuration is a bit tricky, but once it's done you can forget about most file path problems. It's an input filter for text, so it can be used anywhere you can set an input format.

Configuration of Pathologic is covered here. I think it may have issues with internationalization in some cases though.
> 1 votes

# Answer
(This answer assumes a standard setup using MySQL and Apache on linux.)

I'm afraid the best option is to do a manual search-and-replace on your database, replacing `/DirectoryName/` with `/NewDirectoryName/` (or `/`, if your production site does not use a sub directory) in all fields with the WYISIWYG editor enabled. Make sure you search and replace in the field\_data tables (like `field_data_body`) as well as the field\_revision tables (like `field_revision_body`).

I guess you could also add a rewrite rule in .htaccess to rewrite old image paths to new ones, but that doesn't really solve the problem and might make your site more difficult to maintain in the future.

To prevent this problem in future projects, make sure you know beforehand what the production URL is going to be. Set up your local environment with a virtual host to mimic the production URL. For instance, if the production URL will be http://www.example.com/, you can use http://dev.example.com/ for your local environment. If you know the site will run in a subdirectory, eg. http://www.example.com/drupalsite/, set up your local site as http://dev.example.com/drupalsite/.
> 0 votes

---
Tags: wysiwyg, uri, files
---


# Question
Title: media library thumbnails missing for txt and pdf
The http://drupal.org/project/media module cannot display the thumbnails of txt and pdf files in my installation. I'm not expecting a thumbnail of the actual txt or pdf content of course but a generic placeholder.

**Display as list**:

**Display as thumbnail**:

Note that:

* no missing file (404) requests are being tracked in firebug
* this also affects the media popup file chooser from within content editing
* changing the theme doesn't solve this problem
* inspecting the "empty thumbnail" with firebug doesn't show anything useful, the `<a />` is empty.

# Answer
> 0 votes
Using `7.x-2.x-dev` instead of `7.x-1.1` solves this.

# Answer
> 0 votes
I think we've had this problem before when people have the 'Styles' module enabled (and it's sub-module File styles). The use of those modules is now highly discouraged and they should be disabled if possible. I don't know if this is the case however here.

# Answer
> 0 votes
You have to set the file type settings under configuration. If you click on the "File types" under the Media section you will see a list of default media types. The one you want to update is "Application (mulitpurpose)" or "Other". Click "Manage file display" and check the box next to Large filetype icon. You should do this at least for the "Preview" display. Save and reload and your problem should be cleared.

---
Tags: 7, media
---


# Question
Title: How do I redirect back to the source page after the user submits a comment?
How can I access the nid of the current page so that a user can submit their comment and be returned back to the page they just commented from. Here's what I am proposing...

```
function mymodule_form_comment_form_alter(&$form, &$form_state) {
  $nid = arg(2);
  $form_state['redirect'] = 'mymodule/' . $nid;
}

```

...to be placed in `template.php`. However using `$node -> nid` (referenced in comment.module) or `$nid` (referenced in my custom module) throws an undefined error. How can I access the nid to complete my redirecting URL? Or is there a better way of acheiving this?

I believe this is the part of comment.module that I need to hook into and modify - so in a wider sense my question is about hooking into a core module and modifying its function:

```
/**
 * Process comment form submissions; prepare the comment, store it, and set a redirection target.
 */
function comment_form_submit($form, &$form_state) {
  $node = node_load($form_state['values']['nid']);
  $comment = comment_form_submit_build_comment($form, $form_state);
  if (user_access('post comments') && (user_access('administer comments') || $node->comment == COMMENT_NODE_OPEN)) {
    // Save the anonymous user information to a cookie for reuse.
    if (user_is_anonymous()) {
      user_cookie_save(array_intersect_key($form_state['values'], array_flip(array('name', 'mail', 'homepage'))));
    }

    comment_save($comment);
    $form_state['values']['cid'] = $comment->cid;

    // Add an entry to the watchdog log.
    watchdog('content', 'Comment posted: %subject.', array('%subject' => $comment->subject), WATCHDOG_NOTICE, l(t('view'), 'comment/' . $comment->cid, array('fragment' => 'comment-' . $comment->cid)));

    // Explain the approval queue if necessary.
    if ($comment->status == COMMENT_NOT_PUBLISHED) {
      if (!user_access('administer comments')) {
        drupal_set_message(t('Your comment has been queued for review by site administrators and will be published after approval.'));
      }
    }
    else {
      drupal_set_message(t('Your comment has been posted.'));
    }
    $query = array();
    // Find the current display page for this comment.
    $page = comment_get_display_page($comment->cid, $node->type);
    if ($page > 0) {
      $query['page'] = $page;
    }
    // Redirect to the newly posted comment.
    $redirect = array('node/' . $node->nid, array('query' => $query, 'fragment' => 'comment-' . $comment->cid));
  }
  else {
    watchdog('content', 'Comment: unauthorized comment submitted or comment submitted to a closed post %subject.', array('%subject' => $comment->subject), WATCHDOG_WARNING);
    drupal_set_message(t('Comment: unauthorized comment submitted or comment submitted to a closed post %subject.', array('%subject' => $comment->subject)), 'error');
    // Redirect the user to the node they are commenting on.
    $redirect = 'node/' . $node->nid;
  }
  $form_state['redirect'] = $redirect;
  // Clear the block and page caches so that anonymous users see the comment
  // they have posted.
  cache_clear_all();
}

```

Thanks.

# Answer
> 10 votes
To redirect a form after submission you would do this:

```
/**
 * Implements hook_form_FORM_ID_alter().
 */
function MYMODULE_form_comment_form_alter(&$form, &$form_state) {
  // Add a custom submit handler to act when the form submits.
  $form['#submit'][] = 'MYMODULE_custom_comment_submit_handler';
}

/**
 * Custom submit handler for the comment form.
 */
function MYMODULE_custom_comment_submit_handler($form, &$form_state) {
  // Redirect the user after submission
  $nid = arg(2);
  $form_state['redirect'] = 'mymodule/' . $nid;
}

```

# Answer
> 4 votes
What about using the Modules Actions, Trigger and Tokens?

Create an Action "Redirect to URL" on yoursite.com/admin/config/system/actions: Give it a name and an target URL like "node/\[comment:node:nid\]".

Assign that Action to the Trigger "AFTER SAVING A NEW COMMENT" on yoursite.com/admin/structure/trigger/comment

Just my thoughts...

# Answer
> 0 votes
Do You tried to use Rules module? I always use this if I have to do a custom redirects.

---
Tags: comments
---


# Question
Title: Translated taxonomy term in contextupal filter not validating
I have a translated taxonomy term:

And have a simple view:

With a contextual filter on the translated taxonomy term:

Which works in english:

But not in french:

Any idea ?

# Answer
I had to set the taxonomy vocabulary type from "Localize" to "Translate".
> 0 votes

---
Tags: taxonomy-terms, views, i18n-l10n
---


title: Set lightbox effect for the link

text:
# Question
Title: Set lightbox effect for the link
I have a gallery, created as a view:

http://hotelcentralpark.ro/gallery/2

Now the titles are links to the pages. And images have lightbox effect.

I want the links to activate lightbox of the appropriate image. But there are no settings for that in the admin panel.

Here are the settings for the image field:

Settings for the header field in the control panel:

How can I set the link to act as lightbox?

Here is the image content type structure:

# Answer
> 1 votes
In Views Use this code in "Rewrite the output of this field"

```
<a href="imagepath token" rel="lightbox">[title]</a>

```

You can also set the width and height of the popup window, see the read-me file in Lightbox2 module folder.

hope you will get idea from the above!!

---
Tags: 7, media
---


# Question
Title: Views - Combining Fields into a single link?
I'm using the Views module to build some views for our company's locations and employees. What I've got set up is: when a user looks at a page for one of our locations, they get a list of employees there. The 'Employee' content type is set up with separate fields such as "Last Name", "First Name", "Middle Init" and so forth.

What I want to do is to find a way to combine these fields in a single line that forms a link to the employee's profile when clicked.

I've found I can do this by changing the "Title" field to something like "Display Name" and adding that field to the view (as the title field gives you the option to link back to the original content), but I'd really rather do it the other way as the data for the content type is imported and I'd rather not sift through all that to add a "Display" field and everything that goes along with it.

Any ideas or am I out of luck?

# Answer
You can add the 4 fields in this order:

nid
first name
middle name
last name

For the first 3 fields, check the "Exclude from display" checkbox.

For the 4th field, in the rewrite results section, check the "Rewrite the output of this field", then in the "Text" text area use the replacement patterns for the other fields to join them together.

It will be something like this:

\[field\_first\_name\] \[field\_middle\_name\] \[field\_last\_name\]

Then also check the "Output this field as a link" checkbox and for the "Link path" you can again use the replacement patterns (expand the fieldset to see the available replacement tokens).

It will be something like:

node/\[nid\]
> 3 votes

---
Tags: views
---


# Question
Title: how can i get a menu of a parent taxonomy term?
I know menus can be made of taxonomies, with taxonomy menu.

But the real huge problem i have is I CANT get taxonomy menu to show only one term's children in the taxonomy list.For example consider this taxonomy vocabulary:

```
creatures
-insects
--ants
--mosquitoes
-mammals
--rabit
--dog

```

I want the taxonomy menu to show only mammals links, how can i do that?

# Answer
> 0 votes
If your output should be a block or page, you could do it with Views. If not, meaning you want to show only that part as a menu itself, you might want to consider writing your own query for it, and adding it as a hook in your template.php

---
Tags: taxonomy-terms
---


# Question
Title: Preprocess function for node.tpl.php file
I've watched a million videos and read a million tutorials trying to figure out how to create a new variable for use in a version of a node.tpl.php file by utilizing preprocessing functions, but can't figure out what I'm doing wrong.

First, I copied the node.tpl.php file, renamed it node--nameofnodetype.tpl.php, and saved it in my theme folder. Then, I edited the template.php file, trying different variations of the following code.

```
function theme_preprocess_nodename(&$variables, $hook) {
  $variables['link_name'] = 'link content';
}

```

I flushed the cache, and when I tried printing the new variable in the new node file, I got nothing. Can anyone tell me what I'm doing wrong?

# Answer
To create a variable for any type of node you should use yourtheme\_preprocess\_node() function, and in this fuction you should specify a type of node.

**Example:**

```
/**
 * Override or insert variables into the node templates.
 *
 * @param $variables
 *   An array of variables to pass to the theme template.
 * @param $hook
 *   The name of the template being rendered ("node" in this case.)
 */

function YOURTHEME_preprocess_node(&$variables, $hook) {

  //$variables['sample_variable'] = t('Lorem ipsum.');
  // Optionally, run node-type-specific preprocess functions, like
  // YOURTHEME_preprocess_node_page() or YOURTHEME_preprocess_node_story().
  //$function = __FUNCTION__ . '_' . $variables['node']->type;
  //if (function_exists($function)) {
  //  $function($variables, $hook);
  //}

  // define $node object, so it's be easier to use it
  $node = $variables['node'];

  // add variables to node--nameofnodetype.tpl.php file
  if ($node->type == 'nameofnodetype'){

      // $variables: an array with variables
      // you need to add one, so just define it
      $variables['my_variable'] = 'whatever';

      // also you can rewrite those variables which already exists
      // for example variable: $title
      $variables['title'] = t('The new title');
  }
}

```

**In your node--nameofnodetype.tpl.php file:**

```
// check if your new variable exist
print $my_variable;

```

** Don't forget replace 'YOURTHEME' to your theme name*
> 8 votes

# Answer
In Drupal 7, you'll need node--nameofnodetype.tpl.php

node\__nameofnodetype.tpl.php is wrong (underscores define a system name)
> 2 votes

---
Tags: theming
---


title: Print a field in a set display mode

text:
# Question
Title: Print a field in a set display mode
I can print a field in content type tpl file with this:

```
<?php echo render($content['field_name']); ?>

```

But how can I print the field as a different display mode?

EG I might always want to print the teaser version of an image field, regardless of what view mode is being used.

# Answer
There might be a shortcut to this but I don't know it...

```
// Get the bundle settings.
$info = field_info_instance('node', 'field_name', 'content_type');

// Get the field render array
$build = field_view_field('node', $node, 'field_name', $info['display']['teaser']);

// And print it
print render($build);

```

Moving the display building logic to a preprocess function would probably be a good idea.
> 0 votes

---
Tags: 7, theming
---


# Question
Title: Custom feed tamper plugin to convert an image GUID into a URI
I have a feed importer for image files, which stores a column in my source csv as the GUID of the final files in Drupal.

I also have another importer for, say, articles. In the articles csv, there is an "image key" column, that corresponds to the image GUIDs mentioned above.

I'm working on a custom feeds tamper plugin that can convert the GUIDs to the image URIs that have already been imported by the first importer, but I'm completely lost on how to retrieve the images in the code.

So, the question is: **how do I convert an previously imported image file GUID into the actual image's URI?**

# Answer
> 0 votes
I came up with a solution, simply using a DB query to get what I want. Here is the callback for the tamper module. Hopefully someone will find a better solution, if it's possible.

```
function myfeedsmodule_tamper_imagekey_callback($result, $item_key, $element_key, &$field, $settings) {
  $field = trim($field);
  if ($field == 'NULL') {
      $field = NULL;
      return;
  }
  $result = db_select('feeds_item', 'f')
          ->fields('f', array('entity_id'))
          ->condition('guid', $field, '=')
          ->condition('entity_type', 'file', '=')
          ->condition('id', 'my_image_importer', '=')
          ->execute()
          ->fetchField();
  if (!$result) {
      $field = NULL;
      return;
  }
  $entities = entity_load('file', array($result));
  if (!$entities) {
      $field = NULL;
      return;
  }
  $image = current($entities);
  $field = $image->uri;
}

```

---
Tags: media, feeds, files
---


title: curent language token on block body

text:
# Question
Title: curent language token on block body
what is the token used to get the curent language, I want to use this token on a link in the block body, like that:

```
<a href="/[curent-language]/about-us">About us</a>

```

I find this token `[site:url]` is good, but in default language the link become `//about-us` two slashes, otherwise `/fr/about-us` in the french language(good).

# Answer
use this module http://drupal.org/project/token\_custom to create your own token, I create a Token Type `Language` that containt my `path` token, the content of this token is the result of the PHP code(use PHP Filter module to include PHP code):

```
<?php
  global $language;

  return ($language->language === 'en' ? '/' : '/'.$language->language.'/');
?>

```

In the block body, I can use my token like this:

```
<a href="[language:path]about-us">About us</a>

```

---

You can post a comment for any Help, thank you.
> 0 votes

# Answer
try `<a href="/[node:source:language]/about-us">About us</a>`
> 0 votes

---
Tags: hooks, tokens
---


# Question
Title: How can I export users, forums and comments to another site?
I need to move forums containers, topics, their associated comments, and user accounts to another existing Drupal site.

How can I achieve this?

# Answer
If you want to export into a live site where there already exists forums, topics, nodes, comment users that you not want to overwrite, I suggest you check out the Drupal-to-Drupal data migration module. It will let you move the data and refactor it in the process.
> 2 votes

---
Tags: importing-exporting
---


title: Control menu item visibility

text:
# Question
Title: Control menu item visibility
I find myself wanting to control whether a menu item is shown on certain pages, much like how I can control how blocks are only visible on certain pages.

I cloned the menu using the Menu clone module, but have already experience maintenance issues and can only see it becoming more of a problem when the site goes live...

Is there a clever way of controlling menu item visibility?

# Answer
> 2 votes
I have done something along these lines with custom blocks. The basic approach is

* Put everything you want in a menu, regardless of visibility
* Make a custom block; make sure you don't cache it
* In the render callback, get the menu `$menu = menu_tree_all_data('menu-foo');`
* `unset()` any items in the `$menu` according to your visibility rules
* Assign the items to `$block['content']`

Then you can assign the block to a region.

# Answer
> 2 votes
this module is worth a look: http://drupal.org/project/menu\_item\_visibility which allows for menu item filters similar to block filters (but alas no php filtering)

---
Tags: routes
---


# Question
Title: How to create a view block only visible to the Referenced Content Type's Author?
I have 2 custom content types: *Item for sale*, and *Bid (offer)*. The latter has a node reference URL to a node of the first content type.

I created a view (block) which shows the people with their offers.

I need to edit this view in such a way that is will be only visible to the person who created the Item for sale (author of the first content type may only see this block).

How can I achieve this? I cant seem to find a way with contextual filters.

# Answer
> 2 votes
Easiest way to do this:

1. Add a content relationship for the node reference field (i.e. Content: field\_item\_for\_sale\_ref)
2. Add another relationship for the Content Author and select the node reference field relationship from the dropdown list at the top of the window.
3. Filter the view for the current logged in user by selecting the author relationship that was just created in step 2.

OR

1. Add a content relationship for the node reference field (i.e. Content: field\_item\_for\_sale\_ref)
2. Add a contextual filter for the Content: Author uid, select the node reference field relationship from the dropdown list (top of window), select: provide default argument of type: user id from logged in user

Either way the result is the same and it's what you need.

# Answer
> 1 votes
You can restrain block visibility only to node's author in the block's visibility settings. For example select "Pages on which this PHP code returns TRUE (experts only)" and use the following code as a visibility criteria:

```
<?php

    global $user;
    $node = menu_get_object('node');
    if($node) {
       if ($user->uid == $node->uid) {
           return TRUE;
       }
    }
    return FALSE;

```

# Answer
> 0 votes
I presume you are extracting the ID node on display from the current URL for use in a contextual filter? You should also be able to add a relationship to that node and then a filter for the author of that content type = current user. That way there'll be no results when anyone else views the page.

---
Tags: 7, views
---


title: Output a field with PHP

text:
# Question
Title: Output a field with PHP
I have the *content:path* field and I want to output the containing data with a global PHP field.

it shows me this, but the output with `print $row->path` gives out a number only and not the content path.

> **Available variables**
>
> ```
> $row->path: Inhalt: Pfad
>
> ```

I tried `print_r($data)` to look for the correct output information, but I did not find anything about the field.

Is there any solution to get this field's data with PHP?

regards

# Answer
Indeed, views PhP doesn't always get the processed field and only gives you the `nid` instead. You have to use `$data` as you tried *(by the way, easier is to `dpm($data)` than `print_r`)*.

if it doesn't give you any info on what you're looking for, you can simply obtain your content:path by using drupal\_lookup\_path :

```
$path = drupal_lookup_path('alias', 'node/' . $data->nid);

```
> 2 votes

---
Tags: 7, views
---


# Question
Title: How to tell if the current language is written RTL or LTR
I'm looking for the function – if that exists – for asking Drupal about the current language direction (RTL/LTR).

I check the global language variable but it doesn't contain that information.

# Answer
After looking more closely into $GLOBALS\['language'\] I found it actually has the language direction, so the answer is:

```
global $language;
if($language->direction == 1)
    echo 'RTL';
else /* $language->direction == 0 */
    echo 'LTR';

```

Better yet — thank you MPD, I can use the Drupal constants LANGUAGE\_LTR and LANGUAGE\_RTL instead of 0 and 1 respectively, just like this:

```
global $language;
if($language->direction == LANGUAGE_RTL)
    echo 'RTL';
else /* $language->direction == LANGUAGE_LTR */
    echo 'LTR';

```

For reference this is what `$GLOBALS['language']` looks like:

```
stdClass Object
(
    [language] => ar
    [name] => Arabic
    [native] => 'Arabic' [it was in arabic letters but SE refused it]
    [direction] => 1
    [enabled] => 1
    [plurals] => 0
    [formula] =>
    [domain] =>
    [prefix] => ar
    [weight] => 0
    [javascript] =>
    [provider] => language-default
)

```
> 1 votes

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


# Question
Title: ajax update seperate page when a button is clicked on a popup
I created a content type that is used to display a list of videos hosted on brightcove. I have a module that is setting a cookie for the anonymous user when they watch one.

I created a module that will display the video that they clicked in a popup. Inside this popup window there is a button to go to the next video. When they clicked the video that launched the initial popup I can use jquery to change a div class to get a viewed icon to appear next to the video link no problem.

When the "next video" button is clicked I have it play the next video in the same popup. However, I would like to have the "video viewed" icon appear without a refresh on the originating page.

You can see this in action at http://www.lynda.com when you watch one of their videos. You click a video on the course list, a popup appears and you can click the next video button. A viewed icon will appear without refresh on the course list (not the popup).

How do I use ajax in such a way that when a button is clicked it updates a different page? In the pop-up I am passing a video ID as well as the drupal node id of the course the video belongs to.

# Answer
> 0 votes
This answer was a little different than what I had in mind but since I was updating the cookie information when the Next video button was clicked to set the ID of the video in the cookie I used a js cookie listener found here: https://stackoverflow.com/questions/5908504/jquery-cookie-monitor Whenever the cookie is updated I can then check it and mark the video as viewed with jquery. If anyone has another solution I would love to hear it.

# Answer
> 1 votes
If you are using JavaScript to open your new window, you can assign that window a name and refer to its parent (or refer to it from the parent, as well). One site that explains this is at http://www.codeproject.com/Articles/25388/Accessing-parent-window-from-child-window-or-vice

---
Tags: 7, ajax
---


title: Advanced content layout in drupal

text:
# Question
Title: Advanced content layout in drupal
I've been evaluating drupal and I'm at a point where I have my header, footer, and sidebar set up properly. I have a basic page node type and I've created a few test pages. My test pages have been very simple, just headers and paragraph tags. What do I do when I want something more complicated?

If my client wants a certain page to have text and images split into multiple columns at different points in the page instead of just one how can I accomplish this when the only input the end user has is a wysiwyg form?

Is there a module for this type of thing or does it require knowing in advance how the client will want to layout each of the different pages and make templates for them all?

# Answer
> 0 votes
If the end user is good at layout, they can use the WYSIWYG form to do pretty much any kind of layout there. Otherwise, you will probably want to have different inputs for the different areas of the page (which would require a different template, and probably content type, for each layout). For example, I have a site set up which has a home page that is different from all of the subpages, and also has section pages for secondary-level pages. The home page is its own content type, and the section pages are their own content type. That way, I can attach different fields to each of these, for example, making them refer to a separate node which is a slide show.

# Answer
> 1 votes
What you're asking about is usually referred to as "theming", and it is a huge subject.

I suggest you read up on "starter themes", which are Drupal theme projects that are specifically designed for the type of flexibility you want.

As you can see, there are several of these. One that is both popular, well-documented and well-supported is Zen. Getting a grip on Zen takes some effort (it seems both useless and bone-ugly out of the box). But Zen, together with one of the avialable grid frameworks (Zen Grids, 960.gs, Gridset App) gives tremendous flexibility. It is well worth the effort to get to grips with.

---
Tags: 7, theming
---


# Question
Title: restrict profile field to module and admin in drupal 6
I am using profile for storing some more information for users. but I want one field of profile be only editable by administrator and my own module code and viewable by own user and administrator.

I guess I have to set visibility of field to ' Hidden profile field, only accessible by administrators, modules and themes. '

but I don't know if it is right or not.

Thank you.

# Answer
Yep, you got it right.

Inside the profile.module's `profile_view_profile()` function, it uses the following logic when modifying `$user` to include the additional fields for viewing...

```
// Show private fields to administrators and people viewing their own account.
if (user_access('administer users') || $GLOBALS['user']->uid == $user->uid) {
  $result = db_query('SELECT * FROM {profile_fields} WHERE visibility != %d ORDER BY category, weight', PROFILE_HIDDEN);
}
else {
  $result = db_query('SELECT * FROM {profile_fields} WHERE visibility != %d AND visibility != %d ORDER BY category, weight', PROFILE_PRIVATE, PROFILE_HIDDEN);
}

```

...so yes, settings fields to `PROFILE_HIDDEN` will show them only to users with the `administer users` permission and/or to the user who is viewing his/her own account.

When editing a user, the module calls upon the `_profile_get_fields()` function to present the fields to be edited on the resulting form, and there, it uses the logic...

```
if (!user_access('administer users')) {
  $filters[] = 'visibility != %d';
  $args[] = PROFILE_HIDDEN;
}

```

...to restrict the editing of these fields to just users with the `administer users` permission by filtering out those fields from users without that permission.

And, of course, if your module or theme wants to edit anything in the database directly, there is nothing to really stop it.
> 0 votes

---
Tags: 6, users
---


# Question
Title: Handling uploaded resources for local development
With our Drupal site we develop locally, commit to svn and deploy to the live site. Some content gets uploaded on the live site (some images, videos etc). I am trying to sort out the best way to handle those uploaded resources.

Currently, we do daily database dumps, and use those for local development, but if someone has edited a page and added an image, it will 404 on the local since the image doesn't exist.

I rsync content down, but not all the team has ssh access (security). Should I tar up the uploaded assets at the same time as the database dumps? Or, is there a better way to handle this?

Basically; Whats the best way of getting uploaded content, for local development?

# Answer
Yes your database and files need to be kept in sync to avoid 404s as you describe. With our setup all developers have access to a backed up copy of the database and files. The backups of both database and files are synchronised so together they're essentially a snapshot of the production site. I personally use a collection of Drush commands wrapped up in a shell script in order to restore this snapshot to my local machine.
> 0 votes

---
Tags: files
---


# Question
Title: How do you find where a module's directory is located?
I have the following:

I want to find where the module "commerce\_physical" is located in the modules folder, but I can't seem to locate this module. I did a find and a grep to locate where its files might be, but that doesnt seem to work. What are some other ways to find the location of a drupal 7 module?

# Answer
> 2 votes
Look at the `{system}` table. In particular, the `name` column will be the module name (ie, the basename of the .info and .module files). The `filename` column will be the full filename, with path, to the .info file for the module, relative to the DOCROOT of the installation. See `system_schema()` for more information.

---
Tags: 7
---


# Question
Title: Displaying all the entity reference entities in a view
I have a "press release" node type which uses entityreference to link to any number of file\_entity images, another field for file\_entity videos and another to file\_entity audio files.

There is a need for a block to display the first six images from the most recent press release, with some text from the press release.

So I built a view that finds the most recent press release and then displays the first six image entities. Or it should have but it doesn't, it always reports zero images (or zero videos, or zero audio files) regardless of how many there are.

So I ripped into Views to find the problem and discovered that entityreference does not provide a field handler, as a result Views assumes it's referring to a node and not an image and it all goes pear-shaped.

All entityreference does is provide a relationship handler, which is fine as far as it goes but you can only display one entry from the list of references - the first one.

Am I really going to go completely non-intuitive and have the images as the main table, and then sort by and group by parent press release node?

Any better ideas? (Short of writing a proper Views field handler?)

# Answer
> 1 votes
I think you will need to create a view of image entities, rather than nodes. The use a reverse relationship with the node that references it as a filter.

# Answer
> 0 votes
The real solution is a proper field handler, but I don't have time to implement that in my current contract so I'll just bypass the problem:

Create a block that can be configured with a specific entry (or chooses the latest) and hard code the display to be what's required.

That's the way it goes.

# Answer
> 0 votes
You can use the Content Dependency module. It provides you references via tab and supports following modules: node reference / entity reference.

Here is an excerpt about it from the module's project page:

> Provides ability to view reversed referrals/references for content of entity reference & references - node\_reference modules, etc.
>
> Generally, this project enables content authors to see from any current content (entity) its dependent entities content.
>
> Project overcome a major content control difficulty for content authors.
>
> Provide content authors ability to track external content which refers to current content, without the need to check mass of external content to find out whether each external content refers to current content or not.

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


title: Clearing cache causes nginx error

text:
# Question
Title: Clearing cache causes nginx error
Whenever I clear cache from the admin panel (or hit the url directly) I receive an nginx error (but nothing specific is being logged).

There are no PHP error logs being created for this either.

I've narrowed it down to the `/includes/menu.inc` `_menu_router_build` function.

The strange thing is, that if I add an echo to line 2365:

```
// Apply inheritance rules.
foreach ($menu as $path => $v) {
   echo $path; // echo added
   ....
}

```

The cache clears, it doesn't error out, BUT it doesn't seem to complete because all the values are echoed but I'm never redirected. Completely lost on this one.

# Answer
We had a similar issue and traced it to the nginx `fastcgi_read_timeout` option. Because the code to clear the cache doesn't send any output to the browser until it finishes, nginx doesn't receive anything from PHP for 60 seconds. At this point, the default `fastcgi_read_timeout` is reached, so nginx aborts the request.

When you added the `echo $path`, you forced PHP to output something, which meant that nginx had something to read, so it didn't reach the timeout.

You should try increasing the `fastcgi_read_timeout` to, say, `120s` and see if that helps.
> 2 votes

---
Tags: 6
---


# Question
Title: Why is the AJAX replaced drop-down list value not being submitted?
I have an AJAX method for when a value is selected from the `source` drop-down list the `target` drop-down gets replaced with new values. The problem is that the new replaced drop-down list selected value is not being submitted (e.g. not in $form\_state\['values'\]\['target'\] = 'not the val I selected'). It looks like the value submitted is from the `target` drop-down list that is default from when the page first loads.

Any ideas as to why this is happening?

```
function dashboard_node_filter_form(){
  ...
  $form['filters']['source'] = array(
      '#type' => 'select',
      '#options' => source_options(),
      '#title' => 'Source',
      '#ajax' => array(
          'callback' => 'dashboard_node_filter_target',
          'wrapper' => 'edit-target',
          'method' => 'replace',
          'effect' => 'none',
       ),
  );
  // when source is selected this gets replaced
  $form['filters']['target'] = array(
      '#type' => 'select',
      '#options' => get_,
      '#title' => 'Target',
  );
  $form['filters']['submit'] = array(
     '#type' => 'submit',
     '#value' => 'Submit',
  );
}

function dashboard_node_filter_target($form, &$form_state) {
  return $form['filters']['target'] = array(
      '#type' => 'select',
      '#id' => 'edit-target',
      '#options' => display_options($form_state['values']['id']),
  );
}

```

# Answer
> 2 votes
You should make all form manipulations that are supposed to be actually submitted in dashboard\_node\_filter\_form() and use dashboard\_node\_filter\_target() only to tell ajax what part of a form should be updated, and to make aesthetic-only changes that does not affect data.

---
Tags: 7, forms, ajax
---


# Question
Title: "Maintenance mode" message is shown when the site isn't in maintenance
I get the "Operating in maintenance mode. Go online." message and the Drupal 7 site isn't in maintenance mode.

The message doesn't appears all the time; sometimes it goes away when I refresh the page. I cleared cache; I tested, and it is most certainly not in maintenance mode.

I checked Drupal error reports, and I get this one. (I don't know whether it's related.)

> TIPO acceso denegado
> FECHA Martes, 14 May, 2013 - 01:11
> USUARIO Anónimo (-)
> UBICACIÓN http://www.liga.net/cron.php
> REFERENTE
> MENSAJE frontpage
> SEVERIDAD advertencia
> NOMBRE DE LA MÁQUINA xx.xxx.xx.xxx

Sometimes in a complete random way, as an anonymous users, it appears the *Site offline* page. When I reload the page it´s up again.

# Answer
> 4 votes
Search variable table in database. Variable named maintenance\_mode should be there, and should be a serialized representation of false (or numerical 0). If it's not, your site will have a problem. If this appeared after upgrade, re-running update.php might help

---
Tags: cron, maintenance-mode
---


# Question
Title: Auto populate a node add with values of another node
Is there any module that auto-populates the fields of a node/add form with the values of an already existing node? I would like to pass the node ID in the URL and get the form prepopulated with the values taken from that node.

I know it is possible to do; I am just wondering if someone has already done it in a module I could use.

# Answer
Did you mean node clone module?

> The clone module allows users to make a copy of an existing item of site content (a node) and then edit that copy. The authorship is set to the current user, the menu and url aliases are reset, and the words "Clone of" are inserted into the title to remind you that you are not editing the original content.
> 2 votes

---
Tags: 7, nodes
---


title: Date Filter Between Date Odd Behaviour

text:
# Question
Title: Date Filter Between Date Odd Behaviour
Hello i am having problems showing nodes created between '8 days ago and 38 days ago' in my Views filters.

filter Node: Post date: is between An offset from the current time such as "+1 day" or "-2 hours -30 minutes" Min: -8 days Max: +38 days

Im not getting the required behaviour. if i trim it down to

Min: -3 days Max +5 days

it seems to be filtering. With my original -8 and + 38 though its showing all the nodes. Am i doing something wrong?

Thanks

# Answer
> 1 votes
I had a similar type of issue and managed to fix it by changing back to "Single Filter" and adjusting the filter value type to what I wanted to use in "Grouped filters" type. I then went back to "Grouped Filter" and my date filters suddenly started working.

Alternatively, you can just delete the filter and add it again, and try set it correctly from the start.

Hope that helps.

p.s. using Views 7.x-3.6

---
Tags: views, datetime
---


# Question
Title: Getting a 500 error with the Domain Access module
I use Drupal 7.22 with 7.x-3.9 Domain Access Module for multiple subdomains website. Making of subdomains works fine, but I cannot access to subfolders on subdomains.

* example.com works
* example.com/admin/ works
* sub.example.com works
* sub.example.com/admin/ internal server error 500

This error is showing on every sub-folder (content) in every sub-domain. The root domain is fine with all content. Also, theme changing on sub-domains works fine. Am I missing something in documentation?

# Answer
> 1 votes
To debug WSOD, you need info what exactly went wrong. There is a pretty neat article about fixing them \- try to follow it. Around step 2a you should pretty much know what you need to look for in documentation.

---
Tags: domain-access, wsod, subsites
---


# Question
Title: Drupal 6 Site Duplication - Looks Like My Theme is Broken
My goal is to duplicate a Drupal 6 site to a new host, but I am having some problems.

```
  New host - 198.20.226.199/~paul8226/ -- No name resolution setup yet.
  Old host - www.egcasting.com/

```

I performed a fresh Drupal 6 install on the new Host Gator account using the same database name, username/password as my existing site (clean URLs worked.) Then I imported the database from the existing site, and copied over sites/default (except settings.php) and all of sites/all. It looks like the site totally functions, except the theme is not styling anything at all.

Google Chrome developer tools is telling me I am missing the below CSS files, both of which are on my file system:

```
http://198.20.226.199/~paul8226/sites/default/files/css/css_89883be7e51f5fd34095c91a397aee3c.css
http://198.20.226.199/~paul8226/sites/default/files/css/css_6ca651b4b42888393291ef9ea27101fa.css
.
.
.

-rw-rw-r-- 1 paul8226 paul8226 39K May 13 15:57 css_89883be7e51f5fd34095c91a397aee3c.css
-rw-rw-r-- 1 paul8226 paul8226 549 May 13 15:57 css_6ca651b4b42888393291ef9ea27101fa.css

```

The CSS on the old host is working fine. So far, I have looked at the file, and directory, permissions going all the way up. I also tried turning on and off the CSS compression. Turning off CSS compression made the site styling look totally off in another way. When I look at the themes option, it looks like the custom theme I am trying to copy over is having some serious issues:

Broken Theme

Working Theme

I also looked through the theme permissions, and they look like what I think they should be.

```
 # pwd
 /home/paul8226/public_html/sites/all/themes
drwx--x--x 4 paul8226 paul8226 4.0K Aug 25  2009 eg_prod/
.
.
.
# cd eg_prod
# ls -laSh
total 260K
-rw-r--r-- 1 paul8226 paul8226  42K May 13  2009 theme-settings.php
-rw-r--r-- 1 paul8226 paul8226  37K Sep  9  2009 style.css
-rw-r--r-- 1 paul8226 paul8226  32K Aug 21  2009 template.php
-rw-r--r-- 1 paul8226 paul8226  15K Apr 23  2006 LICENSE.txt
-rw-r--r-- 1 paul8226 paul8226 7.8K Apr 20  2009 style-rtl.css

```

Thank you very much for taking the time to help me with this. Normally this 'thanks' section gets edited out, but oh well. Thanks!

# Answer
* `/sites/*/files/css/` and `/sites/*/files/js` should be empty just after migration - do **not** copy their contend. Clear them.
* Before making original site database snapshot, **turn off** css and js aggregation. If you didn't, turn it off now. If you don't, the duplicated site will be looking for the aggregated content which may, or may not be available on the new site.
* On new site, make sure `/sites/*/files/` directories are writeable by your php scripts, and that php can delete files too.
* Search all theme files for not-relative URIs. There shouldn't be any.
* Fix one problem at a time. First, make it work without aggregation (most probably it's URI problem), and only then attempt to fix aggregation issues.
* At the end, if you still have problem - disable and then enable theme. This should ensure all theme-related caches are regenerated and theme settings variables refreshed.
> 6 votes

---
Tags: 6, theming, migrations
---


# Question
Title: Thoughts on best practices for user content management
I have a website where I need specific user roles (restaurant owner) to edit specific content type (their respective restaurant profile and services) which has a node reference field to the main restaurant profile.

I've been developing a website before where I needed to change the author of the node so this user could edit (with right permission) however, I'm sure there should be a better automated practice.

I am thinking of using Profile 2, with node reference user to a specific content type.

Any ideas on what's best to achieve this ?

# Answer
> 0 votes
If nodes are supposed to match 1:1, why not to make them one node, with different displays and access to different fields? Or, actually, if you have only one restaurant per owner and one owner per restaurant (and it looks like that, when you say that changing author works) you could define restaurant info as a set of fields at user's profile itself. That way each user would be able to edit his own data, and data of his restaurant, and you can use views to decide what to show and where.

# Answer
> 0 votes
The Node access user reference module lets you control who can edit what by means of a user reference, so I suggest you look at that as well. It's a more generic solution than Profile 2.

---
Tags: users
---


title: How to translate taxonomy breadcrumbs?

text:
# Question
Title: How to translate taxonomy breadcrumbs?
My breadcrumbs only show in the original language. When I change the language, only the heading of the breadcrumb which is in a `t()` function changes language. I can't put the `$breadcrumb` variable in the function, the string translation interface is also not the right place for it. I am using taxonomy menu and taxonomy breadcrumbs modules. How can I get the breadcrumbs to use either the translated terms or at least work through string translation?

# Answer
Taxonomy Breadcrumb module has maintenance status: Unsupported. It means it's author's answer to all problems with it is simply "stop using it". There is a bug report 2 years 41 weeks old about your problem and I don't really expect it will be fixed any time soon.
> 0 votes

---
Tags: taxonomy-terms, breadcrumbs
---


# Question
Title: How to NOT turn element read only when waiting for '#ajax' callback in Drupal 7 forms?
I need a simple `'#type' => 'textfield'` field. When a user types in it, I want to update another section of my form. Just a more elaborate version of built-in autocomplete field, really. So I added:

```
'#ajax' => array(
  'callback' => 'mymodule_tag',
  'wrapper' => 'edit-tags',
  'method' => 'replace',
  'effect' => 'fade',
  'event' => 'input',
),

```

The only problem is - it turns my field disabled when waiting for the server's reaction. This is unacceptable: User's input should never be blocked, that's a priority. I bet the solution is simple, but googling for it gives me a lot of results about how to disable field, and none about keeping it enabled. Too much noise for my search skills. Any suggestions?

# Answer
> 3 votes
I'm not sure I agree with your premise (interesting question, nonetheless). If performing a second operation while the first is already running would cause a problem client/server side, then that operation should definitely be blocked in my opinion.

If the only issue you have is that the blocking is done by way of disabling the text field, consider that it's just a matter of good UX. If the field wasn't disabled, but the functionality *was*, then there's no feedback to the user, who is left wondering why nothing's happening even though they're typing into a text field that has some rich functionality a few seconds earlier.

That said, if you want to override the behaviour of Drupal's AJAX have a look in the /misc/ajax.js file. You'll need to re-implement at least:

* `Drupal.ajax.prototype.beforeSend`
* `Drupal.ajax.prototype.success`
* `Drupal.ajax.prototype.error`

Those functions set/remove the `disabled` attribute on the element. It should be reasonably straight forward to re-assign those functions in a custom JS file, and you can just remove lines like this:

```
$(this.element).addClass('progress-disabled').attr('disabled', true);

```

Or tweak it to something more palatable for your use case.

---
Tags: forms, ajax
---


title: Extract currency code from $orders

text:
# Question
Title: Extract currency code from $orders
I'm trying to extract the currency code for the current order, I printed the $order variable using print\_r, but I'm not at all a PHP programmer and I don't really know how to extract the currency code, I can see it there, but I don't know how to extract it, can somebody point me to the right direction? I will be delighted if I will learn how to do this kind of actions.

Thanks for your time!

# Answer
The currency data lives in the `commerce_order_total` field by default. You can extract that information easily using `field_get_items()`, though an `entity_metadata_wrapper()` is just more fun:

```
$order = commerce_order_load($order_id);
$order_wrapper = entity_metadata_wrapper('commerce_order', $order);

$currency_code = $order_wrapper->commerce_order_total->currency_code->value();

```
> 5 votes

---
Tags: commerce
---


title: Open A image When the site loads

text:
# Question
Title: Open A image When the site loads
How to open a image when the site loads like in this site. Can this be done wtih lightbox or colorbox

# Answer
You can use Splashify module for this

> Display a splash page anywhere on your site by redirecting the user, showing a lightbox, or displaying a popup. This module is designed to be search engine friendly, mobile device friendly and offers multiple configuration options.

Otherwise you can try with lightbox and custom scripts an example is given here
> 1 votes

---
Tags: media
---


# Question
Title: PHP version changes and Drupal versions issues
i have installed drupal 7.1 on PHP Version 5.2.17 .....now the server people is going to upgrade the php/mysql to a higher version like 5.3.3 ..is there any problem to the current drupal 7.1 websites running ?

Please advice me.

# Answer
It's impossible to say whether your specific setup, with your specific site, will or will not have problems after a PHP upgrade. You'll need to set up a test environment that mirrors your live server as much as possible - and test it. It's unlikely, but you may have contrib modules installed that rely on PHP 5.2, so you need to check your specific installation.

From my own experience, before I upgraded to 5.4 some months back I was running many, many Drupal sites on 5.3 (though not versions as old as 5.3.3, that's pretty old these days). In over a year on dev/test/live I've never seen a single Drupal problem that was caused by the PHP version.

On another note, you really need to update your version of Drupal. We're currently on 7.22 and there have been a lot of security/bug fixes since the release you have installed.

You might also want to have a look at the PHP5.3 compatibility group, there's more detailed information there.
> 3 votes

# Answer
There was several security issues between Drupal 7.1 and current 7.22, so you should upgrade anyway. If you will not, you can expect problems no matter if php will or will not be upgraded. And 7.22 works OK on PHP 5.3.x - unless you are using custom or outdated modules that doesn't.
> 2 votes

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