title: theme hook and rendering

text:
# Question
Title: theme hook and rendering
I am trying to get my head around the drupal 7 render() function but there is something I can't get straight.

The data source that I want to render looks like this:

```
Array
(
    [id] => 3315539862007
    [name] => Some Name
    [picture] => some-facebook-image.jpg
    [link] => http://www.facebook.com/some-page

```

I pass it to a $block\['content'\] like this (I also tried changing '#children' to '#element', but with no success):

```
$block['content'] = array(
  '#theme' => 'opengraph_company',
  '#children' => $data
);

```

but inside my custom theming function the data that is passed looks really weird

```
function theme_opengraph_company($variables) {
  $element = $variables['element'];

  return 'hello';
}

```

if I debug the $variables inside the theming function I get something like this

```
Array
(
    [element] => Array
        (
            [#theme] => opengraph_company
            [#children] => Array
                (
                    [id] => 3315539862007
                    [name] => Some Name

```

which to me looks really weird. The MYMODULE\_theme function looks like this

```
function opengraph_theme() {
  return array(
      'opengraph_company' => array(
      'render element' => 'element',
    ),
  );
}

```

I would expect access to the data based to the theming function to easier, something like

```
function theme_opengraph_company($variables) {
  $element = $variables['element'];

  return $element['name'];
}

```

Am I passing the parameters wrong to the theming function?

# Answer
> 4 votes
When you use `render element`, the element which you apply the theme to is passed into the theme function in the `$vars` array...the index in the array will be whatever you've set `render element` to in your theme function, which in this case is element; hence the element you've asked the theme API to pass in is available in `$vars['element']`, which is a carbon copy of the original render element.

To get the effect you're looking for you would normally use `variables` instead of `render element`:

```
function opengraph_theme() {
  return array(
    'opengraph_company' => array(
      'variables' => array(
        'id' => 0,
        'name' => '',
        'picture' => '',
        'link' => ''
      ),
    ),
  );
}

```

Then you'd build your render element like this:

```
$block['content'] = array(
  '#theme' => 'opengraph_company',
  '#id' => 123,
  '#name' => 'Name',
  '#picture' => 'Picture',
  '#link' => 'Link'
);

```

Or, if you want to use your current `$data` array, you can pass it directly to the theme function:

```
$block['content'] = array(
  '#markup' => theme('opengraph_company', $data)
);

```

Bear in mind with that second method any modules whose hooks might be run after yours will no longer get the chance to alter the theme output, as you're converting it down to a string.

Using either of those methods though, when your theme function is run you will have access to the variables like this:

```
function theme_opengraph_company(&$vars) {
  $id = $vars['id'];
  $name = $vars['name'];
  // etc...
}

```

---
Tags: 7, theming
---


# Question
Title: Drupal site communication with other site
Hello I have a Drupal 7 site. I want users to login without using the drupal form. I will silently send username and password credentials from another site and when users click the link to my drupal site they will be already logged in. So how to communicate with drupal login and send the details of the user from another site or maybe a browser plugin or a PC application etc.

# Answer
This is a fairly complicated thing to do, but the "go to" module for handling integration with third-party sites is the services module.
> 1 votes

---
Tags: users
---


title: Error in file_save()

text:
# Question
Title: Error in file_save()
I have a config page in my module were you can upload a file and change a few other settings. It works fine IF you do upload a new file when you click save however if you don't upload a file and just try to change a setting I get this error:

```
Argument 1 passed to file_save() must be an instance of stdClass, boolean   given, called

```

The message references an error in the following piece of code:

```
function background_audio_form_submit($form, $form_state) {

  // The file is automatically uploaded and saved in the default
  // validation process so you just need to load the file object at this  point,
  // mark that you want to keep it, and save it again.
  // The file ID is contained in the $form_state['values'] array
  $file = file_load($form_state['values']['background_audio_file']);
  file_save($file); <-- THIS IS WERE THE ERROR OCCOURS

  variable_set('background_audio_upload_path', $file->filename);
  variable_set('background_audio_height', $form_state['values']['background_audio_height']);
  variable_set('background_audio_width', $form_state['values']['background_audio_width']);
}

```

Can I do something like `if $file is changed then execute it if it is NOT changed ignore it`? If so how would I do that?

# Answer
> 1 votes
The `$form_state` array variable contains all the information about the current state of the form. `print_r($form_state)` to find out the array key corresponding to the upload element in the form. If there is no new upload, this array key should have an empty value, or maybe the array key won't exist at all. If for example `$form_state['upload_element']` is populated, then you can call `file_save($file);`.

# Answer
> 0 votes
Quick answer is to throw `if`s around things, eg:

```
if ($form_state['values']['background_audio_file']) {
  $file = file_load($form_state['values']['background_audio_file']);
  file_save($file);
  variable_set('background_audio_upload_path', $file->filename);
}

```

---
Tags: forms, files
---


# Question
Title: Redirect to last page visited on 404 error
Just wondering if there is a simple way to automatically redirect users to the last page they have visited if they receive a 404 error? I am using Drupal 7.

# Answer
There's a module for that: CustomError, which has a development snapshot for Drupal 7.

> This module allows the site admin to create custom error pages for 404 (not found), and 403 (access denied), without the need to create nodes for each of them.
>
> Since the error pages are not real nodes, they do not belong a category term, they do not show in the search, and will not show up in node listings, or in Popular Content block.
> 2 votes

# Answer
You can do this with a custom module:

```
function YOUR_MODULE_NAME_boot() {
  if(!menu_get_item($_GET['q'])) {
    if($_SERVER['HTTP_REFERRER']) {
      header('Location: ' . $_SERVER['HTTP_REFERRER']);
    }
  }
}

```
> 1 votes

# Answer
Instead of redirecting users automatically, I suggest you provide a link in the 404 page to link back to the previous page. You can make use of `HTTP_REFERRER` to link back, or any other approach.
> 1 votes

---
Tags: redirection
---


# Question
Title: moving of a database [drupal-commons 6x25]: Which tables can be emptied safely?
I am running Drupal Commons 6.x25 (released February 2012); I have installed it yesterday locally on a lamp, on OpenSuse 12.1. Now I want to move it to the web server, but I have noticed that the fresh database—without any special module, beside the ones that are shipped with commons—is extremely large (16 Mbit).

Sometimes, the moving of a database can be too hard since the database is a way too large. Which Drupal tables are safe to manually clear using PhpMyAdmin?

What about all the "cache\_" prefixed tables be emptied without causing problems?

**Background:** well - sometimes i have some troubles in meging the 16 db at once... but i continue to try to move a drupal-commons in a single step without any emptiying. BTW to **which extend we can lower the db-size of 16 mb - 10 or 5 mb probably.**

# Answer
> 4 votes
I used to empty all "cache" prefixed tables, "watchdog" table and session table.

---
Tags: database
---


title: Serve Drupal files from subdomain

text:
# Question
Title: Serve Drupal files from subdomain
On Drupal 7, I want all files to be served from a a subdomain of my site (eg. files.mydomain.com) for the simple reason that it allows a bit of flexibility going forward. So uploaded files, css and js caches, etc. would all be served from this subdomain.

The files are still located on the same server as Drupal and in a location writable by Drupal.

How can I do this?

# Answer
Take a look at the CDN module it helps you serve files from a different domain. I'm using it myself on a drupal 6 site, and it works great.
> 2 votes

---
Tags: files
---


# Question
Title: Filter a field based on the content type in a view(Drupal 7)
I need to remove a field for a view(Block) for a particular content type.

I have two different content types.One is Article and another is External News.

The following are the fields I added in the view.

```
Field:

      Content: Title
      Content: Post date
      Content: External URl
      Content: Last comment author
      Content: External URl

CONTEXTUAL FILTERS:
   Content: Has taxonomy term ID

FILTER CRITERIA
    Content: Published (Yes)  AND
    Content: Type (in Article, ...)
     AND
     Content: Has taxonomy terms (with depth) (= Technology)  AND | Settings
     Field: Tags

```

Here I need the field Last Comment author to display only when the content type is Article and not for External news.

Can Anyone help me how to filter the field based on the content type for a view block

# Answer
> 1 votes
You can use a preprocess hook to build in some logic to now show the last comment when the content type if of the type is External news. You need to add the content type and exclude it from display. That will make the value available in the preprocess hook.

You could use `hook_preprocess_views_fields` for this.

---
Tags: entities, views
---


# Question
Title: Input format to save page links by ID but render by the URL alias?
I would like an input format that works roughly like this:

* I can enter links to other pages on my site using a special syntax, but importantly, I reference them by their current URL alias.
* When the page is saved to DB, the filter replaces them with node IDs, which never change.
* If I edit the page again, the filter replaces them back with current URL aliases before showing it to me. That way I know what the links are and I don’t even have to care that the DB actually stores node IDs.
* When the page is rendered, the links are rendered to the URL aliases, rather than node IDs.

Is there anything out there that does this already?

Why I want this: so that I can change URL aliases without breaking existing links. I do have automatic redirects created, but that's not quite the same thing. I want pages to link to the correct URL when I change an alias.

# Answer
If you use an wysiwyg editor ie. CKeditor, there are contrib modules that offer you this functionality. For example, take a look at the ckeditor link module. It let's you search for your nodes and make a link to the node path which is what is saved to your database. Drupal automatically shows the url alias frontend, so if you change your url alias at a later point, you will still have a working reference to your node.

Why is it important to you that you reference them by their current url alias?
> 0 votes

---
Tags: 7
---


title: Real Estate Functionality

text:
# Question
Title: Real Estate Functionality
My client wants a real estate website that links to other major sites like Trulia. He wants a way of collecting information from his visitors, and a way of telling that they went through his site to get to the major real estate sites.

How can this be achieved?

# Answer
> 2 votes
You can create an internal url system that redirects to the partner sites. Depending on what you need to do, you could create a node (content) with info about the partner site where you stored the link to it. Then instead of displaying the link directly on the site you could instead display the url: `redirect/[nid]`. The url would be known by your module, and you could store info that you were sending some one over to the partner site before loading the node to find the url to send them over to.

You would have to create a custom module for this, but the above method could be a way of doing this.

You could also use tools like Google Analytics to track outgoing links instead. It depends where you want the data and what you need to do with it.

