# Question
Title: How can I disable default blocks in Drupal 7 without touching the Blocks Config admin?
I'm trying to disable the search form, navigation, and user login blocks from being enabled by default. My main goal is to not touch the admin at all because I want to version control this.

Is there a way to disable the blocks with some sort of hook? I'm newb when it comes to php and coding for Drupal so please be kind.

# Answer
> 2 votes
`hook_block_info_alter()` can be used to alter the *default* configuration of blocks. From there you can set the `status`, `region`, `visibility` and `pages` settings that match the wanted configuration. But once the blocks configuration has been written to the database, changes made with this hook will have no effect.

Sadly there is no other hook to configure blocks. But you can write the needed information to the database yourself as part of a custom module or profile `hook_install()` or `hook_update_N()` implementation. The `standard_install()` function from the standard module provide example code for that. If this is done from an `hook_update_N` implementation or a module, rows for the blocks may already exists in the database. You can then use a merge query for each block to avoid having to deal with the "*is this an insert or a an update*" question yourself.

---
Tags: blocks
---


# Question
Title: Module available for forcing users to re-enter their password to view/edit certain user account fields?
My users have custom fields for their user account that can contain some sensitive information. To protect against privilege escalation vulnerabilities, I'd like to make these fields only readable and editable after users enters their password.

Is there a module available for this?

# Answer
> 1 votes
Most likely this/these fields appear on a certain page/form so you can use the securepages module to define the node/id or page path to assure that only logged in/authenticated users can access it. If not, then the login page will display. You could also use the loginlogout to return to the calling page upon successful login.

# Answer
> 1 votes
**On the per-Form-level:**

If you just want certain forms to be submitted with a password, you may extend the form with a password field and use hook\_form\_validate

1. add a password field to the form
2. implement hook\_form\_validate: only accept the submit if the password matches the users password.

---
Tags: 7, users, security
---


# Question
Title: How can I run javascript code after an item added or removed from an unlimited value field?
I am trying to add some js functionality to an unlimited value field in Drupal 7, it works on page load, but disappears after adding or removing an item, and I did not find a way to notify my code that the table is reloaded, and it is time to reinitialize those functions on the fields. How can I do this?

# Answer
> 4 votes
Create a Drupal behavior. It will be attached to each field when the page loads as well as to new fields added after any ajax calls (adding or removing).

Here is a basic example that will log a click on the text boxes in the field `field_fieldname`

```
(function ($) {
  // Logclick is an arbitrary unique behavior name
  Drupal.behaviors.logclick = {
    // Context here allows your function to run on ajax calls
    attach: function(context, settings) {
      // Your custom jQuery goes here
      $(".field-name-field-fieldname input.form-text",context).once('logclick',function() {
        $(this).click(function() {
          console.log('text box clicked');
          return false;
        });
      });
    }
  };
})(jQuery);

```

`logclick` can be changed to whatever you want to call your behavior.

---
Tags: 7, entities, ajax
---


# Question
Title: Exporting nodes using Views Bonus Pack strips all formatting
I've exported all of my nodes using Views Bonus Pack Export CSV; it works rather nicely. The only trouble is that it strips all of the formatting on my nodes: no paragraphs, no bold text, nothing. The resulting node is a single block of text.

Is there any way I can work around this?

# Answer
> 1 votes
Yes and no - this restriction is by design in the Views Bonus Pack module because of the difficulties in exporting HTML tags in a CSV format but there is a patch available in this d.o thread.

---
Tags: nodes, migrations, importing-exporting
---


# Question
Title: how to check if javascript is enabled in a module drupal7
I'm building a simple module that shows a jQuery UI dialog. I have some HTML in my code but I only want to show this to users that have javascript enabled.

to give you an example here are the contents of my .module file:

```
function popover_init() {
    drupal_add_library('system', 'ui.dialog');
    drupal_add_js(drupal_get_path('module','popover') . '/popover.js', 'file');
}
?>
<div id="dialog" title="D7 jQuery dialog">
    <p> bla bla bla </p>
</div>

```

How do I check the drupal way that javascript is enabled so I can stop my module from loading unnecessary stuff ?

# Answer
You should be able to do the following that will hide the div from non-JS users:

```
function popover_init() {

  $js = "jQuery(document).ready(function(){";
  $js = "jQuery('#dialog').css('display', 'block');";
  $js = "});";

  drupal_add_library('system', 'ui.dialog');
  drupal_add_js(drupal_get_path('module','popover') . '/popover.js', 'file');
  drupal_add_js($js, 'inline');
}

<div id="dialog" title="D7 jQuery dialog" style="display:none">
    <p> bla bla bla </p>
</div>

```

Basically, your dialog div starts out hidden (with the inline CSS), and is then unhidden with jQuery.

If the user doesn't have JavaScript enabled, then the block will not be made visible!

I'm also assuming that this part:

```
<div id="dialog" title="D7 jQuery dialog">
  <p> bla bla bla </p>
</div>

```

is in a template file, and not just sitting outside a function in your module.
> 1 votes

# Answer
I don't think there is a way. Because your module runs on the server and it cannot interact with the client's browser in any way.

Here's an answer on stackoverflow: Check if JavaScript is enabled with PHP
> 1 votes

# Answer
I was thinking you could do something in javascript that calls a php page on the server that sets a session variable and then use that as a flag, and, sure enough, the code to do that is in the stackoverflow article cited by @karthik...

```
<html>
  <head>
    <script type="text/javascript" src="jquery1.4.4.js"></script>
    <script type="text/javascript">
    $(document).ready(function(){
       $.get("myPage.php");
     });
    </script>
  </head>
</html>

```

and

```
<?php
  // not needed for drupal // session_start();
  $_SESSION['js'] = true;
?>

```

So in drupal, you could add the js in the above header and then set up a menu() item and callback that does the php and then in your module you would check on the session variable being set.

Pretty convoluted and probably more time consuming than just putting a

```
<noscript>
  Our site really works much better with javascript enabled....
</noscript>

```

in your page.tpl though, imho...
> 0 votes

---
Tags: 7, javascript
---


title: Can't get computed field to work

text:
# Question
Title: Can't get computed field to work
This is the code:

```
$number->field_max['und'][0]['value'];

$array = array(
    "7mm Shorty over 7mm Jump" => 10,
    "7mm Shorty over 5mm Jump" => 14,
    "7mm Jump" => 13,
    "5mm Shorty over 5mm Jump" => 16,
    "5mm Shorty over 3mm Jump or 7mm Shorty over 3mm Jump" => 19,
    "5mm Jump" => 19,
    "3mm Shorty over 3mm Jump" => 20,
    "3mm Shorty over 2mm jump" => 24,
    "3mm Jump" => 24,
    "2mm Jump" => 27,
);

foreach ($array as $i) {
    $smallest[$i] = abs($i - $number);
}
asort($smallest);

$closest = key($smallest);

$suit = array_search($closest, $array);

$entity_field[0]['value'] = $suit;

$display_output = $entity_field_item['value'];

```

I want it to display the value closest to the number entered in the field\_max field.

# Answer
> 0 votes
In response to various comments and other answers, here is some code that ought to work:

```
$number = $entity->field_max['und'][0]['value'];

$array = array(
  "7mm Shorty over 7mm Jump" => 10,
  "7mm Shorty over 5mm Jump" => 14,
  "7mm Jump" => 13,
  "5mm Shorty over 5mm Jump" => 16,
  "5mm Shorty over 3mm Jump or 7mm Shorty over 3mm Jump" => 19,
  "5mm Jump" => 19,
  "3mm Shorty over 3mm Jump" => 20,
  "3mm Shorty over 2mm jump" => 24,
  "3mm Jump" => 24,
  "2mm Jump" => 27,
);
$smallest_value = PHP_INT_MAX;
$closest_value = -1;
foreach ($array as $val) {
  if(abs($val - $number) < $smallest_value) {
    $smallest_value = abs($val - $number);
    $closest_value = $val;
  }
}
$entity_field[0]['value'] = $closest_value;

```

After this code is done, `$closest_value` should be set to the value closest to the initial value. You can output this however you like. In the display value field, there should be something like `$display_output = $entity_field_item['value'];`

# Answer
> 0 votes
Just edit the first line, and change it to the following one.

```
$number = $entity->field_max['und'][0]['value'];

```

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


title: Webform not working

text:
# Question
Title: Webform not working
We're trying to get a custom module to work. For some reason, it's giving us an error, regardless of which version of Drupal we're trying to run. Here's the image:

Also, are there any modules which can be a replacement for this one?

# Answer
> 0 votes
You're trying to delete from a table that doesn't exist. That's why it doesn't matter what version of Drupal you're running.

What are you trying to achieve with your custom module? Maybe you could post some example code.

---
Tags: webforms
---


# Question
Title: How can I automatically make term relations between all the terms with same term name?
I have multiple Taxonomy Terms which have the same "Term Name" (with different TID). And I need to make term relations between all the terms with the same term name.

```
For example:

    term-A (tid=1)
    term-A (tid=2)
    term-A (tid=3)
    term-B (tid=4)
    term-B (tid=5)
    term-B (tid=6)

Then I would like to make term relations between term A and also between term B

```

Is there any way I can do this automatically? As I have thousands of this kind of terms it's not realistic to do it manually.

# Answer
> 0 votes
I don't think you really want to just display the related terms. Thats a complicated band-aid to a problem you probably would be better off actually solving.

This type of problematic data is often encountered as part of a migration so it is definitely do-able in a migration like process.

Steps:

1. Decide which tid is going to be authoritative.
2. Find all duplicates of that term.
3. Re-assign all references to that duplicate term to the authoritative term.

Install the Taxonomy dupecheck module so you don't get in this kind of trouble again. Some details from its project page:

> Taxonomy dupecheck module prevents Drupal administrators from adding duplicate taxonomy vocabularies and/or terms. It's helpful when entering large amounts of terms or vocabularies in situations where each value must be unique. This saves time by preventing administrators from having to enforce a unique value policy through later cleanup of duplicate terms.
>
> The module provides a configuration screen allowing administrators to choose which should be unique: taxonomy terms, vocabularies or both. It defaults to case-insensitive comparisons, with an option to change to case-sensitive. Both stored and input terms/vocabularies are trimmed before comparison to handle cases such as 'foo ' and 'foo'. Based on the settings, the user will see an error message when adding a duplicate value.
>
> Caveat: due to the inability of hook\_taxonomy\_term\_presave() to stop the saving process, this only works in the taxonomy term and vocabulary forms. If you want to prevent duplicates through other entry points, this module will not prevent that. If someone knows a way around that I will happily add that in, as that was the original plan.

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


