# Question
Title: Subtract one field from another (Quiz, Getting difference between revisions)
I am using the evaluation quiz module. Users fill out the question and (not using the score that is calculated by the quix module) they are given a score by giving each of their answers points which are then totaled.

I'm wondering is there an easy way to subtract one revision of the users answer from another revision to get the difference.

I have no problem getting the results from each revision but just dont know how to subtract the second to latest revision from the latest revision.

# Answer
I could not find a module which does the same, but you can achieve this by custom codes.Not the exact codes but still covers the major things

```
  // get all revisions for a node
  // this function returns array of revision in order of revisions are created,with the latest revision at the top and last revision as the next array element
  $get_revisions = array_values(node_revision_list(node_load($node_id))));
  if(count($get_revisions) > 1) {
    $current_node_version = $get_revisions[0]->vid;
    $last_node_version = $get_revisions[1]->vid;
  } else {
    // No differnece,since there is only one version.
  }

  //Now load the nodes with the versions
  $current_node = node_load($node_id,$latest_node_version);
  $last_node = node_load($node_id,$last_node_version);

  // Once you have loaded nodes you can easily do the custom calculations,something like
  $field_1_diff = $current_node->field_1_diff... - $last_node->field_1_diff...

```
> 1 votes

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


# Question
Title: Openid account validation without password reset
I enabled Openid, and installed the OpenID selector module. When a user logs in via openid, they have to validate their email, and the way to do so is by drupal sending them a one-time login link to reset their password. Is there any other way to validate the email address? Sending a password reset link is confusing for users.

# Answer
> 0 votes
If you want your users to be able to setup their own password, check out LoginToboggan. It adds password fields on the front-end user registration page and optionally links non-verified accounts to a "temporary" role on the site, if you want to limit their behavior/actions until they confirm the email.
It also features a lot of other goodies and tweaks, which make the registration/login process much easier.

Another option is Email Verification, which checks if the domain or host of the email address exist, and tries to validate the account by sending `HELO/MAIL FROM/RCPT TO` to the host's SMTP server.

---
Tags: 7, authentication-authorization
---


# Question
Title: Create new content node upon user creation with populated fields from user profile fields d7
why is it that ordinary tokens appear in fields where use is made of the "token field" and "field default token" modules?

I created a rule which creates a node with the username in the user creation form. I need to have fields in this new node to be populated by custom fields in the user creation form using tokens.

ordinary tokens work fine, tokens from custom fields either turn out as blank for the "field default token" module or as the token name in "token field" module.

Am I missing something?

More Information as requested in the comments:

I have custom fields on the standard user profile. When a user account is created, a content node is created, using the "rules" module. That node's name is pulled off the user profile using the "token" module, the token being for one of the custom fields. This works 100%. Now I want to do the same for two fields in the new content node, i.e. pulling content from the user profile's custom node's and placing them into the content node. This can be done with "field default token" or "token field". For some reason only standard drupal tokens work, tokens for custom fields don't, as described.

# Answer
> 0 votes
This seems to have to do with porting data from a content node field to a user node field. I solved this by creating the User and then creating the node with data pulled from the user node fields.

---
Tags: entities, tokens
---


# Question
Title: Why is my subtheme screenshot not appearing?
I have created a subtheme, and it shows up correctly on the admin/appearance page, but I can't seem to get my screenshot to appear. It only displays the screenshot from the base theme. I have declared the screenshot in mytheme.info, and the PNG file is sized to exactly 294 x 219. Any ideas?

Thanks!

# Answer
Sub theme by default inherit the screenshot from base theme.You can override the screen shot by simply adding screenshot of your sub theme in your sub theme directory

> The optional screenshot key tells Drupal where to find the theme's thumbnail image, used on the theme selection page (admin/build/themes). If this key is omitted from the .info file, Drupal uses the "screenshot.png" file in the theme's directory.
>
> Use this key only if your thumbnail file is not called "screenshot.png" or if you want to place it in a directory outside of your theme's base directory (e.g. screenshot = images/screenshot.png).

```
screenshot = screenshot.png

```

Reference: https://drupal.org/node/171205#screenshot

Other things which may help.

1. As Jhilke comment try clearing your caches.
2. Check the screenshot file permission it should readable by web-server.
> 4 votes

---
Tags: theming
---


# Question
Title: Managing different view modes for a single content type
I have three different view modes for a single content type on my site. Besides the default and teaser view modes, using Display Suite, I made a custom one called "simplified" . What I need is to make a page view with a list of node titles which would link to the nodes in the simplified view mode, which would themselves contain a link to the full content view mode.

I am not sure as to what the best way to do this would be. It could be something very simple which I failed to think of, since I am relatively new to Drupal.

I also found the View Mode Page module, which is a great idea, but it doesn't seem to work at all.

# Answer
> 3 votes
One way to do it:

1. Set up the default view mode to be a simplified version
2. Enable display suite extras, then "View mode switcher" under "Other"
3. In the detailed and simplified view modes, add the "Switch view mode" field
4. Configure the Switch view mode in each instance to provide links to the other view mode

Your view then should link to your content type with the simplified view and give the user links to toggle the view back and forth between detailed and simplified.

Note that Display suite extras also has a feature called "Switch View Mode", which allows you to set the initial view mode on a node by node basis.

More info in this video: https://www.youtube.com/watch?v=tiUzobRKKco

Edit: I notice that if you enable "Switch View Mode" in DS extras, there is also the option to use view mode switching by URL, by appending ?v=viewmode to the URL. So, that's another option for linking to a specific view mode from your view. In that case, you'd need to use the Rewrite feature of views to build your own Title links that include the extra view mode parameter.

---
Tags: 7, entities
---


# Question
Title: Cannot Change Max Upload Size in File Field From 8mb
I have made changes to etc/php5/apache2/php.ini to increase max file upload size to 100mb but when I try to raise or lower the file upload size when creating a file field in a content type, it says that the current limit 8 MB even though the field saves the previous input. Anyone have any experience with this issue and could provide a solution?

# Answer
> 5 votes
There are three variables in php.ini that could be limiting your upload size.

Look for the following in php.ini:

```
memory_limit = 32M
upload_max_filesize = 10M
post_max_size = 20M

```

I imagine one of these is set to 8M in your case.

Also, you will most likely have to restart apache after making the change to php.ini.

# Answer
> 1 votes
While working with Drupal site, to increase/decrease memory of PHP, you can use

```
ini_set('memory_limit','100M');

```

in the ***settings.php*** file.

You can verify the memory limit by going to **Status Report** of your site, i.e. ***admin/reports/status*** where you can see PHP Version, PHP Memory Limit, etc.

---
Tags: nodes, files
---


title: Add shiping cost on add product page

text:
# Question
Title: Add shiping cost on add product page
Can some one please tell how it is possible to add the shipping prices from Add Product Page. Actually I want to add the field on product page where the store admin can define the rates for each specific product type.

# Answer
> 2 votes
I wrote a module that does this!

https://drupal.org/project/commerce\_shipping\_field

It allows you to define a shipping cost for each individual product. Let me know if you have any other questions!

# Answer
> 0 votes
This can be done using the Ubercart global quote

Ubercart Shipping quote module that provides custom shipping quotes based on configurable weight ranges and custom shipping zones.

# Answer
> 0 votes
This was possible in Shipping 1.0 for Drupal Commerce 1.3. You can see more information about this on a post I did in Drupal.org here http://drupal.org/node/1778566.

1. What you need to do is create the shipping price field on your products and set the value of shipping per items.
2. Next you need to create a plugin for checking the cost of shipping via that field.
3. Voila you are done.

Hint: The code in that link can be used exactly for your project...

---
Tags: rules, commerce
---


# Question
Title: How to do result biasing in Apache Solr by node rating?
I have a site with Drupal 7 with Apache Solr & rate module. In this site I have a content type that can be rated but search results are not being biased towards the better rated content.

If I go here: admin/config/search/apachesolr/env-solr/bias I found 3 kinds of biasing:

* result biasing
* type biasing
* field biasing

None of these sections/tabs give me an option to bias the search results to the content that has a better rating.

I know I can relate a View with the search and order the content by rating, but that's not biasing exactly.

Any help would be appreciated. Thanks.

# Answer
I think the Apache Solr Voting API module is just what you're looking for. It seems to have grown out of this issue. In limited testing I found that enabling it does add a bias setting for vote rankings:
> 2 votes

---
Tags: search, rating
---


# Question
Title: Create a menu block based on path using views
I'm trying to use views 3 to create a view that I can place in a block that is based on the url path

For example

example.com/student/ example.com/student/page1 example.com/student/page2 example.com/student/page3

All 4 pages are in the menu along with other pages Students page1 page2 page3

I want to create a view that will display (dynamically) on pages with the following url pattern example.com/student/\* I want the view to only return child menu items that have Student as a parent.

I'm working with menu view, but I can not get the contextual filter and relationship to work correctly. Any tips. Or an alternate way to accomplish

# Answer
You can simply use Menu Block module to accomplish this task. If you want to display a block on specific pages just goto the relevant block configuration and under " Show block on specific pages" select "Only on listed pages" define the following

student/\*

Now your block will appear only if this URL pattern will match. No matter what you have used to create your block.
> 0 votes

---
Tags: routes, views
---


# Question
Title: Hide menu backend side for different roles/users
I'd like to hide some menu on the backend side /admin/structure/menu and make the hidden items to disappear of the navigation menu for a specific user/role.

I managed to hide the list of the menu visible in the page /admin/structure/menu but it's just the list which as been changed, meaning they can access by accessing to the url.

```
function module_menu_alter(&$items) {
    $items['admin/structure/menu/manage/devel']['page callback'] = 'module_change_devel';
    $items['admin/structure/menu']['page callback'] = 'module_change_menus';
}

function module_change_menus() {

    global $user;
    if(!in_array('administrator', $user->roles)){
        $result = db_query("SELECT * FROM {menu_custom}
            WHERE menu_name='menu-contact-us'
            OR menu_name='menu-1'
            OR menu_name = 'menu-3'
            OR menu_name = 'menu-2'
            ORDER BY title",
            array(),
            array('fetch' => PDO::FETCH_ASSOC));
    }
    else{
       $result = db_query("SELECT * FROM {menu_custom}
           ORDER BY title",
           array(),
           array('fetch' => PDO::FETCH_ASSOC));
    }
    $rows = array();
    $header = array(t('Title'), array('data' => t('Operations'), 'colspan' => '3'));
    foreach ($result as $menu) {
    $row = array(theme('menu_admin_overview', array('title' => $menu['title'], 'name' => $menu['menu_name'], 'description' => $menu['description'])));
    $row[] = array('data' => l(t('list links'), 'admin/structure/menu/manage/' . $menu['menu_name']));
    $row[] = array('data' => l(t('edit menu'), 'admin/structure/menu/manage/' . $menu['menu_name'] . '/edit'));
    $row[] = array('data' => l(t('add link'), 'admin/structure/menu/manage/' . $menu['menu_name'] . '/add'));
    $rows[] = $row;
    }
    return theme('table', array('header' => $header, 'rows' => $rows));

}

function menu_change_devel() {

    global $user;
    if(in_array('administrator', $user->roles) == 1){
        $items['admin/structure/menu/manage/devel']['access arguments'] =  array('aminister users');
        return $items;
    }
}

```