---
Tags: commerce
---


# Question
Title: Would hook_access() hide content from Views/Solr if returning FALSE?
If I were to setup my own `hook_access()` and return `FALSE` based on a few different criteria, would this then hide the content from a view in modules like Views and Apache Solr?

# Answer
> 2 votes
`hook_access()` is only called when viewing/editing a *single* node. For all listings, both in core and views, you need to use the node access system. You also need to use that for node types which are not owned by your module.

# Answer
> 1 votes
No; I tried and the Views module does not respect `hook_access()`, at least for drupal 6. Take note that I'm not sure if this is the same for you. Our site has a lot of access modules, like node access, path access, access rules, grant access, I'm not sure about the names due to the madness. With this in mind, I don't really know how `hook_access()` would behave for a clean drupal site.

---
Tags: 6, users
---


title: I18N, translating in template variables

text:
# Question
Title: I18N, translating in template variables
I've got a theme setup, and this theme has a header region (region--header.tpl.php). There are some small ui elements in this template that require translation, but are not tied to blocks, views or nodes. My understanding is that when using something like `<?php print t('Select a topic'); ?>` it should become available to the translation backend. But it does not for me? I have the I18N module and Multilingual Variables module installed.

What am I missing?

# Answer
Ah I found that one needs to view the site in another language than English in order to have the strings to be registered.
> 3 votes

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


# Question
Title: Is there a way to upload file in database instead of in filesystem via webform?
When files are uploaded via webform, the attachment is stored in filesystem. Is there a way to store the attachment in database blob field?

# Answer
You could read the field and write the contents in the database. This could be done in a custom submit handler to the webform form.
> 1 votes

---
Tags: 6, webforms, files
---


title: Errors when running Cron

text:
# Question
Title: Errors when running Cron
I can't run cron; see the video capture I created.

If I click "Run cron" in the admin menu I'm redirected to another URL.

If I go to mysite.com/cron.php, I get the "Access denied" message.

# Answer
> If I click "Run cron" in the admin menu I'm redirected to another URL.

You have a node using the PHP filter, and calling `drupal_goto()`. That node is then indexed, the PHP code is executed, and you are then redirect. Don't do that ;)

> I can't run cron; see the video capture I created.

You need to specify a cron key when accessing cron.php directly. You can find a link with the key on your Status report page (admin/reports/status).
> 3 votes

# Answer
You cannot invoke cron.php directly in Drupal 7 :) Did you try running admin/config/system/cron by going to configuration \> system \> cron ?
> 0 votes

---
Tags: cron
---


title: Group nodes by terms

text:
# Question
Title: Group nodes by terms
How do you group a list of nodes by the taxonomy term?

e.g.

```
Term 1
--- Node 1
--- Node 3
--- Node 7

Term 2
--- Node 6
--- Node 9
--- Node 12

```

I have tried creating a view with "Node" and "Taxonomy Term" as fields. I then enabled grouping, and grouped by the taxonomy term. Doing this outputs the following:

```
Term 1
--- Node 1
Term 1
--- Node 3
Term 1
--- Node 7
Term 2
--- Node 6
Term 2
--- Node 9
Term 2
--- Node 12

```

There is a Drupal 6 tutorial here that explains how to fix it, but it doesn't work under Drupal 7.

It seems like such a simple task, yet after many days of trying, I can't get it to work! I've found many threads of people asking the question, but no solutions (at lease a solution which doesn't involve installing taxonews).

# Answer
In your view add two fields: \- Node title \- Taxonomy Term

You are right up to here.

Now:

* Set the "Taxonomy Term" field to "Exclude from display"
* Select your views' format as unformatted list; use "Edit settings" for the format
* Set "Grouping Field" as "Taxonomy Term"

For details, view my views' export data in pastebin.
> 12 votes

# Answer
I resolved the problem of duplicated grouping fields :D

So, for people who have the same problem, just disable your module Themer and it's done !

Hope it helps.
> -3 votes

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


# Question
Title: For the purpose of creating content, how do block_view and the page callback defined in the menu hook relate?
I'm slightly confused as to how I should get my content on the page from a custom module. I thought I would normally do it with the block\_view hook, but apparently another way is the page callback function. While I think I understand the former, I'm not quite sure how the latter works, and what I should return from it. Should I use one or the other method? When shoul dI use which? Can I use both?

# Answer
> 1 votes
`hook_block_view()` and `hook_menu()` aren't related at all, they're two completely independent concepts.

`hook_block_view()` is for defining *blocks*, which can be assigned to regions within the page template.

Items defined in `hook_menu()` are *pages*, for which a `page callback` is required to build up the content for that page.

I guess the slight confusion is that in Drupal 7 the page content is automatically assigned to a block in the main system region. Whatever you return from your `page callback` function for a menu item will be assigned to that main system block when you access the defined page.

A block is not accessible through a URL; it is a contextual piece of information that you add to different pages/regions when you need to. Think of the shopping cart in an e-commerce site as a perfect example of a block.

A menu item defines a page that *is* accessible through a URL, and may well contain any number of blocks within it.

---
Tags: hooks, blocks
---


# Question
Title: How to override links in each Views feeds?
I would like to override all links in all views feeds through a hook (potentially) - for example adding an extra query param to each item links. I need a general function. When defining a new feed, the field name is unknown, so I can't rely on the exact name -\> cannot use a specific preprocess hook. I checked all Views hooks here: http://drupalcontrib.org/api/drupal/contributions%21views%21docs%21docs.php/6 but couldn't find a right one. I was playing a lot with different preprocess functions, no luck. One idea is to override a field handler, but I'm not sure how to execute that.

What would you suggest?

Thank you!

# Answer
> 0 votes
I found the url\_alter module: http://drupal.org/project/url\_alter,

Some details from the module's project page:

> URL alter is a utility module that adds two new hooks for other modules to implement: hook\_url\_inbound\_alter() and hook\_url\_outbound\_alter(). These hooks also replace the need for the special, silly custom\_url\_rewrite\_inbound() and custom\_url\_rewrite\_outbound() functions commonly found in settings.php.
>
> It also provides an interface for administrators to enter in their own hook\_url\_alter code without needing to create a custom module.

It has some usable hooks:

```
hook_url_inbound_alter() and hook_url_outbound_alter()

```

---
Tags: 6, views
---


title: Disabling update notifications

text:
# Question
Title: Disabling update notifications
I'm trying to remove the update notifications from the Drupal backend. I tried with Update notifications disable module but it breaks the "module" part of the backend. I can disable the Update manager module but i don't like this solution. Is there any other way to solve this problem?

# Answer
> 0 votes
If you just want to remove them for a less cluttered back end, that perhaps doesn't worry non-technical admin users you could maybe CSS them out?

---
Tags: 7, updating, notifications
---


# Question
Title: Advantages of using drupal mobile technology over mobile middlewares
This is a very serious question that every one asks. I have a drupal website now which is not mobile ready. I will tell the scenario. We gave a demo to client of kurogo, which we modified to show content from drupal website. So 1st question was, whats the benefit of this over creating mobile ready themes with in drupal. So my question is, will there be any extra benefit of using external mobile middle ware like Kurogo, then developing drupal mobile themes.

# Answer
> 2 votes
You can do everything in Drupal. My recommendation is to run an m.site.com domain (either to a different multi-site or with branching logic in settings.php) that not only changes to a mobile theme, but also switches to an alternative anonymous page cache bucket and sets a few variables for later use.

Then, whether you are using panels or not, you can set ctools page\_manager overrides for your homepage, content listings, node views etc. and have these only kick in for the mobile domain. This way you can potentially hit the database less for logged in users by showing simple pages, and you can also switch imagecache/'image styles' to be more appropriate to the device and save on bandwidth.

That way you can get all the output you'd get from Diazo or Kurogo but keep it all in Drupal. Which is you are working in a team of Drupallers, is surely a good thing

Hopefully that little ramble described the approach well enough to be useful ;)

I think the http://drupal.org/project/mobile\_tools module contains ways of doing this if you don't know how to write it yourself.

---
Tags: 7
---


title: I can't use strong tag in wysiwyg

text:
# Question
Title: I can't use strong tag in wysiwyg
I watch Introduction Advanced Theming in Drupal 7 (drupalize.me), and I create custom theme frot that video tutorial. I can't use `<strong>` and `<em>` in CkEditor. I can use only `<b>` and `<l>`, but CkEditor create `<strong>` and `<em>`. That tags has no effect when I save my node.
Why? What is wrong? When I change the theme to Bartic, everything works OK, but in the custom theme from that video tutorial, those two tags are not rendered as I would expect.

# Answer
CSS resets usually take the emphasis off of `<strong>` and `<em>` tags by default.

All you need to do is add a rule like this to your main style sheet (main.css):

```
strong {font-weight: bold;}
em {font-style: italic;}

```

That will re-reset the `<strong>` and `<em>` tags to display as you'd normally expect.
> 5 votes

---
Tags: wysiwyg
---


# Question
Title: How to show "New" if the node author is registered within 4 weeks.
I would like to print "New" if the node author is registered within 4 weeks in a field of "node View" by using custom php with Views Custom Field. I tried the code below but didn't work. Am I missing something?

```
   <?php
      $four_weeks_ago = time() - (28 * 24 * 60 * 60);

      $user_created_time=$user->created;

    if ( $user_created_time >= $four_weeks_ago) {
        $this_user_is_new="new";
        print $this_user_is_new;
      }
    ?>

```

# Answer
What if you edit Vikas code with:

```
$node_author = user_load($node->uid);
$author_created_time = $node_author->created;

```
> 1 votes

# Answer
You can try this :

```
global $user; // contains all information of login user

$four_weeks_ago = time() - (28 * 24 * 60 * 60);

$user_created_time = $user->created; // user registration date

if ( $user_created_time >= $four_weeks_ago) {
    $this_user_is_new="new";
    print $this_user_is_new;
}

```
> 0 votes

---
Tags: 6, users
---


# Question
Title: Drupal 6 Content Types fields not saving
I am using Drupal 6 and I am somewhat new to it.

I've been running into a strange behavior.

I have created a new Content Type that have 4 new fields and when I try to make a new Content using this Content Type everything is saved except for the new fields.

Each times that I save the Content the new fields comes out as empty.