title: Issue with Mac OS and AJAX in Forms

text:
# Question
Title: Issue with Mac OS and AJAX in Forms
I'm working on a custom field type module for a Drupal 7 project and tried to make use of Drupal's AJAX framework in forms. For some reason not even the simplest AJAX requests work on my machine (MacBook with Mac OS Lion) whereas the same code works fine on the Linux machines of my colleagues. When I click the button that's supposed to trigger the request I also get that little blue spinner and the "Please wait..." message but nothing happens after it disappears. In Firebug I can see that it posts to /system/ajax and also sends a "200 OK" header but an empty response.

The code was something similar to this:

```
$element['ajax-btn'] = array(
  '#value' => t('AJAX Test'),
  '#type'  => 'button',
  '#ajax'  => array(
    'callback' => 'test_callback',
    'wrapper'  => 'ajax-test',
    'method'   => 'replace',
  )
);

$element['new-ingredients'] = array(
  '#markup' => '<div id="ajax-test">test</div>',
);

function test_callback($form, $form_state) {
  return array('#markup' => 'response');
}

```

Any ideas?

# Answer
> 2 votes
I have a colleague with a similar problem on his OS Lion machine, but not a problem on our Snow Leopard machines. I stumbled across a solution that worked for me and may work for you. I can't see this portion of your code, but the URL that you are requesting is most likely an absolute path:

**http://yourwebsite.com/someFolder/somePage.html**

but what you want is a relative path:

**someFolder/somePage.html**

AJAX requires that all requests come from the same website. This is a principle of Same Origin Policy and is done for security reasons.

If you are requesting an absolute path to a link on the same website (as you probably are doing), the system should look and see that the request is from the same domain, in which case does not break Same Origin Policy. However, the person in charge of coding Lion's AJAX Same Origin Policy has a problem with their code that does not realize this is the case, causing the browser to think you are trying to run a Cross Domain Script. Hopefully they will realize this soon and fix it in the next update.

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


title: Adding panels to regions

text:
# Question
Title: Adding panels to regions
Is there a way where I can use the theme's default regions for displaying panels instead of a layout ?

or Without using page manager, Can I display panes in the sidebar ?

# Answer
The Mini Panels sub-module of Panels allows you to create panels as blocks, which you could then place into any region on your site. There is an abundance of documentation, tutorials, etc. on using Panels and MiniPanels, but which resources to link you to would depend upon the version of Drupal you are using. There is an existing answer that will probably help you learn more.
> 2 votes

---
Tags: panels, 7
---


# Question
Title: What does the "Vary: Cookie" header actually do for serving pages from Varnish?
According to the documentation in default.settings.php, and I've seen similar descriptions elsewhere, `"Without "Vary:Cookie", authenticated users would also be served the anonymous page from the cache."`

However `$conf['omit_vary_cookie'] = TRUE;` is recommended with Varnish in Drupal 7 and doesn't seem to keep users from being able to switch from anon to authenticated sessions. Is this a header that Varnish doesn't actually care about?

# Answer
> 15 votes
To answer my own question. I've found that with `$conf['omit_vary_cookie'] = TRUE;`, users who visit a page as anonymous users and log in will see the cached version of the page until they click "refresh" on their browsers. It is a subtle difference that I didn't notice at first as admininistrator user.

---
Tags: 7, proxies
---


# Question
Title: Can I setup a backup migrate schedule from settings.php
I am using Pantheon to host a development, staging and production drupal 7 site. I have backup migrate module setup to perform period backups. When I migrate the production site's content to the staging site for testing of new features, the backup migrate settings come with, and all of sudden I now have both production and staging servers backing up to a remote server. I don't mind having to delete the schedules every time I perform the migration, however I'd hate to write this step into the SOP for other developers as they come on the project. So is there a way to setup a backup migrate schedule in settings php? My only thought is to add some config variables in settings.php, and then create a custom module that builds a backup migrate schedule based on these config variables. I feel like there could be a more elegant solution than this. Any thoughts?

Thanks

# Answer
> 1 votes
According to this thread (the first part is about the Environment Indicator module but the last part is about Backup and Migrate), Pantheon forbids the use of the Backup and Migrate module on their platform. While it is possible to make Backup and Migrate settings exportable, including for use in settings.php, it's probably best not to violate your web host's policies.

That said, Pantheon should really start writing their rules down clearly somewhere.

---
Tags: 7, backups, configuration, migrations
---


# Question
Title: Image link does not href to proper page in multilingual site
I am honing my Drupal skills by developing a small website: www.find-word.com. It is multilingual with English and French enabled.

On the top right of the screen, I have two flags. The French flag is a link to the French page, but when I click on it, it displays the English page.

I checked with FireBug, and the `href` is correct:

When I type the full French URL in my browser, it is converted into the English one.

I have no idea what's happening. Does anyone know what is causing this? Does anyone have ideas, suggestions? Thanks.

# Answer
Your multilingual detection settings may be configured incorrectly.

On /admin/config/regional/language/configure, make sure `URL` is at the top of the list and enabled.
> 1 votes

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


# Question
Title: How to remove a "new" indicator when clicking on a link?
I'm showing a list of content in a view and there is a red "new" indicator (field content: has new content) next to the title link. The problems is that when you click a link to read the content and then click back the "new" indicator is still shown.

I don't want to reload the list page every time I click the back button. I'm thinking about using some javascript/css to remove the "new" indicator when you click on the link. Is there a "Drupal" way of doing this?

Screenshot:

# Answer
The theme function used to add that marker is theme\_mark(). You can override that theme function to avoid it adds the "new" marker. Supposing that you override `theme_mark()` with `mymodule_theme_mark()`, you could use the following code:

```
function mymodule_theme_mark($variables) {
  global $user;

  if (!empty($user->uid) && $variables['type'] == MARK_NEW) {
    $variables['type'] = MARK_READ;
  }

  return theme_mark($variables);
}

```

The theme function is used, for example, in node\_admin\_nodes(), and in theme\_node\_recent\_content(); the latter function calls the theme function using the following code.

```
$output .= theme('mark', array('type' => node_mark($node->nid, $node->changed)));
$output .= '</div><div class="node-author">';
$output .= theme('username', array('account' => user_load($node->uid)));

```

Even better, since preprocess functions are called also for theme function not using a template file, you can use the following code.

```
function mymodule_preprocess_theme_mark(&$variables) {
  global $user;

  if (!empty($user->uid) && $variables['type'] == MARK_NEW) {
    $variables['type'] = MARK_READ;
  }
}

```

This code is preferable because:

* What you really need to do is changing the value of a variable passed to the theme function, not altering the output of the theme function, and the preprocess function is perfect for this case
* The code works also when another module override the theme function, while the code I shown earlier makes the assumption no other module overrode the theme function
> 2 votes

# Answer
This is the 'tracker' module -- you could just disable it.

http://drupal.org/documentation/modules/tracker

The Drupal way of handling this would be isolating the specific class that is being used to generate the new link and either not displaying it using settings available with that particular view or module or adding a 'display: none' to it in your CSS theme. Have you tried using firebug to isolate the class name?
> 0 votes

---
Tags: 7, javascript, theming
---


# Question
Title: inheriting fields from a base content type
I need to create 10 content types which, apart from their specific fields, will have 4 common fields (e.g `name`, `surname`, `email`, `age`).

Since I'm using `Features` I could create the first and copy paste the definitions to the other 9 content types. The problem though is that if the specifications ever change and I need to add or change any of those common fields I'll still need to do repetitive work.

How should I solve this? Is there a module which allows the construction of a "base content type" from which other content types can inherit fields? Or should I just reuse fields?

The following modules don't seem to be active for D7:

# Answer
**Short answer:** I would simple go with sharing these four fields across the content types that you have. This is boring and repetitive work, but I'm not aware of a well-established way to do it otherwise, so this is the safest bet in my opinion. This gained a bad reputation in D6 as it caused performance problems, but in D7 there is no difference.

**Longer answer:** I did try copy/pasting of features code at one point, it works, but is quite messy and carries a large risk of "getting it wrong" as it's not documented nor entirely obvious what code needs to be updated.

As Joe Beuckman suggests, creating a custom entity is one way of solving this as well. If you add your shared data columns as entity "properties" instead of fields, they will be shared across all bundles of that entity type. A core example of this is the "title" property on nodes. A lot of modules today work in a entity agnostic fashion, but it's important however to note that the entity API was far from finished in D7. There is no general way for example to handle "entity access" which may or may not be a problem.

Also, on the last approach, you may also want to take a look at the Entity Construction Kit (ECK) module. I haven't used it myself yet, but I believe it could be helpful in creating new entities.
> 9 votes

# Answer
A non-ideal option, and not truly a base content type, is to use the Field Collection module.

You can create one or more field collections for your common fields, and then attach the collection(s) to your content types.

An upside of this is that you can have a set of collections that don't all have to be added to each content type, but still have common groups.

The biggest downside with them is only the collection itself appears on **Manage Display** form for the content type, so you have less UI control over how/where fields get rendered. You have to manipulate things with a template\_preprocess\_node or hook\_node\_view, which can get messy.
> 3 votes

# Answer
What you are looking for is exactly Entities in Drupal 7. You can create an entity with your common fields, then create fieldable bundles for each of your subtypes.
> -1 votes

---
Tags: 7
---


# Question
Title: How do you set the #options paramater for checkboxes and radio buttons?
I'm attempting to create a a form using the Form API and I'm unable to get checkboxes and radio buttons working properly. Although they show up in the form, only the first option of each one is displayed, that option is displayed with the title of the form:

I also have a select box on the page which is displaying fine, and I'm passing through the values to the select the same way I'm passing it through to the radio/checkboxes, with an array.

How do you pass values through to the #options parameter for checkboxes and radios, or do I simply having a careless error somewhere in my code (featured below)?

**Code for the radio buttons and checkboxes:**

```
 $facts = array(
        'Ponycon' => t('Attended Ponycon'),
        'PurhcaseMerch' => t('Purhcased My Little Pony: Friendship is Magic merchandise (dolls, cards, shirts, et cetera)'),
        'PurchaseShow' => t('Purhcased Episodes'),
        'Meetups' => t('Attended Brony meet-ups'),
        'Fanclubs' => t('Part of a MY Little Pony: Friendship is Magic fanclub (Facebook, local, et cetera)'),
    );

$form['fan_activities'] = array(
    '#type' => 'checkbox',
    '#title' => t('Which of the following have you done?'),
    '#options' => $facts,
    '#description' => t('Brony activities'),
);

$fdisc = array(
    'friend' => t('A friend told me about it'),
    'ads' => t('Advertisments (commercials, billboards, et certera)'),
    'Internet' => t('The internet, but not through an ad (forum, website article, et cetera)'),
    'Other' => t('Other'),
);

$form['discoverry'] = array(
    '#type' => 'radio',
    '#title' => t('How did you first hear about My Little Pony: Friendship is Magic?'),
    '#options' => $fdisc,
    '#description' => t('How you discovered the show'),
);

```