But the function menu\_change\_devel which is supposed to give the access to admin/structure/menu/manage/devel for the user having the permission to aminister users doesn't seem to work :(

Any idea ?

Cheers

EDIT : I found the solution

```
function MODULE_menu_alter(&$items) {

    //deny the menu if they are not admin (if they don't have the acess right to adsminister users)
    $items['admin/structure/menu/manage/%menu']['access callback'] = array('MODULE_check_menus_access');
    $items['admin/structure/menu/manage/%menu']['access arguments'] = array(4, 'administer menu');
    //edit
    $items['admin/structure/menu/manage/%menu/edit']['access callback'] = array('MODULE_check_menus_access');
    $items['admin/structure/menu/manage/%menu/edit']['access arguments'] = array(4, 'administer menu');
    //add
    $items['admin/structure/menu/manage/%menu/add']['access callback'] = array('MODULE_check_menus_access');
    $items['admin/structure/menu/manage/%menu/add']['access arguments'] = array(4, 'administer menu');
}

function MODULE_check_menus_access($menu, $permission){
    global $user;
    $account = $user;

    if (user_access($permission, $account)) {
        if(array_key_exists ($menu['menu_name'], $menuList)){
            return user_access('can manage '.$menu['menu_name'], $account);
        }
        else{
            return true;
        }
    }
}

/**
 * Implements hook_permission().
 */
function MODULE_permission() {
  return array(
    'can manage navigation' =>  array(
      'title' => t('Can manage navigation menu'),
      'description' => t('Limit access to the navigation menu'),
      ),
    );
}

```

# Answer
> 1 votes
You can use Menu item visibility module to hide the item for specific user role.

> This module exposes configurable and extendable visibility settings for menu links. For example, if you want to create a 'My account' link that points to /user, both anonymous and registered users have access to the /user path, so both will see the link, even if anonymous users do not technically have an account. Using this module will allow you to only have your 'My account' link visible to registered users, and hide it from anonymous users.