I have been looking on search engines without luck, is it a known behavior, is it a bug or is could it be a mismanipulation?

What should I be checking to debug this situation?

The additional fields in question:

```
Label                     Name                      Type
========================================================
Product Subtitle          field_subtitle            Text
Product Overview          field_overview            Text
Product Features          field_features            Text
Product Specifications    field_n_specifications    Text

```

These were defined using the UI at: /admin/content/node-type/\[content-type-name\]/fields

The fields appear correctly when editing/adding new content as well in the listing of the fields in the content type management section.

# Answer
One final possible oops: goto admin/content/node-type/TYPE/display and make sure the fields are being displayed in that content type.

If all looks well there, then from the comment discussion, this is sounding like your database might have become corrupted, lost some tables, or generally needs to be restored from a backup taken before all of this started to happen. If you go into phpmyadmin (assuming you are using mysql) you can check on the following to confirm:

Basically, CCK uses database tables to define the content types it creates, so, you can look for a table called content\_type\_MYCONTENTTYPE, eg, MYCONTENTTYPE would equal story, page, album, product, etc.

So, if you find that table, it will have as fields/columns the field values of the fields of the content type: nid, vid, and then any custom fields UNIQUE to it in CCK. By UNIQUE I mean that no other content type uses that field. If, though, let's say you have a field\_overview that you use in other content types also, well, that won't be listed here.

Where? Once you start sharing a field between content types, it gets its own table, called content\_field\_FIELDNAME and in there you will find your content values.

So, in your description above, let's assume the content type is product and that you don't share those fields with any other content type. In your database, there should be a table called content\_type\_product and in it you should find fields/columns:

```
vid
nid
field_field_subtitle_value
field_overview_value
field_features_value
field_n_specifications_value

```

You should also see fields for FIELDNAME\_format that tell drupal the text format.

If you DO share any of these fields, let's say you share the field\_overview, look for a table called content\_field\_overview and in it, you'll find columns/fields for value and format.

So, in a nutshell, that's how CCK works with respect to saving fields and so forth. If any of the above isn't there, you have to create it or put it back (and of course, try to figure out how/why it got deleted/corrupted in the first place).

If, though, all of the above is there, and there are values in there for your fields, then something else is going on.

Do the values show up when you edit the node, eg, look at a piece of content with those fields, and if you edit it, do those fields have values, or are they blank? If they have values when you are editing it, then something is causing them to not display.

Did you change or add a text filter that is stripping all your content out?

Did you change your node.tpl.php file and now not printing/displaying these fields for some reason?

Or did you change the display parameters mentioned above at the beginning and they are being hidden or excluded from display?

Anyways, lots to track down but let me know what happened and maybe something else will spring to mind to help track it down to a conclusion.
> 1 votes

---
Tags: entities, nodes
---


title: How do I avoid editing Drupal core?

text:
# Question
Title: How do I avoid editing Drupal core?
I was building an exchange with a partners XML service, and I couldn't get the XML right, but as with all things Drupal, the xmlrpc error and action logging is less than robust.

So I did this in includes/xmlrpc.inc.

```
function xmlrpc_request($method, $args) {
  $xmlrpc_request = new stdClass();
  $xmlrpc_request->method = $method;
  $xmlrpc_request->args = $args;
  $xmlrpc_request->xml = <<<EOD
<?xml version="1.0"?>
<methodCall>
<methodName>{$xmlrpc_request->method}</methodName>
<params>
EOD;
  foreach ($xmlrpc_request->args as $arg) {
    $xmlrpc_request->xml .= '<param><value>';
    $v = xmlrpc_value($arg);
    $xmlrpc_request->xml .= xmlrpc_value_get_xml($v);
    $xmlrpc_request->xml .= "</value></param>\n";
  }
  $xmlrpc_request->xml .= '</params></methodCall>';

  /* This part here */
  watchdog('xmlrpc',$xmlrpc_request->xml);
  /* End ridiculously tiny hack */

  return $xmlrpc_request;
}

```

I got the data I needed and in 10 minutes had the partner interface responding appropriately to my request because (shocking I know) logs are good.

I like the extra logging, and I want to keep it. What is the clean, straightforward, and most importantly, Drupal-approved way of doing that?

# Answer
> 11 votes
Hacking core is strongly discouraged for the uninitiated because it effectively reduces the support community of thousands to a support community of one (or whatever your team size is). Without this best practice, helping those new to Drupal would be nigh impossible. It also hinders modularity and, in some cases, security.

This having been said, hacking core is not always as evil as we like to make it out to be. Without modifying core, we wouldn't have distributions like Pressflow and the like that augment core in interesting ways. It's just vitally important that you know exactly what you're doing, that you're distributing your patches with your distribution (preferably in a way that allows you to apply them again automatically post-upgrade), and that you're keeping detailed documentation of what you've changed and why you've changed it.

Depending on how you have things structured, you could certainly make the above change to `xmlrpc_request()`, create a patch, and then use something like Drush Make to automate applying it (note that Drush Make is moving into the Drush project itself for the 5.x release), while supplying additional documentation in the makefile and elsewhere as to what the change does and why it's necessary/desired.

Another common pattern to enhance core functions is to create a wrapper that adds a tiny bit of functionality to a core function, and call the wrapper in lieu of core's implementation. When feasible, this makes things much more modular. Consider the following:

```
/**
 * Wrapper function for xmlrpc_request() to provide logging.
 */
function mymodule_xmlrpc_request($method, $args) {
  $xrr = xmlrpc_request($method, $args);
  watchdog('xmlrpc', $xrr->xml);
  return $xrr;
}

```

Again, depending on what you're doing this may or may not be feasible, but when it is you've saved yourself a few headaches in trying to make sure that core stays patched and documented. Though in this case, a one-off function like this seems like a perfect candidate for such a wrapper. If your implementation is captured in a module, you could even expand on it to control the log level of your entire solution, disabling this functionality on production sites:

```
/**
 * Wrapper function for xmlrpc_request() to provide logging (if enabled).
 */
function mymodule_xmlrpc_request($method, $args) {
  $xrr = xmlrpc_request($method, $args);
  if (variable_get('mymodule_log_level', 0) > 0) {
    watchdog('xmlrpc', $xrr->xml);
  }
}

```

In short, you want to maximize what you can do with modules (and you can do a lot), but there are legitimate reasons for altering core. It should be done with care, that's all.

# Answer
> 9 votes
If you need to alter ***core*** or ***contrib*** modules you should.

> 1. Create a patch with changes.
> 2. Use a deploy system like drush make that will automatically re-apply patches when you update core or modules.
> 3. Document document document.

---
Tags: 7
---


# Question
Title: How can I create another user login block?
I would like the user login block to be standard on the front page, but a link on all other pages. The best way I can think of doing this is having two blocks and restrict them through the block setting.

Is there another way to do this? I have considered fancy login since that gives another login block, but I was curious if it's possible to clone the core login block. Thanks for reading.

# Answer
> 3 votes
You can't have the option assign a block to different region.But you can use the Multiblock

it will allowing you to create multiple Block Instances of already existing blocks.

If you want customize the login block with your own design, then this link will help you.

# Answer
> 1 votes
You could also just restrict the standard login block to the front page and create a block with a simple link to `user` in it and have that placed everywhere else, eg:

```
return l('Click here to login','user');

```

or

```
<div id="my-non-front-page-login">
 <a href="/user">Click here to login</a>
</div>

```

inserted either from a module's hook\_block() (first way) or from the Block Admin Page's create block (second way)

---
Tags: users
---


# Question
Title: How can I configure the User Protect module to avoid editing/deleting users with "edit users" permissions?
I am working in Drupal 6. I have created a role "admin users" with permissions for edit and delete users but I need that this role "admin users" cannot edit/delete the user admin. I have installed the User Protect module but I cannot to configure it correctly for the role "admin users" can not modify it.

# Answer
I had to do it one day and I did like that. But in my case the permission is `edit user 1`. The code simply remove the user from the list. Feel free to change as you want.

```
<?php
function mymodule_menu_alter(&$items) {
  $items['admin/user/permissions']['access callback'] = 'mymodule_user_access';
}

function mymodule_user_access($string, $account = NULL, $reset = FALSE) {
  if ($string == 'administer permissions' && user_access('edit user 1')) {
    return TRUE;
  } else {
    return FALSE;
  }
}

function mymodule_form_alter(&$form, &$form_state, $form_id) {
  $form['#validate'][] = 'mymodule_user_profile_form_validate';
}

function mymodule_user_profile_form_validate(&$form, &$form_state) {
  $account = $form_state['values']['_account'];
  if(!user_access('edit user 1') && $account->uid == 1) {
    form_set_error('category', t('You does not have right to edit this user.'));
  }
}

function mymodule_perm() {
  return array(
    'edit user 1',
  );
}

function mymodule_theme() {
  return array(
    'mymodule_user_admin_account' => array(
      'arguments' => array('form' => NULL),
    ),
  );
}

function mymodule_theme_registry_alter(&$theme_registry) {
  unset($theme_registry['user_admin_account']['file']);
  $theme_registry['user_admin_account']['function'] = 'theme_mymodule_user_admin_account';
  $theme_registry['user_admin_account']['include files'] = array();
  $theme_registry['user_admin_account']['theme path'] = drupal_get_path('module', 'mymodule');
  $theme_registry['user_admin_account']['theme paths'][] = drupal_get_path('module', 'mymodule');
}

function theme_mymodule_user_admin_account($form) {
  // Overview table:
  $header = array(
    theme('table_select_header_cell'),
    array('data' => t('Username'), 'field' => 'u.name'),
    array('data' => t('Status'), 'field' => 'u.status'),
    t('Roles'),
    array('data' => t('Member for'), 'field' => 'u.created', 'sort' => 'desc'),
    array('data' => t('Last access'), 'field' => 'u.access'),
    t('Operations')
  );

  $output = drupal_render($form['options']);
  if (isset($form['name']) && is_array($form['name'])) {
    foreach (element_children($form['name']) as $key) {
      if(!user_access('edit user 1') && $key == 1) {
        unset($form['accounts'][$key]);
        unset($form['name'][$key]);
        unset($form['status'][$key]);
        unset($form['roles'][$key]);
        unset($form['member_for'][$key]);
        unset($form['last_access'][$key]);
        unset($form['operations'][$key]);
      }

      $rows[] = array(
        drupal_render($form['accounts'][$key]),
        drupal_render($form['name'][$key]),
        drupal_render($form['status'][$key]),
        drupal_render($form['roles'][$key]),
        drupal_render($form['member_for'][$key]),
        drupal_render($form['last_access'][$key]),
        drupal_render($form['operations'][$key]),
      );
    }
  }
  else {
    $rows[] = array(array('data' => t('No users available.'), 'colspan' => '7'));
  }

  $output .= theme('table', $header, $rows);
  if ($form['pager']['#value']) {
    $output .= drupal_render($form['pager']);
  }

  $output .= drupal_render($form);

  return $output;
}

```
> 1 votes