**Code for the working select box:**

```
        $fchoices = array(
        'RainbowDash' => t('Rainbow Dash'),
        'TwilightSparkle' => t('Twilight Sparkle'),
        'Rarity' => t('Rarity'),
        'PinkiePie' => t('Pinkie Pie'),
        'Fluttershy' => t('Fluttershy'),
        'Applejack' => t('Applejack'),
    );

    $form['favpony_area']['favpony'] = array(
        '#type' => 'select',
        '#title' => t('Who is your favourite Pony from the mane six?'),
        '#options' => $fchoices,
        '#default_value' => variable_get('favpony', 'RainbowDash'),
        '#description' => t('Your favourite Pony frmo the mane six'),
    );

```

# Answer
The only thing I could suggest would be to try using '#type' =\> 'radios' and '#type' =\> 'checkboxes' instead of radio and checkbox. I believe radio and checkbox without the s on the end only show one option as more of an on off option.

Try having a look at Forms API for more explanation
> 2 votes

---
Tags: 6, forms
---


# Question
Title: Override title with field label instead of key inside a views contextual filter
I have a soccer team Drupal 7 site where I keep track of the players using a user role. I have a view of the players which grids their profile pics and I'm very happy with it. It's URL is /players

Now I want to divide the players into separate groups. My first stab at this was to add a user\_program field onto the User content type. I added this field of type List(text), and gave it keys/values like: youth\_competitive\_program|Youth Competitive Program primary\_competitive\_programe|Primary Competitive Program

I then added a Contextual Filter so that I have /players/youth\_competitive\_program and such. Works very well. Except: when I tell those views to override the title using %1 I get the key instead of the value. What I really want is my human readable value up there, not the key.

# Answer
> 9 votes
edit your `Contextual Filter` check `Specify validation criteria` in `Validator` check `PHP code` and enter following:

```
if ($argument == 'youth_competitive_program') {
  $handler->options['title'] = 'Youth Competitive Program';
  return true;
} else if ($argument == 'primary_competitive_programe') {
  $handler->options['title'] = 'Primary Competitive Program';
  return true;
}
return false;

```

there is another similar way:

```
if (!empty($argument)) {
  $handler->options['title'] = t($argument);
  return true;
}

return false;

```

and translate them, so if you add more option to your `user_program` fields, this code will work better.

but there is another option yet:

```
$field = field_info_field('field_user_program');
if (array_key_exists($argument, $field['settings']['allowed_values'])) {
  $handler->options['title'] = $field['settings']['allowed_values'][$argument];
  return true;
}
return false;

```

I will select the last way

# Answer
> 3 votes
Why don't you use Human readable values for both the key and value of the list? Views should be able to accept an argument with hyphens and substitute spaces in the title. You may have to modify the template to get title cases in your title using something like php's `ucwords()`.

---
Tags: 7, views
---


# Question
Title: Dynamic Persistent Menu problem / module alternatives
I'm using Dynamic Persistent Menu (DPM) but I can't make it work. I have a Main Menu, most of the items have children, and since I don't want those parents to be links I'm using Special Menu Items module (I mention this in case there could be a conflict).

I installed DPM; then go to config \> User interface \> DPM, add new and select Main Menu as the Menu Root and save. I haven't found any steps to follow from there, so I figured that was it, but the children items do not show up. I tried enabling the DPM block but then I get a blank site.

Anyone who has used this module, could you guide me through it? I need the exact functionality this module provides, and from what I've seen neither Superfish nor Nice Menus modules can do this.

Thank you for any help :)

# Answer
Yes, as you mention, their is a conflict between the Dynamic Persistent Menu and Special Menu Items modules.

Dynamic Persistent Menu adds a CSS class (`.dynamic-persistent-menu-menu-item`) to all `<li`\> elements of a menu that is overridden by Special Menu Items.

This bug comes from the special\_menu\_items.module file, line 64. You can remove the following code:

```
$element['#attributes']['class'][] = 'nolink';
$element['#attributes']['class'][] = 'separator';

```

EDIT: The main bugs come from Dynamic Persistent Menu. As you know, the `class` attribute passed to `theme_menu_link()` should be an array, but in Dynamic Persistent Menu a string is passed.

So your WSOD (blank page) comes from `theme_dynamic_persistent_menu_menu_item()` in Dynamic Persistent Menu, where a string is passed instead of array.

When Special Menu Items tries to override it, a fatal error is presented.
> 2 votes

---
Tags: 7, routes
---


# Question
Title: How to choose language for date field in views rss feed?
I am maintaining a bilingual Drupal 6 site with German being default language and English as secondary. The site offers an RSS feed of German articles. This RSS feed is generated with **Views** and **Views RSS**. One of the displayed fields in the feed is the creation date which is in custom format "D, d M Y H:i:s O" for rss clients. The date is always shown in German, i.e. "Mi, 08 Mär 2012 13:44:27 +0200" but I'd like to have this field using English standard, i.e. "Wed, 08 Mar 2012 13:44:27 +0200".

Any idea how I could achieve that?

The feed url is sth. like domain.com/feed (German). If I use the English url domain.com/en/feed, all the date fields are in English format but then the content urls also link to the English version (e.g. domain.com/en/node/123 instead of domain.com/clean-german-url).

Thanks in advance, Paul

# Answer
I found a solution.

First, I installed an additional module (Views PHP). This module provides a PHP field to be used in Views. This field has access to the retrieved data from other fields. Its value I set to

```
<?php
  print date('D, d M Y H:i:s O',$data->pubDate);
?>

```

and in Views RSS items fields I set the pubDate value to this Custom PHP field instead of the Date field (Node creation). Since PHP are not translated by default, the value displayed in the feed is in English while the URLs still have the German format.
> 0 votes

---
Tags: views, 6, feeds
---


# Question
Title: Form API + Module: Nested default value variable_get doesnt behave the same as unnested variable_get
Heres the example code:

```
function mymodule_form($form, &$form_state){
    $form['nest'] = array(
        '#type' => 'fieldset',
        '#title' => t('Nested settings'),
        '#tree' => TRUE,
    );

    $form['nest']['nested_example_item'] = array(
        '#type' => 'textfield',
        '#title' => t('Nested Example Item'),
        '#default_value' => variable_get('nested_example_item', 'example value 1'),
        '#size' => 60,
        '#maxlength' => 128,
        '#description' => t('Nested Example Item'),
    );

    $form['unnested_example_item'] = array(
        '#type' => 'textfield',
        '#title' => t('Unnested Example Item'),
        '#default_value' => variable_get('unnested_example_item', 'example value 2'),
        '#size' => 60,
        '#maxlength' => 128,
        '#description' => t('Unnested Example Item'),
    );

    return system_settings_form($form);    }

```

Now what happens when i change both values and submit the form is the following:

* The unnested field behaves like expected - it reflects the changes.
* The nested field item, does not show this behaviour, does not reflect the changes

I am confused, should I treat the nested `variable_get` differently?

# Answer
I'm pretty sure `system_settings_form()` only looks for variables defined at the root of the `$form_state['values']` array.

Since you have `'#tree' => TRUE` on your fieldset element this will not be the case. If you remove the `'#tree' => TRUE'` line, the value of your nested element will be saved in a variable called `'unnested_example_item'` as you expect.
> 2 votes

---
Tags: 7, forms, configuration
---


title: Update a block from another block

text:
# Question
Title: Update a block from another block
I want to write a page that works like this: http://www.albemarlegallery.com/artists.php

i.e. when I hover over a link from one block, an image in another block updates

How can I do that?

Thanks

# Answer
> 1 votes
You can use javascript and ajax to update your image just when hover your link replace src of image It is javascript only it is not drupal all your html in the same page so it is easy to change any block when hover over another block

---
Tags: blocks, ajax
---


# Question
Title: Override Field.tpl.php for a specific node/add form
**Basic Question**

In Drupal 7, you can override all the fields of a specific content type by changing the `field.tpl.php` file name to `field--YOUR_CONTENT_TYPE.tpl.php`

How can you override the fields that appear on the "node add form" for a content type?

---

**More Info**

I am using Drupal Commerce Bulk Product Creation and with this module you create your nodes at yoursite.com/admin/commerce/products/add-bulk/PRODUCT\_TYPE.

I want to over-ride the field.tpl.php file for this name, but I am not sure how to do it.

I know you can override the node.tpl.php for this "node add form" by using the following in your template.php file:

```
function YOURTHEME_theme($existing, $type, $theme, $path) {
    return array(
        'commerce_bpc_create_bulk_form' => array(
            'arguments' => array('form' => NULL),
            'template' => 'templates/add/node--add--bpc',
            'render element' => 'form',
            ),
    );
}

```

Is there a similar code that can be used to override the field.tpl.php file for this node add form?

# Answer
> 2 votes
Implement hook\_form\_alter() or one of its relatives by setting the #theme key of the form elements.

---
Tags: theming, forms, commerce
---


title: Pathauto url of term for node?

text:
# Question
Title: Pathauto url of term for node?
With Pathauto, is it possible to use the url of a node's term as a token?

In case it makes a difference im using the Taxonomy Menu module aswell. Thanks

UPDATE - The taxonomy is hierarchical. So if I have:

Food/Pizza/Margareta

Then if a node is tagged with 'Margareta' I need the path to be:

Food/Pizza/Margareta/node

# Answer
> 3 votes
Taxonomy terms are attached to nodes using term reference fields in Drupal 7. As such, you have access to the term reference field just like any other in the list of replacement tokens.

Look for fields related to the node with a description of "Term reference field", e.g.

EDIT:

To address your edit, I know it looks ridiculous but something like this will probably work (using `field_school` as an example):

```
[node:field-school:vocabulary]/[node:field-school:parent:parent:name]/[node:field-school:parent:name]/[node:field-school:name]

```

Here's another screenshot showing the extra data available for term reference fields in pathauto:

---
Tags: 7, taxonomy-terms, path-aliases
---


title: Query String and hook_page_alter()

text:
# Question
Title: Query String and hook_page_alter()
Is it possible to read the query string and it's values from the &$page param in the hook\_page\_alter function?

If not, is it possible at all?