# Answer
> 1 votes
I found the solution: function MODULE\_menu\_alter(&$items) {

```
    //deny the menu if they are not admin (if they don't have the acess right to adsminister users)
    $items['admin/structure/menu/manage/%menu']['access callback'] = array('MODULE_check_menus_access');
    $items['admin/structure/menu/manage/%menu']['access arguments'] = array(4, 'administer menu');
    //edit
    $items['admin/structure/menu/manage/%menu/edit']['access callback'] = array('MODULE_check_menus_access');
    $items['admin/structure/menu/manage/%menu/edit']['access arguments'] = array(4, 'administer menu');
    //add
    $items['admin/structure/menu/manage/%menu/add']['access callback'] = array('MODULE_check_menus_access');
    $items['admin/structure/menu/manage/%menu/add']['access arguments'] = array(4, 'administer menu');
}

function MODULE_check_menus_access($menu, $permission){
    global $user;
    $account = $user;

    if (user_access($permission, $account)) {
        if(array_key_exists ($menu['menu_name'], $menuList)){
            return user_access('can manage '.$menu['menu_name'], $account);
        }
        else{
            return true;
        }
    }
}

/**
 * Implements hook_permission().
 */
function MODULE_permission() {
  return array(
    'can manage navigation' =>  array(
      'title' => t('Can manage navigation menu'),
      'description' => t('Limit access to the navigation menu'),
      ),
    );
}

```

---
Tags: 7, routes
---


# Question
Title: how to display filed values form People » Account settings » Manage fields
I've added few more fields in "Administration » Configuration » People » Account settings » Manage fields". See the attached screenshots for more details.
Now I want to display user's First name & Last name in page.tpl file. I know that name can be diplayed like this "$user-\>name". But I want to know how other filed values can be displayed. I want to display the fileds First name, Last name, Phone, Address

# Answer
If you want to display `first name` and `last name` of the logged in user, then you can follow the below code snippets.

```
global $user;

$account = user_load($user->uid);

print "First name:" . $account->field_f_name[LANGUAGE_NONE][0]['value'];
print "Last name:" . $account->field_l_name[LANGUAGE_NONE][0]['value'];

```

The global `$user` object does not load the fields which are attached to user profile. So, We need to use function `user_load()` in code.

If you want to display `First Name` and `Last Name` of the user profile, then you need get uid of the user from the arguments.

```
$uid = arg(1);

$account = user_load($uid)

```
> 3 votes

# Answer
The following can be implemented to get the user details

```
global $user;
$user_load = user_load($user->uid);
$user_load->field_f_name[LANGUAGE_NONE][0]['value'] ;
$user_load->field_l_name[LANGUAGE_NONE][0]['value'] ;
$user_load->field_phone[LANGUAGE_NONE][0]['value'] ;
$user_load->field_address[LANGUAGE_NONE][0]['value']

```
> 0 votes

# Answer
A better way is using the Field API.

I'm not sure which variables are you handling on the page.tpl.php

As harsal says, you can use the global variable $user, but to access each field of the current user, you could do it like this (for example for phone would be):

```
echo render(field_view_field('user', $user, 'field_phone', array('label' => 'hidden')));

```

Additional tip: to protect each field against XSS attacks, you cloud use the Drupal function filter\_xss()
> 0 votes

---
Tags: users
---


# Question
Title: Module broken by drupal core update (mysql_num_rows)
So I just updated my Drupal core to the latest (6.2.9) because of the many critical security recommendations.

I have a module which I built and previously, just before the update I had tested the module which uses a hook\_cron() function and everything seemed to work as expected.

After the update It seems completely broken, I keep getting a warning "warning: mysql\_num\_rows() expects parameter 1 to be resource" which I have read a lot about others having the same problem in other threads, couldn't find a solution which worked, but the thing is, it was literally just working for me!!

I ran the `$result` query in a shell and it seems to return the expected data, I don't know what the problem suddenly is. All other modules appear to work normally.

```
function httprequest_cron() {
  $result  = db_query("SELECT nid FROM {httprequest}");
  if (mysql_num_rows($result)) {
  // results returned
  $url = 'http://localhost:3000/blog?status=fetch';
  $result = drupal_http_request($url);
  if (isset($result) && in_array($result->code, array('200', '302', '307')) && $result->data != '') {
  db_query("DELETE FROM {httprequest} WHERE nid");
  }
  }
  else {
  // no results, but good query
  }
}

```

# Answer
> 2 votes
You should use `db_affected_rows()` function of the Drupal instead of `mysql_num_rows()` function of mysql to check number of rows result from query.

Your code should be:

```
$result  = db_query("SELECT nid FROM {httprequest}");
    if (db_affected_rows()) {
    //your code
    }

```

Instead of

```
$result  = db_query("SELECT nid FROM {httprequest}");
if (mysql_num_rows($result)) {
//your code
}

```

# Answer
> 0 votes
I think there's something wrong on your first query:

```
db_query("SELECT nid FROM {httprequest}");

```

maybe is returning FALSE.

If you need to check how many rows returns certain query, try to use the Drupal database API. For example:

```
$result = db_query('SELECT COUNT([table field]) FROM {[database table]}');
  if (db_result($result) > 0) {
      ....
  }

```

---
Tags: 6, database, hooks
---


# Question
Title: Disable displaying user picture in page--user.tpl.php
I don't want to display the user picture on the user account page. It is not a field, so I can't simply hide it in display settings. How can I disable it in Drupal 7?

# Answer
> 6 votes
If you don't want it at all in the user registration you can navigate to : **admin/config/people/accounts/settings** and uncheck "*Enable user pictures*" on that page.

If you dont want it only on the user profile page you can add this snippet to `template.php` in your theme folder

```
function THEME-NAME_preprocess_page(&$variables){
  if (arg(0)=="user" || arg(0)=="users" ){
    unset ($variables['page']['content']['system_main']['user_picture']);
  }
}

```

# Answer
> 0 votes
If you want to get rid of it, go to **admin/config/people/accounts/settings** and uncheck "*Enable user pictures*" on that page. Notice this will remove the picture form from registration and profile editing forms, as well as comments, nodes and profiles where this used to show up.

If you want to remove it from the profile page only, just preprocess the profile picture out in `template.php`:

```
function THEMENAME_preprocess_user_profile(&$variables) {
  unset($variables['user_profile']['user_picture']);
}

```

# Answer
> -1 votes
If you want to disable the avatar picture in Drupal 7 for any roles in edit case, then you need to change this:

```
function hook_form_alter(&$form, &$form_state, $form_id) {
  global $user;
  if ($form_id == "user_profile_form") {
    if(in_array ( {role_id}, array_keys ( $user->roles ) )) {
      $form ['picture']['#access'] = '0';
    }
}

```

This is working for my case.

---
Tags: 7, users
---


# Question
Title: Use Checkboxes with Drupal Better Exposed filter
Better Exposed Filters is not showing the option for Radio buttons and Check boxes. How do I enable it?

Better Exposed Filter working well and good until I enable the Auto Submit option. My Check boxes are gone and shows simply the list. So I uncheck the auto submit, but still i don't get the options to choose.

The filter criteria are set to "Content: Has taxonomy term"; the selection type is "Dropdown."

# Answer
> 6 votes
This also tripped me up. The settings weren't where I expected them to be and there were a couple of prerequisites. Maybe this is your issue too?

1. Create a View and expose a filter
2. Under *Advanced \> Exposed form \> Exposed form style* select *Better Exposed Filters*
3. Under *BEF Settings* roll down to the bottom where there are the *Exposed Filter settings* and select Checkboxes/Radio Buttons from the drop down menu.

**Note**: You can't select these settings for filters that don't have a limited number of options. (A title won't work, but a term will.) The documentation says:

> BEF only operates on fields that have a limited number of options such as Node:Type or Taxonomy:TermID. Open-ended fields, such as Node:Title, do not work with BEF. Entity References do work, however, if you Enable Render Views filters as select list (a checkbox) in the Entity's entityreference field.

I had utilized the entity reference field pattern. You need to edit the field you are referencing in the *Content types \> \[content type\] \> manage fields \> \[field name\] \> edit*. field settings. There, at the bottom of the page under *Additional Behaviours* you will find a checkbox for *Render Views filters*. That will allow the aforementioned select box (in BEF settings) to properly display the Checkbox/Radio option.

# Answer
> 0 votes
It's possible to make checkboxes list for nodes. Here is a good manual for Drupal 6: Filtering A View By A List Of Nodes With Checkboxes. It helped me with D7 also.

For Drupal 7 it requires several code modifications. Unfortunately, there is no possibility to add comments on this blog with code changes for D7.

---
Tags: views
---


title: Drupal adds unneeded folder to urls

text:
# Question
Title: Drupal adds unneeded folder to urls
I've got the following problem:

We've got a hosting with 2 domains applied (second domain (the drupal site) is pointing to a subfolder of the first domain):
/data/user/www/ \< php-docroot & web-root of first domain
/data/user/www/domain2/ \< web-root of second domain & drupal install

calling http: //domain2.tld/ succesfully showing the drupal site, but instead of:
http: //domain2.tld/content/contact, drupal generates url like:
http: //domain2.tld/domain2/content/contact

I think the problem may be the php-docroot, which is the same for domain1 and domain2.

How to tell Drupal to supress the /domain2/ part in urls?

# Answer
Like i noted above, drupal thinks it's installed in a sub-folder because of the php-docroot lies in the parent-folder of the drupal-install, so it added /domain2/ to the $base\_url.

To fix it, just edit your current settings.php in sites/\* folder:

$base\_url = 'http://domain2.tld'; // NO trailing slash!

Make sure settings.php is writable, it's often read-only!
(this was the problem here, otherwise i would've saved a lot of time searching a alternative ways to fix the $base\_url... looks like there's a overhaul needed in my svn:post\_commit-ftp\_upload-script ;)
> 0 votes

---
Tags: uri
---


title: Jquery ui dialog does not work?

text:
# Question
Title: Jquery ui dialog does not work?
In .module file for a function hook\_form\_alter() I have the following code:

```
  drupal_add_library('system', 'ui.dialog');
        drupal_add_js(drupal_get_path('module', 'abc') . "/custom.js");

```

In .js file I have the following code :

```
var abc = $('#inst').val();
var data = 'Please confirm it';
if (abc == "" ) {
alert(abc);
$("#dialog").html(data);
                    $('#dialog').dialog({
                        modal: true,
                        autoOpen: false,
                        width: 600,
                        buttons: {
                            "Ok": function() {
                                $(this).dialog("close");
                            }}
                    });
                    $('#dialog').dialog('open');
}
                    return false;
                }

```

I am not able to get the dialog whereas I am able to get the alert(abc); What is the error in the code?

# Answer
> 1 votes
You are using `dialog` method like simple substitution for `alert`.

```
$(this).dialog("close");

```

But it isn't. It works that way:

```
$( /* DOM node you want to turn into a dialog */ ).dialog( /* dialog options */ );

```

So your code should look like this:

```
$('<p>' + Drupal.t('Close') + '</p>').dialog({ modal: true });

```

Note that you need jQuery Update module, or one of it's substitutes, to have dialog method available. You need jQuery UI version 1.0 or later, and jQuery Update adds 1.8.11 or (in dev branch) 1.10.1 so as long as you have it at all, you don't need to worry.

Full documentation here: http://jqueryui.com/dialog/

---
Tags: 7, javascript
---


# Question
Title: Display rendered node in view mode X in self node in View mode Y
How can I render a node in itself in a different view mode?

# Answer
If you want to do this job the one way is achieve in `node.tpl.php` (and sub tpls like `yourcontenttype--node.tpl.php` ), and according to variables in node tpl you can use both **teaser** or **full** mode of node .also you can add your desire variable in theme preprocess ... , there is another ways to do this with more developing solution
> 1 votes

---
Tags: nodes
---


title: Where this javascript included?

text:
# Question
Title: Where this javascript included?
In my Drupal site I got this error in google chrome console:

```
GET http://domain.com/file?mq8c07 404 (Not Found)

```

But I can't find where this file is included, how can I find it?

# Answer
there is a lot of ways a javascript file may be included. Ex: theme.info | drupal\_add\_js etc. Try clear cache and if not work try to see if you delete any file or some module require any file.
> 0 votes

# Answer
The simple way is search this URL in your codes completly , if you reach bash command prompt you can do it by **grep** command .
> 2 votes

---
Tags: 7, javascript
---


# Question
Title: How do you theme an autocomplete dropdown
I'm trying to theme an autocomplete dropdown from a textfield. In this case the autocomplete is provided from the finder module.

I need to theme it beyond just simply adding css. Ideally I'd like a theme function to override or a template file but I can't find one.

I have tried using the theme function which is provided by the finder module, however all that does is theme the resulting page, not the autocomplete drop down.

Can anyone advise?

# Answer
> 1 votes
To theme the Drupal 7 finder autocomplete dropdown take a look at this video. Generally you write PHP into the 'Rewrite' settings on the advanced options of the finder. I would avoid using the theme() function, it might be obsolete.

To theme the Drupal 6 finder version, you may find this article helpful. It uses theme functions.

---
Tags: forms, ajax
---


# Question
Title: how to create a new node of a content type when a new node created of another content type?
my problem is : I have a content type called job posting, every job post will associated with a test set that every candidate should write to get qualified for that job i.e., when I create a node of job posting content type another node of type test has to be automatically created.

what is the best approach towards it. It thought to try actions, but it is won't help me in any way. could any body suggest me a way to do it.

# Answer
> 2 votes
As said by @drupality

```
function hook_node_insert($node) {
 if ($node->type != 'job_posting') {
   return;
 }
$node = new stdClass(); // Create a new node object
$node->type = "test";
node_object_prepare($node); // Set some default values

$node->title    = "YOUR title";
$node->language = LANGUAGE_NONE; // Or e.g. 'en' if locale is enabled

$node->uid = 1; // UID of the author of the node; or use $node->name

.
.
.//Enter your other field values
.
node_save($node);
}

```

---
Tags: nodes, hooks, actions
---


# Question
Title: Target single block with amended theme function?
I have amended `theme_user_list` so that the user picture is printed out just before the username. I would like to use this function only on the `Who's online` block. Is there anyway I can make this block be the only target for my amended function? Thanks.

```
function MY-THEME_user_list($variables) {
  $users = $variables['users'];
  $title = $variables['title'];
  $items = array();

  if (!empty($users)) {
    foreach ($users as $user) {

      // $items[] = theme('username', array('account' => $user));

      $picture = theme_get_setting('toggle_comment_user_picture') ? theme('user_picture', array('account' => $user)) : '';
      $username = theme('username', array('account' => $user));
      $items[] = $picture . $username;
    }

  }
  return theme('item_list', array('items' => $items, 'title' => $title));
}

```

# Answer
you can use preprocess\_block function as follows:

```
 function mytheme_preprocess_block(&$variables) {
      if ($variables['block_id']->bid === 'target_block_id') {
       $users = $variables['users'];
      $title = $variables['title'];
      $items = array();

      if (!empty($users)) {
        foreach ($users as $user) {

          // $items[] = theme('username', array('account' => $user));

          $picture = theme_get_setting('toggle_comment_user_picture') ? theme('user_picture', array('account' => $user)) : '';
          $username = theme('username', array('account' => $user));
          $items[] = $picture . $username;
        }

      }
      return theme('item_list', array('items' => $items, 'title' => $title));
      }
    }

```
> 0 votes

---
Tags: theming
---


title: Ways to filter drupal search results

text:
# Question
Title: Ways to filter drupal search results
I'm running into some trouble to setup a search in Drupal between some related nodes with some decent filters.

I've tried to use **search\_api**, **search\_api\_db** & the **facet\_api**, it work's like a charm except that there doesn't seem to be a functionality to select multiple options to filter on. (or functionality).

For example when you've got a list with some options:

* Option 1 (10)
* Option 2 (2)
* Option 3 (8)

When you click Option 1, facet\_api will only show:

* x Option 1 (10)

I'd like the possibility to select multiple options, and extend my filter.

* x Option 1 (10)
* Option 2 (2)
* x Option 3 (8)

While searching I ran into some issues posted at drupal.org that state that it's possible with search\_api\_solr but not with search\_api\_db.

http://drupal.org/node/1390586 (Implement support for search\_api\_facets\_operator\_or - search\_api\_db)

http://drupal.org/node/1679974 (Allow multiple checkboxes to be selected in a facet - FacetAPI )

My question is: **Is it possible with the search\_api, search\_api\_db and facet\_api to let this work, or are there other solutions out there that will provide the functionality described above?**

**It needs to work with multiple facets and update the number of results behind the options.**

# Answer
I think you can change your facets to using the facetapi to use checkboxes instead of links. I believe you can go into your index and then edit the facet and choose under Display Widget: Links with checkboxes.
> 0 votes

# Answer
The answer to your question is as follows:

1) Within that facets filters - **un-check** *"Do not display active items"*

2) Within that facets display - **select** *"Or"* \- **N.B. This option will only be available on Solr driven servers!**

I hope that helps!

---

Originally found here: Allow multiple check-boxes to be selected on a facet

Thanks goes to: deggertsen
> 0 votes

# Answer
You could achieve multiple facet selections with Apachesolr module:

> This module integrates Drupal with the Apache Solr search platform. Solr search can be used as a replacement for core content search and boasts both extra features and better performance. If you're looking for Apache Solr integration, this is possibly the best option available.
> -2 votes

---
Tags: search
---


# Question
Title: Registration form customization to meet COPPA and similar "under 13" laws?
I want to add an extra field for user age. If age is below 13, it should show another text input for getting mail address of user's parent or other legal guardian. Accounts with age under 13 should only be activated after email verification by said parent.

How can I add this field, validate age and process validation mail?

# Answer
> 3 votes
Simply go to *Home \> Administration \> Configuration \> People \> Account settings* and add fields you need. Use Conditional Fields module to conditionally show a text box.

Now you need to use Rules. See registration rules post for example - what you want is to automatically enable account if checkbox is empty, and send email if checkbox is checked. How to do the very last thing, and how to process verification link, is a material for a separate question.

Questions that may help with further development a bit:

---
Tags: forms, users
---


title: Drush pm-update strange behavior