---
Tags: users
---


# Question
Title: How can I ensure that a user account on my local dev server has the same uid as an account on my production server?
I have a local dev server that I use for testing and a production server. I have written several rules (with the rules module) that send private messages (using the private message module) to users.

I want these messages to be sent from a special administrative support user; the problem is that this user has a uid of 7 on my local site and 9 on the production site.

Since I am still early in the development process, it is simple enough for me to reset the databases and start over so that the uids are in sync. However, since this may come up again at a point where it is not convenient to reset, is there a good way to ensure that accounts on different servers have the same UID?

# Answer
**It's not currently possible to export Users into a Feature.**

There's an open issue for adding support to uuid\_features.module.
> 1 votes

# Answer
If I were you and I had a database access I would export the users table from production to my dev site, after taking a backup from my dev users table.
> 0 votes

---
Tags: 7, rules, features
---


# Question
Title: Is it possible to use an image in my themes directory as the default image of an image field?
This question addresses how to add an image using a URL rather than a direct upload using the filefield sources module. However, that module does not allow the "Default image" to be set.

For my image field, I want users to only be able to upload files (just the way Drupal comes by default). However, I want the default image to be stored in my themes directory if possible in order to ease deployment across multiple sites. Is there a way to set the default image to an image on the server rather than having to upload it?

I'm using Drupal 7.

# Answer
> 1 votes
You could make a module whose sole purpose in life is to copy an image into the appropriate place in the file system. Then it would be in code and versionable, independent of what you did with the theme.

---
Tags: entities, media
---


# Question
Title: How can I customize the message after register?
How can I change, or customize, the message shown to the user after registration in Drupal 7?

> Further instructions have been sent to your e-mail address.

I tried the following code, but it didn't work for me.

```
function mymodule_message_alter(&$messages) {
  switch($messages->messages['status'][0]) {
    case 'Further instructions have been sent to your e-mail address.':
      $messages->messages['status'][0] = t('Your reset password instructions have been sent to your e-mail address. Please check your email and follow the instructions</p>');
    break;
  }

  // Disabling / Suppress all messages on a page and only display one Message
  if(arg(0) =='your-custom-page') {
    if($messages->messages['error']) {
      unset($messages->messages['error']);
      $messages->messages['error'][0] = t('This is my custom message to replace 10 system messages :) ');
    }
  }
  return $messages;
}

```

# Answer
> 6 votes
It might be overkill for a single message but the String Overrides module would work.

It includes a UI for quickly adding string replacements for anything that is passed through the `t()` function, which includes the message that you're trying to replace.

---
Tags: users
---


# Question
Title: How do you hook into a path being created via pathauto?
I can't seem to make hook\_pathauto\_alias\_alter() get called in my custom module, in either 1.x or 2.x. I'm not certain, but I'm not clear if this hook is even in pathauto 1.x.

I am trying to hook into a Pathauto alias right before it's saved, so I can make some changes to the path (remove certain words). How do you do this? Is there another method besides a hook in the Pathauto module?

I have a module that let's the user enter in a list of words they want to filter from nodes; I would prefer not to enter it in two places.

# Answer
> 6 votes
The UI has this built in as it happens, if you visit http://mysite.com/admin/build/path/pathauto and look in the "General Settings" fieldset you'll find a textbox containing a list of strings to remove from aliases:

`hook_pathauto_alias_alter` is definitely the right way to do it; it's available in both the 1.x and 2.x branches. Have you run any debug code to see if the hook is actually being called? And did you clear the caches? Hook implementations are cached (in Drupal 7 anyway; I can't remember if they are in Drupal 6 or not).

In case you're still wondering most modules that declare hooks come with a MODULENAME.api.php file which lists those hooks and how to use them. In the case of pathauto the file and hook function declarations are there, but sadly there's no documentation.

---
Tags: 6, hooks, path-aliases
---


# Question
Title: Trying to get IMCE with Filefield Sources working (no Upload button in popup)
I've got a clean install of D6.22, CCK, Filefield, ImageField, Filefield Sources and IMCE. No other modules.

When i go to http://mysite.com/imce it all works perfectly (see screenshot).

But when i try to implement an image field with IMCE as a filefield source, i can click the "browse" link and the IMCE popup comes up, but the only button i get at the top of the popup is "Insert file". No upload, no delete, no resize etc. Here's the screenshot.

I see from the popup's page info that its URL is... http://mysite.com/filefield/imce/page/field\_pics?app=pics|url@edit-field-pics-0-imce-path (the image field's human name and machine\_name are both "pics"). I'm logged in as user-1, and the IMCE user-1 profile is looking good.

Also, there are no javascript errors, and if inspect the popup with Firebug, the upload button is there, but hidden. If I unhide it and click the button, I get the alert "You can not perform this operation". So it seems to be a permissions problem rather than a javascript problem.

I'm sure i've missed something so simple nobody's bothered to mention it in any of the docs. Can someone enlighten me?!

# Answer
> 1 votes
Ah! Like, Filefield Sources no longer lets IMCE do anything except browse your files and select one of them (for security reasons i think). That's what the situation *seems* to be, though i can't find anywhere that says that explicitly.

Luckily there's a patch which reinstates the missing functionality...

http://drupal.org/node/877452#comment-4499144

The maintainer of Filefield Sources links to that patch from the module's project page, so it's a recommended patch.

All functioning now :) Can i have my Sunday back now please?

++Thanks to ufku for providing the patch.

# Answer
> 1 votes
After installing the patch (thank's to chichilatte) you have to check the file browser mode "Full" under field settings -\> file sources -\> imce file browser settings. Otherwise you can not rename, delete or upload a file.

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


# Question
Title: Form redirection to registration for anonymous users while preserving data entered
How is it possible to have CCK form on the front page for instance and once the user clicks on "Save", check if the user is already signed in and if not, redirect to the creation of an account, but by keeping the data entered in the CCK form to avoid them to reenter every field ?

I've checked on the net but nothing seems to do this so far...

Thanks for any help :-)

# Answer
> 2 votes
One option would be to do this in a custom module with hook\_form\_alter(). You could use it to alter the CCK form to add a custom validation/submit handler that redirects anonymous users to the registration page. The inserted form data could be stored in the session (before redirecting) from where you can retrieve it later to fill in the form with default values (using hook\_form\_alter() again). I'm assuming that you do not need to store the data for long periods of time since session is not suitable for that. You should also unset the used session variables after use.

---
Tags: entities, 6
---


# Question
Title: How do I count the number of nodes in a View
I would like to display the number of nodes in a particular view OUTSIDE OF THAT VIEW. For example, on the home page (page--front.tpl.php) I want to insert a simple php echo statement that pulls the number of nodes in "View X", and another php echo statement that pulls the number of nodes from "View Y", etc.

```
function theme_get_node_count($content_type) {
     $query = "SELECT COUNT(*) amount FROM {node} n ".
              "WHERE n.type = :type";
     $result = db_query($query, array(':type' => $content_type))->fetch();
     return $result->amount;
}

```

The previous code does not work because I am not counting a content type. Is there a $view variable I can plugin into this function to achieve the same results?

Thanks

# Answer
> 2 votes
In an executed view object, you can access how many rows or results are returned by looking at:

```
$count=count($view->results);

```

So, if your view returns 2 rows, $count would be 2, if 1, $count would be 1, etc. This can be accessed from a module that executed a view itself or from inside almost any of the views templates as well.

---
Tags: views, nodes
---


title: Refresh button instead pager in views

text:
# Question
Title: Refresh button instead pager in views
Recently I developed a cg related image gallery with drupal, here: http://cgart.ir/en.

top rated images displayed in quicktabs and provided by views. I need a refresh button instead pager. currently I theme next link as refresh button and hide previous link.

how can I add refresh button in views?

# Answer
What you could do is hooking into the pager function and changing its functionality in that page.

I would also recommend using mini pager instead of pager since its much shorter and easier to manipulate. take a look here and here
> 1 votes

---
Tags: 7, views, paging
---


# Question
Title: Does pre-populated body for content types in Drupal 7 affect performance too?
From highest rated answer of this post (Drupal 6 case): Does having too many content types negatively affect site speed and performance?

It is said that:

> Sharing fields among the content types does affect the performance.

But when creating new content type in Drupal 7, the body field will be pre-populated. When many content types created, if not deleted, this field will be shared among all content types.

This is the body field as seen in `admin/reports/fields`:

The question is, does it affect performance? and what is the best to do for performance? Do I need to delete the pre-populated body?

# Answer
tl;dr: No.

What happened in D6 when you shared a field, was that it got moved to it's own table. This became irrelevant with D7, as *all* fields are now stored in separate tables, which was a very controversial decision, due to the performance effects this has.

If you want to increase performance, you can read some more here: How do you improve drupal performance.
> 2 votes

# Answer
The Drupal 7 fields module is a complete rewrite of CCK, it's of course strongly influenced by it but differs in many aspects.

One of those aspects is that Drupal 7 fields *always* behave like shared fields in Drupal 6. Meaning, every field gets it's own table (two, in fact, one for revisions).

So what this is means is that there is no negative effect for performance for shared fields. The opposite actually, shared fields means less database tables and less metadata to keep in memory (The configuration of every single field of the complete installation is kept in a single cache, this behavior is currently being improved here).
> 2 votes

---
Tags: 7, entities, performance
---


# Question
Title: How to return all the tags from a specific vocabulary for the current node
I am trying to return all tags from a vocabulary but the code below keeps giving me error.