# Answer
I'm not sure why you'd need to get it from the `$page` variable, you can get the query string from the `$_SERVER` superglobal at any point in the page execution, and convert it into an array with PHP's `parse_str()`:

```
function MYMODULE_page_alter(&$page) {
  // Convert the query string to an associative array named $qs
  parse_str($_SERVER['QUERY_STRING'], $qs);

  // For the string name=jeff&foo=bar:
  //
  // $qs['name'] = 'jeff';
  // $qs['foo'] = 'bar';
}

```
> 1 votes

---
Tags: hooks
---


# Question
Title: drupal_render in hook_form_alter prevents javascript from being included in the header
I'm calling `drupal_render` to render a textarea element in another element's `#prefix` field in `hook_form_customtype_node_form_alter()`. When I load the form, most of the script tags in the header do not get printed. If I comment out the line with `drupal_render` they print out and the accordions and sliders load on the page.

Why would calling `drupal_render` prevent some of the javascript files from being included in the page header?

**UPDATE**

Here's my code:

```
$deltas = preg_grep('/^[0-9]*$/',     array_keys($form['field_recommendation_reference'][LANGUAGE_NONE]));
foreach ($deltas as $delta) {
  if ($form['field_recommendation_reference'][LANGUAGE_NONE][$delta]['field_key']['#default_value']['finding_wrapper'] == $wrapper_field_name) {
    $wrapper = $form[$wrapper_field_name];
    $wrapper['#printed'] = FALSE;
    $wrapper['#value'] = 'test';
    //$form[$field]['#suffix'] = drupal_render($wrapper);
    dpm(drupal_render($wrapper));
  }
}

```

When I output the element with dpm, the form loads all of the javascript. Also, when I include the markup without using drupal\_render, the page loads correctly.

If I included the rendered markup manually the form doesn't load all of the javascript. Could it be a conflict with id's being used already? I have the same element stored in the $form array but with #printed set to TRUE.

**Found the Issue**

if I set #autocomplete\_path = '', the form element's markup does not disrupt the rest of the page. Is it possible to get autocomplete to work with drupal render? I saw some comments related to this on the drupal\_render api documentation

# Answer
> 0 votes
Setting the #id to `$wrapper['#id'] = drupal_html_id('edit-' . str_replace('_', '-', $wrapper_field_name));` resolved the issue. `theme_textarea` was unable to get a value for `$element['#id']`.

**edit**

I still had trouble getting the #ajax elements to be processed even after adding a call to ajax\_pre\_render\_element.

I restructured my alter hook so that it prints the textarea inside the form element that I'm trying to append to. that way it prints both fields one after the other. This way, I'm not touching drupal\_render and everything works.

---
Tags: 7, forms, hooks
---


# Question
Title: Drupal 7: Permissions when Apache is running as user account
My current host has it set up so that Apache runs as the same account that I use to manipulate files on the file system and, subsequently, the same user that I used to install Drupal 7.

I'm trying to pass the checks in the Security Review module, but it keeps complaining that (pretty much all) files and directories are accessible. I've looked at the handbook page and tried applying the script, but to no success.

Can anyone suggest the proper permissions for my files and directories?

# Answer
> 1 votes
If you're on a shared host this is to be expected, a lot of them operate like that.

Most use suEXEC as the Apache PHP handler which is what makes the web user have full read/write rights over the whole document root. Unless you have access to change the Apache PHP handler (or at least its settings) I doubt you'll be able to change this yourself.

Your hosting provider might do it for you if you get in touch with them, but going on past experience they're normally reluctant to change this sort of thing (in the case of a shared server they might not even be able to do it on a site-by-site basis).

---
Tags: 7, users
---


# Question
Title: trying to add a template file to my module using hook_theme_registry_alter
Here's my .module code:

```
/**
 * Implements hook_theme_registery_alter()
 */
function popover_theme_registery_alter(&$theme_registery) {
    $theme_registery['popover'] = array(
        'template' => drupal_get_path('module','popover'). '/popover.tpl.php',
        'type' => 'module',
    );
}

```

I'm having some plain html elements in the tpl.php file so that might be not good? or do I have to call this hook somewhere? what's wrong?

# Answer
> 3 votes
I'd imagine you should be using `hook_theme()` instead of `hook_registry_alter()` to define your theme function:

```
function MYMODULE_theme() {
  return array(
    'popover' => array(
      'template' => 'popover',
      'variables' => array('var1' => array(), 'var2' => '')
    )
  );
}

```

Then you can call it from anywhere (including a page callback, which I think is where you're trying to return this from given your comment above):

```
$output = theme('popover', array('var1' => $var1, 'var2' => $var2));

```

In the `popover.tpl.php` file in your module's root folder you'll have access to the variables `$var1` and `$var2`, which will be the vars you defined/passed into the theme function.

Then you can build up your HTML as you need.

---
Tags: 7, hooks, theming
---


title: What exactly is watchdog?

text:
# Question
Title: What exactly is watchdog?
I am aware of the watchdog table in the Drupal database, but I am not sure how to use it effectively. Is it simply a message function that adds to the table like a stack in the database for debugging? I have found old references to modules and odds and ends in content, but have not located a broad discussion of different ways it can be used effectively. Also, how do I get the reports?

# Answer
http://api.drupal.org/api/drupal/includes%21bootstrap.inc/function/watchdog/6 talks about the `watchdog()` call, and you access the reports it generates from `admin/reports/dblog` provided that you've turned on the optional Database Logging core module (dblog).
> 6 votes

---
Tags: log-messages
---


title: field theme that have add more option

text:
# Question
Title: field theme that have add more option
I have an Image field that I can add more than one field but I want the user when upload an Image the image appear below the input not above it and sort them desc so the input form will be above the table of images not below them

# Answer
> 1 votes
What you are wanting to do is re-theme cck's `theme_content_multiple_values()` call that creates the html table with the input on top instead of the bottom. Quick and dirty in drupal 6 at least, I went into content.module and pulled out that function as well as the helper function that does the sort, copied them into my theme's template.php and named them appropriately with this being the result:

```
function YOURTHEME_content_multiple_values($element) {
  $field_name = $element['#field_name'];
  $field = content_fields($field_name);
  $output = '';

  if ($field['multiple'] >= 1) {
    $table_id = $element['#field_name'] .'_values';
    $order_class = $element['#field_name'] .'-delta-order';
    $required = !empty($element['#required']) ? '<span class="form-required" title="'. t('This field is required.') .'">*</span>' : '';

    $header = array(
      array(
        'data' => t('!title: !required', array('!title' => $element['#title'], '!required' => $required)),
        'colspan' => 2
      ),
      t('Order'),
    );
    $rows = array();

    // Sort items according to '_weight' (needed when the form comes back after
    // preview or failed validation)
    $items = array();
    foreach (element_children($element) as $key) {
      if ($key !== $element['#field_name'] .'_add_more') {
        $items[] = &$element[$key];
      }
    }
    usort($items, 'YOURTHEME_content_sort_items_value_helper'); // MOD 1

    // Add the items as table rows.
    foreach ($items as $key => $item) {
      $item['_weight']['#attributes']['class'] = $order_class;
      $delta_element = drupal_render($item['_weight']);
      $cells = array(
        array('data' => '', 'class' => 'content-multiple-drag'),
        drupal_render($item),
        array('data' => $delta_element, 'class' => 'delta-order'),
      );
      $rows[] = array(
        'data' => $cells,
        'class' => 'draggable',
      );
    }

    $output .= drupal_render($element[$element['#field_name'] .'_add_more']); // MOD 2
    $output .= theme('table', $header, $rows, array('id' => $table_id, 'class' => 'content-multiple-table'));
    $output .= $element['#description'] ? '<div class="description">'. $element['#description'] .'</div>' : '';

    drupal_add_tabledrag($table_id, 'order', 'sibling', $order_class);
  }
  else {
    foreach (element_children($element) as $key) {
      $output .= drupal_render($element[$key]);
    }
  }

  return $output;
}

function YOURTHEME_content_sort_items_value_helper($a, $b) {
  $a_weight = (is_array($a) && isset($a['_weight']['#value'])) ? $a['_weight']['#value'] : 0;
  $b_weight = (is_array($b) && isset($b['_weight']['#value'])) ? $b['_weight']['#value'] : 0;
  if ($a_weight == $b_weight) {
    return 0;
  }
  return ($a_weight > $b_weight) ? -1 : 1; // MOD 3
}

```

There are only three modifications to the code:

MOD 1 : changed the second argument to point to "my" sort function instead of CCK's

MOD 2: moved the add-more button to display before the table instead of after it

MOD 3: changed \< to \> to it sorts "backwards" from the default

Clear your theme registry cache and if all is well and good in the world of my thursday brain, you should now have your add more and enter buttons on top of the table instead of below.

---
Tags: entities, theming, files
---


title: highlighted and help regions

text:
# Question
Title: highlighted and help regions
I'm teaching myself Drupal theming, so naturally, one of the first things to think about with my (Zen) sub-theme are regions. However, the documentation is lacking in its explanation of the meaning of a couple of the defaults.

On the Assigning Content to Regions page, it says:

> Drupal 7 adds Highlighted and Help as default regions. By default, the textual content of the Help region is the same as the $help variable was in page.tpl.php for Drupal 6.

This is very bad copy, because it never actually states what these regions are for. And although the meaning of most of the regions (content, header, footer, the sidebars, etc.) is pretty obvious, I'm a bit fuzzy on the precise meanings of Highlighted and Help. Is Help the place where system messages (like the "theme cache is being rebuilt on every page view" message I get while I develop) are printed... or is that what Highlighted is for?

# Answer
Basically:

1. `$messages` is where your system messages are put via `drupal_set_message()`
2. $help is created from http://api.drupal.org/api/drupal/modules%21help%21help.api.php/function/hook\_help/7
3. and I have never used the mission statement stuff but apparently that's what the highlighted region is used for now and is described in greater detail in http://drupal.org/update/themes/6/7 which has a lot of information on the d6 -\> d7 theme changes.
> 4 votes

---
Tags: 7, theming
---


# Question
Title: How to turn off url aliases on dev site?
I'm using path auto to automatically generate url aliases. On my dev site it would be convenient to use standard node/123 urls. Is there a way to do that? Just turning off pathauto and path won't do the trick

# Answer
I think the problem is that the `{url_alias}` still has the aliases in it.

My suggestion would be to take a backup, then delete a few manually from "admin/build/path" (Drupal 6) or "admin/config/search/path" (Drupal 7), and then try the "node/nid" paths for the entries you deleted. Then, take another backup :) and either delete them via the **Delete aliases** tab.
> 1 votes