text:
# Question
Title: Drush pm-update strange behavior
I have a bunch of sites running both on Drupal 6 and Drupal 7 on my server. Every site has its own folder (ie. I don't use multisites feature). I created a small script to run `drush pm-update` on every site.

All of this is working okay, but I noticed something strange. Often when I run, either manually or via the script above mentioned, the `drush pm-update` finds a update for a version of a module or core in one site, but not for others.

I tried to clear drush cache but it showed no result.

Have anyone seen this behavior and has a hint of what it is? I'm curious about it :-)

**Update**: Now I think it's related to this issue https://drupal.org/node/952394

# Answer
The thing is, every Drupal site has a variable, in `{variable}` table, called `update_last_check` that stores the last time the site had a update check. This variable is mostly update by Drupal cron. It happens that, in some of my sites, this date is too small to need a new check, so Drush skipped it and considered the site up to date. So, in other words, if you want to ensure there's a new update, you should first run a `drush cron` and then run a `drush pm-update`.
> 3 votes

---
Tags: drush
---


# Question
Title: How to identify permissions which current user lacks to access node create page?
I have a user with custom role. This role has permission custom-type: create new content.

When I try to access `node/add/custom-type` I am getting 403. Site is quite complex. What is the quickest way to find which permissions I need to add to this user role to access that page?

# Answer
Devel Node Access (DNA) provides detailed information on permissions that take effect.

> View the node access entries for the node(s) that are shown on a page. Essential for developers of node access modules and useful for site admins in debugging problems with those modules.

Unless some modules abuse access system with dirty hacks, it should pretty reliably identify which module refused access to given user.
> 1 votes

---
Tags: 7, users
---


title: Date field: prepopulate off

text:
# Question
Title: Date field: prepopulate off
When adding a new node with a date field in it, the date field is prepopulated with the current date. Is there a way to easily switch that feature off so that the date field is empty?

# Answer
You can set the default-values in your Content-type \> Field-settings \> More settings and values \> Default values, (Now, Relative, No default value) set it to "No default value".
> 2 votes

---
Tags: datetime
---


title: colorbox content wrong size

text:
# Question
Title: colorbox content wrong size
I created a page in Drupal 7 using two pictures and would like to display them with color box. The link: http://quaaoutlodge.com/content/salmon-run now two problems: There for some reasons seem to be 4 pictures in the group, two of which are totally out of size and get stretched to 650 x 800 px but I just want them to show in their original size. How can I get rid of the stretched ones?

# Answer
> 1 votes
In ur html `rel="gallery-all"` is available which means you allow to load all the images in the galery or page, for resolving your issue (for single load) remove this rel attribute.

The rel attribute specifies the relationship between the current document and the linked document.In colorbox "gallery-all" means it will load all images to colorbox. For eg here load 4 images, perhaps select "single" load the main image

# Answer
> 0 votes
I checked your page/colorbox, the colorbox-size seems to be correct, the box has the size of the shown image.
So i suggest that you check the image-style settings of the "gallery-cblarge"-imagestyle.

---
Tags: media, javascript
---


title: Multi-site just separated content

text:
# Question
Title: Multi-site just separated content
There is a lot of blog posts and tutorial about multi-site with content sharing.

But what about inverse of it? Multi-site with separated contents?

Exactly which tables should be shared?

here is my settings.php for sub-site:

```
$databases = array(
    'default' =>
    array(
        'default' =>
        array(
            'database' => 'xxx',
            'username' => 'xxx',
            'password' => 'xxx',
            'host' => 'localhost',
            'port' => '',
            'driver' => 'mysql',
            'prefix' => 'default_portal_',
            'prefix' => array(
                'default' => 'default_portal_',
                // Users
                'users' => '',
                'sessions' => '',
                'role' => '',
                'role_permission' => '',
                'authmap' => '',
                'blocked_ips' => '',

                // Blocks
                'block' => '',
                'block_custom' => '',
                'block_node_type' => '',
                'block_role' => '',

                // CKEditor
                'ckeditor_input_format' => '',
                'ckeditor_settings' => '',

                'comment_notify_user_settings' => '',

                // Configuration
                'date_formats' => '',
                'date_format_locale' => '',
                'date_format_type' => '',
                'field_config' => '',
                'field_config_instance' => '',
                'filter' => '',
                'filter_format' => '',
                'i18n_block_language' => '',
                'i18n_string' => '',
                'i18n_translation_set' => '',
                'image_effects' => '',
                'image_styles' => '',
                'languages' => '',
                'locales_source' => '',
                'locales_target' => '',
                'node_type' => '',
                'quicktabs' => '',
                'rdf_mapping' => '',

                // Support
                'support_assigned' => '',
                'support_client' => '',
                'support_priority' => '',
                'support_reference' => '',
                'support_states' => '',
                'support_ticket' => '',
                'support_ticket_comment' => '',

                // System
                'system' => '',
                'taxonomy_term_data' => '',
                'taxonomy_term_hierarchy' => '',
                'taxonomy_vocabulary' => '',
                'variable' => '',
                'variable_store' => '',

                // Views
                'views_display' => '',
                'views_view' => '',

                // WYSIWYG
                'wysiwyg' => '',
                'wysiwyg_user' => '',
            ),
        ),
    ),
);

```

**EDIT**

Above configuration works after cache clearing, but some tables should not shared: `variable` and `variable_store` because of site\_title and site\_slogan ...

**EDIT**

If I share `block` table, I should enable all themes in main site.

yet I have question to ensure which tables should share?

# Answer
> 1 votes
Yes , this is good idea, in one of my past work we do something like this, dedicated drupal core but with separate content .

---
Tags: 7, multi-sites
---


# Question
Title: How to place Drupal_Security_Do_Not_Remove_See_SA_* into httpd.conf instead of .htaccess
I run several Drupal 7 installations on a dedicated server with CentOS 6.4 and Apache 2 (the package `httpd-2.2.15-29.el6.centos.x86_64`).

I wonder, how to properly configure the Drupal\_Security\_Do\_Not\_Remove\_\* handlers in my `/etc/httpd/conf/httpd.conf` file since `.htaccess` files are disabled at my server by `AllowOverride None` directive.

Currently I have the following sections in `httpd.conf` for each of my sites:

```
<Directory "/var/www/html">
    Options Indexes FollowSymLinks
    AllowOverride None
    Order allow,deny
    Allow from all
</Directory>
......
<VirtualHost 123.123.123.123:80>
    DocumentRoot /var/www/html/mysite1.de
    ServerName mysite1.de
    ServerAlias mysite1.de *.mysite1.de

    <IfModule mod_rewrite.c>
        <Directory "/var/www/html/mysite1.de">
            RewriteEngine on
            RewriteCond %{REQUEST_FILENAME} !-f
            RewriteCond %{REQUEST_FILENAME} !-d
            RewriteCond %{REQUEST_URI} !=/favicon.ico
            RewriteRule ^ index.php [L]
        </Directory>
    </IfModule>
</VirtualHost>

```

And the recommended settings for the `.htaccess` are those here:

```
Options None
Options +FollowSymLinks

SetHandler Drupal_Security_Do_Not_Remove_See_SA_2006_006
<Files *>
  SetHandler Drupal_Security_Do_Not_Remove_See_SA_2013_003
</Files>

<IfModule mod_php5.c>
  php_flag engine off
</IfModule>

```

Should the result in my case be the following?

```
<Directory "/var/www/html">
    Options Indexes FollowSymLinks
    AllowOverride None
    Order allow,deny
    Allow from all
</Directory>
......
<VirtualHost 123.123.123.123:80>
    DocumentRoot /var/www/html/mysite1.de
    ServerName mysite1.de
    ServerAlias mysite1.de *.mysite1.de

    Options None
    Options +FollowSymLinks
    SetHandler Drupal_Security_Do_Not_Remove_See_SA_2006_006
    <Files /var/www/html/mysite1.de/sites/default/files/*>
        SetHandler Drupal_Security_Do_Not_Remove_See_SA_2013_003
    </Files>

    <IfModule mod_rewrite.c>
        <Directory "/var/www/html/mysite1.de">
            RewriteEngine on
            RewriteCond %{REQUEST_FILENAME} !-f
            RewriteCond %{REQUEST_FILENAME} !-d
            RewriteCond %{REQUEST_URI} !=/favicon.ico
            RewriteRule ^ index.php [L]
        </Directory>

        <Directory "/var/www/html/mysite1.de/sites/default/files">
            php_flag engine off
        </Directory>
    </IfModule>
</VirtualHost>

```

# Answer
.htaccess files are just convienance mechanisms to change Apache configuration without needing to restart Apache (.htaccess are scanned/run any request) -- for performance reasons you may want to place any directives in .htaccess files directly into a vhost entry so the configuration is loaded and stored only one time; on Apache startup.

From the security notice SA-2013-003:

> Warning: Fixing the code execution prevention may require server configuration; please read:
>
> To fix the code execution prevention vulnerability on existing Apache installations also requires changes **to your site's .htaccess files in the *files* directories**. Until you do this, your site's status report page at admin/reports/status will display error messages about the problem. Please note that if you are using a different web server such as Nginx the .htaccess files have no effect and you need to configure PHP execution protection yourself in the respective server configuration files.
>
> To fix this issue, you must edit or replace the old .htaccess files manually. Copies of the .htaccess files are found in the public files directory and temporary files directory, and (for Drupal 7 only) the private files directory if your site is configured to use one.

So you take whatever is in the .htaccess file in your websites configured files directories (public, private, etc) and assure those same rules are in the vhost entry for the same set of directories. Typically you do this with a `<Directory>` directive:

```
<Directory "/var/www/html">
    Options Indexes FollowSymLinks
    AllowOverride None
    Order allow,deny
    Allow from all
</Directory>
......
<VirtualHost 123.123.123.123:80>
    DocumentRoot /var/www/html/mysite1.de
    ServerName mysite1.de
    ServerAlias mysite1.de *.mysite1.de

    <IfModule mod_rewrite.c>
        <Directory "/var/www/html/mysite1.de">
            RewriteEngine on
            RewriteCond %{REQUEST_FILENAME} !-f
            RewriteCond %{REQUEST_FILENAME} !-d
            RewriteCond %{REQUEST_URI} !=/favicon.ico
            RewriteRule ^ index.php [L]
        </Directory>
    </IfModule>

    # Enforce new security rules from SA-CORE-2013-003.
    # repeat this block as needed per known "files" directories.
    <Directory "/var/www/html/mysite1.de/sites/default/files">
      # Turn off all options we don't need.
      Options None
      Options +FollowSymLinks

      # Set the catch-all handler to prevent scripts from being executed.
      SetHandler Drupal_Security_Do_Not_Remove_See_SA_2006_006
      <Files *>
        # Override the handler again if we're run later in the evaluation list.
        SetHandler Drupal_Security_Do_Not_Remove_See_SA_2013_003
      </Files>

      # If we know how to do it safely, disable the PHP engine entirely.
      <IfModule mod_php5.c>
        php_flag engine off
      </IfModule>
    </Directory>
</VirtualHost>

```

It doesnt matter if the default web directory has `AllowOverride None`; typically another conf file included down the apache startup chain, or the virtual host loading setup (such as the following in Ubuntu) can be tweaked to allow any combination of Overrides:

```
# Ubuntu apache2.conf last line ...
# Include the virtual host configurations:
Include sites-enabled/

```

This is just saying include `*.conf` from `sites-enabled` these dont *have* to be vhost entries they can be any files with apache directives (but its cleanest to have them be vhost entries) and apache loads the configuration files following a filename pattern/sort.
> 5 votes

---
Tags: security, .htaccess
---


title: Big Views query and PHP memory limits

text:
# Question
Title: Big Views query and PHP memory limits
I have a custom table, from which I create a paged table using views and data module. When I get somewhere over 15000 rows, PHP runs out of memory. Is there any way to avoid this? Thanks

# Answer
Sounds like your memory limit on your server is too low.

Have a look under Reports \>\> Status report what it is. Default on most servers are 32M. This is too low.

If you do not manage your own server then go beg your server admin to increase it. I can't give you a number, best to increase in 32Mb steps until you are happy. I normally set mine to 256Mb during development and drop it to 128Mb on fairly large sites (this is just a guideline what I do).

If your server admin does not want to change it then first answer would be to get a new provider, which I know is not always the correct route. But read here how you might be able to set it yourself. Increase PHP settings
> 2 votes

---
Tags: views
---


# Question
Title: Submitting webform without refreshing the page
I have a webform displayed as a block:

Is it possible to submit the form without refreshing the page, followed by a message saying the webform has successfully been submitted? If so, could someone guide me in the right direction?

Thanks!

# Answer
> 9 votes
Check out Webform AJAX module.

> This module adds AJAX support to Webform (3.0 and above).
>
> As a first step it focusses to simply add form AJAX paging and submit. Form submissions get ajaxified including prev/next pages. Especially for multipage forms, this leads to faster loading (less data transfer), better usability and finally smaller server load.

I think that may do what you are asking. Should then show up as options in form settings.

Also, be sure you are set to "no redirect"

# Answer
> 0 votes
There is an option on the block configuration page to "Show all webform pages in block", that will do what you what you need.

See, attachment:

---
Tags: 7, blocks, webforms
---


title: Remove custom link in teaser

text:
# Question
Title: Remove custom link in teaser
In drupal 7 I created new content type and also created new view to display nodes of this content type. After playing a bit with Calendar module I managed somehow to put link to calendar to node teaser links. Now I can see "*Read more*" link inline with "*Calendar*" link. It's pointing to calendar view which no longer exists.

Could you please advise me how to get rid of this "*Calenar*" link in teaser links? When I uncheck "Display links" in view settings (`Edit View -> Format -> Show -> Content | Teaser`), it disappears together with "*Read more*" link. But I'd like to have "*Read more*" link without "*Calendar*" link.

Thanks for any suggestions.

# Answer
Uncheck the Display links and add the below line in your `node.tpl.php` present under your themes folder `sites/all/themes/yourtheme`

```
<a href='<?php print $node_url; ?>'>read more..</a><br/>

```
> 0 votes

# Answer
If you unchecked the `Display links` from the view, then you can display the `read more` link in your `node` template file.

You need to create `node` template for your content type like `node--[contenttype].tpl.php` where `contenttype` is your content type, in your theme directory and clear the cache.

You can add below code in `node` template for your content type to display links `read more` only in teaser view.

```
if ($teaser) {

 print render($content['links']['node']);
}

```

There is another method for the same.

You can select `content` as `format` in your view and can add `title`, `Content: Link` fields in your view.
> 0 votes

# Answer
Thanks, guys, for your suggestions.

When my problem appeared, I didn't modify any tpl files, so I felt this has to be solved in some other way. When I removed this content type and view and recreated them again, calendar link was still there.

So I removed it again and created a dump of my DB. I was fulltext searching for that content type name and I found it.

In table `variable` there was variable with name `calendar_date_link_<my content type name>`. I removed it and calendar link disappeared. I hope this hasn't broken anything else.
> 0 votes

---
Tags: navigation, datetime, nodes
---


title: Link to files stored in drive

text:
# Question
Title: Link to files stored in drive
In a content type I have a links fields using Link Module which has **Title** and **URL** set. This is useful to link the external files but I have a requirements also to link the files stored in ***Networked hard disk***.

In an intranet system there is a drive eg: **Z drive**, which is same for all the systems in Intranet. The drive is actually an intranet server which stores all the doc files for everyone's use. When System Admins set-up new computers they set-up in such way that server drive is always **Z drive** in any computer *(company preference)*.

I have a task to link to the file from Drupal site, lets say the file path is:
`z:\popular-documents\how-to-use-pc.docx`

When I give the above file path to ***link field***, it changes the whole Link completely like:
`http://localhost/Z%3A%5Cpopular-documents%5Chow-to-use-pc.docx`

How can I use Link Module to link to the file and display the file link ***as it is*** instead of having `http://` which link module adds by default.

The reason I have to use Link Module is I also want to be able to link it to external files too, lets say Google docs.

**Not a requirement but good to have, *if possible*** when the link is clicked it would open the file *(I guess this is not possible from web interface)*.

# Answer
As I also stated in my comment, try to give a real network path. For example if the shared folder **Z:** is mapped to `\\server\folder`, the real network path of the file would be:

> `file:///\\server\folder\popular-documents\how-to-use-pc.docx`

UPDATE:

According to Link module page:

> Filter allowed protocols module This module allows you to change the default protocols that are set by Drupal to include new protocols like skype. The default protocols, for reference, are 'ftp', 'http', 'https', 'irc', 'mailto', 'news', 'nntp', 'rtsp', 'sftp', 'ssh', 'tel', 'telnet', and 'webcal'.

You can try this module to include 'file://' protocol.
> 2 votes

# Answer
I solved this but I admit its not sustainable solution *(if anyone is looking for something like this)*.

* Install Double Field Module
* Made a field in my content type as Double Field.
* Select both fields as string type of **varchar 255**
* Make a **label** for content admin to know that s/he must use *First field* for ***Title*** and *second field* for ***URL or Filepath***

Now when the content is created, it is saved in the database exactly what was entered.
eg:

> **File Title**-------------------- **Path**
> How to use PC ------------- z:\popular-documents\how-to-use-pc.docx
> Drupal Guide ------------- https://drupal.org/documentation
> Office Map ----------------- file://network-file/office-map.pdf

For only the *link-like-field* to be displayed as ***clickable links***, I used **jQuery** in frontend to convert any ***text*** that starts with `http(s)://` as clickable link *(like DSE does)*.

So, now I am not using Link Module.

There is performance implication if I ask **jQuery** to iterate through all the DOMs in the page, so, I decided to limit the iteration to only `div` that contains this *My created* Links, like:

```
$('#theLinkDivId li').html(function (_, html) {
                return html.replace(/((?:http|https):\/\/.+)$/g, '<a href="$1" target="_blank">$1</a>'); // with RegEx
            });

```

### Confess

This is really not a good solution, as I have to expect the content admin to fill the information in right order, instead of dictating him via the programming logic I have to request *(hope for)* him not to be naughty.

It solved my problem as I am making the site for intranet system where external factors would not be playing security risks. **So**, use at your own risk.

I am keeping this question open as I expect somebody would come with brilliant solution for these kind of use cases.
> 0 votes

---
Tags: 7, navigation, files
---


title: Attach image to taxonomy term?

text:
# Question
Title: Attach image to taxonomy term?
In my panel in "Taxonomy Term Template" I have shown the children terms in the current parent term page. Now I need to attach/associate an image to each term to make it look nice. I do see the option of selecting the term image field in the panel settings but that field shows the current parent term's image not of the children.

I have already added images for each term in my vocabulary.

I'm on Drupal 7.

Here is the screenshot to elaborate the scene.

# Answer
> 1 votes
You should make a view that lists the terms in your node (use contextual filters) and add the image fields you added to that term.

1. Create a node view that lists the node type that the categorized nodes come from.
2. Add the fields used to categorize the nodes.
3. Remove any other fields.
4. Add a contextual filter for the node id (Content:Nid).
5. Configure the contextual filter to have a default value and choose the 'id from url' option.
6. If you add that block to a region, it should show a list of terms associated with a node.
7. Now add the image field from the term, if you don't see that field you might need to add a relationship to that term field.

# Answer
> 0 votes
Maybe this helps: https://drupal.org/node/1224916. I'm going to test it myself right now.

---
Tags: taxonomy-terms, media
---


# Question
Title: How do I construct a thin controller with a dependent service?
For the first time I am trying to architect a reasonably complex Drupal 8 module, and not sure of best practice for the controller.

* I need to route paths to a controller.
* I intend the controller to be thin (very little logic, doesn't need to testable)
* Heavy lifting will be via service class/es configured and defined by the module.

Extending *ControllerBase* should be the right path for a thin controller, however when I look in Core at the moment I notice a number of controllers that both *extend ControllerBase* and implement *ContainerInjectionInterface*. I would only implement ContainerInjectionInterface to be able to inject a different container for testing, not just selection of service in the *create* method, but Core is still in flux and I am not sure exactly why they are doing this.

I feel that I should extend *ControllerBase*, add a \__construct that fetches the container and pulls in the non-standard service/s that I require via *$this-\>container()-\>get()* and indeed that does work. I also don't need the create method required to implement *ContainerInjectionInterface*.

Am I correct? I know I will need to go through a few iterations of getting the services right but want to get THIS bit right from the start and understand why I am doing it.

Thanks in advance.

# Answer
> 7 votes
ContainerInjectionInterface is used as a part of a static factory method pattern.

This way, a class's constructor can specify all of the services it needs, and its factory method, in this case `create()`, can satisfy the constructor by retrieving services from the container.

The instantiated controller should never have its own copy of the container, if at all avoidable.

A brief example:

```
<?php

namespace Drupal\book\Controller;

use Drupal\book\BookManager;
use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\DependencyInjection\ContainerInjectionInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;

class BookController extends ControllerBase implements ContainerInjectionInterface {
  protected $bookManager;

  public function __construct(BookManager $bookManager) {
    $this->bookManager = $bookManager;
  }

  public static function create(ContainerInterface $container) {
    return new static(
      $container->get('book.manager')
    );
  }

  public function bookRender() {
    $book_list = array();
    foreach ($this->bookManager->getAllBooks() as $book) {
      $book_list[] = l($book['title'], $book['href'], $book['options']);
    }
    return array(
      '#theme' => 'item_list',
      '#items' => $book_list,
    );
  }
}

```

This would be declared as a controller in a routing file like this:

`_content: \Drupal\book\Controller\BookController::bookRender`

---
Tags: 8
---


# Question
Title: Calendar: How to add additional month specific calendar views
By default - calendar will create Month, Week, Day, Year views for a calendar. The month view is for the current month. I need to create a Next Month view as well. Or perhaps a view for a specific upcoming month.

How can I do this?

Mike R

# Answer
A view of the calendar should have previous and next buttons to link to views of the previous and next months. each of these have a specific url that you can reference or use if you need to access them other than through the buttons.
> 0 votes

---
Tags: views, datetime
---


# Question
Title: Cant get desired results for multiple sort criteria in a view
I have created a points table for a race event and would like to sort the results in a specific order.

I am working with a table view that contains 3 sort criteria:

1. the race event (working fine done via table settings)
2. class of a car A, B , C and
3. the points each driver receives.

I would like the order to be A then points B then points C then points regardless of what class has the highest points.

## Problem:

If for example a C class car has points higher than any B class car then the stacking order is ACB. As soon as any B class car gets higher points than the C class car then the order is ABC (how I would like it). This can be seen in class A where Driver 2 has the lowest points of all.

I have tried re arranging the sort order but that does nothing.

# Answer
Can i suggest removing the grouping and getting the single table to display as you would like it and then once you have done that apply the grouping. It sounds as if youre sorting by points not by car class - can you change the sort to car class then add the group.

Or **group** by event and then **sort** by car class and points.
> 0 votes

# Answer
You can use hierarchical select module which has good option for customizing the hierarchical points
> -1 votes

---
Tags: views
---


title: How to get fid of taxonomy term image?

text:
# Question
Title: How to get fid of taxonomy term image?
Is it possible to get the fid of an image from a taxonomy term?

# Answer
> 6 votes
Yes, it is.

```
$tid = 1; // Term id
$term = taxonomy_term_load($tid); // Load term
// Output term data with debug()
// See watchdog log at /admin/reports/dblog
debug($term, 'Taxonomy Term');

```

For example, file fid will be

```
$fid = $term->field_image[LANGUAGE_NONE][0]['fid'];

```

You could also get the rendered image, or url with something like:

```
// Get rendered HTML image tag using image styles.
$image = theme('image_style', 'medium', $term->field_image[LANGUAGE_NONE][0]['uri']);

// Get path to image style image
$path = image_style_url('medium', $term->field_image[LANGUAGE_NONE][0]['uri']);

```

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


# Question
Title: How do I removed the breadcrumb from the front page?
I am trying to remove the breadcrumb from the front page. I am using the Bartik theme. I have a page--front.tpl.php template file and I tried to removing the following code lines.

```
<?php if ($logo): ?>
  <a href="<?php print $front_page; ?>" title="<?php print t('Home'); ?>" rel="home" id="logo">
    <img src="<?php print $logo; ?>" alt="<?php print t('Home'); ?>" />
  </a>
<?php endif; ?>

```

```
<?php if ($breadcrumb): ?>
  <div id="breadcrumb"><?php print $breadcrumb; ?></div>
<?php endif; ?>

```

I just realized that my front page isn't picking up the page--front.tpl template. Why would this happen?

# Answer
Another solution could be the Disable breadcrumbs module. The pros of the modules are that writing code is not necessary and it is independent from the theme; in this way, you don't need to alter the theme each time you change the theme being used.

> Disable breadcrumbs on a per node, per content type, or by path (any path) basis; Omitting the need to write additional code in the theme layer (template.php file etc..) to determine the visibilty of breadcrumbs on specific pages. This can be administered on node edit forms and from the content administration page (node operations) to select/unselect multiple nodes for enabled types.
> 0 votes

# Answer
You can also comment them out on the page.tpl.php like so

```
<?php /* if ($breadcrumb): ?>
       <div id="breadcrumb"><?php print $breadcrumb; ?></div>
   <?php endif; */?>

```

And then if you want them back later... take the /\* s out. :)
> 1 votes

# Answer
You can also use this code.

```
if (!$is_front && !empty($breadcrumb)) {
  print $breadcrumb;
}

```

Otherwise, go to your theme folder and remove the code in page.tpl.php. This will be remove the breadcrumbs from your site.

Be careful: It will completely remove the breadcrumbs. If you want to get them back later, then keep the code in another file.

This is the code for the Bartik theme.

```
<?php if ($breadcrumb): ?>
  <div id="breadcrumb">
    <?php print $breadcrumb; ?>
  </div>
<?php endif; ?>

```
> -1 votes

---
Tags: 7, theming, breadcrumbs
---


# Question
Title: How to retrieve default Title in custom module block
I have custom module that implements a block with our own template file to render:

```
function MODULE_NAME_block_view($delta = ''){
    $blocks = array();
    switch($delta){
        case 'twitter_feed':{
            $blocks['subject'] = t('');
            $blocks['content'] = theme_render_template(drupal_get_path('module', 'MODULE_NAME').'/inc/block--twitter-feed.tpl.php', twitter_feed_config());
            break;
        }
    }
    return $blocks;
}

```

I would like to pass the title value set in UI in blocks section to the template via the function twitter\_feed\_config specified above as following:

```
function twitter_feed_config(){
  return array(
       'title' => 'title set by user i am unable to retrieve'
   );
}

```

However, I don't seem to find a way to retrieve the value of title for this block configured via UI in the admin/block section. How to get this title value, so i can pass it to the template for rendering? Thank You

# Answer
I think you should use hook\_block\_views\_alter(&$data, $block).

Var `$data['subject'];` will have the title info of the block as per my knowledge.
> 0 votes

---
Tags: 7
---


# Question
Title: Results in view page having multiple duplicate result
I am having a gallery view page taken from a content type which is displaying the results based on relationship and contextual filters. I am getting multiple fields of a node that seem to be duplicates, even though I have checked the reduce duplicate check box in contextual filter field. Anyone can help on this issues to get perfect value.

# Answer
What version of Drupal/Views are you using? In Views v7.x-3.x you can use hook\_views\_pre\_render() in your template.php file or in a module to filter duplicate results like this:

```
function YOURTHEMENAME_views_pre_render(&$view) {
  $used_nids = array();
  $new_view_result = array();

  if ($view->name == 'YOURVIEWNAME') {
    foreach ($view->result as $row) {
        if (!in_array($row->nid, $used_nids)) {
          $new_view_result[] = $row;
          $used_nids[] = $row->nid;
        }
    }

    $view->result = $new_view_result;
  }
}

```
> 2 votes

# Answer
Edit your view and expand "Advanced" section. In "Other" subsection choose "Query settings" and check "Distinct" - that's all.
> 1 votes

# Answer
Only problem with hook\_views\_pre\_render() is that you're loosing related field values. For example if node contains multiple value referenced field you're left with only one. I have modified solution given by hachesilva slightly so you can access all values in fields array:

`function YOURTHEMENAME_views_pre_render(&$view) {`

````
$used_nids = array();
$new_view_result = array();

if ($view->name == 'YOURVIEWNAME' && $view->current_display == 'YOURDISPLAYID') {
  foreach ($view->result as $row) {
    if (!in_array($row->nid, $used_nids)) {
      $new_view_result[$row->nid] = $row;
      $used_nids[] = $row->nid;
    } else {
      $new_view_result[$row->nid]->YOURFIELDNAME[] = $row->YOURFIELDNAME[0];
    }
  }
  $view->result = $new_view_result;
}

````

`}`

Use `dpm($row);` to check avalible fields name. In my case `field_author` is named `field_field_author`. Of course You don't have to check
`$view->current_display == 'YOURDISPLAYID'`
> 0 votes

---
Tags: views
---


title: Hide the price when stock is 0

text:
# Question
Title: Hide the price when stock is 0
Is there a way to hide the price on display of a product when the stock goes to zero?

# Answer
> 2 votes
This explains how I did something similar. You'll just need to adjust your selectors to hide the price as well as the add to cart button...

Step 1 – Create New “Product Status” Field

Go to Administration \> Store settings \> Product settings \> Variation types and select “Manage Fields” for the variation type you want to modify (I just use the default “Product” variation type for my site). Add a new field called “Product Status” of the type “List (text).” For “Allowed values list,” I entered the following because it occurred to me the client might want similar display-but-don’t-sell functionality for upcoming releases…

soldout|SOLD OUT comingsoon|COMING SOON Of course you can just include the sold out line if you prefer. The string before the pipe is the machine name and the part after the pipe is what will display. Save your changes. Now go to “Manage Display” for the product variation type and add the new field for any display types you use for your products. I just use the default and teaser display types on my site. Remember to adjust the label settings (I’m guessing you want “hidden”) and to order the field so it displays relative to other fields as you desire. Save your display changes.

Step 2 – Set Products to Product Status = SOLD OUT

Go to Products \> Manage Products and edit your sold out products, setting the new status field to SOLD OUT as appropriate. Note: this is the only step the client will need to do in the future whenever he runs out of a certain product…

Screen Shot 2013-09-24 at 4.59.24 PMSave your changes.

OK – we’ve created a mechanism for indicating when something is sold out, but this doesn’t prevent site visitors from adding sold out items to their carts. Probably nobody would try to put these items in their cart, but you never know. I certainly don’t want my client to have to hassle with issuing PayPal refunds, so I’m going to make sure these products can’t be added to the cart. It seems to me the easiest way to do this is to use jQuery to remove the add-to-cart button for sold out products.

Step 3 – jQuery to Remove Add-to-Cart Button From Sold Out Product Displays

The following jQuery script simply looks for the class that wraps my Product Status (“field-name-field-product-status”): if it finds the class, it removes the Add-to-Cart form for that product. This works because Drupal’s default behavior is to not render the field and its wrapper classes if there is no data to display. In other words, only products I set to “Sold Out” (or “COMING SOON”) will have this field and class. I reiterate this technique because there are two possible display pages for products on my site (full and a teaser view), and each has a different DOM that needs to be traversed differently. You will almost certainly need to adjust my selectors for your particular needs (browser developer tools, firebug or just viewing the page source will guide you)…

```
/*Script for Gench product pages - removes add-to-cart button/form if product is sold out*/
/*wrap everything in a safety  "no-conflict" function so dollar sign works*/
(function($){
/*wait until page is fully loaded before firing script*/
$(document).ready(function(){
        /*remove add-to-cart button if product has status of sold out - for product display page*/
        $(".field-name-field-product-status").closest("td.views-field").find("form.commerce-add-to-cart").remove();
        /*remove add-to-cart button if product has status of sold out - for product teasers page*/
        $(".field-name-field-product-status").closest("div.content").find("form.commerce-add-to-cart").remove();
    });
})(jQuery);
Because I was already using javascript on my product pages, I just added the above script to the existing script, so I don’t have to do anything additional to call the new script. If you write this as a stand-alone .js file in your sites/all/themes/themename directory, you’ll need to reference the script which can be done globally in your theme’s .info file, or for select content, in your theme’s template.php file. For example…

function genchstyle_preprocess_page(&$variables, $user) {

  if(arg(0) === 'productdisplay' || 'store') {
    drupal_add_js(path_to_theme().'/js/soldout.js');
    $variables['scripts'] = drupal_get_js();
    $scripts = drupal_get_js();
  }
}

```

Here is what a product looks like when it is in stock (full display)…

And this is what it looks like when it is no longer in stock…

Again, you probably want to go with an actual inventory control module/approach for bigger/busier sites, but this kluge works pretty well for my purposes (and doesn’t preclude adding the Commerce Stock module later should the need arise).

Cheers

---
Tags: 7, commerce
---


# Question
Title: What are common methods of intrusion into a Drupal website?
I am running Drupal 6.28 that was recently hacked and there were scripts being executed out of the /tmp directory, apparently running a bitcoin mining server and other brute force scripts.

I would get random processes sometimes 2-4 at a time that would each consume over 100% cpu(core) for an indefinite period of time. Which would make sense if they were running some type of bitcoin mining operation or brute force attack.

To the best of my knowledge the attacker uploaded a file named 32.tar.gz to the site. Drupal moved this file to the /tmp directory, then attacker extracted into the same /tmp directory, which has 777 permissions.

I would gladly change the permissions on this folder to something more sane like 755, but in doing so, Drupal stops functioning properly.

All files/folders in my drupal install directory are owned like: myUser:www-data, where www-data is the user that PHP/Apache is running as.

The /tmp folder is owned by the same user and group, so I would think that it would be writable at 755, but that just isn't the case for some reason. Is there a way to harden the security of the site that would prevent this from happening?

# Answer
The first question is how they are uploading and extracting the file. That is likely only possible via a vulnerable contributed module (probably an out of date one) or because they have credentials to your server (either at the drupal layer or the server - ie ssh or sftp layer).

The second question is why your tmp directory is in a publicly accessible location (is it?). If it's not then it seems more likely the problem is arbitrary code execution or credentials compromised.

Solutions: basically you have to "start over."

* Audit every single account and permission
* Audit every single file of code - download fresh copies from drupal.org and ensure the versions on your site match them exactly.
* Install the security review and paranoia modules and read their documentation to ensure they are working properly. They will help audit your permissions and content.
> 1 votes

---
Tags: security
---


# Question
Title: How do I return JSON data compatible with the Boost module?
In a custom module a, I return a JSON string that needs to be compatible with the Boost module.

My first try was using the following code:

```
if ((isset($_SERVER['HTTP_X_REQUESTED_WITH']) && 'XMLHttpRequest' == $_SERVER['HTTP_X_REQUESTED_WITH']) || strpos($_SERVER['REQUEST_URI'], '?json') !== FALSE) {
  header('Cache-Control: no-cache, must-revalidate');
  header('Content-type: application/json', true);
  $json = loadData();
  die(json_encode($json));
}

```

This is obviously that this output won't be cached. Than I replaced the line with `die()` with the following one:

```
return drupal_json_output(($json));

```

This works, but it is not cached. I enabled the JSON output in Boost, but nothing happens.

What should I try?

---

Removing the two `header` lines does not change anything. The function `drupal_json_output` adds the `Content-Type: application/json`. But I belive that boost only accepts `text/javascript`. Also if I override the `Content-Type` again nothing will be cached.

# Answer
> 0 votes
You need to add

module\_invoke\_all('exit');

to the template-file, immediately prior to the `exit` or `die` statement. This will trigger the boost-module's code that stores the generated output in a cache-file. Additionally, you need to change the content-type to `text/javascript`.

# Answer
> 0 votes
Why do you need to cache `JSON` output? Anyhow, try removing `header('Cache-Control: no-cache, must-revalidate');` and see what happens.

# Answer
> 0 votes
Boost currently doesn't support `application/json` Content-Type. See this issue for details and patches.

# Answer
> 0 votes
This might help others who are trying to have Boost cache JSON data.

Boost wont cache **"application/json"**, but there are settings to cache TEXT/JAVASCRIPT AJAX request of type **"text/javascript"**

One problem you are going to find with : **drupal\_json\_output()** It uses : **drupal\_add\_http\_header('Content-Type', 'application/json');**

So a solution you can try is this :

```
$data = array("hello","world");
drupal_add_http_header('Content-Type', 'text/javascript');
echo drupal_json_encode($data);
drupal_exit();

```

So if you have Boost "AJAX/JSON SETTINGS" enabled it should now cache the data.

---
Tags: 7, ajax, caching
---


# Question
Title: Add javascript to views exposed form after ajax submit
I've read millions of similar posts on this but I just can't get my head around it. So far I understand that I need to use Drupal.attachBehaviors, and I've tried so many different approaches that I've seen but nothing works.

Basically I have a jQuery plugin that is styling any select boxes on the site, which works great, apart from on my views exposed form with ajax enabled. The jQuery is literally as simple as $('select').styledSelect(); after including the plugin itself.

EDIT: this is almost there:

```
      Drupal.behaviors.styledSelect = {
        attach: function() {
          $("select").styledSelect();
        }
      };

```

But now the ajax call seems to be looping.

EDIT again:

Well it seems to be something to do with the actual plugin, as other Javascript seems to work fine. I'm so close! Here is the plugin:

```
jQuery.fn.styledSelect = function(options) {
var isFF2 = jQuery.browser.mozilla && jQuery.browser.version.indexOf('1.8.')==0;
var prefs = {
    coverClass : 'select-replace-cover',
    innerClass : 'select-replace',
    adjustPosition : { top:0, left:0 },
    selectOpacity : 0
    }
if (options) jQuery.extend(prefs,options);
return this.each( function() {
    if (isFF2) return false;
    var selElm = jQuery(this);
    selElm.wrap('<span><'+'/span>');
    selElm.after('<span><'+'/span>');
    var selReplace = selElm.next();
    var selCover = selElm.parent();
    selElm.css({
        'opacity':prefs.selectOpacity,
        'visibility':'visible',
        'position':'absolute',
        'top':0,
        'left':0,
        'display':'inline',
        'z-index':1
        });
    selCover.addClass(prefs.coverClass).css({
        'display':'inline-block',
        'position':'relative',
        'top':prefs.adjustPosition.top,
        'left':prefs.adjustPosition.left,
        'z-index':0,
        'vertical-align':'middle',
        'text-align':'left'
        });
    selReplace.addClass(prefs.innerClass).css({
        'display':'block',
        'white-space':'nowrap'
        });

    selElm.bind('change',function() {
        jQuery(this).next().text(this.options[this.selectedIndex].text);
        }).bind('resize',function() {
        jQuery(this).parent().width( jQuery(this).width()+'px' );
        });
    selElm.trigger('change').trigger('resize');
    });
}

```

EDIT again:

it was the trigger 'change' that was causing the problems - I've changed it to click, and it all seems good woohoo!

As ever, thanks for everyone's wonderful advice.

# Answer
You'll need to wrap the JS in a Drupal behaviour, so that it is attached after the ajax refresh.

You should also ensure it only runs once

```
 Drupal.behaviors.styledSelect = {
   attach: function() {
     $('select').once('ss', function() {
       $(this).styledSelect();
     }
   }
 };

```

That way it won't get 'styled' on every ajax change.
> 1 votes

# Answer
I do not like to use drupal behaviors in this instance as it does fire multiple times. Another option is to simply wait for the ajax to complete like this:

```
$(document).ajaxComplete(function(){
  $("select").styledSelect();
});

```

Ideally you want to replace document with the element that is getting fired via ajax. But this works as well but will fire on any ajax on the page (or globally if its loaded on every page)
> 1 votes

---
Tags: views, ajax
---


# Question
Title: Multiple formatters for a field collection - best approach?
I'm building a site with a "function" content type, to manage a list of functions and their arguments. Because arguments can be zero or more, and have multiple properties (name, required, usage notes) it seems best to handle them as a field collection, using field collection table as the input widget. Therefore, on the node edit form for the "function" content type, the input widget would look something like this:

On the display side, I need to display the argument data in at least two ways: (1) in a table formatter provided by field collection table and (2) in an arbitrary "syntax" format, where only the arguments are output, but with some kind of visual indication of which arguments are required. So, something like this:

My questions:

1. What's the best way to add a custom formatter for the field collection (i.e. in code, in a field template of some kind, using the custom formatters module, etc.)?
2. What's the best way to output two instances of the field collection field, each in a different format?

I do have Display Suite installed on this site, if that helps. Also interested in any general advice if there's a better way to handle this use case.

# Answer
> 1 votes
This sounds like it would be best output as two separate views. The first view would be set in your first format and the second in the other format. Probably using a view template of some sort. The issue is that the field collections attached to the node are actually referenced separately and you only know they belong to the same node because the field collection entity has a reference to the NID.

The view would reference by nid in the contextual filters.

The other option is to programmatically load the fields via the node.tpl.php file (assuming you are loading them on the node page). in which you simply gather the data via the $node object and display it as you need.

https://drupal.org/project/field\_collection\_views

https://api.drupal.org/api/drupal/modules%21node%21node.tpl.php/7

http://www.youtube.com/watch?v=\_GlfYhsk3X0

---
Tags: 7, entities
---


# Question
Title: Whats the most effective way to intergrate a javascript cost calculator to a specific node
I'm going to use a JavaScript cost calculator for perspective customers to calculate costs. I was wondering what was the most effective way to integrate the script within a node.

# Answer
> 0 votes
You can use JS injector module

> Allows administrators to inject JS into the page output based on configurable rules. It's useful for adding simple JS tweaks without modifying a site's official theme - for example, a 'nighttime' color scheme could be added during certain hours. The JS is added using Drupal's standard drupal\_add\_js() function and respects page caching, etc.

or simply use drupal\_add\_js in body field with enabled PHP input mode and take a look at this page

---
Tags: 7, nodes, javascript
---


# Question
Title: cannot remove $base_url address from a link
There is a Ads block in my website in which some websites logo and their address are placed in there. I created a content type for it , called `Ads` (and also a view `Ads__view`). it has two fields : 1.link 2.logo . I created a slide show using `slideShow` module and it slides the logos. I want my website to redirect to these websites when user clicks on any of them, so I created a page called `views-view-fields--Ads__view.tpl.php` and this is the code of it :

```
<?php
$address = strip_tags($fields['field_Ads_link']->content);
?>
<a href="<?php print $address ?>"><?php print $fields['field_Ads_photo']->content; ?></a>

```

the problem is `$base_url` of my website is attached at the beginning of the `($fields['field_Ads_link']->content` for example `www.google.com` will be `www.mywebsite.com/www.google.com` . how can I remove this attachment ?

# Answer
You need to prefix `http://` with your link. If you will not add prefix `http://` with your link, Drupal will treat this as internal url of Drupal site.

So, you should add url `http://www.google.com` in your content.

Or you can use Link module to create a `link` field.

> With `link` module links can be added easily to any content types and profiles and include advanced validating and different ways of storing internal or external links and URLs. It also supports additional link text title, site wide tokens for titles and title attributes, target attributes, css class attribution, static repeating values, input conversion, and many more.
> 2 votes

---
Tags: 7, javascript
---


# Question
Title: Display another field as 'Node author' if node posted anonymously
Currently on my D6 site registered as well as anonymous users can post articles. A custom text field has to be filled by unregistered users while creating an article. This text field's value is shown as Node author for anonymous posters.

Now I am all set to upgrade this site to D7. I tried using the following snippet to display custom text field value as the 'node author' if posted by Anonymous user, But it has some issues...

1. menu\_get\_object() works only for full node view and not for teasers etc.
2. It also changes $name every where on the page eg: for unregistered comments too.

```
function mytheme_username_alter(&$name, $account) {
  $node = menu_get_object();
    if($account->uid == "0") {
      $name = $node->field_custom_author['und'][0]['value'];
     }
}
```

**Question:** How can I tweak this function to display custom text field's value as 'Node Author' if the node is created by an anonymous user, without changing $name elsewhere on the page?

If there's a better function/solution than this, i am all open to try that too.

# Answer
You have two viable options:

1. In theme system, use either node.tpl.php file to do it, or probably better `template_preprocess_node(&$variables)`. I'll discuss function as that's what I prefer. When using function, copy it to your own template.php, renaming to `mytheme_preprocess_node(&$variables)`. As a source, use parent theme if it implements it. If not, or if there is no parent theme, use link I provided above.

Then find a line like this:

```
$variables['node'] = $variables['elements']['#node'];

```

and after it modify `$variables['node']` as you see fit.
2. Use Computed Field to create a field that shows author's name, and in case of anonymous authors displays arbitrary text. Turn off displaying author and use this field instead.
> 1 votes

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


# Question
Title: scheduling backup_migrate with elysia cron
I am looking at scheduling backup & migrate jobs with the elysia cron module. Can I ask how to call backup & migrate directly from the elysia script? Or should I be calling "drush bam"?

# Answer
It all depends on your preferences and situation.

**Elysia** is designed to work in environment when you can trigger Elysia every minute (or every five, or ten minutes, but regularly 24/7). In that environment it would be more convenient to simply schedule Backup and Migrate with Elysia. Just remember to keep what you set in *Home \> Administration \> Configuration \> System \> Backup and Migrate \> Schedules* in sync with what you set in *Home \> Administration \> Configuration \> System \> Cron \> Settings*.

**Benefit** of that solution is easily accessible status of a cron task, the fact that you can see with GUI how long it took and when it was last fired, without login to any other tools but your Drupal.

**Problem** is that if cron system gets delayed, you may lost next sheduled backup - it may be mere 23h 58m since last time Elysia fired BaM task, so BaM may decide it's too soon to take another "everyday" backup. It's common problem with one scheduler calling another. And if you will make Elysia to trigger BaM every 5 minutes, to make sure everyday backup will be triggered consistently, you will waste a lot of CPU power for nothing.

**`drush bam`** approach is more direct. Long story short, it's main pros is lack of problems described above, and main cons is lack of benefits described above. And it's slightly faster in execution overall, as one "layer" less is in use.
> 0 votes

---
Tags: 7, backups
---


# Question
Title: admin/content/comment/approval -> 410 Gone error (linked from content -> comments -> unapproved comments)
I have no idea when this happened (I've been trying to fix Mollom + PostgreSQL, to the point where I tried, and removed, some core patches), but when I go to Content / Comments / Unapproved Comments (which leads to `admin/content/comment/approval`) I get a 410 Gone error.

Was this supposed to be a view? How does one recreate such core views? Is the link the result of some module long since uninstalled?

# Answer
The problem was a RewriteRule (written by me) attempting to get rid of the non-numeric comment error (https://drupal.org/node/1838338). I didn't count on the admin/comment/approval path
> 0 votes

# Answer
You could try installing the module

admin\_views

As well as converting core administration pages (admin/content/node, admin/people etc.. ) to use VBO, it will add a view to `admin/content/comment/approval`

Recommended.
> 0 votes

---
Tags: views, comments
---


# Question
Title: Context Module Rehashing Blocks Slows Website on Development
So I'm working on a big website that runs fine on live (A bit on the slow side, but not unbearable), but when it comes to development servers it runs like ass (30 seconds to load a page ass). I used xdebug to profile the code, and what I found was that about half of the time in execution is spent updating the database. More specifically, on every page load when the Context module would load the the block list, it would look for block info in the cache, find nothing and then go and call \_block\_rehash, which then does DB updates for what appears to be every block. I tracked it down to where the context module tries to get a cache with

```
$cache = get_cache('context', 'cache');

```

And it comes back empty. I have caching enabled, block caching enabled, and I'm not sure why this is happening. Can anybody shed some light on this issue? This is an installation of Drupal 7 and Context 7-3.1

# Answer
It turns out that my settings.php file had some custom code to completely disable caching for localhost machines, so that developers wouldn't be forced to refresh the cache all the time. Commenting out that code produced the performance that I expected
> 0 votes

---
Tags: blocks, caching, performance, 7
---


# Question
Title: How to override the default image style for displaying user picture?
I have Statuses Module installed on one of my site. I have created a view to display the status along with the user picture and the following comments.

The view displays the user picture along with the statuses, but the image style used is the default 'thumbnail' style. I have created my own image style for displaying these images.

Usually in a view when images are added we get a option by default to add image style to it. But in this case I dont have that option.

After a bit of searching I found the following code in the statuses.module to display the user picture:

```
function statuses_display_user_picture($account, $preset = NULL) {
  drupal_add_css(drupal_get_path('module', 'statuses') .'/resources/statuses.css');
  $image_vars = array('account' => $account);
  if (!empty($preset) && module_exists('imagecache_profiles')) {
    $image_vars['user_picture_style'] = $preset;
  }
  return theme('user_picture', $image_vars);
}

```

How do I override this code to display the image with my choice of 'image style'.

# Answer
Use hook\_preprocess\_user\_picture(). See template\_preprocess\_user\_picture().

Here a sample code:

```
/**
 * Implements hook_preprocess_user_picture().
 *
 * @see template_preprocess_user_picture().
 */
function example_preprocess_user_picture(&$variables) {
  $style = 'your_style';

  $account = $variables['account'];
  if (is_numeric($account->picture)) {
    $account->picture = file_load($account->picture);
  }
  if (!empty($account->picture->uri)) {
    $filepath = $account->picture->uri;
  }

  if (isset($filepath)) {
    $alt = t("@user's picture", array('@user' => format_username($account)));
    $variables['user_picture'] = theme('image_style', array('style_name' => $style, 'path' => $filepath, 'alt' => $alt, 'title' => $alt));
  }
}

```
> 5 votes

---
Tags: media
---


# Question
Title: Replacing menu link text with image: overriding the right function?
I try to use images instead of text in main menu, in a theme I'm building. Used different solutions in my template.php, without any luck. Drupal prints the link to the image and not the image itself. I even use the suggested Drupal modules (menuicon and menuimage). But I got the same bad result.

Same kind of questions was asked here around but with no working solution for me, as far as I tried.

Yesterday, a similar question was asked on Stackoverflow and get a comment from Clive (https://stackoverflow.com/questions/19788449/overridden-theme-menu-link-is-not-used). Clive gave a hint on maybe this user is overriding the wrong function. But unfortunately, the question was removed by the user last night. Yes, I'm that kind of unlucky guy :-)

So, I will try to ask it myself with some posted code, hoping that someone can give me a clue to solve the issue.

Here is the code in my template.php:

```
    function caracole_menu_link($link) {
       $element = $link['element'];
       // Allows for images as menu items. Just supply the path to the image as the title
       if ( strpos($element ['#title'], '.png') !== false || strpos($element ['#title'], '.jpg') !== false || strpos($element ['#title'], '.gif') !== false) {
       $link['element']['#title'] =  '<img alt="'. $element['#original_link']['description'].'" src="'. url($link['element']['#title']) .'" title="'. $element['#original_link']['description'] .'">';
       $link['element']['#localized_options']['html'] = TRUE;
    }
    return theme_menu_link($link);
    }

```

It's one of the solutions provided on forums. But I can't get it to work for me...

best regards,

plouf

# Answer
Consider using hook\_preprocess\_link().

Here's a snippet:

```
/**
 * Implements hook_preprocess_link().
 */
function example_preprocess_link(&$variables) {
  if ($variables['path'] == 'path/of/link/to/change') {
    $variables['options']['attributes']['class'][] = 'class-use-image';
  }
}

```

Then in your CSS file, define the class that replaces the text with the image:

```
.class-use-image {
  width: 350px;
  height: 75px;
  background: url("images/<your-iamge>");
  text-indent: -9999px;
}

```

More techniques on replacing text with image here.
> 1 votes

---
Tags: routes, media, theming
---


# Question
Title: I want to add a additional html link to the node view ? How can I do it?
I want to add some extra information like an additional html link along with the node data at node render.

Hope I tried googling but came to know that we can do it through `hook_node_view_alter`, but not able to do it.

# Answer
> 1 votes
You can do it with any of the following hooks:

The choice of hook would depend on the requirements and/or personal preference.

Using hook\_node\_view\_alter():

```
/**
 * Implements hook_node_view_alter().
 */
function example_node_view_alter(&$build) {
  $build['#suffix'] = '<strong>Hello</strong>';
}

```

Using hook\_node\_view():

```
function nodeapi_example_node_view($node, $build_mode = 'full') {
  if (variable_get('nodeapi_example_node_type_' . $node->type, FALSE)) {
    // Make sure to set a rating, also for nodes saved previously and not yet rated.
    $rating = isset($node->nodeapi_example_rating) ? $node->nodeapi_example_rating : 0;
    $node->content['nodeapi_example'] = array(
      '#markup' => theme('nodeapi_example_rating', array('rating' => $rating)),
        '#weight' => -1,
    );
  }
}

```

*(Snippet from the excellent examples module)*

---
Tags: nodes, hooks
---