```
$vid = 1;
$nid = arg(1);

$getterms = db_query('SELECT t.tid, t.* FROM {taxonomy_term_data} t INNER JOIN {taxonomy_index} r ON r.tid = t.tid WHERE t.vid = :vid AND r.nid = :node_nid ORDER BY weight', array(':vid' => $vid, ':node_nid' => $nid->nid));

```

I am getting 2 errors:

* Notice: Trying to get property of non-object in eval() ...
* Recoverable fatal error: Object of class DatabaseStatementBase could not be converted to string in eval() ...

# Answer
`arg()` returns a string so `$nid` is not an object. You're currently adding your `:node_nid` database condition with a value of `$nid->nid`, when you should just be using `$nid`:

```
$vid = 1;
$nid = arg(1);

// Updated as per comments below
$sql = 'SELECT t.name FROM {taxonomy_term_data} t INNER JOIN {taxonomy_index} r ON r.tid = t.tid WHERE t.vid = :vid AND r.nid = :node_nid ORDER BY weight';
$args = array(':vid' => $vid, ':node_nid' => $nid);

$terms = db_query($sql, $args)->fetchCol();
$comma_separated = implode(', ', $terms);

```

If you want to load the node object related to the current path then you can use `menu_get_object()`; then you can access the nid as part of the object:

```
$node = menu_get_object();
$nid = $node->nid;

```

But I suspect that will be overkill as you only really need the `$nid`, and not the full node object for your query.
> 1 votes

---
Tags: taxonomy-terms
---


title: How does Browscap work?

text:
# Question
Title: How does Browscap work?
How does Browscap work? Every Browser seems to be a crawler. I think that is a bug. How can I fix that?

I'll used this tutorial and get this execption on the mobile url:

> PDOException: SQLSTATE\[HY000\]: General error: 1366 Incorrect integer value: 'false' for column 'is\_crawler' at row 1: UPDATE {browscap\_statistics} SET counter=counter + 1, is\_crawler=:db\_update\_placeholder\_0 WHERE ( (parent = :db\_condition\_placeholder\_0) ); Array ( \[:db\_update\_placeholder\_0\] =\> false \[:db\_condition\_placeholder\_0\] =\> Firefox 10.0 ) in browscap\_exit() (Zeile 134 von x:\somewhere\sites\all\modules\browscap\browscap.module).

---

In replay to paul-m here are my settings:

Current browscap data version: 4911.
Enable automatic updates is enabled.
Enable user agent log is also enabled.

If I refresh the Browscap data I'll get everytime a timeout after 30 seconds. Also If run the cronjob it timesout after 240 seconds. Not sure what I do wrong.

`/admin/reports/browscap/browsers` shows me an empty list, but `/admin/reports/browscap/crawlers` containes all browsers.

# Answer
> 1 votes
I vaguely recall having that same error message, and running update.php solved it. So make sure you've installed the latest version and run update.php.

To get Browscap to log non-crawler user agents, head to `/admin/reports/browscap/browsers` and follow the instructions. They tell you to enable 'Monitor browsers' on the Browscap configuration screen.

To participate in the issue queue of Browscap, or any Drupal project, go to the project page and look on the right side. You'll see a list of maintainers, and under that a section called Issues for Browscap. Search for your issue there. Or just go to the project's issue list.

---
Tags: 7, theming, mobile-tools
---


# Question
Title: $form_state['values'] empty in form _submit hook
I have an issue with a form I built in a custom module using `drupal_get_form()` on a menu callback.

My form callback function is `_foo_form($form, $form_state)` and my submit function `_foo_form_submit($form, $form_state)`.

When I submit the form, `$form_state['values']` contains the value in the form callback, but in the submission handler `$form_state['values']` is empty.

Here is my module code:

```
function configurator_menu() {
  $items = array();
  $items['node/%/configurator/items'] = array(
    'title' => 'Steps & items',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('_configurator_node_edit_item', 'list', 1, ''),
    'access arguments' => array('administrer configurator'),
    'type' => MENU_DEFAULT_LOCAL_TASK,
  );
}

function _configurator_node_edit_item($form_state, $op, $nid, $iid) {
  $form = array();
  $form['nid'] = array(
    '#type' => 'hidden',
    '#value' => $nid
  );
  $form['title'] = array(
    '#title' => 'Step label',
    '#type' => 'textfield',
    '#value' => '',
    '#size' => 30
  );
  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => 'Save',
  );

  return $form;
}

function _configurator_node_edit_item_submit($form, $form_state) {
  dpm($form_state['values']); // devel function to print variable in drupal messages
  // returns an empty array
}

```

Do you have any idea?

# Answer
> 4 votes
Change property '#value' to '#default\_value'.

---
Tags: forms
---


