# Question
Title: XHR2 upload using Drupal 7's ajax framework
I'm trying to implement XHR level 2 (file API upload) using Drupal 7's JQuery $.ajax implementation. I've got the feeling I'm almost there.

First of all, I got XHR.send() working according to orginal example on HTML5 demos. But now, I want to use Drupal 7's built in ajax framework.

I found some examples how do this with JQuery but I can't get it working for Drupal 7 with a custom ajax responce. I also found a related (D8) discussion about this on drupal.org.

Here's the code, which returns a ajax error "Illegal invocation". Probably because formData is not in a proper format?

```
    // 'files' below is a correct object with at least one file

    var file = files[0];
    var formData = new FormData();

    formData.append('file', files[0]);

    // element_settings: see ajax.js in drupal
    var element_settings = {};

    element_settings.progress = { 'type': 'none' };
    element_settings.url = '/mymodule/save/ajax';
    element_settings.data = file;
    element_settings.cache = false;
    element_settings.contentType = file.type;
    element_settings.processData = false;
    element_settings.submit = {
      'savedata': formData
    };

    element_settings.xhr = function() {
      myXhr = $.ajaxSettings.xhr();
      if (myXhr.upload) {
        myXhr.upload.addEventListener('progress', progressHandlerFunction, false);
      } else {
        console.log("Upload progress is not supported.");
      }
      return myXhr;
    };

    var base = '#myelement';
    ajax = new Drupal.ajax(base, $('#myelement'), element_settings);
    ajax.eventResponse($(ajax.element));

```

On the server site, I'm using a menu hook with ajax\_deliver as delivery callback. This works, but I can't access $\_FILES in the same way which is possible if you use xhr.send().

By, the way, I'm aware this only works in modern browsers. I'm using Chrome.

# Answer
> 3 votes
I think your approach is flawed. You should use as much of Drupal's ajax system as possible, even though is wildly uncomprehensible and weird. Don't create your own Drupal.ajax object. Let Drupal handle that and the events and triggers that come with that.

Then there are only 2 problems left:

1. Don't create an iframe and a fake form and submit that. Use Ajax.
2. Don't serialize and preprocess that request. Use only what I'm giving you.

They're combined in `jquery.form.js` apparently. So all you have to do, is override where `ajax.form.ajaxSubmit(ajax.options);` is called: `Drupal.ajax.prototype.eventResponse`.

The result inside my failed-attempt-module.

It's an override of `Drupal.ajax.prototype.eventResponse`. I've added everything inside `if ( 'FormData' in window )`

My original plan (as the module name says) was to make all file fields drop containers for HTML5 File drag/drop. My approach was flawed too. I think with this approach, it's not so difficult. Just extend the `FormData` object at the right time.

---
Tags: ajax
---


# Question
Title: How do I use field_view_field() to print a user profile picture?
I'm trying to print a user profile's picture in a block that gets displayed on a node page. I have the nodes author be loaded as in the following code:

```
<?php
$node = menu_get_object('node');
$user = user_load($node->uid);
?>

```

This is the code I have come up with for the block:

```
<div class="author-block">
  <h4>Meet the author</h4>
  <?php print drupal_render(field_view_field('user', $user, 'picture', 'user-pic-style'));?>
</div>

```

This isn't working and doesn't print anything. I want the user's picture be loaded if users have one, or the default user picture if they don't. I have other custom user fields that are printing just fine using the field\_view\_field(), so I am wondering why I am not having luck.

# Answer
Try this

```
<div class="author-block">
  <h4>Meet the author</h4>
  <?php print drupal_render(field_view_field('user', $user, 'picture', array('settings' => array('image_style' => 'user-pic-style'))));?>
</div>

```
> 2 votes

# Answer
I'm not entirely sure why the field isn't returning any data, but I think it has something to do with it being an image, and you not setting a style. Here's how I've done similar things with images before. Please note that I have altered the code below both to protect my original customer, and to hide the fact this was done as a Ctools plugin, instead of a block. So there could be minor issues like misspellings and the like. My apologies if that's the case.

```
// Create a shortcut to the image we want to render
$image_data = $image_node->field_images[LANGUAGE_NONE][0];

// Image rendering data
$variables = array(
  'style_name' => 'blurb_208x208',
  'path' => $image_data['filename'],
  'alt' => '',
  'title' => '',
);

$styles = image_styles(); // Get all available styles
$style = $styles['blurb_208x208'];

// We are responsible ourselves for ensuring the derived image is available.
$derivative_uri = image_style_path($style['name'], $path_to_original_image);
if (!file_exists($derivative_uri)) {
  image_style_create_derivative(
    $style,
    $image_data['uri'],
    $derivative_uri
  );
}

$markup = '<div class="image-wrapper">' . theme('image_style', $variables) . '</div>';

```
> 0 votes

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


title: After PHP upgrade Drush Fails

text:
# Question
Title: After PHP upgrade Drush Fails
After ugrading PHP 5.3 to 5.4.10, drush fails with the following error for most of commands: Command watchdog-show needs a higher bootstrap level to run - you will need to invoke drush from a more \[error\] functional Drupal environment to run this command ...

I reinstalled Drush(Drush 5.8 does not work on Mac OSx 10.7.5, so downgraded to 5.0.0), but it did not solve the problem.

Is Drush compatible with php 5.4.10.? Why would i get these errors and how to troubleshoot?

Thank You

# Answer
As mentioned here drush is not yet completely compatible with PHP 5.4

And regarding the error message `you will need to invoke drush from a more [error] functional Drupal environment to run this command` , in general cases it means that you are running drush from a location which is not associate to a drupal instance. To be on a safer side go location-of-your-drupal-instance/sites/all/modules and run the command.
> 3 votes

# Answer
I was able solve the problem:

What helped me was turn drush into debug mode by adding flag '--debug'

That showed me that pdo extensions were not loaded

It end up that my new PHP5.4 upgrade compiled from source had issues. Reinstalled PHP 5.4 this time with macports as described in https://gist.github.com/2721719

Afterwards, to make sure php-cli is pointing to the new php.ini run 'php -i | grep php.ini'. This is important because drush uses the php-cli configurations that may point to old php.ini

To make sure all of the extensions are loading properly run 'php -v' which will show issues if there is any before displaying the actual version that you can also validate if your upgrade is inline with php-cli

At last, to make drush work with my new PHP 5.4 upgrade, i needed to remove drush and install again. Drush 5.8 works fine with PHP 5.4 so far. However, I needed to create a symbolic link to make it work. It was looking for drush.php in the wrong directory. Used 'locate drush.php' to find the right drush.php link to.

I hope this is helpful. Thanks to community with so much info out there
> 1 votes

---
Tags: drush
---


# Question
Title: display different header text if view has taxonomy term
I have a view which displays different taxonomy terms, I would like to set a different "header text" depending on what term the view is filtering by. Right now whatever header text I choose I can only apply to all pages of the view. I would like to display different header text depending on what term is being filtered.

# Answer
> 2 votes
Instead of a Global: text area, you should embed another (new) view in the header.

This blog post explains how you can display the term description that way. That way you would have a different text for each term.

---
Tags: views
---


# Question
Title: Using symlinks / multisite to display one drupal site at two domains
Does it create any problems for me to use symlinks to display the same drupal site at more than one domain? It appears to work, but I'm not sure if bugs might appear in the future due to scripts being misinterpreted as XSS attacks or something.

## Example

I own two domains, sweet-bro.com and hellajeff.net . They're hosted on the same account, such that people who go to sweet-bro.com see the files in `~/sweet-bro/html` and people who go to hellajeff.net see the files in `~/hellajeff/html`

There's a drupal 7 site at `http://sweet-bro.com/drupal` and I want visitors to see the same site if they go to `http://hellajeff.net/ruse` . So, first I make a symlink in the html directory:

```
ln -s ~/sweet-bro/html/drupal  ~/hellajeff/html/ruse

```

Then I make a symlink in the sites directory:

```
ln -s ~/sweet-bro/html/drupal/sites/default  ~/sweet-bro/html/drupal/sites/hellajeff.net.ruse

```

This is what I've done and it seems to be working. Is there any reason not to do it this way?

# Answer
I don't think it's going to cause any problems, but it seems you just make things complicated for no reason. So, that would be a reason not do it that way :)

Just point both domaines to ~/sweet-bro/html and get rid of the symlink in /sites/.

Both domains will be showing the same site, as long as you don't use a .htaccess rule to redirect to one or the other.
> 1 votes

---
Tags: multi-sites
---


title: Views link image to field

text:
# Question
Title: Views link image to field
I've created a view with two fields(field\_img & field\_pdf) and the Format as Fields.

Now I want to download the field\_pdf file when I click on the field\_img.

How to achieve this one?

Thank you.

# Answer
> 2 votes
You may be able to use "Rewrite the output of this field" to wrap the image in a link using the "replacement pattern" token for the PDF file url as the href there.

Note you can "Exclude field from display" to add a field to the token list without displaying it.

You'll also need to drag the field, in the field order, above the one you want to use it in as a token for it to be available.

hth

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


title: Content type load via PHP

text:
# Question
Title: Content type load via PHP
We load a specific node in our template.php file via `node_load()`, in the same way `<?php if ($content = render($page['content'])): ?>` is used for loading a block.

I have a content type (news), and I want to load this content type items on my template.php file. How can I do it?

# Answer
Try using the views module and views\_embed\_view
> 1 votes

---
Tags: 7, nodes
---


title: display content type in view

text:
# Question
Title: display content type in view
I have 2 content types courses and courses\_type, I added courses\_types as node reference in courses.

when going to build view to dispaly all courses with thier courses\_type the courses\_type column is empty. what i am doing wrong?

# Answer
> 1 votes
For Drupal 7, use the Entity and Entity Reference modules. This is just a simple view. You don't need to create any relationship. Just add course type in Fields.

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


title: Create content fields order

text:
# Question
Title: Create content fields order
How can i reorder fields in "node/add/"?

the current order:

```
title
vocabularies
body
...

```

i would like to have

```
    title
    body
    vocabularies

...

```

# Answer
> 0 votes
Drag and drop the fields in the order you want at page at the "manage fields" or "manage display" pages.

You can reach these pages for eacht content-type via the links beside eacht content type at:

admin/structure/types

Manage fields is used at the node/add or edit screens. Manage display is used for the actual display, like when a visitors sees the page.

# Answer
> 0 votes
If you are familiar with custom moduling, you could implement hook\_form\_alter() and adjust the `#weight` attribute of each element. The heaviest weight is the last appeared.