---
Tags: path-aliases, uri
---


# Question
Title: Removing the email validation requirement
I'm building a premium membership site where a visitor can purchase a role, and gain access to the privileged content using the Ubercart module. I've got all that working fine, but the last tiny snag that my client wants to remove is to remove the validation email requirement that's fired when someone signs up on the site in Login Toboggan (6.1.9). I've got nothing set that is forcing this extra step and I've come to believe that this may be a feature in Drupal (Acquia distro 6.22) core for any user that registers. I was hoping that this module (Logintoboggan) would eliminate that step but I've not as of yet been able to do so.

I can allow the newly registered user access by setting that in the module, but the notification and validation email requirement still remains. Can anyone recommend a way around this? I just want them to be able to come to the site purchase their membership without any validation/confirmation email. Is this possible?

# Answer
> 3 votes
That setting is part of core Drupal.

Go to admin/user/settings, and under 'User Registration Settings' set 'Public registrations' to 'Visitors can create accounts and no administrator approval is required'. Also untick the 'Require e-mail verification when a visitor creates an account' checkbox and you should be good to go.

Once you've done that it might be worth re-checking your Login Toboggan settings just to make sure there's nothing interfering with your new settings.

# Answer
> 0 votes
You should be able to inject your own logic using either hook\_user() to set an email which will validate, or perhaps use hook\_form\_alter() to adjust the values submitted during registration.

I've had to do the former for a site where we imported a large user DB with some blank and some duplicate emails; we checked for emails which would trigger errors, and replaced them with emails of the form UID@internal.example.org, which are valid but not deliverable. It was some years ago - apologies for not recalling the exact details!

The exact details of how you'd do this will depend on your site setup. For example: do you want to bypass validation in order to permit non-standard emails, or blank emails, or what? As Drupal expects emails to be unique per account, you may need to look out for what happens if you permit, say, blank emails.

---
Tags: 6, users
---


# Question
Title: including new field to views_nivo_slider
I created a slideshow using views\_nivo\_slider, with two fields, one content: image, and content: description. and I want the description field to be used as a description for the image in slide, but the problem is that description field doesnt work with nivo slider, it's not changing with the image, and I only have some static description fields. thanks

# Answer
> 1 votes
The issue here is that the `views_nivo_slider` only accepts three values: an image, a link and a title, and therefore doesn't have anything inside it to display another field/description.

Now, if instead what you are saying is that the title isn't showing up with the image, then you need to go into Views' `Row Style: Views Nivo Slider` configuration and tell it what field you want to use for the title. You do that by clicking on the wheel/gear widget thing to the right of that and then select from the menu.

---
Tags: views, 6
---


# Question
Title: How to show two dropdown select lists using a single ajax call in form api .?
I have a form in which user needs to input his height. I have two radio buttons to select the format in which the user wishes to input his height. one is "feet-inch" and another is "centimeters". I want to show a dropdown if "feet-inch" is selected, or else a textfield if "centimeters"is selected using ajax.

**Am being able to show the textfield and a single dropdown successfully with ajax call triggered from the selection of the radio buttons,** But I need to have two dropdowns, one to select "feet" and another to select "inches" right..?

**So my problem is that am not being able to show two dropdowns with one single ajax call. How can I achieve it...?? Or in other words, how can I replace two separate divs (both containing a dropdown select) with one single ajax call..?**

Alseo do let me know, if there are any other better ways to achieve this kind of height selection form..?

Please provide, codes for both form elements and the ajax call if possible.

Thanks in advance.

**//// EDIT /////**

I put both select fields inside a fieldset and wrapped that fieldset with the wrapper to be replaced. and put it inside the something\_form() function with an if statement. I dont know where am going wrong... Below is my code, please show me wats wrong....

```
<?php
function my_form($form,&form_state)
{
$form['health_set']['height_set'] = array(
        '#title'=>t('Input your height'),
        '#type'=>'fieldset',
            '#tree'=>TRUE,
            );

$form['health_set']['height_set']['height_radio'] = array(
    '#title' => t("Height input format"),
    '#type' => 'radios',
    '#options' => array(
      1 => t('feet'),
      2 => t('centimeters'),
      ),

    '#required'=>TRUE,
    '#ajax' => array(
       'callback' => 'health_height_callback',
       'wrapper' => 'health_height-wrapper',
      'effect'=>'slide',
     ),
    );

if($form_state['values']['health_set']['height_set']['height_radio']==1)
{

$form['health_set']['height_set']['feet-inch'] = array(
   '#type'=>'fieldset',
   '#tree'=>TRUE,
    '#prefix'=>'<div id="health_height-wrapper">',
    '#suffix'=>'</div>',
  );

      $options1 = array(
    1=>t('1 ft'),
        2=>t('2 ft'),
        3=>t('3 ft'),
        4=>t('4 ft'),
        5=>t('5 ft'),
    6=>t('6 ft'),
    7=>t('7 ft'),
     );

$form['health_my_bmi']['height_set']['feet-inch']['feet'] = array(
        '#type'=>'select',
        '#options'=>$options1,
        '#required'=>TRUE,
        '#description'=>t('Whats your height in feet?'),
      );

$options2 = array(
    1=>t('1 inch'),
        2=>t('2 inch'),
        3=>t('3 inch'),
        4=>t('4 inch'),
        5=>t('5 inch'),
    6=>t('6 inch'),
    7=>t('7 inch'),
        8=>t('8 inch'),
        9=>t('9 inch'),
        10=>t('10 inch'),
        11=>t('11 inch'),
     );

$form['health_set']['height_set']['feet-inch']['inch'] = array(
       '#type'=>'select',
        '#options'=>$options2,
        '#title'=>t('Inches'),
        '#description'=>t('how many inches ?'),
        '#required'=>TRUE,

      );

}

else if($form_state['values']['health_set']['height_set']['height_radio']==2)
{

   $form['health_set']['height_set']['centi'] = array(
        '#type'=>'textfield',
        '#title'=>'Height in centimeters',
        '#prefix'=>'<div id="health_height-wrapper">',
        '#suffix'=>'</div>',
         '#maxlength'=>3,
         '#size'=>6,
        '#required'=>TRUE,
      );

}

  return $form;

}
?>

```

below is the code of the callback function,

```
<?php
function health_height_callback($form, $form_state)
{
       if($form_state['values']['health_set']['height_set']['height_radio']==1)
           return $form['health_set']['height_set']['feet-inch'];

      else if($form_state['values']['health_set']['height_set']['height_radio']==2)
           return $form['health_set']['height_set']['centi'];

}
?>

```

# Answer
I got the answer. thanks to drupal forums. The above code works, I just have to put the this fieldset code,

```
$form['health_set']['height_set']['feet-inch'] = array(
   '#type'=>'fieldset',
   '#tree'=>TRUE,
    '#prefix'=>'<div id="health_height-wrapper">',
    '#suffix'=>'</div>',
  );

```

outside the 'if'.
> 0 votes

# Answer
I'm not sure exactly. But if you just want to show some FAPI elements based on the condition that radio is X or Y .... I would just use `#states` in the D7 FAPI api.
> 0 votes

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


# Question
Title: How to tag content from external databases?
I have an external database with a couple of hundred rows and columns. Is there a way in which I can tag content while or after I import the database to my drupal 7 website? Is there any module already contributed which could be used for this purpose?

# Answer
> 1 votes
by tagging you mean reference taxonomy terms ?

you could import those rows with the migrate module as nodes, with taxonomy reference (a normal taxonomy field), into your drupal DB.

---
Tags: taxonomy-terms, database
---


title: Hook Page Alter using Page ID

text:
# Question
Title: Hook Page Alter using Page ID
Is it possible to use a Page ID to target a specific page i.e.

```
function module_pageid_page_alter(&page){
}

```

# Answer
By page ID I guess you mean the page path? There isn't a hook like the one you've suggested but you can do basically the same thing in a standard `hook_page_alter()` like so:

```
function MYMODULE_page_alter(&$page) {
  if ($_GET['q'] == 'node/1') {
    // Do something for node 1
  }
  else if ($_GET['q'] == 'admin') {
    // Do something for the root admin page
  }
}

```
> 7 votes

---
Tags: hooks
---


# Question
Title: Error in query : Call to a member function execute()
My query return me an error. I have the gid of a organic group. I want to retrieve the last news for this group.

```
 $query = db_select('node','n');
 $result = $query
 ->fields('n')
 ->condition('type','news','=')
 ->join('field_data_group_audience','fdga','n.nid = fdga.entity_id AND fdga.group_audience_gid = :gid', array(':gid' => $gid))
 ->execute();

```

This query give me a : Fatal error: Call to a member function execute() on a non-object

Thanks

# Answer
> 10 votes
The `join()` method doesn't return the query object, so can't be used in a chain like you're currently doing. You'll need to do something like this instead:

```
$query = db_select('node','n');
  ->fields('n')
  ->condition('type','news','=');

$query->join('field_data_group_audience','fdga','n.nid = fdga.entity_id AND fdga.group_audience_gid = :gid', array(':gid' => $gid));

$result = $query->execute();

```

---
Tags: 7
---


# Question
Title: Running a function before a View executes
I have a carousel built using Views (7.x-3.x) that displays 10 items. In this carousel I would like to place 1 item (inclusive of the 10) that displays Twitter content.

What I would like to do is run the function that uses the Twitter API before the View is built/executed. If it succeeds then the View should display 9 items from it's own query (10 items total.) If it fails, then the View would display 10 items from it's own query.

I have successfully implemented the View and the Twitter function running on the theme layer though in order to have a 'fall back' by altering the number of items displayed I would need to do this before the View is built/executed.

Can anyone point me in the right direction for this?

I believe I am looking at the right function "hook\_views\_query\_alter" but I'm not sure how to set "items\_per\_page"

Thanks

# Answer
> 0 votes
I first used hook\_views\_query\_alter(). While the code below does work I needed a solution that was a better fit my entire situation.

```
$view->init_pager();
$view->set_items_per_page(x);

```

The better solution was to call the Twitter API during the hook\_views\_pre\_render() phase. If good data was returned then I appended this data to $views for use later.

```
function mymod_views_pre_render(&$view) {
  if ($view->name == 'carousel') {
    $view->mymod_carousel = array();

    $data = twitter(); // custom function that requests data from Twitter API
    if (!empty($data)) {
        $count = count($view->result); // we need to remove the last node in the views result so we always have the same number of items
        if ($count) {
            unset($view->result[$count-1]);
            $view->mymod_carousel['twitter'] = $data;
        }
    }
}

```