# Question
Title: Display menu items deeper as second level. (show as expanded doesn't actually expand menu items)
I have a menu that needs to be 3 levels deep. The last level never shows up. All menu items are set to 'Show as expanded'. But if go look at the html of the li items that make up the menu, I see `<li class="collapsed" >menuitemname </li>`

This problem occurs in bartik as well as b2nature (the one that the site should go live with)

Keep in mind that I made really really sure that under the menu configuration, I set each and every menu item as 'Show as expanded'.

**Update** The problem even seems a little tougher than I would think. I made a script that changed all of the class values that said 'collapsed' into 'expanded'. After checking the HTML I can see that the script works, but even with all the classes set to 'expanded' still no level 3 to be seen.

Here's the script for what it's worth

```
window.onload = function(){

    var mainMenu = document.getElementById('block-menu-block-1');
    var menuItems = mainMenu.getElementsByTagName("li");

    for (var i=0; i < menuItems.length; i++ ){

        var attributes = menuItems[i].getAttribute('class');
        var arrayAttributes = attributes.split(' ');
        for (var j=0; j < arrayAttributes.length; j++ ){

            if (arrayAttributes[j] == 'collapsed'){
                arrayAttributes[j] = 'expanded';
                }
            }

        var newAttributes = arrayAttributes.join(' ');
            menuItems[i].removeAttribute('class');
            menuItems[i].setAttribute('class', newAttributes);
        }
}

```

**Update**: I can confirm that this problem must be due to a bug.

I reconstructed the same menu on another site(locally this time). When I would put the block of that menu in any region, the expanded menu items just show up because I checked the 'Show as expanded'-checkbox in the configuration after clicking '+ Add link'. It didn't matter if the expanded menu items had actual nodes as path or as path. All worked just fine. Then I also reconstructed the same menu on my problem-site just starting from scratch but the problem persisted.

**Update** The 3rd level also isn't there in HTML. I also installed and configured the Menu Blocks module to see if this would be of any help but it isn't.

# Answer
> 0 votes
So the reason that the HTML was missing for the 3rd level was because of a language problem. English was set to default and enabled while some menu items where in dutch. That's why the those items didn't show anywhere.

# Answer
> 6 votes
This is "by design" of drupal / the themes.

With the help of a module like Menu Block you can create blocks that have the functionality you are searching for and then place the Blocks where the menu was.

---
Tags: 7, routes
---


# Question
Title: How to set a different theme for editing one's account
I read somewhere that editing account information can be done a different theme or in the admin theme but can't for the life of me find it neither on google.

# Answer
> 0 votes
Maybe you should install and check out the administration theme module - http://drupal.org/project/admin\_theme

We have used it to show the admin theme on certain urls, like the user edit page.

Here is a description from the project page:

The Administration theme module allows you to use this theme on more pages like : \- batch processing pages \- devel node load and render pages \- coder code review pages \- pages you define yourself in the provided textarea

Hope that helps

# Answer
> 0 votes
If you go to `admin/settings/admin` you can select your admin theme as well as using it for content editing.

---
Tags: 6, users
---


# Question
Title: Is there some way to arbitrarily set the active trail?
I have a menu as such:

* Home
* Performances
* News
* Learning
* ...

I have a content type called 'Event' and when viewing a node of the event type I want to set the 'Performances' menu item as active. How would I go about doing this?

menu\_set\_active\_trail() doesn't seem to work :s

# Answer
If you're using Drupal 7.9 or later you can use the `menu_tree_set_path()` function, e.g.

```
menu_tree_set_path('main-menu', 'performances');

```
> 10 votes

# Answer
Menu Position should do what you need (Drupal 7), it's fairly broad and contextual in scope. Once installed, go to /admin/structure/menu-position and add a new Menu Position rule. You will see there are all kinds of contexts, then theme away with Firebug and CSS (or you may not even need to depending on how your menus are already set up for active items / trails).
> 4 votes

---
Tags: 7, routes
---


# Question
Title: I18N site: welcome page with links to translated pages, or translatable content type?
I need to create a small web site with a single page that has to be translated into multiple languages. My site is I18N, and Locale + Locale updates enabled.

The page manager allows one to create a landing page and set it as the default page. However, I am not really clear how I could automate the translation of that page. I am considering creating a neutral page with links to translated pages. Something tells me this is not the right way to do it in Drupal.

On the other side, I know I could create a "Welcome" content type, with translation attributes/fields. But then, how do I make sure it would be displayed as the landing page with the correct language? Should I create a landing page with one instance of this content type and translate it?

I am still new to i18n in Drupal.

# Answer
Not sure what you mean by "automate" the translation page but I think you're on the right track for what I think you're trying to accomplish.

1. First make sure you have at least the **Multilingual content** module enabled.
2. You likely want to also go to `admin/config/regional/i18n/strings` and make sure that **Filtered HTML** is translatable
3. Then go to `admin/structure/types/manage/page` and then **Publishing options** and choose **Enabled, with translation** under the **Multilingual support** option.

You should now have a basic page that is translatable. There will be a **Translate** option next to the **Edit** option on the node that should allow you to do the translation. Enabling the **Language switcher** as well as translating menus and paths is also recommended.
> 1 votes

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


title: Upload and insert image in-place

text:
# Question
Title: Upload and insert image in-place
Is there a module that allows images to be uploaded and inserted in place, like in a block or something similar?

# Answer
> 2 votes
I think you're looking for the Insert module.

Here is the description from the Project page on Drupal.org

> Insert is a utility that makes inserting images and links to files into text areas or WYSIWYGs much easier. It adds a simple JavaScript-based button to FileField and ImageField widgets. When used with ImageField and ImageCache, images may be inserted into text areas with a specific ImageCache preset.

# Answer
> 1 votes
you can read all images that uploaded in a folder using custom block

```
  $output = '';
  $directory = 'public://myfolder';
  $files = file_scan_directory($directory, '/.*/');

  foreach ($files as $file) {
    $output .= '
      <div>
        ' . theme('image_style', array('style_name' => 'thumbnail', 'path' => $file->uri)) . '
      </div>';
  }
return output;

```

but If you need only images to be displayed in a block you can use editor like ckeditor All u have to do to make the block description as full html and upload image using ckfinder or from url

# Answer
> 0 votes
Check the IMCE module. IMCE is an image/file uploader and browser that supports personal directories and quota.

# Answer
> 0 votes
How I've done this is to create a content type called splash that has (at a minimum) two fields:

```
 1.  an image field, and,
 2.  a text field to be used as the path.

```

Set up permissions to allow whoever you want on your site to be able to create all the above.

If you don't want to create a module yourself, you can then use Views to create a block display that:

```
 1.  Filters on published nodes of type splash
 2.  Returns only 1 result
 3.  Sorts descending by node publish or modification date or however you want
 4.  uses the text field as an argument (or contextual filter) that
     a.  uses PHP to return a default argument:
         i)  return drupal_get_path_alias($_GET['q']);
 5.  uses the image field to display the image

```

and then have this block displayed wherever you want your splash header displayed.

And provided my brain is engaged that should set you on a path that, when a user creates a node of type splash, they enter an image file to upload and a path that it should be displayed on (foo/bar/bazz, path/to/my/node, etc) on your site.

# Answer
> 0 votes
I had a similar problem for one of my clients: the problem was that it was too difficult for him to click 3 different buttons in order to upload an image. I searched a lot and finally I found the easiest and more straightforward solution in this question: Using ImageField to add an inline image.

It basically describes a way of inserting an inline image just by using a file upload field. You will predetermine where the image will appear and then the client will only have to press a button and select the image in his machine.

If you want to give your client the freedom to move around the image, you will also have to add some complexity to your approach. Which means that you will probably have to go with IMCE. But you can still make his/her life easier by using the Image Resize Filter to make Drupal automatically create the thumbnails when your user is graphically resizing the images. You can see the Image Resize Filter module in action in Lullabot's video or in Mustardseed's video

---
Tags: views, 7, nodes, blocks
---


title: SMTP Vs. elastic_email

text:
# Question
Title: SMTP Vs. elastic_email
From my understanding, smtp just changes the smtp server you use to send your mail, while elastic\_email is a web service. Do I still need smtp if I'll only be using elastic\_email for all emails? Thanks.

# Answer
> 2 votes
First of all, I'm assuming that you are referring to the SMTP Authentication Support and the Elastic Email modules. The answer to your question is rather straightforward: you only have to use one of the 2 modules. So, if you are sending all your emails using the Elastic Email module, you can pretty much disable the SMTP Authentication Support.

The reason is that the 2 modules are actually doing the exact same thing: they give you a way of bypassing the default PHP mail() function. If you have decided that you want to use Elastic Email, you don't need the SMTP Authentication Support module (and I'm not sure how they interact with each other so, it's better if you disable SMTP just to be on the safe side on this).

---
Tags: hooks
---


# Question
Title: Deny/allow access to group-content only for some roles
I have a private group with a "notebook"...most pages of that notebook may be accessed by all members of that group, but some pages shouldn't. I tried to control access with the module "Content access" but that only works with node types that are not part of any group because organic groups seems to grant access to all nodes if the user belongs to that group. Is there a way to deny access (based on roles) to nodes that belong to a group if the user is in the group?

# Answer
> 2 votes
Install the Module Grants module. It will solve the conflict. Actually, it will take the conflict into account, which Drupal does not.

> Module Grants makes modules that deal with content access permissions operate better on unpublished (as well as published) content. It also makes sure that access grants behave in an orderly fashion when such modules are used together.

# Answer
> 1 votes
You can use the hook\_node\_access function for this. You can build an array of all your nodes and check this every time a user (linked with his role) access a node. You can allow, deny or ignore the request.
If you can't figure it out yourself, provide me with some info and I'll make you an example.

---
Tags: 6, organic-groups, users, distributions
---


# Question
Title: Is it possible to select a row with tableselect.js?
Drupal includes tableselect.js in a view I am using that uses views bulk operations. I am wondering if it is possible to use the table select code to select a row by id or some other selector. My goal is for the select all checkbox to get checked if all rows are selected.

Here is the tableselect code:

```
Drupal.behaviors.tableSelect = function (context) {
  $('form table:has(th.select-all):not(.tableSelect-processed)', context).each(Drupal.tableSelect);
};

Drupal.tableSelect = function() {
  // Do not add a "Select all" checkbox if there are no rows with checkboxes in the table
  if ($('td input:checkbox', this).size() == 0) {
    return;
  }

  // Keep track of the table, which checkbox is checked and alias the settings.
  var table = this, checkboxes, lastChecked;
  var strings = { 'selectAll': Drupal.t('Select all rows in this table'), 'selectNone': Drupal.t('Deselect all rows in this table') };
  var updateSelectAll = function(state) {
    $('th.select-all input:checkbox', table).each(function() {
      $(this).attr('title', state ? strings.selectNone : strings.selectAll);
      this.checked = state;
    });
  };

  // Find all <th> with class select-all, and insert the check all checkbox.
  $('th.select-all', table).prepend($('<input type="checkbox" class="form-checkbox" />').attr('title', strings.selectAll)).click(function(event) {
    if ($(event.target).is('input:checkbox')) {
      // Loop through all checkboxes and set their state to the select all checkbox' state.
      checkboxes.each(function() {
        this.checked = event.target.checked;
        // Either add or remove the selected class based on the state of the check all checkbox.
        $(this).parents('tr:first')[ this.checked ? 'addClass' : 'removeClass' ]('selected');
      });
      // Update the title and the state of the check all box.
      updateSelectAll(event.target.checked);
    }
  });

  // For each of the checkboxes within the table.
  checkboxes = $('td input:checkbox', table).click(function(e) {
    // Either add or remove the selected class based on the state of the check all checkbox.
    $(this).parents('tr:first')[ this.checked ? 'addClass' : 'removeClass' ]('selected');

    // If this is a shift click, we need to highlight everything in the range.
    // Also make sure that we are actually checking checkboxes over a range and
    // that a checkbox has been checked or unchecked before.
    if (e.shiftKey && lastChecked && lastChecked != e.target) {
      // We use the checkbox's parent TR to do our range searching.
      Drupal.tableSelectRange($(e.target).parents('tr')[0], $(lastChecked).parents('tr')[0], e.target.checked);
    }

    // If all checkboxes are checked, make sure the select-all one is checked too, otherwise keep unchecked.
    updateSelectAll((checkboxes.length == $(checkboxes).filter(':checked').length));

    // Keep track of the last checked checkbox.
    lastChecked = e.target;
  });
  $(this).addClass('tableSelect-processed');
};

Drupal.tableSelectRange = function(from, to, state) {
  // We determine the looping mode based on the the order of from and to.
  var mode = from.rowIndex > to.rowIndex ? 'previousSibling' : 'nextSibling';

  // Traverse through the sibling nodes.
  for (var i = from[mode]; i; i = i[mode]) {
    // Make sure that we're only dealing with elements.
    if (i.nodeType != 1) {
      continue;
    }

    // Either add or remove the selected class based on the state of the target checkbox.
    $(i)[ state ? 'addClass' : 'removeClass' ]('selected');
    $('input:checkbox', i).each(function() {
      this.checked = state;
    });

    if (to.nodeType) {
      // If we are at the end of the range, stop.
      if (i == to) {
        break;
      }
    }
    // A faster alternative to doing $(i).filter(to).length.
    else if (jQuery.filter(to, [i]).r.length) {
      break;
    }
  }
};

```

# Answer
> 1 votes
The answer is to forget about tableSelect.js and trigger the appropriate eventHandler when setting the checkboxe's attribute to 'checked'.

Here is the code:

```
var checkbox = tr.find('td input:checkbox');
checkbox.attr('checked', 'checked').triggerHandler('click');

```

http://drupal.org/node/1477522

---
Tags: 6, javascript
---


# Question
Title: Autocreating new node based on non-existing node reference
Are there pre-existing modules compatible with drupal 7 that let me autocreate a new node when I enter a value into an autocomplete node reference field that doesn't exist? Sort of like with taxonomy, but with node references instead. The new content is based on what's on the form only there's no need for a separate page to show up to fill in more details. I was wondering if there's something that does this, I'm aware that I could just create a simple module with a hook on node\_insert to do this but I was wondering if I could leverage something that already exists.

# Answer
You can use Node Reference Create module.

It will create the node automatically without having to fill in the node fields.
> 1 votes

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


# Question
Title: How can I prefill taxonomy tags for a new node being created through the node form?
I have created a cck node type and associated a tagging taxonomy vocabulary with it. When users create new content, I would like to be able to prepopulate the node form.

For example, if the node type were 'cars' and one term was 'antique', I want to be able to create new instances of cars with the tag 'antique' already populated in the editing form.

I have gotten as far as creating a path such as `'node/add/auto?tid=3'` ... but how do I then take that tid and use it to prepopulate the vocabulary tags field in the auto\_node\_form?

# Answer
> 2 votes
Have a look at the Prepopulate module.

Read the documentation on how to use it.

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


title: Disable editing of post during update

text:
# Question
Title: Disable editing of post during update
I would like to disable user access to the administration during updates, such as bugfixes and additions of new content-types etc. I'm not completly sure on how to achive this. What would be the best solution, setting the site in maintaince mode is not an option.

# Answer
It sounds like you're running into a common deployment issue with Drupal: the fact that content and configuration reside in the same database. This generally puts a kink somewhere in most deployment strategies, as you start to run into issues whenever you have to merge existing user content (often a moving target) with upstream configuration changes.

Depending on how else you may have things set up, this may or may not involve drastic changes to your workflow, though this is the generally recommended solution for such issues. I'm not sure how much experience you have on these topics, so I'm going to break it down piece-by-piece for the benefit of anyone running into similar issues.

**Dev/Test/Prod Workflow**

Generally speaking, we have at least three servers in an optimal workflow. A "Development" server where our main version control repository lives (if you're not using one already, I highly recommend it!), a "Staging" server where we run our last rounds of acceptance testing and start adding default content, and a live "Production" server where everything is served to the end user.

**Dev/Test/Prod in Drupal**

As mentioned above, the fact that the database contains both content and configuration makes things quite messy. It's difficult to check a database into revision control, it makes configuration much less portable, and most attempts to decouple content and configuration are met with frustration (as with locking out certain privileges while making major updates to the site).

The adage "configuration moves forward, content moves backward" through the dev/stage/prod workflow still holds true as best practice with Drupal. We want to put as much configuration into code as possible, removing it from the database in an effort to decouple the two. This way, we can push features forward through the workflow as normal, and then take content from the live site and pull it back to dev when needed, without getting in the user's way.

**Moving Configuration to Code**

How do we move configuration to code, though? The Features module allows you to export the configuration of most popular modules to code as "feature modules"--in fact, anything that implements CTools Exportables is fair game. You could even add your own hooks to these exported feature modules and bundle them in an installation profile for one-click deployment (they're still just modules!).

In the rare cases where you can't achieve the desired functionality using Features alone and absolutely must hack at the database, you can do so through a custom module or an existing exported feature, using `hook_install()` and `hook_uninstall()`. `hook_update_N()` can be used for incremental updates, but remember to update `hook_install()` to reflect the same changes as well!

**Moving Content**

If required, content from staging can also be pushed to live using a solution like the Deploy module. This way, you can push updates from dev to staging, and then use maintenance mode on staging only when polished functionality is being pushed forward from Dev. You could also use it to push content from your live site back to the Dev server, to ensure that you always have easy access to the latest live content.

That said, now that configuration has been stripped out from the database, it becomes much easier to just move the database around as a content store, rather than a hodge-podge of content and configuration.

**In Closing**

This is a difficult and long-standing problem in Drupal, and doesn't have a quick fix, though I've used the above workflow on several projects with a high degree of success. I'd be happy to clarify any parts of my answer.
> 15 votes

# Answer
Depending on how complex your roles are, you could have a restricted role which all restricted users are moved to temporarily whilst the updates are made, then returned to their regular role once the updates are complete.
> 0 votes

---
Tags: 7, users, maintenance-mode, deployment
---


# Question
Title: On D.O., where to file reports for spam users?
On drupal.org, where does one file reports for a suspected spam account?

My google searches have turned out results about a spam module and such.

# Answer
The only way I know is creating an issue in the webmaster queue. There is a Spam category there.
> 2 votes

---
Tags: community-official-site, advertising
---


# Question
Title: Debugging help- rules are getting fired multiple times (recursively) when they should not be
I'm running Drupal 7 with Rules 2.0. I also tried the latest dev version (March 08) and I'm running into the same problem.

I have two rules that are set to run whenever a user account is updated. Each rule should only be executed once per account update. The "Activate- Lex" rule behaves properly; however, the "Activate-Friends" rule executes twice. Both rules are nearly identical in structure except for the fields that they check.

In the Rules evaluation log, I see "Reacting on event- After updating a user account" and both rules fire once. Then, near the bottom there is an additional entry for "Reacting on event- After updating an existing user account" and under this entry the "Activate- Friends" rule fires again but for "Activate- Lex" there is this message: "Not evaluating reaction rule Activate- Lex to prevent recursion."

How can I prevent "Activate- Friends" from also being fired recursively?

I am including the rules below.

"Activate- Friends" fires twice:

```
{ "rules_activate_friends" : {
    "LABEL" : "Activate- Friends",
    "PLUGIN" : "reaction rule",
    "TAGS" : [ "profile_management" ],
    "REQUIRES" : [ "rules" ],
    "ON" : [ "user_update" ],
    "IF" : [
      { "NOT data_is" : { "data" : [ "account-unchanged:field-acc-friends" ], "value" : 1 } },
      { "data_is" : { "data" : [ "account:field-acc-friends" ], "value" : 1 } }
    ],
    "DO" : [
      { "component_rules_activate_friends_features" : { "acc_to_add_friends" : [ "account" ] } }
    ]
  }
}

```

While "Activate- Lex" fires only once (correctly):

```
{ "rules_activate_lex" : {
    "LABEL" : "Activate- Lex",
    "PLUGIN" : "reaction rule",
    "TAGS" : [ "profile_management" ],
    "REQUIRES" : [ "rules" ],
    "ON" : [ "user_update" ],
    "IF" : [
      { "NOT data_is" : { "data" : [ "account-unchanged:field-acc-lex" ], "value" : 1 } },
      { "data_is" : { "data" : [ "account:field-acc-lex" ], "value" : 1 } }
    ],
    "DO" : [
      { "component_rules_activate_lex_features" : { "acc_to_add_lex" : [ "account" ] } }
    ]
  }
}

```

# Answer
The problem was with the components. It turns out that the "Activate Friends" rule component only had a heartbeat "Log Activity" action, which was the source of the problem.
> 0 votes

---
Tags: 7, rules
---


# Question
Title: Localization vs Translation from a Drupal perspective
Been wondering what is the difference between the meaning of these two words when it comes to Drupal, and it seems they are used interchangeably. Is that a correct understanding?

# Answer
> 2 votes
Localization is about making your site "local". One of the tasks in doing so would be to translate the content, but you also could "translate" the urls, setup menus differently etc. The main part is the translation and the locale module is what handles that.

So in short, it's pretty much the same thing, but localization can cover a few things that translation does not.

# Answer
> 5 votes
In Drupal, the terms "localize" and "translate" have special meaning (beyond the typical Internationalization/Localization meanings).

"translate" - this typically means that you end up with a "translation set" of objects. For example, an English source node with its German & French translated nodes (3 related objects). Or, a French source taxonomy term and its Spanish translated term (2 related objects).

"localize" - this typically means that you only have one "object" but can translate the textual information related to the object via string translation. For example, for a menu item, you have one English menu item but then translate the title of the menu item into Spanish (while both languages have the same link).

I've sorted this all out because I'm writing a book on Drupal 7 multilingual sites for Packt that will be out very soon: http://www.packtpub.com/drupal-7-multilingual-sites/book

---
Tags: i18n-l10n
---


# Question
Title: Programmatically download last module version
Is is possible to download the last version of a module during an hook\_update\_N() of my custom drupal 6 module? I am in a case where the module I created needs the last version of CCK and I would like to programmatically download this version and enable it? Or maybe is it possible to add the plugin version in the .info dependencies array?

# Answer
It's dangerous process what you're looking for.

What if the user has a older CCK version ? What if the user patched is CCK ? What if the latest version of CCK won't works ?

Also, it's not fair to download modules without letting knowing the user what you're doing. From my point of view, the best solution it's to add dependency in the info file and with the hook\_init you can check the version of CCK and display a message to as the user download the latest version of CCK.
> 3 votes

---
Tags: 6, updating
---


title: Display View in Simplenews Email

text:
# Question
Title: Display View in Simplenews Email
I have a view block on my frontpage ('news-block') that displays 3 headings which are links to the 3 latest news articles in my website (content-type = 'news').

How do I display this view block in my Simplenews? Alternative suggestions are welcome. I assume this data will display whatever it is at the time of sending, which is fine.

# Answer
> 4 votes
Depending on what you want, you can either use a module like Insert View that allows to embed views as a token inside the newsletter body (dynamically, you can choose the view per newsletter issue) or you override the newsletter body template and embed the view there using views\_embed\_view() (hardcoded per newsletter category).

---
Tags: views, 6, emails
---


# Question
Title: What are the best practices to manage site mirrors with Drupal?
I have gone through the reading of this Backing up and migrating a site from which i know basically there are two parts to backup - keeping the Drupal folder and the dump of MySql.

I am not really planning to migrate a site, but want to create a development environment separate and then push it to the live site.

Apart from the link above, are there any best practices that are worth doing? What are the problems or pit falls that should i avoid? What tools works best?

Looking at the practical experiences people have been through which is not obvious.

PS: I am planning to host it in a Linux based environment.

# Answer
> 2 votes
It always a big deal with Drupal to have a Staging and Production environment. Because you can't just make a simple mirror.

Because you are going to do Site Building in your Staging area, you can't export the database and import it in production, because of user content generation. The inverse its also a problem, as you have done some Site Building.

Of corse you have some tools like Selinium IDE that helps you to save your configuration and that you can use after in production.

The others solution its to move everything, configuration I mean, into files. You've couples of modules that can helps you. First of all, Features that allow you export configurations as feature and you can enable it easily once on production.

For variable and blocks, you've Strongarm and Boxes. Finally the hook\_update\_N will help you to archive the last goals.

For the code part of your project, I guess nothing is better than versioning, like Subversion or Git (goes for Git as it's use by drupal.org). And for the workflow model I can just advice this one that works pretty well in our organization.

---
Tags: migrations, workflows
---


title: Get vocabulary name from vid function

text:
# Question
Title: Get vocabulary name from vid function
I am trying to extract the vocabulary's name from it's vid. Is there a function that does that or do I have to create it?

# Answer
> 6 votes
You can load the vocabulary object using `taxonomy_vocabulary_load()` and get the name that way:

```
$vid = 1; // Vocabulary ID
$vocab = taxonomy_vocabulary_load($vid);
$vocab_name = $vocab->name;

```

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


title: Style the reset password link

text:
# Question
Title: Style the reset password link
I want to give the reset password link a different class so I can style it. How can I do this in drupal 7? my layout here http://www.lusciousanime.com/

# Answer
> 1 votes
If you mean the link in the right hand login block I'm pretty sure you've already got enough surrounding CSS to target it without adding any more classes, e.g:

```
.block-user #user-login-form a { color: blue; }

```

---
Tags: users
---


# Question
Title: How to define a timestamp field using drupal6 schema
In this way I can create a table with a timestamp field in MySQL:

```
CREATE TABLE foo (
  id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
  created_at TIMESTAMP,
  name varchar(255)
);

```

Which would automatically insert a timestamp value each time a new row is inserted.

For example:

```
INSERT INTO foo (name) VALUES ('bar');
SELECT * FROM foo;

```

Output:

```
+----+---------------------+------+
| id | created_at          | name |
+----+---------------------+------+
|  1 | 2012-03-12 10:47:02 | bar  |
+----+---------------------+------+

```

How can I create a timestamp field like this using the drupal6 schema API?

# Answer
> 5 votes
In short, you cannot do this because the schema API does not support the TIMESTAMP type.

> The MySQL implementation of the Schema API implements the datetime field using MySQL's **DATETIME** type. That type does not support automatic initializiation/update to the current time.
>
> MySQL's type **TIMESTAMP** supports automatic initializiation/update to the current time. Switching from DATETIME to TIMESTAMP is not an option, though:
>
> TIMESTAMP behaves differently in MySQL versions 4.1, 4.1.2, 4.1.3, 4.1.6 The first TIMESTAMP column in a table behaves different than other TIMESTAMP columns in that table.

---
Tags: entities, database
---


# Question
Title: Drupal 7 cache page for anonymous users causes issues when loading different css files based on browser version
If you have "cache page for anonymous users" on and are using server logic(http\_user\_agent) to load different css based on the browser version, that logic will not fire and you will get the css that was cached from the last visitor. This seems as if this will also cause some issues when loading js and css based on browser version and for responsive design...more specifically to browsers that don't understand media queries....pre IE 9 browsers. Does anyone have any solution on a work-around for using anonymous cache and loading the correct css based on server logic?

# Answer
Serving up different content based on request headers isn't the best idea in general, especially if you aren't sending back a `Vary` header.

The best workaround is to use markup rather than server side logic. When you do this, Drupal will cache things properly.

For IE, this means either using HTML conditionals and/or Paul Irish's method and/or JS "cleanup".

Pre-IE9 support for media queries has a few popular solutions, including the the Respond library.

For Drupal, I would recommend using a HTML5-aware base theme like Omega, which wraps all of this up in a nice package.
> 2 votes

---
Tags: caching
---


# Question
Title: How to replace links and embedded image references after migrating of content
I want to import content from a legacy system into Drupal using the migrate module. The URL structure is going to change.

Some of the content has links pointing to the old content and there are also embedded images with soon to be outdated links.

After migrate is done I'll have a mapping from old urls to new urls and should be able to run a custom script. This script would check for all nodes with old urls and replace it with the new urls and then just node\_save() it.

Is this a good approach or is there a better solution?

Btw, I'm also planning on setting up a simple php site under the domain to 302 redirect old urls to the new url.

# Answer
> 1 votes
Drupal has a built-in API that allows to **preserve the data as it has been input** but modify its display. It is called the Input Filter system, and it is used to strip markup, generate links and even preprocess Markdown into HTML (using contrib modules). See http://api.drupal.org/api/drupal/modules%21filter%21filter.api.php/function/hook\_filter\_info/7

This is the *proper* way to do it, since it is not destructive of the actual data.

# Answer
> 1 votes
Writing a script that does a node\_load(), search/replace, and then node\_save() is definitely the best way to go about it, and I would argue that it is also the "proper" way to handle the situation. If you go with this approach, you can refine and/or alter the script each pass to account for differences in the URLs.

In the past, I have

* Use rewrites in .htaccess
* Done search/replace on a database backup file
* Put search/replace in a preprocess\_page

to handle the situation, and all of these are not ideal, mainly because of slight variations in URL structure.

---
Tags: 7, migrations
---


# Question
Title: Given a form, how do I find the fields present in them?
How do I get the list of fields present in a certain form, I know the form id, I just need the names of the fields present in that form ?

# Answer
go to your template "template.php for example" or your module, and use

hook\_form\_alter(&$form, &$form\_state, $form\_id){ var\_dump($form);exit(); }

and you will get very detailed look at your form
> 1 votes

---
Tags: 7, forms
---


# Question
Title: Is there a way to know the type of output inside a template file?
I am making a website for both WAP and smartphone browser, and I am using two themes to display WML and HTML. Now I have a problem to show a `<anchor>` link. The pseudo-code for the code I would use in the template file is the following one:

```
if (HTML_THEME) {
  print '<a href = "history.go(-1)">BACK</a>';
}
else{
  print '<anchor>BACK<prev/></anchor>';
}

```

Could anybody tell me how to implement this?

# Answer
I think you're looking for the `$theme_key` global, which gives you the:

> Name of the active theme.

You can use it like so:

```
global $theme_key;
if ($theme_key == 'mobile_theme') {
  // ...
}
else {
  // ...
}

```
> 1 votes

---
Tags: theming
---


title: I lost my gmap macro builder

text:
# Question
Title: I lost my gmap macro builder
I'm embarrassed but I can't find the gmap macro builder anymore. I looked under

`config->content-authoring->location` and all its tabs
as well as `configuration->web services-> GMap` and all its tabs
and `configuration->web services->GMap location` and everything under that.

I also made sure that GMAp macro builder module is enabled

The following modules are also enabled:

* Gmap 7.x-1.x dev
* Gmap location 7.x-1.x dev
* Gmap macro builder 7.x-1.x dev
* Gmap taxonomy markers 7.x-1.x dev
* Location 7.x - 4x dev
* Location add another 7.x - 4x dev
* Location Search 7.x -4.x ev
* Node locations

# Answer
A peek in the code reveals that the macro builder registers the path map/macro.

```
function gmap_macro_builder_menu() {
  $items['map/macro'] = array(
    'type' => MENU_NORMAL_ITEM,
    'title' => 'Build a GMap macro',
    'access arguments' => array('create gmap macro'),
    'page callback' => 'drupal_get_form',
    'page arguments' => array('gmap_macro_builder_form'),
  );
  return $items;
}

```

It is understandably hard to find when it's not under admin; though, perhaps, gmap registers map for its own set of admin pages.
> 2 votes

---
Tags: 7, google-maps
---


# Question
Title: Context for panel not activating for custom menu item
I'm loading a group node from a custom menu item I've created in a module. The reason I've created a custom menu item is because I wanted to use a different path than the one associated with the node.

I have a panel with a selection rule set to all group nodes. The custom menu item works and loads the group node, however, the panel is not being activated. I think it is something to do with the way I am loading the node from my hook\_menu function which is preventing the context from being activated. The code I'm using is:

```
function mymodule_menu() {

$items['course/course-1/resources'] = array(
    'title' => 'Resources',
    'access callback' => TRUE,
    'page callback' => '_getpage1',
    'page arguments' => array(1),
    'type' => MENU_NORMAL_ITEM,
    'menu_name' => 'menu-course-menu',
    'weight' => '1',
);

return $items;

 }

function _getpage1($arg1) {
    $path = drupal_get_normal_path("course/" . $arg1);
    $node=menu_get_object('node',1,$path);
    return node_page_view($node);
 }

```

Is there anything I need to add to activate the context for the group?

Many thanks,

Ben

ADDTIONAL INFORMATION:

I have two variants set up.

For the first:

Selection rule: Node is an OG group AND path matches "course/\*/resources".

Context: No context is set

Relationship: OG Group from node

For the second:

Selection rule: Node is an OG group.

Context: No context is set

Relationship: OG Group from node

The first variant is supposed to be activated for the same group node when the path "course/course-1/resources" is used, and the second is supposed to be activated when the path is simply "course/course-1". At the moment only the second variant is being activated. When the path "course/course-1/resources" path is used it just shows the Course 1 group node in it's default layout with no panels being used.

# Answer
I managed to solve the problem. I did some research and a post at Url aliases and arguments/ Panels put me on the right track.

The Drupal path module does not match sub-paths but only full URLs, so I downloaded and enabled the Sub-pathauto module and then the panels were being activated correctly. Now I can have different variants activated by different arguments at the end of the URL (ie alternative displays for the same organic group node). I needed this module as I was using aliases. So there was nothing wrong with the panel set up it was just the sub-path was not being added for Drupal.
> 0 votes

# Answer
I like to test a panel answer before I post it, but will be gone for a couple days, so I'll give you my speculation on what may be causing this. I suspect your page panel path is `/course/%course` and so that is the only path that is intercepted. It does not matter that you have a variant for resources because it never gets tested. The basic panel definition has already rejected it. Try changing the basic path to `/course/%course/!other`. The `!other` variable is optional so the panel should intercept 2 and 3 level paths matching the pattern. Your variant should then be triggered.

The variable labels in the path (%course & !other) are used to identify associated contexts listed on the context/relationships tab for defining the variant and the specific label name does not matter. Hope this works. If not, I'll check back in a couple days.
> 1 votes

---
Tags: panels, 7, routes
---


# Question
Title: How can I avoid  the "The file x.jpg is in use and cannot be deleted." warning I get when I try to delete a media file?
On the page admin/content/media I'm trying to remove a file, and I get the following warning:

> The file x.jpg is in use and cannot be deleted.

We've been struggling with this issue for some time now, and it looked like the root of the problem was related to the list of revisions in the node the file was in. Deleting the revisions enabled us to delete the file.

Has anybody experienced this issue? Is there a way to fix it?

It's not a great idea for us to have to remove all previous revisions of a node in order to just delete some duplicated files from the media library.

# Answer
> 2 votes
To be honest this is the behaviour that should be *expected* of the field/revision system.

If you have an image file that is attached to a node revision, Drupal (rightly) makes sure that another process in the system cannot delete it. If this wasn't done you'd end up with incomplete/erroneous node revisions.

The only options you've got (in terms of the UI anyway) are either deleting the revisions (which you already know about), or removing the reference to the file from the revision(s) in question.

If you're feeling brave you could dive straight into these tables and make the changes manually:

* node
* node\_revision
* field\_data\_field\_FIELDNAME
* field\_revision\_field\_FIELDNAME

But I strongly advise you only go down that route if you really, really know what you're doing, and have a good backup system in place :)

---
Tags: media
---


# Question
Title: Entity Reference, references dont display
I have an article content type, and this article can be assigned to a topic content type. I have created a bunch of articles and topics, and this worked before. But for some reason, all of the sudden no more topics show up when editing an article content-type.

I was in the progress of adding a 'featured' story field with entity reference to the topic. This might have confused the database? Anyway, can I roll back without redo-ing everything and get this two sided relationship working?

\** edit \**

It seems that the old references still exist in the database as well, but dont show up as options in the article content-type add/edit forms.

# Answer
> 1 votes
Okay, found it. I had changed the language for my user session on the frontend. Content wasn't yet populated in that langauge, therefore it didn't display.

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