```
function MYMODULE_form_alter(&$form, &$form_state, $form_id){
    if( $form_id == 'your_node_form' ){
        $form['title']['#weight']   = 1;
        $form['body']['#weight']    = 2;
        $form['vocal']['#weight']   = 3;
    }
}

```

It is valid since D6.

---
Tags: nodes, entities
---


# Question
Title: How do I add COUNT(foo.bar) to a dynamic query?
I have a query like the following:

```
SELECT t.tid, t.name, t.description, COUNT(i.nid)
  FROM taxonomy_term_data t
  LEFT JOIN taxonomy_index AS i ON i.tid = t.tid
  GROUP BY i.nid
  LIMIT 60

```

I wish to write this as a dynamic query.

This is what I come up with, but it fails on the `COUNT()` part.

```
$query = db_select('taxonomy_term_data', 't');
$query->addField('t', 'tid');
$query->addField('t', 'name');
$query->addField('t', 'description');
$query->addField('COUNT(i.nid)', 'count');
$query->leftjoin('taxonomy_index', 'i', 'i.nid = t.nid');
$query->range(0, 60)->groupBy('i.nid');

```

The string representation of the query is:

```
SELECT t.tid AS tid, t.name AS name, t.description AS description, COUNTi.nid.count AS count FROM {taxonomy_term_data} t LEFT OUTER JOIN {taxonomy_index} i ON i.nid = t.nid GROUP BY i.nid LIMIT 60 OFFSET 0

```

`COUNTi.nid.count AS count` is obviously wrong.

How do I add `COUNT(foo.bar)` to a dynamic query?

# Answer
You've got the right idea, but you need to use the `addExpression` method instead:

`$query->addExpression('COUNT(i.nid)', 'count');`

Also, I believe you need to call this method after the `leftJoin` for the `taxonomy_index` table to be in object scope.

See here for an example: https://drupal.org/node/1848358
> 4 votes

# Answer
@MEsch is right about the method to call, but I would rather write the code as the following.

```
$query = db_select('taxonomy_term_data', 't')
  ->fields('t', array('tid', 'name', 'description'));

$alias = $query->leftjoin('taxonomy_index', 'i', '%alias.nid = t.nid');

$query->addExpression("COUNT($alias.nid)", 'count');
$query->range(0, 60)->groupBy("$alias.nid");

```

SelectQuery::leftJoin() returns the alias effectively used in the query, and the code I wrote is more generic.

As for calling `SelectQuery::addExpression()` before `SelectQuery::leftJoin()`, the result doesn't change, if you are not using the alias returned from `SelectQuery::leftJoin()`. The following queries return both the same result.

```
$query = db_select('taxonomy_term_data', 't')
  ->fields('t', array('tid', 'name', 'description'));
$query->leftjoin('taxonomy_index', 'i', 'i.nid = t.nid');
$query->addExpression("COUNT(i.nid)", 'count');
$query->range(0, 60)->groupBy("i.nid");

```

```
$query = db_select('taxonomy_term_data', 't')
  ->fields('t', array('tid', 'name', 'description'));
$query->addExpression("COUNT(i.nid)", 'count');
$query->leftjoin('taxonomy_index', 'i', 'i.nid = t.nid');
$query->range(0, 60)->groupBy("i.nid");

```

When you print `$query`, you get the following, in both the cases.

```
SELECT t.tid AS tid, t.name AS name, t.description AS description, COUNT(i.nid) AS count
FROM
{taxonomy_term_data} t
LEFT OUTER JOIN {taxonomy_index} i ON i.nid = t.nid
GROUP BY i.nid
LIMIT 60 OFFSET 0

```
> 5 votes

---
Tags: database
---


# Question
Title: drupal 7 user registration custom url returning a blank page
I dont think my url is working. I am trying to use page/medical then use the page callback to redirect to medical\_reg\_form\_user\_register\_form\_alter. Instead of displaying the form I get a blank page.

```
function medical_reg_user_register_menu() {
  $items['page/medical'] = array(
    'page callback' => 'medical_reg_form_user_register_form_alter',
    'access arguments' => array('access content'),
    'type' => MENU_CALLBACK
    );
  return $items;
}

function medical_reg_form_user_register_form_alter(&$form, &$form_state, $form_id) {
  $form['#theme'] = 'medical_register';
  $form['actions']['submit']['#value'] = t('Nextdfd');
}

```

# Answer
> 4 votes
You can't call a hook in `hook_menu()`. You can either create an alias for the user registration page or replace your menu item with:

```
function medical_reg_user_register_menu() {
  $items['page/medical'] = array(
    'page callback' => 'drupal_get_form',
    'page arguments' => array('user_register_form'),
    'access arguments' => array('access content'),
    'type' => MENU_CALLBACK
    );
  return $items;
}

```

---
Tags: users, routes
---


# Question
Title: How to disable Webform form element validation without removing required flag?
I inherited a website which contains a Webform made form to which I was asked to make some modifications.

The form contains two drop-down selection lists, one with predefined options, one who's content is dynamically filled in by making a request to a web-service based on the selected value of the first drop-down list.

Filling the second drop-down list is not the problem, but since it's marked as required this means that the form is also validated and that's where the error pops up: *An illegal choice has been detected. Please contact the site administrator.*

Now, since the content of the drop-down is dynamically generated the error itself makes sense as the selected value is compared to the available options. I want to disable the validation without removing the required flag from the form element.

I tried modifying the element options both via `hook_form_alter()` and a custom validate function, various combinations and I can see that the variable is set and contains the value, yet it is still validated.

```
$form['submitted']['ss_function']['#needs_validation'] = FALSE;
$form['submitted']['ss_function']['#webform_validated'] = TRUE;

```

How can I disable the actual form validation without removing the required flag from a Webform form?

# Answer
> 3 votes
After some more trial and error I found my mistake. The `'#needs_validation'` property of the element is set at a later stage than the `hook_form_alter()` call.

In my `hook_form_alter()` implementation I added a custom validation function in which I unset the property. The trick is to actually **unset** it, because it's only validated with an `isset()` call.

```
function mymodule_webform_client_form_FORMID_alter(&$form, &$form_state, $form_id) {
  array_unshift($form['#validate'], 'mymodule_validate_FORMID');
}

function mymodule_validate_FORMID(&$form, &$form_state) {
  unset($form['submitted']['FIELDNAME']['#needs_validation']);
}

```

---
Tags: 7, webforms
---


# Question
Title: Different sets of language icons per theme
I'm using Language Icons and Language Switcher modules. The flag icons are added to the language switcher block, but the icons are stored in **sites/all/modules/languageicons/flags**. They are of fixed height of 12 pixels by default and they are used by every theme.

I want to use different sets of flag icons with different dimensions per theme, for example, Theme 1 will use the default icons of 12x12 pixels, but Theme 2 will use the icons of 19x19 pixels. I will have my custom flag icons in my custom module or in my custom themes.

I would do this by using hook\_block\_view\_alter() to override the block output per theme, but I'm looking for a better and right way.

# Answer
As mentioned in my question, I could not do this by using `hook_block_view_alter()` because I can only have the renderable HTML of the block content in that hook.

I found a theme function `theme_languageicons_icon`, which renders the icons, in the file **sites/all/modules/ languageicons/languageicons.module**. I copied the theme function into my custom module and implemented hook\_theme\_registry\_alter() to override it. Then, I updated the function as my need and flushed caches. It gave me exactly what I needed.

```
function MYMODULE_theme_registry_alter(&$theme_registry){
    if( isset($theme_registry['languageicons_icon']) ){
        $theme_registry['languageicons_icon']['function'] = 'theme_mymodule_languageicons_icon';
    }
}

function theme_mymodule_languageicons_icon($variables) {
  global $theme;
  $language = $variables['language'];
  $title    = $variables['title'];
  # define icons path for various themes
  $default_path = variable_get('languageicons_path', drupal_get_path('module', 'languageicons') . '/flags/*.png');
  $path_by_theme = array(
    'theme1' => drupal_get_path('theme', 'theme1') . '/flags/*.png'
    'theme2' => drupal_get_path('theme', 'theme2') . '/flags/*.png'
  );
  $path = (isset($path_by_theme[$theme]) && file_exists($path_by_theme[$theme])) ? $path_by_theme[$theme] : $default_path;
  # define dimension for various themes
  $default_size = check_plain(variable_get('languageicons_size', '16x12'));
  $size_by_theme = array(
    'theme1' => '19x19',
    'theme2' => '25x24',
  );
  $size = (isset($size_by_theme[$theme])) ? $size_by_theme[$theme] : $default_size;

  if ($path) {
    $title = $title ? $title : $language->native;
    // Build up $image for theme_image() consumption.
    $image = array(
      'path' => str_replace('*', $language->language, check_plain($path)),
      'alt' => $title,
      'title' => $title,
      'attributes' => array(
        'class' => 'language-icon',
      ),
    );
    if ($size) {
      list($width, $height) = explode('x', $size);
      $image += array('width' => $width, 'height' => $height);
    }
    return theme('image', $image);
  }
}

```

If you have a better solution, it is welcome.
> 1 votes

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


title: Private data in node format

text:
# Question
Title: Private data in node format
**The Overall Plan**

I'm creating a staff "portal" area for a non-profit. In the future I want to migrate the current static front-end website to Drupal, so I thought it would make sense to develop this portal area as a custom module into the back-end Drupal administration.

**About the custom module**

The non-profit provides a Child Sponsorship program, allowing supporters to pay a monthly fee which pays the school fees for children in East Africa. So the idea of the portal will be that it will reduce the administration of staff by holding the sponsorship database online. The database is split into two: children who are sponsored and children on the waiting list. So I want to produce a module where each child is effectively a node. The node will contain sensitive information such as DOB, Address, School Exam Results etc and so isn't AT ALL for public viewing.

However, that when a child is added to the waiting list, a short bio will feed into the front-end website allowing them to be sponsored. This is one reason for trying to build it into Drupal from the beginning. In the future, it is also planned that when a user goes onto the front-end website, chooses a child to sponsor, they will be made a 'user' in Drupal, and given the ability to view certain information about their child such as a school report.

**Questions**

Is it conventional use of Drupal to build a module specifically for internal use where primarily the data is not for the public or front-end website? Is it an appropriate use?

To me it makes sense that each child functions as a node of content type 'child', however I'm worried about making them actual nodes.....as I said the data is private, and Drupal currently sets node public at URL `node/{nid}` What is the best solution moving forward with creating this database within Drupal? Could I make an equivalent 'node' style format?