Then during hook\_views\_post\_render() I test for this new data and if it is present then I basically result $output using hook\_theme() from the jCarousel module.

```
function mymod_views_post_render(&$view, &$output, &$cache) {
  if ($view->name == 'carousel') {
    $result = $view->result;
    $items = array();
    $count = 0;
    foreach($result as $node) { // loop through the results of the view and add our Twitter data at a specific location
        if ($count == 2) {
            if (!empty($view->mymod_carousel['twitter'])) {
                $data = $view->mymod_carousel['twitter'];
                $items[] = theme('mymod_carousel_twitter', array('data' => $data));
                $count++;
            }
        }
        if (!empty($node)) {
            $items[] = theme('mymod_carousel_item', array('node' => $node));
        }
        $count++;
    }

    $options = $view->style_options;
    $output = theme('jcarousel', array('items' => $items, 'options' => $options));
    }
}

```

# Answer
> 0 votes
You might be interested in a similiar kind of question I answered here:

How do you customize the title of an RSS feed created by Views RSS?

I would just set the view size to 10 always. And then use array\_unshift() as I did in that reply to "prepend" the new item Object to the front of the view results array, if your Twitter call return its 1 item of content. Or else you just let the original 10 come from Views.

# Answer
> 0 votes
The hook you're looking for is probably pre\_render. There you can execute your function and replace the first row of the view with whatever you want.

# Answer
> 0 votes
Not a full answer to your question, but I typically set `items_per_page` in hook\_views\_pre\_build, like

```
function mymodule_views_pre_build (&$view)
{
    if ($_GET["perpage"]) {
        $perpage = check_plain($_GET["perpage"]);

        if (is_numeric($perpage) && (int) $perpage > 1) {
            $view->pager["use_pager"] = TRUE;
            $view->pager["items_per_page"] = (int) $perpage;
        } else if ($perpage == "all") {
            $view->pager["use_pager"] = FALSE;
            $view->pager["items_per_page"] = 0;
        }
    }
}

```

This is from a Drupal 6 Views 2 site, but I am pretty sure this still works with Drupal 7 and Views 3.

---
Tags: views
---


title: How to prevent all UPPERCASE body text?

text:
# Question
Title: How to prevent all UPPERCASE body text?
Some users enter body copy and comments with the caps lock on. All uppercase is considered shouting and I would like to convert it to lowercase or "natural" with uppercase characters at the beginning of a sentence.

Any easy solutions?

# Answer
> 2 votes
Converting the post to all lower case would be pretty simple; you can implement your own filter like so:

```
function MYMODULE_filter_info() {
  $filter['allcaps_filter'] = array(
    'title' => t('Disallow ALL CAPS posts'),
    'description' => t('Rudimentary filter which converts all text to lowercase'),
    'process callback' => 'MYMODULE_allcaps_filter_process'
  );

  return $filter;
}

function MYMODULE_allcaps_filter_process($text) {
  // Attempt to make the first letter of the first word uppercase. This is very
  // likely to fail as the inputted string will probably be HTML.
  return ucfirst(strtolower($text));
}

```

Once you clear the caches you'll be able to add that filter to any text format you want.

It's worth noting that the description *rudimentary* in the comments is very, very apt...for example this will also convert any HTML attributes/tags to lowercase which might break embedded image paths etc. It might provide a good place to start though.

Constructing more naturally cased alternatives is going to be very tricky, mainly because you haven't just got text in there...you've got HTML as well. I can't think of a decent way to do this at the moment to be honest, short of importing the string into a `DOMDocument` and looping through every element, converting the text in chunks as you go.

I'd provide an example for that but I think you've got one ;)

# Answer
> 2 votes
As alternative to the Clive solution, I would implement different hooks, which are hook\_comment\_view\_alter() for comments, and hook\_node\_view\_alter() for nodes; you could also implement hook\_entity\_view\_alter() that is called also for nodes, and comments.

There are some differences between the two approaches that needs to be considered.

* Input filters don't get any information about the source of the text they are called to process; they can be called for a node body, a node content, a field content, or a view.

The following screenshot shows part of the settings for a "long text" field; when "Filtered text" is selected, the user can select the input format that is used for the field being written.

The following screenshot shows the settings the Views module has for a view header; selecting "Global: Text area" as header, these are the settings Views would present for the view's header.

In any of those cases, the input filter is not able to understand when it is called, and for what. If your purpose is just changing the content of nodes, and comments, an input filter is not what you should implement. If your purpose is to change every input given from users (independently from the roles they have), then you can implement an input filter, but consider that input filters can be used in contexts completely different from the ones you could know of. What done from the Views module can be done from any other module that accepts input from the users, and allows them to decide the type of the input format (between the ones they can use).

Differently, `hook_comment_view_alter()` is given some information about the comment being viewed, as those hook implementations are called with the following code. (See comment\_view().)

```
  // Populate $comment->content with a render() array.
  comment_build_content($comment, $node, $view_mode, $langcode);

  $build = $comment->content;
  // We don't need duplicate rendering info in comment->content.
  unset($comment->content);

  $build += array(
    '#theme' => 'comment__node_' . $node->type,
    '#comment' => $comment,
    '#node' => $node,
    '#view_mode' => $view_mode,
    '#language' => $langcode,
  );

  // …

  // Allow modules to modify the structured comment.
  $type = 'comment';
  drupal_alter(array('comment_view', 'entity_view'), $build, $type);

```

The same happens to `hook_node_view_alter()` which is invoked by node\_view().

```
  // Populate $node->content with a render() array.
  node_build_content($node, $view_mode, $langcode);

  $build = $node->content;
  // We don't need duplicate rendering info in node->content.
  unset($node->content);

  $build += array(
    '#theme' => 'node',
    '#node' => $node,
    '#view_mode' => $view_mode,
    '#language' => $langcode,
  );

  // Add contextual links for this node, except when the node is already being
  // displayed on its own page. Modules may alter this behavior (for example,
  // to restrict contextual links to certain view modes) by implementing
  // hook_node_view_alter().
  if (!empty($node->nid) && !($view_mode == 'full' && node_is_page($node))) {
    $build['#contextual_links']['node'] = array('node', array($node->nid));
  }

  // Allow modules to modify the structured node.
  $type = 'node';
  drupal_alter(array('node_view', 'entity_view'), $build, $type);

```

In both the cases, also `hook_entity_view_alter()` is invoked, and it gets a parameter saying which type of entity is being altered. `hook_entity_view_alter()` is probably preferable when the same code is used for more than one entity (such as nodes, and comments).
* The output of check\_markup(), which is the function used to get the output of an input format, is cached. With the actual code, the cache is not used for comments, as the function (whose declaration is `check_markup($text, $format_id = NULL, $langcode = '', $cache = FALSE)`) is called without its fourth parameter, such as in comment\_submit().

```
if (isset($comment_body['format'])) {
  $comment_text = check_markup($comment_body['value'], $comment_body['format']);
}
else {
  $comment_text = check_plain($comment_body['value']);
}

```

This is not what happens with fields, where the code used is the following one. (See \_text\_sanitize().)

```
// If the value uses a cacheable text format, text_field_load() precomputes
// the sanitized string.
if (isset($item["safe_$column"])) {
  return $item["safe_$column"];
}
return $instance['settings']['text_processing'] ? check_markup($item[$column], $item['format'], $langcode) : check_plain($item[$column]);

```

The code that in `check_markup()` checks for values stored in the cache is the following one.

```
// Check for a cached version of this piece of text.
$cache = $cache && !empty($format->cache);
$cache_id = '';
if ($cache) {
  $cache_id = $format->format . ':' . $langcode . ':' . hash('sha256', $text);
  if ($cached = cache_get($cache_id, 'cache_filter')) {
    return $cached->data;
  }
}

```

When `$cache` is `FALSE`, `$cache && !empty($format->cache)` is `FALSE` too, and the cache is not used. This is what happens with comments, for example. For fields, it is the module implementing the field that decides when to use a cached value, or not. (In the case of the node body, it is used a cached value.)

As side note, when the input of a user can contain any UTF-8 code, it is preferable to use drupal\_strlower(), and drupal\_ucfirst(), which are coded to always work with UTF-8 strings. See the code of `drupal_strlower()` as example. (`drupal_ucfirst()` calls `drupal_strlower()`.)

```
  global $multibyte;
  if ($multibyte == UNICODE_MULTIBYTE) {
    return mb_strtoupper($text);
  }
  else {
    // Use C-locale for ASCII-only uppercase
    $text = strtoupper($text);
    // Case flip Latin-1 accented letters
    $text = preg_replace_callback('/\xC3[\xA0-\xB6\xB8-\xBE]/', '_unicode_caseflip', $text);
    return $text;

```

# Answer
> 1 votes
QUICK AND DIRTY, or should I say quick and dirty....you could plug this logic into @Clive's filter....

```
    <?php

$text='This is a TEST of the <b>EMERGENCY BROADCAST</b> system.<br>This is only a test. Had this been an actual <span class="EMERGENCY">emergency</span>, you would have been vaporized about <i>3 milliseconds</i> ago.  this concludes this test.';

$input=str_split($text);
$output='';

$intag=FALSE;
$afterperiod=TRUE;
$aftercap=FALSE;

$numupper=0;
$total=strlen($text);

foreach($input as $t) {

  if ($intag) {
    switch ($t) {
      case '>':
        $intag=FALSE;
      default:
        $output.=$t;
    }
  } else {
    if ($afterperiod) {
      switch($t) {
        case '<':
          $intag=TRUE;
        case ' ':
        case '.':
          $output.=$t;
          break;

        default:
          $output.=$t;
          $afterperiod=FALSE;

          if (ctype_upper($t)) {
            $numupper++;
          }
      }
    } else {
      switch ($t) {
        case '.':
          $afterperiod=TRUE;
          $output.=$t;
          break;

        case '<':
          $intag=true;
          $output.=$t;
          break;

        default:
          $output.=strtolower($t);

          if (ctype_upper($t)) {
            $numupper++;
          }
      }
    }
  }
}

$shouting=$numupper/$total;

if ($shouting > .5) {
  return $output;
} else {
  return $text;
}

```

but this turns all caps to lower in the text except for those at the beginning of a sentence (assuming no newlines, tabs, etc) and ignoring any tags. Additional logic could be added to look for only repeating caps etc. ADDITION: But then again, it does this only if more than half the characters are uppercase....

# Answer
> -1 votes
```
text-transform:uppercase;

```

use this in css

---
Tags: forms
---


# Question
Title: Trying to embed a video in a Views Header
I am trying to embed a video in the header of Drupal 7 View. I have the header text format set to full HTML. The full HTML text format is set to: (X = checked)