# Answer
Drupal only sets node/nid as public when you give anonymous users permission to "access content". Additionally, you can use modules like http://drupal.org/project/content\_access to specify what roles can access specific content types. Lastly, you can use http://drupal.org/project/field\_permissions to specify what roles have access to specific fields on your nodes.

To answer your other questions, I don't think you need to write any custom modules to cover these needs and using Drupal to provide content only to privileged members is a very common use case.
> 7 votes

---
Tags: nodes
---


# Question
Title: How to configure Context to set active on Menu item
This other SO post says that Context provides this functionality out of the box, but when I add settings which seem reasonable, the active and/or active-trail classes are not set on my menu items.

How am I supposed to configure Context to set the active and/or active-trail on my menu items?

Here is my set up:

I've added some terms to the standard Tags taxonomy. For example: `Surf`, `Skate`, `Volleyball`.

I've used Pathauto to set dynamic paths for my taxonomy terms. `blog/Surf`, `blog/Skate`, etc.

I created a Menu with an item called `Surf` with a path of `blog/Surf`, as well as for Skate and Volleyball, etc.

I added that menu to the Highlighted region of my site.

When I browse to blog/Surf, my menu item does not receive the active nor the active-trail class so that I can style it appropriately to show the user that is where they currently are in the site.

I tried creating a Context for it and guessing at how it should be configured.

How do I get the active and/or active-trail classes on my `blog/Surf` menu item?

# Answer
> 2 votes
The only reason I can think of is that the context modules is actually adding the trail classes but the theme that you are using is not using them.

You can verify this in two ways,

1. Change the theme back to Bartik and see if it works.
2. Checkout the template file of your theme, print the variables that are passed to `theme_menu_item` in your `template.php` file

If the problem is your theme, then you will need to override the `theme_menu_item` accordingly in your theme.

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


# Question
Title: How do I retrieve values of a taxonomy field inside a field collection of a profile2 node?
Can someone tell me how can I retrieve values of a taxonomy field inside a field collection of a profile2 node?

Thanks

# Answer
> 0 votes
You could try using entity\_metadata\_wrapper to load the profile2 entity.

You could then drill down to the field value on the field\_collection.

Something like:

```
$profile = profile2_load_by_user($account, 'main');
// Use entity metadata wrapper, because it's awesome.
$profile_wrapper = entity_metadata_wrapper('profile2', $profile);
// We can access the term as the "value" of the field_collection child field
$term = $profile_wrapper->get('field_my_field_collection')->field_my_taxonomy_term->value();
// Just print out the term for now
drupal_set_message('<pre>'.var_export($term,1).'</pre>');

```

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


title: How is my website infected?

text:
# Question
Title: How is my website infected?
My web server company recently reported me that my website is sending spams. I scanned the whole file system and found a number of infected php files like *index.main.php*, *ipopup.php* and *wtm9309n.php* in `sites/default/files` directory.

All permissions for files and directories are set correctly. I have only one custom content type having 2 textbox fields that all users can create a new content of that type.

I checked the `files` table in database. except my uploaded files, there was no other files listed there, so (I think) that means the infected files are not uploaded via upload forms.

This is the only infected website among of the tens in my web server, so I think this a problem with this website instead of other things like OS vulnerabilities and ...

**Enabled modules:**

* admin
* cck
* contact\_forms
* faq
* filefield
* imageapi
* imagecache
* imagefield
* imce
* nice\_menus
* node\_export
* views

Any suggestion? (Drupal 6.20)

# Answer
There really isn't a lot to go on here. You really need to try to match up the ctime (creation timestamp) on the malicious files with the Apache logs to see what may have happened.

Other than that, you should

* Take a backup.
* Do a `yum update` on your server to make sure you have all relevant patches.
* Clean out your temp folders on the server, and reboot it.
* Bring Drupal core up to date. You are several versions behind, and have other security vulnerabilities.
* Bring your contrib modules up to date.
* Double check all permissions that may involve PHP input, like the PHP input filter, block visibility rules, view rules, etc. To be honest, I would disable the PHP input filter altogether.
* Audit your custom code to see if there are any problems.
> 3 votes

# Answer
Although a WYSIWYG module was not mentioned in your module list, a recent vulnerability in CK and FCKEditor allowed arbitrary file uploads which has resulted in similar hack attacks on vulnerable installations.

If you're running CKEditor or FCKEditor as the rich-text editor, update it and check this security advisory:

http://drupal.org/node/1482528

Ensure all other modules are also at their latest stable versions.

Good luck.
> 1 votes

---
Tags: 6, security
---


# Question
Title: How to create user profile theme hook suggestion for custom template?
I'm using the Chaos tools display suite module to create a 'mini\_teaser' view mode for my user profiles, but I can't seem to get drupal to read a custom template `'user-profile__mini_teaser.tpl.php'` in my theme folder. In my user preprocess function, I'm adding theme suggestions, but they don't seem to work. Any ideas?

# Answer
> 1 votes
It's hard to tell without seeing your code but off the top of my head your preprocess function should look something like this:

```
function MYTHEME_preprocess_user_profile(&$vars) {
  if ($vars['view_mode'] == 'mini_teaser') {
    $vars['theme_hook_suggestions'][] = 'user_profile__mini_teaser';
  }
}

```

Or a more generic solution:

```
function MYTHEME_preprocess_user_profile(&$vars) {
  $vars['theme_hook_suggestions'][] = 'user_profile__' . $vars['view_mode'];
}

```

# Answer
> 0 votes
Normally you would replace the underscores from

```
$variables['theme_hook_suggestions'][] = 'user_profile__mini_teaser';

```

with hyphens in the template file name:

i.e, rename template file to:

```
user-profile--mini-teaser.tpl.php

```

After clearing theme registry cache, see if that, or a similar underscore / hyphen filename adjustment helps.

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


title: Provide support for embedding feature

text:
# Question
Title: Provide support for embedding feature
I am wondering how can I provide support for embedding feature. Actually in my application when user creates article/content, I need to take option from user that if his content can be embedded via embed code to some other web sites. For that he selects yes, then, system should display embed code in the article page, by using which, other people can embed this article.

Please suggest is their any module in drupal that helps me to achieve this or some tutorial helping me to achieve this will also be useful.

Thanks for your time.

# Answer
> 0 votes
For D6 there is Embed widgets

> Embed widgets allows content such as pages, blocks, views, and nodes from your Drupal site to be embedded in external sites (including non-Drupal ones).

If its D7 there is Embeddables

> Embeddable provide a method for embed thingies in content.It is a pluggable system that currently allows the embedding of nodes and blocks.

Found 136 results containing the words: Embed on drupal.org

---
Tags: nodes
---


# Question
Title: Overriding region theme file for user profile pages
I am on D7 using Omega as a base theme. The `<h1>` tag of my theme can be found in the **region--content.tpl.php** theme file.

But I want to override this theme in one specific situation: on the user profile pages, I don't want the title to be set on **region--content.tpl.php**. I will take care of the title on the **user-profile.tpl.php** theme file. So what I want is a theme file that will override the custom default region theme file in the specific situation where user profiles are being viewed. That theme won't have a title set in it.

I have tried creating specific themes called **region--content--user.tpl.php** and **region--content--user-profile.tpl.php**, but they didn't override the default **region--content.tpl.php** theme. Any ideas? Thank you.

# Answer
I found solution on this blog http://eureka.ykyuen.info/2012/05/10/drupal-7-customize-region-template-file-for-specific-content-type/ and here is my code to suggest a user profile region.

```
    function YOURTHEME_alpha_preprocess_region(&$vars) {
      $menu_object = menu_get_object();
      if (isset($menu_object->type) && $vars['region'] == 'content') {
        $vars['theme_hook_suggestions'][] = 'region__content__'.$menu_object->type;
        $vars['attributes_array']['class'][] = 'region-content-'.$menu_object->type;
      }
//theme suggestion for user profile
      elseif ($vars['region'] == 'content' && $vars['elements']["system_main"] && $vars['elements']["system_main"]["#entity_type"] == 'user') {
        $vars['theme_hook_suggestions'][] = 'region__content__userprofile';
        $vars['attributes_array']['class'][] = 'region-content-userprofile';
      }
    }

```
> 1 votes

---
Tags: users, theming
---


# Question
Title: Where is a UI-configured Views display definition read from?
**General question:** In Views 3, on Drupal 7, when a View display in configured using Views UI, what is the location where the configuration is 'read' and applied when...:

* ...creating a query to generate a page?
* ...loading its Views UI page (I believe this is the table `views_display`)?

---

**Background / why asking:** I've encountered a very strange problem where (despite repeatedly clearing all caches including Views cache and even disabling Views caching in Views advanced settings), the output a view generates *in situ* in a panel / block on the page doesn't match the rules shown for it on editting it in Views UI.

**Edit:** Actually, looks like they are both coming from the same place but the two displays got merged and became non-overridden in a strange way. I'll keep this open as I'd like to know for sure where these are stored in the DB for future reference anyway.

---

It's a dev environment with no memcache / memcached / boost etc - no additional layers of caching.

There's one existing question where someone finds Views UI somehow 'loses' the override settings for a views display, but it's not related to my case: there's nothing on my general question, the cause doesn't apply in my case, and none of the suggestions there help. There's also a question which includes my general question on drupal.org but none of the replies answer my question.

# Answer
The table `{views_view}` has the list of views. The more or less matches up with what is on admin/structure/views, except for views created by modules.

The table `{views_display}` has displays for each view, keyed to `{views_view}` with the `vid` column. The `id` column is the machine name from admin/structure/views/view/foo/edit. There is one row per display. The `display_options` column has a serialized version settings from the edit form, and it more or less matches up with the display section when you export a view from admin/structure/views/view/foo/export. I am also pretty sure that the actual query is essentially built up from the same column.

In my years of using a sledgehammer to make Drupal do what my clients need, I don't recall ever poking through the views tables for anything. I will periodically look at an export to see what is going on with a view, and export/edit/import views to adjust things, though.
> 1 votes

---
Tags: views
---


# Question
Title: Difference between Media and Asset module
Today I saw a "new" module: Asset.

It looks interesting but I don't understand the difference between this module and the Media module, in the 7-2.x version.

Could someone help me?

# Answer
> 6 votes
Looking at this issue in the media module issue queue, the main technical difference (apart from UI) would be that the Asset module creates its own entity while Media uses the core managed\_files API. In other words: Asset is 'an island' and other modules must specifically support Asset module. Integration with media module is easier because it uses core infrastructure.

There actually is a request to merge parts of Asset & Media code.

I took the module for a quick spin, it looks pretty easy but less flexible then the media module. However, I always found the media module configuration very complicated (file styles) because of its flexibility probably.

---
Tags: 7, media
---


title: Unpublish content problem on update

text:
# Question
Title: Unpublish content problem on update
I use the Content Approval module for queue for approval content. If users add article, there's no problem as it is unpublished then . I'm admin i publish this content later. But, then when user update the published content it isn't unpublished again. How can I do this?

# Answer
If you're using the Rules module, here's a simple rules export for the purpose.

* Event: node\_presave
* Condition: authenticated user
* Action: unpublish node

You could change the role condition to suit your site user config.

e.g: Add the role condition "Adminstrator" and click the "Negate" checkbox for "NOT Administrator role" condition.

You could also, for example, add a Rules action to show a message under "System \> Show a message on the site" after unpublishing the node.

Exported Rule:

```
{ "rules_unpublish_updated_content" : {
    "LABEL" : "Unpublish updated content",
    "PLUGIN" : "reaction rule",
    "REQUIRES" : [ "rules" ],
    "ON" : [ "node_presave" ],
    "IF" : [
      { "user_has_role" : {
          "account" : [ "site:current-user" ],
          "roles" : { "value" : { "2" : "2" } },
          "operation" : "OR"
        }
      }
    ],
    "DO" : [ { "node_unpublish" : { "node" : [ "node" ] } } ]
  }
}

```

You can import the Rule at:

**/admin/config/workflow/rules/reaction/import**
> 2 votes

---
Tags: 7, nodes
---


title: Print Emvideo Field in node.tpl

text:
# Question
Title: Print Emvideo Field in node.tpl
Hello im playing about with my node.tpl so as i can show the title of a video below the video ala youtube. Ive managed to sort that ok but my body field was showing above the title still so i rectified that with

```
<?php print $node->content['body']['#value'];?>

```

Now im going to remove the print content bit from my node.tpl but that will mean no video.

could anyone advise on how to display the video field?

Im presumming i need to add some code which shows the fields and then print out the field.

This is where i am stuck.

thanks

(drupal 6)

# Answer
> 1 votes
In D6 / CCK, assuming the field is set to display, you can simply use:

```
print $FIELD_NAME_rendered;

```

i.e:

```
print $field_videourl_rendered;

```

in node.tpl.php

# Answer
> 1 votes
Instead of print\_r try:

```
<?php print var_dump($node);?>

```

Look at your source, find the video field you've setup, then copy and paste the complete path the the CCK variable you've setup. The problem is your outputting the entire body field where as it sounds like you just need two fields "$node-\>title" and "$node-\>MyVideoField" but without knowing the complete variable path I can't really help.

---
Tags: 6, theming
---


title: Cron jobs stuck in drupal 6

text:
# Question
Title: Cron jobs stuck in drupal 6
I am maintaining a site on drupal 6. I have installed a birthday module which can send mails to users on their bday. But it doesnt do so. None of the other cron related tasks are done, though cron runs daily, and I do get a notification on mail . I tried to install a new module called ultimate cron (6.x-1.7), this could solve my problem earlier when I last installed it. But on re-installation this also doesnt work. None of the triggered rules that should be fired on cron run are fired.

On site config -\> cron it lists all the processes, but they are in starting state. And on background process page , it shows first task with 0 progress n none other are being processed. I have tried to install latest version of ultimate cron modules, but that gives some error saying "**Unknown field: start stamp**". Please help me with this.

# Answer
For the latest version of Ultimate Cron, you also need the latest versions of Background Process and Progress. The versions might not match, or the database schema may not have been updated properly. Try completely uninstalling Ultimate Cron, Background Process and Progress, and then re-install them.
> 0 votes

# Answer
I'd say rtfm (that's f for 'friendly') for the birthday module. It clearly wants a CCK field which doesn't exist. Reconfigure, try again.
> 0 votes

# Answer
I've used a temporary patch to time the duration of each module's cron run. It helps a lot to debug cron issues.

I posted a patch for D8/D7 here:

http://drupal.org/node/1143082

A code snippet for manual D6 patching can be found here:

http://drupal.org/node/23714#comment-2633550

i.e D6 common.inc drupal\_cron\_run

```
// Iterate through the modules calling their cron handlers (if any):
$cron_timer = variable_get('cron_timer', '1'); // can add to settings form, defaults to on
if ($cron_timer) {
  // start timer for cron total
  timer_start('cron');
  foreach (module_implements('cron') as $module) {
    watchdog('cron', t('Starting cron for @module', array('@module' => $module)));
    $function = $module .'_cron';
    // start timer for this module, using module cron function name as id
    timer_start($function);
    // call cron hook
    $function();
    $timer = timer_stop($function);
    // get total in seconds
    $total = round($timer['time']/1000, 2);
    watchdog('cron', t('Cron time elapsed for @module is @secs seconds.'), array('@module' => $module, '@secs' => $total) );
  }
  $cron_timer = timer_stop('cron');
  $total = round($cron_timer['time']/1000, 2);
  watchdog('cron', t('Cron time total was @secs seconds.'), array('@secs' => $total) );
}else{
  // just run cron
  module_invoke_all('cron');
}

```

HTH
> 0 votes

---
Tags: entities, cron
---


# Question
Title: How can I monitor the number of user password reset requests?
I would like to keep track of the number of times users request that their password be reset to make sure that users are able to reset their password successfully. I am getting reports a couple of times a month that users are experiencing difficulty resetting their passwords; to see how common this is, I want to see if users are requesting their password be reset several times in a row (within the same day).

To do this, I was thinking of e-mailing myself every time a user requests that their password be reset. My first instinct was to do this with Rules, but there is no Event like "When a user requests that their password be reset."

# Answer
> 3 votes
Note, in user\_pass\_submit

```
watchdog('user', 'Password reset instructions mailed to %name at %email.', array('%name' => $account->name, '%email' => $account->mail));

```

There's already a watchdog log entry created when the user requests a password reset.

Perhaps you can simply monitor the watchdog log at

Admin \> Reports \> Recent log entries?

---
Tags: users, nodes
---


# Question
Title: Access one Field from another field via field.tpl.php
In Drupal 7, I have two fields `field_cta_button` and `field_cta_text`.

I am using `field--field-cta-button.tpl.php` to modify the outputs of the field.

I need the `field_cta_button` to change depending on the values of `field_cta_text`.

How can I access `field_cta_text` from `field--field-cta-button.tpl.php`?

If possible, I would like to do it without installing any extra modules.

---

Steps I have tired:

**1) Node Load**

I have used the following code from this page:

```
 <?php
$node = node_load($nid);
$field = field_get_items('node', $node, 'field_cta_text');
$output = field_view_value('node', $node, 'field_ctac_text', $field[$delta]);
?>

```

However, it just outputs this error message: Notice: Undefined variable: nid in include() (line 60 of /\[SITE NAME\]/sites/all/themes/legendary/\[MY THEME\]/field--field-call-to-action.tpl.php). EntityMalformedException: Missing bundle property on entity of type node. in entity\_extract\_ids() (line 7562 of /\[SITE NAME\]/includes/common.inc).

**2) Entity Field Query** I thought I might be able to use EntityFieldQuery(), but I'm not sure how to get it to load the current node.

# Answer
Have you tried using theme\_field functions and/or template\_preprocess\_node() in template.php? For example:

```
/**
 * Implements theme_field__field_name().
 */
function myThemeName_field__field_cta_button($vars) {
  // Get the current value of cta_text, if it exists.
  if ($field_cta_text = field_get_items('node', $vars['element']['#object'], 'field_cta_text')) {
    $cta_text = $field_cta_text[0]['value'];
  }
  // If cta_text isn't set for this node, set a default. You may not need this.
  else {
    $cta_text = '';
  }

  // Print the button differently depending on whether or not cta_text is available.
  // This could mean you actually return different markup here, or you could alter the variables available to you in the tpl (I would just return the markup here if it's simpler).
  switch ($cta_text) {
    case 'foo':
      return "<button class='foo'>{$vars['element']['#items'][0]['value']}</button>";
      break;

    case 'bar':
    default:
      return "<button class='bar'>{$vars['element']['#items'][0]['value']}</button>";
      break;
  }
}

```

OR in `template_preprocess_node()`:

```
myThemeName_preprocess_node(&$vars) {
  if ($vars['node']->type == 'your_content_type') {
    $field_cta_text = field_get_items('node', $vars['node'], 'field_cta_text');
    if ($field_cta_text[0]['value'] == 'foo') {
      $vars['node']->field_cta_button['custom_key'] = 'custom value'; // This would be available to you in the theme_field__field_cta_button() function as well as in the field .tpl file.
    }
  }
}

```

You can still do it in the .tpl as is noted in the other answer by accessing $element\['#object'\], but I would recommend doing it in the theme\_field() function or in the preprocess function. From the field.module documentation:

```
 * Theme developers who prefer to customize templates instead of overriding
 * functions may copy the "field.tpl.php" from the "modules/field/theme" folder
 * of the Drupal installation to somewhere within the theme's folder and
 * customize it, just like customizing other Drupal templates such as
 * page.tpl.php or node.tpl.php. However, it takes longer for the server to
 * process templates than to call a function, so for websites with many fields
 * displayed on a page, this can result in a noticeable slowdown of the website.
 * For these websites, developers are discouraged from placing a field.tpl.php
 * file into the theme's folder, but may customize templates for specific
 * fields.

```
> 1 votes

# Answer
You can access to the entity (node) to which the field is attached using `$element['#object']` variable from the field template (or preprocess function).

For example, add this code in `field--field-cta-button.tpl.php`:

```
<?php
$field_cta_text = $element['#object']->field_cta_text;
echo $field_cta_text[LANGUAGE_NONE][0]['value'];
?>

```

If you installed devel module you can use `dpm($element['#object'])` function to inspect the entity variable.
> 4 votes

# Answer
Another option is to use hook\_field\_attach\_load early on to adjust the loaded fields on the entity.
> 0 votes

---
Tags: entities, theming
---


# Question
Title: How to deal with someone trying to login as admin?
During these last days, I noticed in my dblog, that someone has been trying to sneak around.

The person tried finding the login url (my website isn't open for user registration) so they tried everything from my-domain.com/admin, my-domain.com/administrator.. and also my-domain.com/wp-login (which indicates that the person isn't familiar with drupal..)

Once the person ended up on /user he or she tried to login as admin by trying different usernames : admin, administrator etc... (I never use 'admin' as a username for the root user)

is there a way to prevent/protect a drupal website from this sort of things ?

Thanks

ps : i'm interested in how to do this both for d6 and d7.