* _ Limit allowed HTML tags
* _ Display any HTML as plain text
* X Convert line breaks into HTML (i.e. \<br\> and \<p\>)
* X Convert URLs into links

The code below is what we used to embed the video in our Drupal 6 site but it was in an article not a views header. No video is showing up in the header and view source shows that the code is getting stripped out.

```
<div id="mainFlash">
<embed id="mainFlash" width="550" height="440" quality="high" name="mainFlash" src="http://www.oursite.com/main-video-en.swf" type="application/x-shockwave-flash">
</div>

```

Is it possible to embed the video? Do I need to use the \<object\> tag instead?

# Answer
The 'Full HTML' format in Drupal 7 by default still strips out some of your tags, check your format settings under Administer » Configuration » Content authoring » Text format, or /admin/config/content/formats/ and you'll see that for the Full HTML format, you're limited to the following tags:

```
<a> <em> <strong> <cite> <blockquote> <code> <ul> <ol> <li> <dl> <dt> <dd>

```

You can either add an object, embed tag here to make these work for this input format or you can add a separate input format that has no restrictions. The choice will really depend on what kind of site you are running and who else might have access to this format. If I were letting users use the 'Full HTML' format for adding comments, content, I would definitely want to restrict the tags they use and allow only admins access to an unfiltered format.
> 1 votes

---
Tags: views, files
---


title: Lightbox2 theming

text:
# Question
Title: Lightbox2 theming
Can anyone advice me on how to theme the lightbox popup?

I have a design where the close and image navigation bottons have to be repositioned from their default location.

Please help!?

# Answer
The easiest way is to create a new CSS file (or add lines to your existing file) and overwrite the rules that are applied to the lightbox. Unfortunately we cannot help you any further if you don't give more information. Can you give an online test case and preferably an image of what you are trying to achieve?
> 1 votes

---
Tags: theming, javascript
---


# Question
Title: How to learn JQuery coming from a Drupal background but with little to no knowledge of Javascript?
So here I am in 2012 and although I've been making websites in my spare time for several years, I've managed to get the results I needed by using Drupal and simply cutting and pasting Javascript snippets, etc. when necessary.

Recently, I've got into development more seriously and I have some time to study the right way to do things so I've decided that I'd like to learn jQuery. Basically, I'd like to make my sites a little more exciting and interactive; in the past, the sites I have built have been praised/criticized as "highly informative but very plain."

That said, I don't know much about Javascript to begin with. Where should I start? If it matters all my projects going forward will be in Drupal 7.

I was looking forward to the JQuery and Drupal videos on drupalize.me, but unfortunately I live in Japan and have a slow Internet connection which makes it almost impossible to stream the videos.

# Answer
> 1 votes
As said, you should try and pick up some knowledge of JavaScript (JS).

A good way to learn jQuery, which is a library of JavaScript, when you know the basis of JS is 30 Days to Learn jQuery. I've done this course myself and they give a lot of tips and best practices! Also Learning jQuery has some good tips.

To start off with JavaScript itself, take a peek at W3Schools!

# Answer
> 1 votes
Understanding basics of Javascript is very important to effectively use and extend jQuery. http://www.youtube.com/watch?v=v2ifWcnQs6M

---
Tags: 7, javascript
---


# Question
Title: how to set a variable in module and get it in theme
i want set a variable in module and use it in my theme, (except variable\_set and variable\_get way.)

for instance . in module file

```
      if(in_array(arg(1),$ex))
      {
//      set a variable
      }

```

in theme file

```
if(//variable)
{
echo '<div class=d7></div>';
}

```

thank you so much for help me

# Answer
HOWEVER:

You should really look into the various \_preprocess() hooks. From further commentary below, I am thinking that's where you should be doing all this.

ORIGINAL ANSWER:

If you don't want to use the system wide `variable_set()` or `variable_get()` you can always set a variable in the global `$_SESSION` array that would be seen by the current logged in user only, eg,

```
if ( // whatever ) {
  $_SESSION['MYMODULE_variable_name']= // whatever
}

```

SUPER DUPER OVER SIMPLIFIED ADDITION:

```
function MYMODULE_foo($value=NULL) {
  static $bar;

  if ($value) {
     $bar=$value;
  }

  return $bar;
}

```

accomplishes it inside your module, eg, you can do:

```
MYMODULE_foo('this is cool');

```

and then in your theme do:

```
$baz=MYMODULE_foo();

```
> 0 votes

---
Tags: 7, theming
---


# Question
Title: What is the easiest way to export Field settings into a .install file?
I have a bunch of custom fields on a custom content type. I'm trying to make my module create these fields and remove them on install and uninstall respectively.

There was a previous question and answer on this: https://drupal.stackexchange.com/a/629/2384 However, it is not adequate. The code was not completely presented. The author used node\_type\_delete() without deleting the content first, and that allegedly leads to trouble later down the line. So I checked the node\_example.module as per recommendations on Drupal.org, node\_example.install etc. These files provide insight into the structure of the module, but do not discuss all the varieties of fields (like file, taxonomy, etc.,) and how they are to be structured in the .install array.

I have tried to export my content type using Features, and it does produce an array. But the syntax is radically different from what was presented in the example, and I was lost in the arrays and sub-sub arrays.

Is there a simple guide somewhere, that can help me convert my content type into an array specification I can smoothly fit into my hook\_install declarations?

# Answer
> 1 votes
There are some useful resources on how to do this. And you **dont** have to use Features.

Features is great if you understand what it's doing (calling Field API in an automated fashion and exporting definitions). You can use the Field API to define, create instances, attach fields to entities -- and then remove them all module uninistall as you need.

The easiest way for me to do this is look at the functions in the link above and use var\_dump() on `$field` or its `$settings` after you make it using the Field UI. Then just use the appropriate Field API call like field\_create\_instance() to wire these var\_dump'd arrays into your modules hook\_install(). So i'm saying dont create the arrays by hand, create them in Drupal and just copy an export to your code ...

---
Tags: 7, nodes, installation
---


title: Send node path alias to user

text:
# Question
Title: Send node path alias to user
When I create a new content, I would like to send an email that contains "node path alias".

### Pathauto pattern

```
[title-raw]-[nid]

```

### Rules

```
ON event After saving new content
IF
Created content is Les entreprises
AND
Created content is new
Add a condition
DO
Send a mail to a user

```

### Rules email

```
[node:node-path]

```

I receive the email, but the content is 'node/16565'. I would like to receive 'les-entreprises-16565'.

If I inspect token with the Devel module, I get: node-path (String, 21 characters) les-entreprises-16565.

Why didn't I receive this node path alias? Is the Rules module sending the mail too quickly, and the path alias is not yet created?

# Answer
Have you included the condition “Entity is of type … Node”? Having to specify this condition may seem redundant, since you have already established this rule is triggered by the Event “After saving new content”. However, I have experienced that without this condition a very limited amount of tokens holding data from the node will be available to the Action and any Components invoked by the rule. Good Luck! Susan
> 0 votes

---
Tags: rules, path-aliases
---


title: Use content panes as blocks

text:
# Question
Title: Use content panes as blocks
I am currently working with drupal 7 and I'm using page manager to edit different pages on the site.

I tried creating a mini panel and adding it to a region, but i do not know how to add content panes to it. Is it possible to use content panes as blocks and add then to regions ? the reason I wanna try doing this is i don't want to choose a layout from page manager and add content panes to it instead i wanna add then to the drupal regions.

# Answer
A mini panel acts like a block, except that it has subregions. To add content, select the mini panel for editing and select the "content" editing display. Next pick the gear in the upper right corner of the desired region in the mini panel and select 'add content' The pop-up will give you the selection of available content that can be placed in the panel.

Once you have the mini panel configured, you place it in a theme region just as you would a block. You select the mini panel from the admin/structure/blocks page for your theme. It can be found in the list of disabled blocks at the bottom of the layout page form.
> 1 votes

---
Tags: panels
---


# Question
Title: Are there any embedded video/media field modules which integrate with Rules?
I'm trying to set up some Rules conditions which deal with whether or not a user has added a YouTube URL into a media field for a node. The idea is to use a Media type module to embed the YouTube video into the forum post. But I want a specific Rule to fire if the user saves their forum post without adding a YouTube video URL to that custom field.

However, I can't seem to find a module like Media or Video Embed Field, or Embedded Media field which expose that field entity to Rules.

# Answer
> 1 votes
You could use a hook\_form\_alter() to check if a youtube video has been added. Then run rules\_invoke\_event() to trigger the rule.

Btw, I personally like the Video Embed Field module.

# Answer
> -1 votes
I haven't perused them all, but Johan Falk posted a new bunch of Rules videos just before Drupalcon Denver. You may find a solution within them: http://www.youtube.com/watch?v=BunFdtCTfK0&feature=results\_main&playnext=1&list=PL84B6FFA4F7ACAD57 Best of luck! Susan

---
Tags: rules
---


# Question
Title: Do exposed filters work in Views 7.x-3.3?
When I create a filter, check the expose filter box, click save, then open the filter up again the exposed filter checkbox is uncheked...

I noticed when clicking save the filter is called: "Content: Assessment (or Unknown) | Settings" instead of "Content: Assessment (exposed) | Settings"

Anybody know what's going on here? I've tried creating an entirely new view and the same thing happens.

---

The field I am exposing is a simple taxonomy list.

I created a short video showing the issue: http://www2.intensiveintervention.org/views\_issue/

---

I found a thread on a seemingly related issue: http://drupal.org/node/1343482 but this did not solve my problem.

---

Downgrading views to 7.x-3.1 did not have any effect.

# Answer
> 3 votes
Okay I figured out the problem.

There is, as of today, incompatibility between Views and Theme Developer. If I disable Theme Developer views acts normally.

FYI for everybody else having this problem!

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


# Question
Title: How to obtain contents from a drupal 7 query?
I am trying to perform the below simple query:

```
$query = db_select('sage.USER', 'USER')
  ->fields('USER', array('USER_ID', 'OFFICE_ID'));
$result = $query->execute();

```

I would like to then pull out the 'office\_id' that is returned by the query, which I have been told can be done with the following:

```
$office = $result->office_id;

```

However, when I do 'print\_r($office)' or 'echo $office', it would seem the $office string is empty. The database is not empty and contains the appropriate values.

Could someone please how I can pull out the contents of a drupal 7 query?

# Answer
> 3 votes
`execute()` returns a resource you can iterate over in a `foreach` loop, e.g:

```
foreach ($result as $record) {
  $office_id = $record->office_id;
}

```

In your case you probably want to use the `fetchObject()` method to actually retrieve the first record returned from the query:

```
$result = $query->execute()->fetchObject();
$office = $result->office_id;

```

---
Tags: 7
---


title: error history view_galleriffic

text:
# Question
Title: error history view_galleriffic
I'm using Views Galleriffic (6.x-1.x-dev) and Node Gallery module and there is an error.

In the Firebug console, my error is shown as:

```
$("a[rel='history']").live is not a function in line 93 $("a[rel='history']").live('click', function(e) in file view_galleriffic.js

```

I uploaded jquery.history.js in module view\_galleriffic/js/... my website link :http://demo.dolphin-sch.ir/nagara/fa/galleriffic/95 help me

# Answer
The `live()` method wasn't added to jQuery until v1.3. Your site is currently using the standard jQuery library included in Drupal 6, v1.2.6.

To fix this all you need to do is download and install the jQuery Update module. That will upgrade your site's jQuery library to v1.3.2 and you should stop getting the errors.
> 0 votes

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


# Question
Title: Can we create a core PHP file inside the files folder?
As per Drupal's folder structure, custom code is always in sites/modules or in the theme folder. One of my colleagues created a custom PHP file in the files folder. Is this OK or are there any security issues?

# Answer
Files under that folder are writable by the web server. You could argue that makes it a security risk, but your server would already have to have been compromised in one way or another for it to become so. If your server is configured properly it will only execute PHP files, not serve them for plain-text download.

From the point of view of convention, though, you shouldn't do this. Putting code files all over the file structure makes maintainability infinitely harder.
> 4 votes

# Answer
Drupal's .htaccess file will try to prevent this by adding the line to an .htaccess file in the files directory:

```
SetHandler Drupal_Security_Do_Not_Remove_See_SA_2006_006

```

If you remove that line then the code will execute, but you are making your site less secure in the case that a file upload module doesn't properly use file\_munge\_filename.

I would avoid putting scripts into the files directory if at all possible. Instead you can place them into a module directory or the Drupal root or into a sub-folder inside your Drupal root that will make it obvious what they are: "site-scripts/"

Doing things in a standard way makes it easier to manage your site in the long run. It also increases the likelihood that another person who takes over the site for you will be able to quickly learn how to do key tasks like upgrade it.

There are also modules and tools which will look at the files directory and delete any files that are not "managed" by Drupal (i.e. that are not in the "files" database table). If you put your .php files in that directory there is a chance at a future date they will be deleted.

For security and maintainability and stability I just can't see a good reason to put executable scripts into the files directory.
> 2 votes

# Answer
You should guarantee that this PHP file will be executed only by authorized parties by implementing access checking inside the file, or browser headers cheking, or `.htaccess`, or file system read/write permissions.

By default, PHP files cannot be read by HTTP requests, only executed if `.htaccess` or the web-server is properly configured.

And you can place your files whereever you want, but you must make sure, that you follow the Drupal logic as a framework and follow the agreed usage conventions.
> 1 votes

---
Tags: files
---


# Question
Title: en/ language prefix remains after uninstalling internationalization module and dependencies
I have cloned an existing internationalized Drupal website to create a new website. This new website does not need internationalization and translation. Therefore, I uninstalled all corresponding modules.

Unfortunately, the navigation through pages still use the default language prefix `en/`. Drupal complains that it does not find pages anymore. Yet, when I remove the prefix manually from the URL, the pages are reachable again.

How can I have Drupal stop using the `en/` prefix in URLs?

# Answer
> 3 votes
the en/ prefix comes from core module **Locale**, you can change the configuration here: `/admin/config/regional`

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


# Question
Title: How to use a field value in Template.php
Im sure this is an easy question, just not for me because of lack of experience with the Drupal preprocess hooks. I am removing the standard "Read More" links from my content. I want the ability to replace them with a css button. I can do that, the tricky part come when I want to use a FIELD from the CONTENT TYPE, as the name for the button.

```
function bootstrap_preprocess_node(&$variables) {

 unset($variables['content']['links']['node']['#links']['node-readmore']);

   $variables['newreadmore'] = t('<span class="newreadmore"> <a href="!title" class="btn
  btn-info" >'.$readmoretext.'</a> </span>',
   array(
    '!title' => $variables['node_url'],
  )
);
}

```

My question is how can i HOOK into the node and retrieve the field for my variable $readmoretext

Thanks!

# Answer
> 5 votes
You can find the node object in `$variables['node']`, and from there you can use the `field_get_items()` function to extract your field value:

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

// field_get_items() always returns an array, even if the field is limited to one value
$field_items = field_get_items('node', $node, 'field_name');

// Get the value from the first item in the array (if that's the one you need)
$title = $field_items[0]['value'];

```

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


# Question
Title: What's the proper way to create a new page option?
I want to show comments of a node on a separate page instead of on the node page. Since this is just a "comment archive" and not active I would like a simple solution without a big module or a lot of code.

I can "hack" the node--mytype.tpl.php page to show comments when the "?archive" is in the URI:

```
    $uri =  check_plain($_SERVER['REQUEST_URI']);
    if (strpos($uri, '?archive') > 0){
        print render($content['comments']);
    }
    else {
        print l('View Comment Archive', $uri.'?archive');
    }

```

This works fine, even with the comment pager. I'm curious what the "proper" way in Drupal would look like.

# Answer
I would use the Views module for this. Even though you don't want to use a "big module" but Views is used in almost every Drupal site and will allow you to do this without custom code.

Here are the quick steps:

1) Create a new view of Comments with a display type of "page" and a url of "node/%/archived"

2) Add a contextual filter that uses "content id from url" as a default argument 3) Add a "Menu tab" by clicking menu and title it "Archived".

Viola! There will be an archived tab on your nodes with all comments.
> 3 votes

# Answer
The easiest way to to use Views.

You can create a view over Comments, or you can make a view over Content and then add a relationship to the node's comments. There are advantages and disadvantages to both. You just need to play with them to see what works best for your situation.

With either method, you can use any of the normal means for adding a view to you site.
> 3 votes

---
Tags: nodes
---


# Question
Title: unset the timezone and group in the profile form
The version of Drupal is 7.x

Hi, I need unset the timezone the user\_profile\_form and the timezone doesn't remove the page. I tried with this code:

```
function mymodule_form_alter(&$form, &$form_state, $form_id){
if($form_id == 'user_profile_form')
 { unset($form['account']['timezone']);
}

```

What is my error?.

Also, I have a group in the profile named: group\_my\_information. How can I remove it with unset? I tried this code:

```
unset($form['group_my_information']);

```

What is my error?

Thanks for your help.

# Answer
> 4 votes
The reason is because your module in which you write you hook\_form\_alter has a weight of 0. In your database table "system" for your site look for your new module's row and edit its weight to a higher value. I set mine to 100. After you do this "clear your caches" just in case. Then you should now see the line item in your $form variable this is "timezone". Now your unset should work.

unset($form\['timezone'\]);

Keep in mind that if you uninstall your module you will have to re set the weight again.

If you add this in your "MYMODULENAME.install" file you will be able to set this on intall

```
    /**
     * Implementation of hook_install()
     */
    function MYMODULENAME_install() {
      // New module weights in core: put MYMODULENAME as the very last in the chain.
      db_query("UPDATE {system} SET weight = 100 WHERE name = 'MYMODULENAME'");
    }

```

Hope this helps

---
Tags: 7, users
---


# Question
Title: Create Related Terms Block Showing Terms on Taxonomy Term Page
Hi i have been hunting high and low for years to create this and i still havent found an answer. I have seen folks looking for similar but these questions usually went unanswered as if the answer is still unknown.

Im using views 2 and drupal 6. I am using the 'related terms' bit of when i edit a term. I would like to show the related terms to a term when viewing a taxonomy term page. I dont want to show nodes just terms.

I have created a term view and have played about with the Taxonomy: Related terms argument and Taxonomy: Related terms relationship but to no avail.

It sounds like quite a simple thing for drupal and views but for some reason there doesnt seem to be a definate answer to this. all help appreciated. thaks

# Answer
First off, I wanted to let you know that this is not necessarily intuitive, and there's very hacked methods of doing this. Another thing that I want to mention is that I did this in Drupal 7 with Views 3. However, one of the things that I *think* is most different is the UI. So text descriptions should be able to guide you. :)

The way that I went about doing this is as follows:

In Views, I created a block which is to display the content type of the related items (mine was recipes). I added the fields which I wanted to appear, which were just pictures and titles. Then in Contextual Filters (I think D6/Views2 calls this arguments), I added two.

The first is "Content: Nid" and I configured it as follows: When filter value is not available =\> Provide default value =\> Type: Content ID from URL. Under "more" (not sure what V2 calls it), there's an option called "exclude", which if selected, the numbers entered for the filter will be excluded rather than limiting the view. This is great because it essentially says, "Return me the list of everything of this content type EXCEPT this one that I'm on."

The second filter is "Content: Has taxonomy term ID". This one was a bit trivial because I want to provide relationships on multiple vocabularies of taxonomy terms. So it's configured as follows: When the filter value is NOT available =\> Provide Default Value =\> Taxonomy term ID from URL =\> Load default filter from **node** page =\> Limit terms by vocabulary =\> Selected my vocabularies =\> Multiple-value handling -\> filter to items that share any term.

When the filter value IS available or a default is provided =\> Specify validation criteria =\> Validator = Taxonomy term, with my previous chosen vocabularies selected again =\> Filter value type =\> Term IDs separated by , o + . Under "more", I checked "allow multiple filter values to work together."

This was the way that I was able to get the related content. I specified the amount of results that I wanted in the pager.

Hope that this helps!
> 2 votes

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


# Question
Title: How can I use the Date tools without requiring an end date?
I used the Date module's Date Tools (admin/content/date/tools) to add a date field to an existing content type. When I go to create a new node, it displays both a From date and a To date. When I go the Manage Fields section for the content type, I only see one date field.

Is there any way to make it display only a single date field when creating new content? I don't want to allow users to choose a date range, rather only a single date.

# Answer
It is an option to choose end date or only start date try to make a new date field and in option before saving there is a check box if you want an end date or not
> 3 votes

---
Tags: 6, datetime
---


title: Currency Drop down

text:
# Question
Title: Currency Drop down
I need a currency drop down in my module to choose the currency with amount. Is there any feature to get this in Drupal?

# Answer
The Money module provides a field allowing content editors to select an amount and currency.

Currently this module is only available for Drupal 6.x. There's an issue for porting it to Drupal 7.x.

An alternative is the Units of Measurement module, which currently has a Drupal 7.x development release published.
> 0 votes

---
Tags: forms
---