# Answer
> 14 votes
These kinds of probes are very common across the internet. There are a few things you can potentially do to block this problem and reduce the success of an attacker.

First, I recommend everyone use Two Factor Authentication so that even if the attacker guesses your username and password they still can't login. There was a bounty for $500 to break TFA and although the white-hat attackers had username and password they couldn't break in.

The security review module or Droptor can help monitor these failed logins. If they happen a lot then you need to start taking more actions. Brute force attacks on passwords only work if someone does them *a lot* so if it just happens a few dozen times I wouldn't worry.

You can track the IP address in use by this person using watchdog entries and then use the built-in D6 Access Rules (or the d7 equivalent - http://drupal.org/project/user\_restrictions ) to block access via that IP. You could also deny access to the IP in Apache or some other server level firewall. The firewall/webserver is a more efficient place to block the users in terms of load on the server, but it usually requires a bit more effort.

For Drupal 6 and 7, AjitS has provided an answer with a good description of how to use a rate-limiting feature to prevent repeated login attempts from the same IP.

# Answer
> 3 votes
Perhaps using rename admin paths would help?

> The purpose of this module is to secure drupal backend by overriding admin path.

# Answer
> 3 votes
For Drupal 6 you should check for the Login Security module.

> Login Security module improves the security options in the login operation of a Drupal site. By default, Drupal introduces only basic access control denying IP access to the full content of the site.
>
> With Login Security module, a site administrator may protect and restrict access by adding access control features to the login forms (default login form in /user and the block called "login form block"). Enabling this module, a site administrator may limit the number of invalid login attempts before blocking accounts, or denying access by IP address, temporarily or permanently. A set of notifications may help the site administrator to know when something is happening with the login form of their site: password and account guessing, bruteforce login attempts or just unexpected behaviour with the login operation.

For Drupal 7, as @saadlulu said that there's already a feature of locking the access after 5 unsuccessful attempts to login. If you want more control, you could try the Flood Control module.

> This project is intended to add an administration interface for hidden flood control variables in Drupal 7, like the login attempt limiters and any future hidden variables.

# Answer
> 3 votes
I'd want to handle this in the same way that failed logins from other sources (e.g. ssh, ftp) are handled, so they are all dealt with consistently. For that I'd be looking at fail2ban, which I've had great success using against brute force SSH logins. It also feeds in nicely to monitoring tools, and blocks at the firewall level, which is generally more secure than preventing just Drupal logins because it's common for multiple attack vectors to come from the same place, for example if they're running things like metasploit.

# Answer
> 3 votes
This is actually totally expected behavior. Whenever you publish a website on a public ip, within hours / days you will start getting traffic of the sort. 99.99% of the time, these are just bots that run a generic script looking for unpatched applications or easy passwords. This explains why you see hits on domain.com/wp-login, the (automated) attacking host does not even know initially you are running Drupal, it is trying all the paths of the popular CMS's , Wordpress, Drupal, etc ....

I say don't waste too much time worrying about this. Whatever you do you will *always* find these scripts scraping your site ... from all over the world.

Two simple things will make your app relatively secure:

1. Serve login and admin pages via https
2. Have a decent password for admin

Whatever security scheme you implement, ALWAYS have a recent backup of your stuff.

Good-luck, happy new-year friend.

# Answer
> 2 votes
What are you asking for is not logical if you mean removing or preventing access to /user page.

If you manage somehow to prevent that page, how are you going to access it?

Plus Drupal already provides a way to stop such attacks by locking access to a user after 5 attempts.

You can limit the attempts to your admin account though.

---
Tags: security, users
---


# Question
Title: Add basic page title and its teaser view in basic page
I wanted to have one basic page, that allows me to add brief data about other basic pages like title and some data in teaser view. ie to create basic page, whose content is, some content of other basic pages.

I know that we can achieve this by using view. But I wanted to know if there is module available that allows me to do this, so that I can select the pages which are to be embed in the page I am creating.

# Answer
> 2 votes
You can try Node Embed module.

Node Embed provides an input filter for CKEditor & FCKEditor integration allowing a content editor the ability to embed the rendering of nodes within the body/fields of another node.

Nice documentation for this module can be found here.

---
Tags: 7, nodes
---


title: Term translation in views

text:
# Question
Title: Term translation in views
i try to create a multilingual page with drupal.

http://alarabi.biz/category-listing

I created some categoreis and translated them with the Internationalization plugin and i18nviews.

So I can chouse the language in views settings

but all I get is language "und" I think it means undefined.

How to fix it? Terms are translated.

# Answer
You need to use the Name (Translated) handler provided by i18nviews.
> 2 votes

# Answer
You can configure the language settings for the View on the edit page under:

Advanced \> Other \> Field Language
> 0 votes

---
Tags: views, i18n-l10n
---


title: Integrating Search API and Views?

text:
# Question
Title: Integrating Search API and Views?
I just today decided to try out using Search API instead of just the regular exposed filters within views. However, even with the Search API Views module enabled, my indexes don't appear to be exposed to Views as filters. Documentation on integrating Search API and Views is relatively non-existent, so I can't really go to that for help. In fact, the documentation for the integration module states that "Most features should be clear to users of Views." Well apparently not. Any help would be appreciated.

# Answer
> 3 votes
You have first to connect to the server and, then, create an index. So when you click to "add view" you have to choose what kind of view: contents, taxonomies, users or the index you have created. At this point you have field and filters from the search api index (you have to choose which fields should be indexed). Have you a solr server or you want to add a "simple" mysql server to search api?

# Answer
> 15 votes
The important points, which I can't seem to find stated clearly anywhere:

* Each Search API search index you create becomes an option in the "Show \[content\]" dropdown at the top when you first create a new view. Unlike regular search views (where you could just take any old view and add a "Search" contextual filter), to use search API in views, you have to create a special type of view, choosing and fixing the search index to use *at the point of creating the view*, by choosing it in this dropdown.
* You'll need to pipe the actual search terms in somehow. A common way is to use the "Search fulltext" contextual filter, which interprets an argument in the URL as the search terms to use. There's also (depending on search server, I believe) the popular "Search More like this" option, which uses the content of the entity loaded via the contextual filter as the search terms (so if it's a block on a node page set to use the node's nid, it gives you results as if you searched using that node's content). Another way is using an exposed filter then getting the search terms from the input or exposed filter part of the URL query string.
* For reasons I don't quite understand (probably something to to do with how entity API module does views integration for entity views, which has some limitations, more info at http://drupal.org/node/1378656), some elements of a Search API view are different to how they would be normally. For example, where in a node view, the path would be \[path\], in a Search API index view on a search index set to search nodes, it's \[url\]. It's no big deal, mostly the differences are fairly easy to figure out, but it's something to watch out for. Some things e.g. some relationships don't work for similar reasons - test complex views thoroughly and look at both Search API and Entity API issue queues if you find problems.

There is, technically, a documentation page that touches on some of this, which might be of some use to someone.

# Answer
> 8 votes
Be sure to have have "Search Views" module enabled. Something which nobody seems to mention is needed in the documentation anywhere.

---
Tags: views, search
---


# Question
Title: Show new result each time I visit the page
I want to display a result in a view, and each time I visit the page, the result will be the next node from the choosen contenttype.

Is this something I can manage in views or is there any other way?

# Answer
> 1 votes
In Views **Sort criteria** Section Choose the **Global** and then choose **Global: Random** field, it will display each time different result(when the page is refreshed) but it will be random.

I hope it will help you.

# Answer
> 0 votes
In a nutshell you need to create a view with a contextual filters "nid".

then in your custom module you should implement hook\_node\_view() and inside this hook you should set a variable after incremental.

then you would need something like views embed view to send the variable to the view and get your result.

let me know how it goes.

---
Tags: views
---


# Question
Title: How do I modify the _trackPageview output of the Google Analytics Drupal 7 module?
I am working with the Google Analytics (googleanalytics) module in Drupal 7 and I need to get search categories added to the code. The module itself doesn't seem to offer any hooks in for an operation like this. I am considering trying to go into the storage of drupal\_add\_js to modify it. But I don't like how hacky that is.

So my next thought is to modify the module. But I would rather not do this to a contrib module. So any thoughts? I have been also wondering if I can push \_trackPageview twice to Google on the same page, with the second time being with the search query and category. But I don't know how Google Analytics will work with that option.

# Answer
> 0 votes
If your question is "how to pass custom values to Google Analytics ?", then why wouldn't you use the Custom Variables feature of Google Analytics, populated by custom tokens ?

1. Create custom token containing search categories (via hook\_token\_info() and hook\_tokens())
2. In Google Analytics Module interface, in the "Custom Variables" fieldset, add your custom token

---
Tags: javascript, google-analytics
---


# Question
Title: When should "'target' => 'slave'" be used in a query?
Looking at Drupal code, I notice that sometimes a query is being executed using `array('target' => 'slave')` as options, and I don't understand in which case that should be done.

I thought it was done when query where executed in parallel to others, but then I thought that could be said for almost any query executed by Drupal, when more than one user is looking at the pages of a site.
In which cases should `array('target' => 'slave')` be used?

```
  // node_update_index()
  $result = db_query_range("SELECT n.nid FROM {node} n LEFT JOIN {search_dataset} d ON d.type = 'node' AND d.sid = n.nid WHERE d.sid IS NULL OR d.reindex <> 0 ORDER BY d.reindex ASC, n.nid ASC", 0, $limit, array(), array('target' => 'slave'));

```

```
// search_index()
$node = db_query('SELECT title, nid, vid FROM {node} WHERE nid = :nid', array(':nid' => $linknid), array('target' => 'slave'))->fetchObject();

```

Also, looking at Drupal core code, why is `array('target' => 'slave')` sometimes used, and sometimes no?

# Answer
SELECT (read) queries can go to the slave, other such as UPDATE and DELETE (write) queries should go to master then propagate across to the slave database.

> Also, looking at Drupal core code, why is `array('target' => 'slave')` sometimes used, and sometimes no?

That's probably just historical / legacy reasons due to the nature of how the Drupal code base is gradually committed. Potentially any SELECT queries could target the slave database.
> 2 votes

# Answer
I guess this depends on your database architecture. If you have 1 (ore more) dedicated slave database servers (in read only), then it makes sense to send 'safe' read queries to them. This frees your master database server up to deal with writes and hopefully gives your application better performance overall.

You also may be interested in this related post on getting drupal core to send more queries towards them How to get core to leverage a MySQL master/slave configuration?
> 0 votes

---
Tags: database
---


# Question
Title: Bulk action on views only works for the administrator role?
I have a view with a VBO field to execute a bulk operation over nodes.

The bulk operation for this VBO field is a rule component (which I have created) **Get Voucher**

This component execute some actions.

Now in the view I can execute the VBO only if I'm logged as a administrator. But not with any other role.

I make sure that the permission of all action are enabled. But the action for the component **Get Voucher** is not listed here.

The button for the bulk operation is shown but when I click it nothing happens.

Which other permission do I need to enable?

**UPDATE 1**: I know that the problem is related to the actions executed in the compoment. Here is the exported component

**UPDATE 2**: trying with a more simple component (just one action to show a message)

```
{ "rules_test_registered_user" : {
    "LABEL" : "test registered user",
    "PLUGIN" : "rule set",
    "REQUIRES" : [ "rules" ],
    "ACCESS_EXPOSED" : "1",
    "USES VARIABLES" : { "node" : { "label" : "Node", "type" : "node" } },
    "RULES" : [
      { "RULE" : {
          "DO" : [ { "drupal_message" : { "message" : " Hello" } } ],
          "LABEL" : "first rule"
        }
      }
    ]
  }
}

```

# Answer
**Solved** but with some implications.

The problem was that I have to enable the permission to Edit the nodes listed in the view (vouchers content type).

I did that, but now this role will have permission to edit this type of node and this is not what I need.

I understand that vbo needs this permission because it assumes that the user will execute action in the node, but this not my situation, I need the action to **just read** a value of the node (labpoints field) and then execute an action in the user informations (deduct)(user userpoints). So I don't need that the user has the permission to edit the node at all.

I guess I'll use the field permission module to narrow the permissions for this content type.
> 1 votes

# Answer
If using Action Permissions, under Admin \> People \> Permissions, double check the "Execute action name" permission is enabled for the role(s).

It may also be that the user role needs permission to eval that php code in the Rule as well as possibly a userpoints grant points permission required.

Lastly, check the Rules module user permissions and also in edit form for the actions on the rule itself.
> 1 votes

---
Tags: users, views
---


title: Use theme_get_setting to get a value

text:
# Question
Title: Use theme_get_setting to get a value
I am using theme settings in my Drupal 7 theme to provide a theme option as follows:

```
$form['layout']['body_image_position'] = array(
  '#type' => 'select',
  '#title' => t('How should Body Image be Positioned'),
  '#options' => array(
        'body_image_position_right' => t('Image on Right'),
        'body_image_position_bottom' => t('Image on Left'),
        'body_image_position_left' => t('Image Below'),
         ),
  '#default_value' => 'body_image_position_right',

```

);

I then use theme\_get\_setting('body\_image\_position') to call the value of the setting.

Using this command returns the 'machine name' of the setting (e.g. 'body\_image\_position\_right '). But I want the 'friendly name' (e.g. 'Image on Right'). How can I do this?

# Answer
> 2 votes
The easiest way would be to use a helper function to provide your positions which you can then reference back to. For example

```
// In the form function
$form['layout']['body_image_position'] = array(
  '#type' => 'select',
  '#title' => t('How should Body Image be Positioned'),
  '#options' => MYTHEME_position_settings()
  '#default_value' => 'body_image_position_right'
);

function MYTHEME_position_settings() {
  return array(
    'body_image_position_right' => t('Image on Right'),
    'body_image_position_bottom' => t('Image on Left'),
    'body_image_position_left' => t('Image Below'),
  );
}

// In the retrieval function
$key = theme_get_setting('body_image_position');
$settings = MYTHEME_position_settings();
$friendly_name = $settings[$key];

```

The form submission will essentially ignore the label for checkboxes/radios/select lists as it only deals with the key so you'll need to implement some sort of mechanism like this to get at your original labels.

---
Tags: 7, forms
---


# Question
Title: Read contents of uploaded file before saving
I am using `hook_node_presave()` to build a module (which I am new to) in **Drupal 7**. I am able to reference **fields** via `$node->field_foo[$node->language][0]['value']` (which I have seen mentioned several times here in Drupal Answers).

This particular content type I am working on has the ability to upload files. I am new to Drupal 7, but I noticed that:

1. First, the user uploads the file
2. Then, the user saves the node (with a reference to the file)

How do I access the content of that file after it has been uploaded, with `hook_node_presave()`?

# Answer
The `['value']` value is typically found on fields that just store 1 kind of thing, like a text field. Other field types use whatever they need – case in point, the `file` field type will have an array of many values:

```
$node->field_some_file_field_name['und'][0] = array(
  fid => 650, // The file ID, which is important and cool.
  display => 1, // Show the file when a user views the node.
  description => 'foo',
  uid => 7, // The user ID who uploaded this file.
  filename => some_file.pdf, // The **original** filename.
  uri => public://some-dir/some_file.pdf, // The URI to access the actual file.
  filemime => application/pdf,
  filesize => 3067583,
  status => 1,
  timestamp => 1352331360,
);

```

The FID is a cool thing, because the `file_managed` table stores the references to files (including all of the info above) and an entity only needs to know the FID in order to join with this table and get all of the file's metadata without reading the file.

To read the contents of the file, you have a few options:

Not sure what you mean explicitly by "read contents", but a literal file\_get\_contents() would look like this:

```
$filepath = drupal_realpath($node->field_some_file_field_name['und'][0]['uri']);
$file_contents = file_get_contents($filepath);

```

If you want to check the MIME or filesize or something like that, you already have that data available to you in the field's array.

If you can elaborate on "reading" the file and what you might like to do before the file field is attached to the node, please update your post and I'll try to update this answer accordingly. There may be another, better place for your work to happen.
> 12 votes

---
Tags: 7, files
---


title: Apache solr views, Drupal 7

text:
# Question
Title: Apache solr views, Drupal 7
I am using D7, views 3, apache solr views modules. I have created a view with 2 contextual filters for apache solr. I want to view the solr query built using my contextual filters. But the view preview is displaying the text "No query was run".

Is there any way to view the solr query at preview page?

# Answer
> 1 votes
You can use the Devel module, and enable page show devel page query.

**Devel:**

> A suite of modules containing fun for module developers and themers.
>
> * Helper functions for Drupal developers and inquisitive admins. This module can print a summary of all database queries for each page request at the bottom of each page. The summary includes how many times each query was executed on a page (shouldn't run same query multiple times), and how long each query took (short is good - use cache for complex queries).
> * Also a `dprint_r($array)` function is provided, which pretty prints arrays. Useful during development. Similarly, a `ddebug_backtrace()` is offerred. See full demo.
> * Accelerate development of your site or module by quickly generating nodes, comments, terms, users, and more.

---
Tags: 7, views, search
---


# Question
Title: No "body" when creating a node programatically, with Internationalization
I am trying to create event type nodes in Drupal 7, using data from an external database. It's reading correctly, and creating a node almost perfectly. But, it doesn't seem to save the "body" part of the node.

```
db_set_active('default');

foreach ($results as $record) { // Results gained from an ext DB
  echo 'Creating event: ' . $record->name;

  $node = new stdClass();
  $node->type = 'event';
  node_object_prepare($node);

  $node->title    = $record->name;
  $node->language = "en";;

  $node->body[$node->language][0]['value']   = $record->bodytext;  /* This line ?? */

  $path = 'content/programmatically_created_node_' . date('YmdHis');
  $node->path = array('alias' => $path);

  node_save($node);
}

```

This is early stages, and I have a number of fields to put into events type nodes, including some custom fields.

I am unsure how to map the fields in the external database to node fields. The line above might be completely wrong at this stage, but it's gone though many many failing iterations.

As requested: DPM output of the node (after save)

```
... (Object) stdClass
type (String, 5 characters ) event
uid (String, 2 characters ) 10
status (Integer) 1
promote (Integer) 0
sticky (Integer) 0
created (Integer) 1357635638
revision (Boolean) FALSE
comment (String, 1 characters ) 1
language (String, 3 characters ) und
menu (Array, 13 elements)
title (String, 42 characters ) Starter Course
field_pakp_p1_id (String, 36 characters ) 78ee9b05-9225-fb5b-9bbb-508eada6ba81
body (Array, 1 element)
  en (Array, 1 element)
    0 (Array, 3 elements)
      value (String, 19 characters ) This is a body text
      summary (String, 19 characters ) Here goes a summary
      format (String, 13 characters ) filtered_html
path (Array, 1 element)
validated (Boolean) TRUE
changed (Integer) 1357635638
timestamp (Integer) 1357635638
publish_on (Integer) 0
unpublish_on (Integer) 0
log (String, 0 characters )
nid (String, 3 characters ) 423
tnid (Integer) 0
translate (Integer) 0
vid (String, 3 characters ) 423
field_event_status (Array, 1 element)
xmlsitemap (Array, 15 elements)

```

...

I also tried using the drupal\_form\_submit method..

```
foreach ($results as $record) { // Results gained from an ext DB
    echo 'Creating event: ' . $record->name;
    $node = (object) array(
      'type' => 'event',
      'language' => LANGUAGE_NONE
    );
    node_object_prepare($node);

    $form_state = array();
    $form_state['values']['language'] = "en";
    $form_state['values']['title'] = $record->name;
    $form_state['values']['description']['value'] = "description....";
    $form_state['values']['body']['value'] = "body....";
    $form_state['values']['body']['format'] = filter_default_format();
    $form_state['values']['body']['LANGUAGE'] = "en";
    $form_state['values']['name'] = $user->name;
    $form_state['values']['op'] = t('Save');

    drupal_form_submit("{$node->type}_node_form", $form_state, $node);

}

```

But again, try as I might, using this method I could not get the "body" to be saved. (I know there is some junk in this code, it's my experimentation.)

Questions.

1. Which is the best method to use for my application. node\_save or drupal\_form\_submit
2. For the correct method, which is the best way to store the body text?
3. How do I know what are valid $form\_state array keys, or $node elements, so I can find the correct place for further field mapping?

# Answer
> 1 votes
If your site is multi-lingual then 'en' would contain the English-language translations of your original node (I think that's right).

Going out on a limb, I'd say you're not running a multilingual site and instead want to use the `LANGUAGE_NONE` constant, e.g.

```
$node->language = LANGUAGE_NONE;

```

If your site isn't multi-lingual, using 'en' would probably explain why you're not seeing the body value saved. It might even be there in the database, but because the field system is looking for fields with a `LANGUAGE_NONE` when it's attaching data to a language-neutral node, nothing gets found.

That might be a load of nonsense though ;)

# Answer
> 0 votes
Drupal 6 or 7?

I would use `node_save()`. Try using `dpm()` to inspect the structure of the specific node type. Maybe post it here?

I have just done something similar:

```
/**
 * Import upload form.
 */
function mymodule_import_form($form, &$form_state) {
  $form = array();

  $form['#attributes'] = array('enctype' => "multipart/form-data");

  $form['import_file'] = array(
    '#type' => 'file',
    '#title' => t('Import file'),
    '#description' => t('CSV file containing xx data.'),
  );

  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Import'),
  );

  return $form;
}

/**
 * Import submit callback.
 */
function mymodule_import_form_submit($form, &$form_state) {
  $validators = array(
    'file_validate_extensions' => array('csv'),
  );

  if ($file = file_save_upload('import_file', $validators)) {
    $fp = fopen($file->uri, 'r');

    $count = 0;
    while ($row = fgetcsv($fp)) {

      // If event already exists, don't do anything.
      $result = db_query(
        "SELECT nid FROM node WHERE type = 'event' AND created = :created AND title = :title",
        array(':created' => $row[3], ':title' => $row[7])
      );
      $nid = $result->fetchField();
      if ($nid) {
        drupal_set_message('Already exists: ' . l($row[7], 'node/' . $nid . '/edit'));
        continue;
      }

      // Create event node
      $node = new stdClass();
      $node->type = 'event';
      node_object_prepare($node);
      $node->uid = 0;
      $node->created = $row[3];
      $node->title = $row[7];
      $node->language = 'da';
      $node->body['und'][0]['value'] = $row[10];
      $node->field_company_name['und'][0]['value'] = $row[8];
      $node->field_email['und'][0]['value'] = $row[10];
      $node->field_phone['und'][0]['value'] = $row[9];
      node_save($node);

      drupal_set_message('Created: ' . l($node->title, 'node/' . $node->nid . '/edit'));

      $count++;
      if ($count > 50) break;
    }
  }
}

```

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


# Question
Title: How to clean the html output of textfield using CKeditor?
I have a textfield using the wysiwyg http://drupal.org/project/ckeditor text editor module.

If I insert a table in the text then the table is wrapped with the following tags

```
<p>
     </p>

```

I thought that the http://drupal.org/project/htmlpurifier module would remove this tags but it doesn't.

How can I remove these lines?

# Answer
> 3 votes
I have run into this, I'm not sure if there is a configuration value to avoid this. I usually end up installing Empty Paragraph Killer.

> Empty paragraph killer is a filter module, helpful on sites which use WYSIWYG editors.
>
> People often hit the return key twice at the end of a paragraph. Most, if not all site layouts manage the paragraph spacing, so the extra empty paragraphs created can detract from the look and feel of a site. This module filters out the empty paragraphs of all user-entered data on a site. It does so by following the fundamental Drupal way - non-destructively.

---
Tags: wysiwyg
---


title: Make CSS classes styled in WYSIWYG

text:
# Question
Title: Make CSS classes styled in WYSIWYG
How can I make CSS classes that can be added to content in a WYSIWYG style in the edit view?

I've added the following 'CSS classes' and I've used my site's normal CSS to float them left and right respectively and give them a width of 51%:

```
Left=div.posLeft
Right=div.posRight

```

When I save the node this works fine. However in the editor the styles are not shown. How can I make them show up?

# Answer
As @tenken says, on the WYSIWYG profile edit page, under the 'CSS' panel, in the 'CSS path' filed you can link to a CSS file to be used on the edit view.

/admin/config/content/wysiwyg/profile/PROFILE-NAME/edit
> 2 votes

---
Tags: wysiwyg
---


# Question
Title: Programmatically Access custom user field
I added a Node-reference field (machine name: field\_node) to all users at:

```
example.com/admin/config/people/accounts/fields/

```

I am now working in a custom module & `hook_node_access`

How do I access the Node-reference field programmatically when the user is logged in?

# Answer
You can get field values from any entity with `field_get_items()`; the logged in user is available in the global `$user` object, and to load fields onto that object you can use `user_load()`.

Put those together and you get something like this:

```
// Get a fully loaded entity object for the logged in user.
$account = user_load($GLOBALS['user']->uid);

// Extract the field items
$field_items = field_get_items('user', $account, 'field_node');
if ($field_items) {
  // This will be 'target_id' if you're using the Entity Reference module,
  // or 'nid' if you're using References
  $column_name = '?';

  $nid = $field_items[0][$column_name];
}

```

That's the abstract code if you like.

It's worth bearing in mind that `hook_node_access()` is passed an `$account` object already (which will be the logged in user if the access check is happening for them) so you would probably be better off using that to check against. You might still need to run it through `user_load()`, it'll be easy enough to check that with a bit of debugging.
> 10 votes

# Answer
Two options here, using core API or entity\_metadata\_wrapper

```
global $user;
// Load full user account object
$account = user_load($user->uid);
// Get field;
$items = field_get_items('user', $account, 'field_node');
// Debug info
drupal_set_message('<pre>'.var_export($items,1).'</pre>');
// This gets the sanitized output, from the first field delta value (0)
$output = field_view_value('user', $account, 'field_node', $items[0]);

```

Relevant functions:

You can also, if using the Entity API module, use entity\_metadata\_wrapper

```
global $user;
$user_wrapper = entity_metadata_wrapper('user', $user);
drupal_set_message('<pre>'.var_export($user_wrapper->field_node->raw(),1).'</pre>'); // Raw value
drupal_set_message('<pre>'.var_export($user_wrapper->field_node->value(),1).'</pre>'); // Loaded value

```

**EDIT**: Sorry, answer was posted while I was posting this answer.
> 7 votes

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


# Question
Title: What is best coding practices for providing an upgrade path to a new module version?
I'm getting ready to build a new version of a module of mine. The new version can have an upgrade path from the current version to the new version that will be released, but as you know, new major verions come with database restructuring, entity refactoring, and what not.

Is there a standard practice in the way the upgrade path is provided? For instance, should I build code in the install hook of the new version, and update hook, or some stand alone script?

Suggestions welcomed.

# Answer
Add the install information required for the new module version in the hook\_install and hook\_schema.

Users upgrading presumably won't be re-installing the module, so you'll need to use hook\_update\_N for those users. Check if the upgrade path is required for that installation and proceed with the update as needed.
> 2 votes

---
Tags: 7, updating
---


# Question
Title: Is there any way to take a preexisting field with content, and generate taxonomy from it?
I have a content type called 'classes' in the content type is a text field called 'instructor'. I also have a separate content type called 'instructor profile'. The two content types 'classes' and 'instructor profile' are not tied to together in anyway unfortunately (not setup by me).

I would like to tag the existing 'instructor profile' content type with their 'classes'. So for example, if you are looking at the instructor profile, you can see what classes he/she teaches. The easiest way to do this would be take the existing 'instructor' text field under 'classes' and generate the vocabulary so I can match those up with "instructor profile' under a view later on by tagging the Instructor's profile with the right vocabulary.

However, I can't seem to find a module that will take an preexisting field and generate terms from it (or convert that field into a free-tagging taxonomy term). Any idea?

# Answer
It sounds like a job for an entity reference field

For example, add a "field\_classes" entityreference field to "Instructor profile" referencing the class nodes that instructor teaches.

Alternatively, add a "field\_instructor" entityreference field to the "Classes" content type, referencing the instructor profile(s) for that class.

Using Entity Reference, each content type can easily list the related instructors and classes.
> 0 votes

---
Tags: taxonomy-terms
---


# Question
Title: How to act on paramters being passed to the homepage?
We have external sites direct users to our homepage. These external sites add information to the url which add additional information. This is an internal academic site so these parameters look like, for example, http://www.example.edu/?dept=classics How can I get our homepage to detect and act on these parameters?

# Answer
I think my approach would be to use `$_SERVER['REQUEST_URI']` in a `hook_preprocess_HOOK` (see this) on `template.php` in a theme folder if all I needed to do is theming based on it. For example:

```
function example_preprocess_page(&$variables) {
  $current_path = $_SERVER['REQUEST_URI'];
  // and so on
}

```

And then you could `explode()` it, modify stuff in the page array or the node array, etc.
> 0 votes

# Answer
My suggestion would be in the `function example_preprocess_page(&$variables)` of your template.php file you can use the `drupal_is_front_page()` to determine if you are on the homepage. Then use `$somevariable = $_GET['q'];` to pull out the variable and act on that. Please note, this is untested.
> 0 votes

---
Tags: 7, uri
---


title: File upload drag and drop

text:
# Question
Title: File upload drag and drop
> **Possible Duplicate:**
> Drag & drop files into drupal site?

I need to implement drag and drop file upload functionality. Does Drupal make this easy somehow? Should I use a JS toolkit, like Dojo or Mootools?

# Answer
> 1 votes
Although -dev for D7, You could try http://drupal.org/project/dragndrop\_uploads

> The Drag'n'Drop Uploads module adds the ability to drag an image from your local filesystem, drop it onto a node body textarea and have the file automatically uploaded and referenced in your node.

---
Tags: 7, files
---


# Question
Title: tell drush to update anything not part of a profile
I'm using an installation profile (open-outreach) and additional modules / themes. I don't want drush to update modules that are part of the profile, but would like to update everything else. Is there a command to do this?

# Answer
> 4 votes
This would be a good feature request for the pm-updatecode command. I'd say that the best workaround for this missing functionality would be to tell Drush to lock the modules you do not want it to update. Do this one time:

drush pm-updatecode --lock=project1,project2,project3

Replace 'project1,project2,project3' with a comma-separated list of all of the projects in your installation profile. When you do this, Drush will write a lockfile into the mail directory of each project you mention, creating a persistent lock. Thereafter, you may run drush pm-updatecode without the --lock parameter, and Drush will remember that it should not update any of those modules.

If you wish, you may also lock the modules with http://drupal.org/project/update\_advanced, and Drush should respect that as well. Works great in Drupal 6, but I have not tried Drupal 7 (only a dev release is available).

# Answer
> 2 votes
In the RC7 release of Open Outreach we introduced some related functionality cribbed from the Commerce Kickstart distro, see http://drupal.org/node/1852898. There isn't Drush support, but you could navigate to the update notifications page and note there the list of modules that show up.

---
Tags: drush, distributions
---


# Question
Title: How to add a background image wallpaper to a drupal site from within the drupal admin?
How can I add a background image wallpaper to a drupal site from within the drupal admin i.e. not editing themes or PHP?

I'm not adverse to PHP or themes but adding a background image wallpaper is a generic non-theme specific feature so should require editing a specific theme.

This has to be one of the simplest/fundamental/popular things one wants to do with their site. It ought to be obvious in Drupal -and- possible within the Drupal admin, not via editing themes / PHP code.

Is there a way to do it?

I found some promising modules (actively depveloped for Drupal 7) but am a little unsure how to use them:

* http://drupal.org/project/bg\_image (Instructions say: "provide a css selector and color and repeat attributes in the 'Default CSS Settings' section." - but how do I know what CSS selector to use? Yes I know CSS but in the context of Drupal, is there more than one I need to consider and why? Perhaps an *example* would help here)
* http://drupal.org/project/dynamic\_background (This has more advanced settings for specific entities in drupal: User, Blog, Panels, Node, Views (beta), Context) - OK fine. BUT *WHICH* one do I use to simply put up a background image for the pages of my Drupal site?!

# Answer
> 1 votes
Here's an example answer from me for my question (I don't necessarily expect to accept my own answer, I'd rather a non code-editing in-drupal-admin solution)

Using the minimal theme / acq\_minimal, located in my installation at path

```
../sites/default/themes/mythemes/acq_minimal

```

There is a file called

```
palette.css

```

In this file there is CSS for the body html tag. Edit this to add a background image:

```
body {
  background-color: #000000; /* new background colour */
  background-image: url('wallpaper.jpg'); /* inserted line for background image */
  background-repeat:no-repeat; /* inserted line to not repeat */
  color: #333333;
}

```

It's a shame that there isn't a standardised way to do this within Drupal web-based admin without having to resort to editing the theme code (editing the code (via FTP and a code editor) breaks the wonderful user permissions system drupal has within its admin. Fewer people (or even just one) person may be allowed FTP access to the docroot of the drupal installation. This creates a bottleneck and complicates the administration of user rights.

**Update**

Ideally I should do this as a sub theme based off of this theme (so that should the orignal theme be updated, those updates won't clash with/overwrite my change during an upgrade) - need to work out how to do this.

However this does not quite answer my question about doing it within Drupal admin. But it still gets the job done. My suggested initial solutions are also worth exploring:

* http://drupal.org/project/bg\_image (Instructions say: "provide a css selector and color and repeat attributes in the 'Default CSS Settings' section." - but how do I know what CSS selector to use? Yes I know CSS but in the context of Drupal, is there more than one I need to consider and why? Perhaps an example would help here)
* http://drupal.org/project/dynamic\_background (This has more advanced settings for specific entities in drupal: User, Blog, Panels, Node, Views (beta), Context) - OK fine. BUT WHICH one do I use to simply put up a background image for the pages of my Drupal site?!

# Answer
> 3 votes
For simple Drupal themes we use Artisteer. You can change most properties of a theme with just a mouse click. Please note that the tool is not free (and I'm just a happy user).

# Answer
> 2 votes
I agree with your assessment that setting a background is one of the first things a new web designer wants to do, but what I found is that while Drupal is incredibly flexible and capable, it is not uniform or flexible in its approach to appearance issues. Drupal is not an out of the box website solution. It is a programming methodology for creating and managing web content, written by programmers for programmers. Many modules arose to streamline input for repetitive tasks, not to make things user friendly. Drupal provides a framework for the graphics with themes and regions but again it looks more like an effort to streamline tasks than to create a user interface for non-programmers. ON top of the themes, modules dealing with generating content, menus, and the like will add their own theme input as it applies to their part. Again Drupal is incredibly good at gathering all this input and providing flexibility for modules to direct things, but both themes and modules are created by separate groups and do not necessarily follow the same approach for styling the content.

The result is that it is difficult to figure out which themes and modules to use and what they are doing without some detailed research into their innards. The most frustrating thing for me has been trying to unravel the styling spaghetti that ends up displaying a page. Many themes have a limited UI that allows you to change some colors etc, but they are far from comprehensive Theme UIs. Things got so complex at times with so many inheritance levels, that I began using a style stripping css snippet to strip as much out as possible so that I can make sense of what is doing what in the CSS stylesheets.

One solution might be to keep things as simple as possible. Administrative pages are rendered in the "Seven' theme, which is very simple indeed. Very few divs, classes and overall theming with few regions. To arrange the layout I want I use the Panels Module. This module creates a very clear layout and content assignment interface that taps into Drupal's Content Management system and can alter or totally bypass themes. You will need to do some css stylesheet work to establish your sites character, but you will be doing it the way you want and know where everything is. I use several themes as reference materials, if there is some affect I especially want to use. But I have gotten where I want much faster this way.

# Answer
> 0 votes
This will need to be a function in an already existing base theme, or you will need a module. I am currently not aware of any base themes that have this, as it is not a very semantic way of doing things.

The modules you listed above are a good start, but if you are expressly wanting to upload an image through an upload file field it will take some theme alterations.

# Answer
> 0 votes
I found something that works for me! Under ...sites\default\files\color\[subdir name based on template\] there is colors.css, edit the following:

under "#header"

add this:

```
{background-image: url('imagename.png');}

```

delete or comment this out:

```
{background-color: #ab3a0d;

  background-image: -moz-linear-gradient(top, #893210 0%, #ab3a0d 100%);

  background-image: -ms-linear-gradient(top, #893210 0%, #ab3a0d 100%);

  background-image: -o-linear-gradient(top, #893210 0%, #ab3a0d 100%);

  background-image: -webkit-gradient(linear, left top, left bottom, color-stop(0, #893210), color-stop(1, #ab3a0d));

  background-image: -webkit-linear-gradient(top, #893210 0%, #ab3a0d 100%);

  background-image: linear-gradient(top, #893210 0%, #ab3a0d 100%);
}

```

---
Tags: 7, media
---


# Question
Title: How do I know whether drupal_write_record has done an insert or an update?
I use the function to insert or update records in a table, but sometimes I would like to know whether the function has executed an update or an insert. In my scenario I always provide the primary key:

```
drupal_write_record('mytable',$entry,'key');

```

The function inserts a record if `$entry['key']` does not exists and updates the record with the new information otherwise.

Is there somewhere I can check to see what the function has done ?

# Answer
Turns out that in order to know if the operation was an `UPDATE` or an `INSERT` you need to know whether the record existed or not before committing the transaction. This is not what drupal\_write\_record() does. This function just checks it's arguments and issues an update or an insert accordingly. So there is **really no way** to tell if the function did an `INSERT` or an `UPDATE`.

The solution is using db\_merge() query, it is a relatively new SQL ANSI standard that does exactly what I needed (and in the case of MySQL does it in an atomic transaction).

```
$return_value = db_merge('mytable')
            ->key(array('id' => $key))
            ->fields($fields)
            ->updateFields(array(
                'updatedon' => $now,
            ))
            ->execute();

```

The return value is an integer returning 1 for inserts and 2 for updates.
> 3 votes

# Answer
`drupal_write_record()` returns

* `SAVED_NEW`

> Return status for saving which involved creating a new item.
* or `SAVED_UPDATED`

> Return status for saving which involved an update to an existing item.

You can use that return value to determine what type of query was executed.
> 1 votes

---
Tags: 7, database
---


# Question
Title: How can I add a log entry to watchdog every time form_set_error() is triggered on user_account_form_validate()?
I'm not much of a coder so I'm having a real hard time figuring this out.

I have a custom module and I'm trying to override `user_account_form_validate()` (from user.module) so that I can add a watchdog entry every time a specific instance of `form_set_error()` is called:

```
elseif ((bool) db_select('users')->fields('users', array('uid'))->condition('uid', $account->uid, '<>')->condition('name', db_like($form_state['values']['name']), 'LIKE')->range(0, 1)->execute()->fetchField()) {
  form_set_error('name', t('The name %name is already taken.', array('%name' => $form_state['values']['name'])));
}

```

I need to do this because sometimes the Email registration module causes this error to fire and I want to make sure that this doesn't occur; so, to ensure users aren't seeing this error, I want to log it in watchdog if it occurs.

I know I can hack core and add the following line just after form\_set\_error:

```
watchdog('mymodule', 'Registration error: %name was already registered.', array('%name' => $form_state['values']['name']), WATCHDOG_ALERT);

```

But how I can I do this without hacking core? I tried various permutations of function

> function mytheme\_user\_register\_form\_validate (&$form, &$form\_state) {}

in a custom module but I couldn't successfully get Drupal to use my function instead of the core one.

# Answer
To add a new validation handler to a form, you need to implement `hook_form_alter()`. In your case, I would use the following code, which adds an extra validation handler that is executed before the other ones added by the User module.

```
function mymodule_form_user_register_form_alter(&$form, &$form_state) {
  array_unshift($form['#validate'], 'mymodule_user_register_validate');
}

function mymodule_user_register_validate($form, &$form_state) {
  $account = $form['#user'];

  if (isset($form_state['values']['name'])) {
    if ($error = user_validate_name($form_state['values']['name'])) {
      // This is intentionally empty.
    }
    elseif ((bool) db_select('users')->fields('users', array('uid'))->condition('uid', $account->uid, '<>')->condition('name', db_like($form_state['values']['name']), 'LIKE')->range(0, 1)->execute()->fetchField()) {
      // Log the error with watchdog().
    }
  }
}

```
> 1 votes

---
Tags: hooks, forms
---


# Question
Title: Make search block appear for anonymous user
I have defined a region in my theme in which I've placed the search box. But, it only appears when a user is logged in. I checked to see the visibility and made sure the block is also visible to anonymous users; but it doesn't show up.
I searched online for the issue but I wasn't able to find a good (working) solution. Is there a way to do so?

My search block visibility settings:

# Answer
I think you and I had the same problem; the fix "Under Search give 'Use search ' permission for anonymous user" actually worked for me, but because of this, it didn't work immediately:

Home » Administration » Configuration » Development » Performance

"Cache pages for anonymous users"

just hit "Clear all cache" & your good to go!
> 1 votes

# Answer
There is one more permission need to set at admin/people/permissions. Under Search give 'Use search ' permission for anonymous user
> 3 votes

---
Tags: 7, blocks, search
---


title: Site logo on user registration email

text:
# Question
Title: Site logo on user registration email
I am using drupal 7. I want to add the site logo on the user registration email, when new user added with my site. How can i include the logo path on the user registration settings. It doesn't support the html tag format. I have also searched with tokens, but there is no token for including logo. How can i add the logo. Please help me.

Thanks, Sathish

# Answer
Drupal doesn't support HTML e-mails out of the box. To do this, you can download either:

or

You will also need the Mail System module. On my own site, I use the Mime Mail module with a PHP template that I designed (following the instructions in the Mime Mail documentation) to attach my logo to outgoing e-mail messages.
> 2 votes

---
Tags: emails
---