title: Export watchdog to CSV

text:
# Question
Title: Export watchdog to CSV
I would like to export everything in the `watchdog` table to a CSV file occasionally using `hook_cron()`. I do not have access to PHPMyAdmin and don't want to waste time with modules like so.

Right now, I have all records for the watchdog table, but I can't figure out how to format messages properly.

```
$log = db_query("SELECT uid, type, message, variables, severity, location, timestamp FROM {watchdog}")->fetchAll();
dsm($log);
// Output: "message => '%type: !message in %function (line %line of %file).'"
//         "variables => 'a:6:{s:5:"%type";s:6:"Notice";s:8:"!message";s:27:"Undefined index:..."

```

How the heck am I supposed to replace symbols in `$log['message']` with what's in `$log['variables']`?

I have tried using `t($log['message'], $log['variables'])` and `format_string($log['message'], $log['variables'])` but this won't work.

# Answer
> 2 votes
Rather than "waste time" with modules, I'll spend a little time looking at how a module like https://www.drupal.org/project/views\_watchdog handles something I want to do. Turns out it's like so...

```
function views_watchdog_format_message($message, $variables) {
  return $variables === 'N;' ? $message : t($message, unserialize($variables));
}

```

# Answer
> 0 votes
This is how dblog output message on dblog.admin.inc:

```
/**
 * Returns HTML for a log message.
 *
 * @param array $variables
 *   An associative array containing:
 *   - event: An object with at least the message and variables properties.
 *   - link: (optional) Format message as link, event->wid is required.
 *
 * @ingroup themeable
 */
function theme_dblog_message($variables) {
  $output = '';
  $event = $variables['event'];
  // Check for required properties.
  if (isset($event->message) && isset($event->variables)) {
    // Messages without variables or user specified text.
    if ($event->variables === 'N;') {
      $output = $event->message;
    }
    // Message to translate with injected variables.
    else {
      $output = t($event->message, unserialize($event->variables));
    }
    if ($variables['link'] && isset($event->wid)) {
      // Truncate message to 56 chars.
      $output = truncate_utf8(filter_xss($output, array()), 56, TRUE, TRUE);
      $output = l($output, 'admin/reports/event/' . $event->wid, array('html' => TRUE));
    }
  }
  return $output;
}

```

So you can do next:

```
module_load_include('inc', 'dblog', 'dblog.admin');
$result = db_query('SELECT w.*, u.name, u.uid FROM {watchdog} w INNER JOIN {users} u ON w.uid = u.uid')->fetchAll();

foreach ($result as $row) {
  $message4row = theme('dblog_message', array('event' => $row)));
  // Do something with $message4row for CSV output.
}

```

---
Tags: cron, log-messages
---


# Question
Title: Get tid as integer from tid array returned by EntityFieldQuery
I am using an EntityFieldQuery to return an array of taxonomy terms matching a provided custom field value. Using the example given in this question, I wrote a function that accepts the vocabulary, field name, and field value as arguments and returns an array of matching terms. That works perfectly, but what I really want to get back is just the integer values corresponding to the matching terms, not the array of terms.

The problem is, the data structure that's being returned looks like this:

```
Array
(
    [6] => stdClass Object
        (
            [tid] => 6
            [vocabulary_machine_name] => features_of_interest
        )

)

```

for one item, and for another:

```
Array
(
    [79] => stdClass Object
        (
            [tid] => 79
            [vocabulary_machine_name] => features_of_interest
        )

)

```

Because of this, I can't see how to isolate the \[tid\] value (6 or 79 in the examples). I'd like to be able to say

```
$int_tid = $terms[XXX]['tid'];

```

but I can't get my head around whatever syntax is needed.

I've pasted my function below in case it helps. Ideally I would like to loop through the array of items, isolate each term ID value as an integer, and push it onto an array which the function would then return.

```
  function get_tids_from_custom_field($vocabulary, $field, $value) {

    $vocab_machine_name = taxonomy_vocabulary_machine_name_load($vocabulary);
    $query = new EntityFieldQuery();
    $query
      ->entityCondition('entity_type', 'taxonomy_term')
      ->entityCondition('bundle', $vocabulary)
      ->propertyCondition('vid', $vocab_machine_name->vid)
      ->fieldCondition($field, 'value', $value, '=');

    $terms = $query->execute();
    $int_ids = array();

    foreach ($terms as $term) {
      dpm($term);
      array_push($int_ids, $term);
    }
    return $int_ids;
 }

```

# Answer
The standard(?) pattern to get ids from a query over a single entity type is to use `array_keys()`. Something like this:

```
function get_tids_from_custom_field($vocabulary, $field, $value) {
  $vocab_machine_name = taxonomy_vocabulary_machine_name_load($vocabulary);
  $query = new EntityFieldQuery();
  $query
    ->entityCondition('entity_type', 'taxonomy_term')
    ->entityCondition('bundle', $vocabulary)
    ->propertyCondition('vid', $vocab_machine_name->vid)
    ->fieldCondition($field, 'value', $value, '=');

  $results = $query->execute();

  return !empty($results['taxonomy_term']) ? array_keys($results['taxonomy_term']) : array();
}

```

The results array is keyed by the entity ID.
> 2 votes

# Answer
Try this:

```
foreach ($terms as $term){
  foreach ($term as $key => $value){
    array_push($int_ids, $key);
  }
}

```

It's probably not the best solution if you only ever have one term in a field but it should do the trick.
> 1 votes

---
Tags: entities
---


# Question
Title: Cookies for anonymous users aren't read nor checked
I currently have a module on http://hitechwolf.com that creates a welcome overlay upon a user's first visit, This should work by utilizing a jquery created cookie and showing the overlay based on its existence. The jquery works, the cookie is created, but for anonymous users the cookie is ignored and the overlay shows on every page. I've implemented jquery.cookie but it still completely ignores the cookie for anonymous users. I'm at the end of my rope, any help or alternatives would really be appreciated.

### welcome-overlay.js

```
/**
 * @file
 *  Toggles Welcome Overlay, upon first button
 *  clicks toggles different content, second toggles overlay
 */

(function ($, Drupal) {
  Drupal.behaviors.welcomeOverlay = {
    attach: function () {
      var cookieName = 'firstWelcome';
      cookieValue = 'returning';
      cookieDays = 60;

      /** Create Cookie Creation Function **/
      function createCookie(name, value, days) {
        if (days) {
          var date = new Date();
          date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
              expires = "; expires=" + date.toGMTString();
        }
        else {
          var expires = "";
        }
          document.cookie = name + "=" + value + expires + "; path=/";
      }

      /** Check for Specfic Cookie **/
      function readCookie(name) {
        var nameEQ = name + "=";
            ca = document.cookie.split(';');
        for (var i = 0; i < ca.length; i++) {
          var c = ca[i];
          while (c.charAt(0) == ' ') { c = c.substring(1, c.length);
            if (c.indexOf(nameEQ) === 0) {
              return c.substring(nameEQ.length, c.length);
            }
          }
        }
        return null;
      }

    /** Sets value corresponding to cookie existance **/
      var visited = readCookie(cookieName);
          visited2 = document.cookie.search(cookieName);

      /** If Non-existant Create Cookie and Show Content **/
      if (visited === null || visited2 < 0) {
          // $(document).ready(function () {
          // Seconds Before Overlay Slides Over Content
          setTimeout(function () {
            overlay.slideToggle('800', 'linear', function () {
              appearFirst.fadeTo('800', 1, 'linear');
            });
          }, 1500);
          createCookie(cookieName, cookieValue, cookieDays);
      }
    }
  }
})(jQuery, Drupal);

```

### welcome-overlay.module

```
function welcome_overlay_preprocess_page(&$variables) {
  /** Include the jquery.cookie plugin **/
 drupal_add_library('system', 'jquery.cookie');
 /** Attach jquery/css to module **/
  $path = drupal_get_path('module', 'welcome_overlay');
  drupal_add_css($path . '/welcome_overlay.css');
  drupal_add_js($path . '/welcome_overlay.js');
}

```

# Answer
Instead of making a custom cookie, try using Drupal's cookie system.

Set:

```
user_cookie_save(array('key' => 'value'));

```

Get:

```
var = $_COOKIE['Drupal_visitor_key'];

```

---

I just realised this is in php, not javascript as you have used so I will expand. I made my overlay by creating a new page with `hook_menu` and am using `hook_init` to check for cookie values, redirecting to my new page if required.
> 0 votes

---
Tags: javascript, cookies
---


# Question
Title: Render a Views row ID using NID (Node ID)
I can easily add NID (Node ID) as a field in my view and then render it as a class for the Views Row using replacement patterns for the row class of an unformatted typical view. (See screen capture).

However, I'd like to render the NID as an **ID** for each row for use for some special theming I am doing. If I use devel themer, I see my template is `views-view-unformatted.tpl.php` so I can of course copy this template into my theme's template folder with a custom name specific to my view and then theme it.

The relevant line of code in the template that renders the row class is:

```
  <div<?php if ($classes_array[$id]) { print ' class="' . $classes_array[$id] .'"';  } ?>>

```

If I change it to:

```
<div<?php if ($classes_array[$id]) { print ' class="' . $classes_array[$id] .'"';  } ?>
    id="<?php print $fields['nid']->content ?>">

```

...However, this does not work as I don't think fields are available at this level in the views row.

So essentially right now my rendered output is:

```
<div class="views-row views-row-1 views-row-odd views-row-first mynid-63">
<div class="views-row views-row-2 views-row-even mynid-64">

```

... when I'd like it to be

```
<div class="views-row views-row-1 views-row-odd views-row-first" id="mynid-63">
<div class="views-row views-row-3 views-row-even" id="mynid-64">

```

My question, is there a way to just render the associated NID where I want it as an id other then the method I am trying to use?

# Answer
In most Views templates, the entire `$view` object is available. So, assuming you have a `nid` field in the row, you should be able to access it with something like this:

```
$view->result[$id]->nid

```

so, give

```
id="my-nid-is-<?php print $view->result[$id]->nid; ?>">

```

a try in your template.

If this doesn't work exactly, a `print_r($view->result);` up at the top of the template will give you a gander at what you have to work with.
> 9 votes

# Answer
The NID is added via the format settings as last in the class string; ' $classes\_array\[$id\]

Get the last class in the class string (which is the Nid added via views) Then just add the $last as proper ID to the row after the classes

so change this to:

```
<div<?php if ($classes_array[$id]) { print ' class="' . $classes_array[$id] .'"';  } ?>>

```

to:

```
<div<?php if ($classes_array[$id]) {
    $class_string = explode(' ', $classes_array[$id]);
    $last = end($class_string);
    print ' class="' . $classes_array[$id] .'"' . ' id="' . $last . '"';
 } ?>>

```
> 1 votes

# Answer
You need to use the `views-view-fields--[name].tpl.php` for construct the main row div. So, put in your \`views-view-fields:

```
<div id="<?php print $row->nid; ?>">
<?php foreach ($fields as $id => $field): ?>
  <?php if (!empty($field->separator)): ?>
    <?php print $field->separator; ?>
  <?php endif; ?>

  <?php print $field->wrapper_prefix; ?>
    <?php print $field->label_html; ?>
    <?php print $field->content; ?>
  <?php print $field->wrapper_suffix; ?>
<?php endforeach; ?>
</div>

```

The main problem is that you have two `<div>` tags. So you can choose to delete the div into `views-view-unformatted.tpl.php`.
> -1 votes

---
Tags: 7, views, theming
---


# Question
Title: How to change number of item per page in taxonomy page?
I have multiple content types. I want to change number of item per page in teaser mode and it is different for every content type.

In `admin/config/system/site-information` we can change number of item for all content types. But I want to change number of items for each content type.

What do I do? Please help.

.

# Answer
> 1 votes
Go to `Admin > Structure > Views`. Enable the `Taxonomy Term` View :

In views configuration change the pager settings as you want.

---
Tags: theming, taxonomy-terms, 7, paging
---


# Question
Title: How to use Tamil language in my website?
I have installed the language selection page module. I have *Tamil*, *English* language to be chosen by users.

If user chooses *English* means site will appear in *English* Language. If user chooses *Tamil* language means site will appear in *Tamil* language.

So, how can I install *Tamil* language in Drupal 7.34?

# Answer
> 6 votes
Use Internationalization module to make your site multi language. It gives you translate interface for every language you select in configuration.

After enabling the module you have to add *Tamil* as language under `admin/config/regional/language/add`.

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


# Question
Title: Is there a way to swap webform object between nodes?
I have a weird situation.

Webform Localization module allows localization by string translation. That's good, that's what I wanted to use. Sadly, it treats all strings as if their "original" language was English. That's a limit/bug I can live with, but one of my editors created webform under node in another language. I can't simply change node's language, because it's title etc are set up OK. Or rather, I can, but I'll have enough work with Webform already that I want to avoid it.

Is there a way to connect that webform to English node, and connect empty webfrom from English node to this one? i only need to do it once, so it doesn't need to be pretty.

Simply swapping Node IDs in `{webform}` table does not help. It swaps confirmation messages etc (but these i would prefer to leave where they are), but does not swap actual webform components.

# Answer
Simply swapping Node IDs in `{webform}` table does not help, but switching them in `{webform_component}` is.

The way I did it was to swap nids in following tables:

* `{webform}`
* `{webform_component}`
* `{webform_emails}`

I didn't touch submission tables because I was planning to purge them anyway, but for test purposes I needed to swap:

* `{webform_submissions}`
* `{webform_submitted_data}`

That did it. Don't know if it is really enough, but I see no errors after a long time of use.
> 0 votes

---
Tags: webforms
---


# Question
Title: How to add page argument in hook_menu for dynamic callback function?
I'm using groups for my website and I would like to create functions that will work for every group. I've created a tab configuration for every group like this.

```
$groups = group_load_by_type('community');
foreach($groups as $key => $value) {
  $items[CONFIG_GLOBAL_ADMIN_PATH . '/groups/' . $key] = array(
    'title' => $value->title,
    'description' => 'Group ' . $value->title,
    'page callback' => 'drupal_get_form',
    'page arguments' => array('myModule_group_settings_form'),
    'access arguments' => array('administer site configuration'),
    'file' => 'myModule_group.admin.inc',
    'type' => MENU_LOCAL_TASK,
    'weight' => 1,
  );
}

```

It's working pretty well this way, I have the config for all the groups at the `path/groups/groupID` which is what I want.

But I would like to add an argument to my function `myModule_group_setting_form($form, &$form_state)` and do something like this:

```
'page arguments' => array('myModule_group_settings_form', $key->title),

```

and change my function to this :

```
myModule_group_setting_form($form, &$form_state, $groupName)

```

In my function, I'm using variables so the groups can hide some informations if they want. Actually if I want to do this, I have to create a function for every group and do something like this :

```
'page arguments' => array('myModule_group_' . $key->title . '_settings_form'

```

And I have to create a new function every time I have a new group. Since I don't have static groups, and I may have to create others in the future, this way doesn't suits me.

Thanks for your help :)

# Answer
You are creating a new menu for new group. It will be better to use dynamic arguments.

```
$items[CONFIG_GLOBAL_ADMIN_PATH . '/groups/%'] = array(
  'description' => 'Some Group Description',
  'page callback' => 'drupal_get_form',
  'page arguments' => array('myModule_group_settings_form', 3),
  'access arguments' => array('administer site configuration'),
  'file' => 'myModule_group.admin.inc',
  'type' => MENU_LOCAL_TASK,
  'weight' => 1,
);

```

and In your function :

```
function myModule_group_setting_form($form, &$form_state, $key) {
  $groups = group_load_by_type('community');
  $value = (isset($groups[$key])) ? $groups[$key] : NULL;
  if (!$value) {
    drupal_set_title($value->title);
    // Whatever you do with $value->title;
  }
  else {
    drupal_not_found(); exit();
  }
}

```
> 1 votes

---
Tags: 7, hooks
---


# Question
Title: Strange behavior while assigning the role programmatically
I used this code to set role to a user :

```
    user_external_login_register($form_state['values']['name'], 'beneficiaire');
    $account = user_external_load($form_state['values']['name']);
    $form_state['uid'] = $account->uid;
    $account->roles[]= 3;
    user_save($account);

```

My user is weel registered as admin, but if I logout and login, my user has an empty role in addition of the administrator.

Replacing `3` by `administrator` does not fix.

Do you have an idea of what's going on?

Thanks.

# Answer
This is the roles element in $user object ( $user-\>roles )

```
roles => array(
  2 => "authenticated user",
  4 => "Site Administrator",
  6 => "Author",
),

```

You must set the user role like:

```
$user->roles[ROLE_ID] = 'ROLE_NAME'

```
> 0 votes

---
Tags: users
---


title: When hook_field_info_alter is invoked?

text:
# Question
Title: When hook_field_info_alter is invoked?
I am trying drush cc all, but no luck.

https://api.drupal.org/api/drupal/modules!field!field.api.php/function/hook\_field\_info\_alter/7

I need to programmatically hide a field and thinks that this is place to go.

# Answer
> 1 votes
It's invoked in several places. It happens in `_field_info_collate_types()`, which is called from

* `field_info_cache_clear()`
* `field_info_field_types()`
* `field_info_formatter_types()`
* `field_info_storage_types()`
* `field_info_widget_types()`

So there's a fairly large surface area for invocation.

`hook_field_info()` is for providing metadata about fields, though, so using it to programatically hide a field is doomed to failure. You simply don't have that option in the info hook.

Depending on what you mean by "hide" you'll either want to implement a form alter hook (to remove a field from a form), or a preprocess/view hook to hide it from being rendered, or maybe both. Obviously YMMV if you mean something other than those options.

---
Tags: 7, entities
---


# Question
Title: How to delete content of sheetnode spreadsheet field?
I am using the Sheetnode spreadsheet module to upload data. I am looking for ideas on how to clear the contents of the spreadsheet each time the form is loaded.

I have tried setting form state using all the following ways:

```
hottopicsresearchsheet_form_hottopics_node_form_alter() {
  $node = $form_state['node'];
  $node_wrapper = entity_metadata_wrapper('node', $node);
  unset($node->field_spreadsheet[$node->language][0]);
  $form['#node']->field_spreadsheet[$node->language][0]['value'] = "";
  $node_wrapper->field_spreadsheet->set(NULL);
}

function hottopicsresearchsheet_field_widget_sheetfield_spreadsheet_form_alter(&$element, &$form_state, $context) {
  $element['#entity']->field_spreadsheet['und']['0']['value'] = "";
  $form_state['field']['field_spreadsheet'] = array('name' => '', 'value' => '');
}

```

# Answer
Solution I found was to not save the data in the first place. Will make debugging harder, but here it is:

```
function hottopicsresearchsheet_node_presave($node) {
  // Check that the nodes of the type I need and process data...

  // Clear data.
  if (!empty($node->field_spreadsheet[$node->language][0]['value'])) {
    unset($node->field_spreadsheet[$node->language]);
  }
}

```
> 0 votes

---
Tags: 7, entities
---


# Question
Title: Use Webform for multiple possible inputs
I want to create a webform that will replace a excisting excell file (visitors download a excell file, fill it in and send it back to the company). Under here a simplified example of the excell file...

As you can see above the visitor can fill in one line or more lines...

I could make a webform for entering one-line (one product), not so difficult.

But the client should be able to fill in more than one demand (if he wants). So after putting in one demand, there should be a possibility, to say/click add one more...

Don't know if this possible with only "webform" module, or is there a other module for this.

Any tips, links, video's , comments are welcome!

K.

# Answer
The Webform Table Element module will allow you to setup your webform in a tabular format.

But I don't think it allows for unlimited number of lines as an excel sheet would. Still it could be a reasonable (quick) solution for your need.
> 0 votes

---
Tags: webforms, forms
---


title: Force the usage of path aliases

text:
# Question
Title: Force the usage of path aliases
The title is explaining what I'm trying, my question is: Am I doing it right?

```
function hook_entity_view($entity, $type) {
    if (arg(0)=='node') {
        drupal_goto($entity->type.'/'.$entity->nid);
    }
}

```

My aliases look like this: `article/123`

* `article` is the entity type.
* `123` is the node ID.

When I go to ../node/123 than I get a 503.

# Answer
Looks like you are creating loop redirection. But that you can test by examining logs. I believe there is an easier way: already implemented Global Redirect module:

> This module uses hook\_init to interrupt the page load and action the alias lookups. If any of the above rules apply then the appropriate action is taken. If no rules apply then the page load continues uninterrupted. An example of this in use is on the site it was developed for. http://www.sportbusiness.com/node/160559 will redirect to http://www.sportbusiness.com/news/160559/lagardere-sets-up-sports-division due to the alias setup on this site.
> 1 votes

---
Tags: nodes, uri
---


# Question
Title: Is there a module that allow to access a page using a specific URL?
I remember seeing this module a while ago, but can't for the life of me finding it. What it did was to only allow a page to be accessible by a specific link you set for it. So, if you just entered the URL into your browser, you would be redirected to, say, your home page.

Does anyone recall this module?

# Answer
> 0 votes
I remember doing something similar with the Rules module a while ago.

Take a look at the integrations for extended functionality - I think you can use the Tokens module with it.

# Answer
> 0 votes
I see 2 options:

1. By keeping the url just using an alias: http://www.your-site.tld/admin/config/search/path/add

Existing system path * http://www.your-site.tld/node/NID (also=http://www.your-site.tld/lang/content/long-existing-url-blabla)
Path alias * http://www.your-site.tld/here

2. Using a shortened url with the shorten module to create a url alias like yste.co/loc

---
Tags: 7, users
---


title: node:id token from panel or view

text:
# Question
Title: node:id token from panel or view
I have spent 4 days looking for information on many pages without result, I would like to make a view from which to send an email with the information of a node, with view send and user view I can send emails to those I have select.

But my problem is when to send information from the title of the node, the node apparently not sent. From the panel where the view I can show the node to which I Referencing the URL node *`/% node / my_view`*, but apparently not saved when sending mail.

I've found a way to call a certain node with *`[aet: node: title]`* and *`[current-page: url: args: value: 1]`*, but does not work *`[aet: node:% [current-page: url: args: value: 1]: title]`*.

Any ideas?

# Answer
finally I managed to send the fields I need from the node through to post in the view send php code, creating a variable to calculate the node id and then use that variable in the token

```
<?php
$var=token_replace('[current-page:url:args:value:1]', array('node' => $node));
?>

[aet:node:<?php echo $var; ?>:title]

```

This is the list of modules:

1. **tokens,**
2. **token filter,**
3. **views send,**
4. **token tweks,**
5. **Advanced Entity Tokens,**
6. **mime mail,**
7. **mailsystem,**
8. **phpfilter**
> 0 votes

---
Tags: nodes, tokens, views
---


# Question
Title: How to programmatically hide field from display?
I want to reproduce programmatically hiding of a field that can be obtain by Manage Display -\> Format -\> (hidden)

URL: admin/config/people/accounts/fields.

Field I want to hide is added by OG module. Probably. Machine name: og\_user\_user.

I found one solution based on hook\_field\_access but I need to find other.

This solution doesn't help me too.

# Answer
> 1 votes
Solution is pretty damn simple. I forgot about field\_update\_instance function.

To get data for passing to this function there is a need of debug: field\_ui\_display\_overview\_form\_submit

where all Manage Display forms are submitted.

I end up using custom drush command after all custom modules are installed

---
Tags: 7, entities
---


# Question
Title: Restrict access to edit page for specific user
I have 2 accounts where I need to prohibit them from editing the profile. I managed to hide the edit button but when I type edit into the URL it still allows them to edit the user profile.

```
if ($user->uid == 267 OR $user->uid == 268){
} // demo profiles, prohibit editing profile
else{
print l(t('Edit My Profile'), "user/{$GLOBALS['user']->uid}/edit");
}

```

I can't do this based on their role. Thanks

# Answer
> 5 votes
Looks like you're looking for Edit own user account permission.

> This module add 'edit own user account' permission.
>
> The goal of this module to prevent changes in user account information in the demo sites.

Or to do it in code:

```
function mymodule_menu_alter(&$items) {
  if (isset($items['user/%user/edit'])) {
    $items['user/%user/edit']['access callback'] = 'mymodule_user_edit_access';
  }
}

function mymodule_user_edit_access($user) {
  if ($user->uid == 267 || $user->uid == 268) {
    return FALSE;
  }
  else {
     return TRUE;
  }
}

```

---
Tags: users
---


# Question
Title: Error uploading file. An unrecoverable error occurred
I've been troubleshooting a form in Drupal 7 that has two file upload fields.

If you upload a file with one field, then the other, the second upload will usually give an error. This occurs regardless of the order that the files are uploaded. The error does not occur if the files are both added to the "Choose File" fields and the **whole page** is submitted at once with the save button. The error also does not occur if JavaScript is disabled in the browser, and the individual upload buttons are used.

The easiest workaround I can imagine would be to disable javascript for the form controls on the specific /node/add page, but I do not know how to do this, and I have been unable to find people with a similar need.

The server is PHP/Apache2, with mod\_security disabled and with the PHP post size limit and uploaded file size limit set to high limits as per the screenshot. File uploads work normally, leading me to rule out permissions as a culprit.

The watchdog logs and server error\_log have no messages of interest, unfortunately.

If anyone has any advice to disable javascript for a page, or to resolve this error, please let me know. Thanks!

# Answer
This error is for this line in file.module 241 --if (empty($\_POST\['form\_build\_id'\]) || $form\_build\_id != $\_POST\['form\_build\_id'\]) {

You should revise your URL
> 1 votes

---
Tags: nodes, entities
---


title: Batch API callback method is not call

text:
# Question
Title: Batch API callback method is not call
Here is my source:

```
function sc_delete_user_confirm_form_submit($form, &$form_state) {
   //...
      $batch = array(
        'operations' => array(),
        'finished' => 'user_delete_tickets_batch_finished',
        'title' => t('Processing delete user tickets'),
        'init_message' => t('Deleting user tickets is starting.'),
        'progress_message' => t('Processing...'),
        'error_message' => t('Deleting user tickets has encountered an error.'),
      );
      $batch['operations'][] = array('user_delete_tickets_batch_process', array());
      batch_set($batch);
  //...
}

function user_delete_tickets_batch_process(&$context) {
  watchdog('my_module', 'user_delete_tickets_batch_process ENTER!', array(),  WATCHDOG_ERROR);
  //...
}

function user_delete_tickets_batch_finished($success, $results, $operations) {
  watchdog(my_module', 'user_delete_tickets_batch_finished ENTER!', array(), WATCHDOG_ERROR);
  //...
}

```

I see progress bar but it not call my callback method `user_delete_tickets_batch_process` (I didn't see log in `/admin/reports/dblog`), also it not call `user_delete_tickets_batch_finished`. What is wrong in this my source.

# Answer
Try specifing the file where your functions are located.

Even if those functions are in the same file as your #submit callback, the `file` path may be needed.

```
$batch = array(
  'operations' => array(),
  'finished' => 'user_delete_tickets_batch_finished',
  'title' => t('Processing delete user tickets'),
  'init_message' => t('Deleting user tickets is starting.'),
  'progress_message' => t('Processing...'),
  'error_message' => t('Deleting user tickets has encountered an error.'),
  'file' => drupal_get_path('module', 'your_module') . '/your_module.module'
);

```
> 1 votes

---
Tags: batch-operations
---


# Question
Title: How to use Sort By desc by default with toggle link enabled?
I am using better exposed filter and added `toggle link` sorting for a field. But the toggle link sort Asc order on first click. I want to make it Sort Desc on first click.

I tried to write :

```
MyField Desc|MyLabel
MyField Asc|MyLabel

```

But it doesn't work.

# Answer
> 0 votes
I didn't found any suitable way to do this. What I actually did, I changed the link using `jQuery`.

---
Tags: 7, views
---


# Question
Title: Shortcut menu not showing after admin menu installed
I have installed the admin menu module and now the shortcuts menu has disappeared. This is quite confusing

# Answer
Toolbar is the core drupal module which displays the shortcuts near the top of the page, along with an Edit shortcuts link. After installing admin-menu we do not need core toolbar module otherwise it causes redundancy for admin menu,uninstalling the toolbar module causes vanish of shortcut bar with it.

Shortcut bar comes from shortcut module, which simply allows us to place the shortcut block by going to (Administer \> Structure \> Blocks) and look for Shotcut block which by default goes under disabled block.
> 1 votes

---
Tags: 7
---


# Question
Title: Ambiguity of using '.' as a separator in the site directory name might have security implications?
In a Drupal installation, which is served through the web server's default server config (i.e. it gets any request for an otherwise unknown domain) I have a settings file at `DRUPAL_ROOT/sites/example.com.au/settings.php`.

This site is normally requested as `http://example.com.au/`, but what's given that the request gets to the server (and the user agent may not follow the directives of DNS here), what's to prevent it being served as a response for `http://example.com/au/` or `http://example/com/au/`?

The testing I've done suggests something blocks this from working (I get a redirect to the install page), but I want to be clear on what's going on, and to be sure that it's reliable.

If accessing a drupal installation through divisions of the domain name and path other than the expected one is possible, then there would be security implications.

EDIT:

In response to @tenken:

From https://api.drupal.org/api/drupal/sites!example.sites.php/7

> This file allows you to define a set of aliases that map hostnames, ports, and pathnames to configuration directories in the sites directory. These aliases are loaded prior to scanning for directories, and they are exempt from the normal discovery rules. See default.settings.php to view how Drupal discovers the configuration directory when no alias is found.

It's not perfectly clear, but that sounds like the directory in the sites file will will still be used if a request arrives with a domain name that was not anticipated, in which case the problem remains.

# Answer
> 2 votes
Your virtual host rules are as secure as you've written them. If you want complete control on what URLs map to what multi-site installations then use the `sites.php` placed in `sites/sites.php` of your `sites` folder to *explicitly* set what URL(s) go to which Drupal installation using PHP.

The sites.php file resolves the URL -\> site mapping after the webserver directs traffic to Drupal.

**EDIT**

Drupal can be run in multi-site or standalone. This is accomplished on how you configure your webserver. The "problem" you're describing is you want to use multi-site but not have Drupal try to discover invalid site addresses. This is purely dependant on how you setup your webserver.

An example of how to setup *Apache* for multisite might be:

```
<VirtualHost *:80>
  ServerName example.com
  ServerAlias *.example.com
  DocumentRoot /var/www/example.com
</VritualHost>

```

This will resolve example.com to the docroot and any subdomain site at \*.example.com -- including "invalid" subdomains which may not exist and attempt to route to an invalid url as you've described. This is by design by Drupal when using multi-site installation.

How might this be fixed for *Apache*? By fixing Apache vhost entries to limit what valid domains the virtual host is used for. This is not necessarily fixable via Drupal (although I still like using `sites.php` personally).

For instance we can change our virtualhost to the following:

```
<VirtualHost *:80>
  ServerName example.com
  ServerAlias site1.example.com abc.example.com xyz.example.com example
  DocumentRoot /var/www/example.com
</VritualHost>

```

This revised *Apache* virtualhost routes example.com and **exactly** 4 subdomains and no others to the docroot. No other domain traffic will be routed to this drupal installation from the webserver.

A similar technique should be available for most webservers. Your virtual host rules are as secure and as organized as you've written them for your own production servers. I use Nginx as a proxy for Apache on a few websites, and Nginx as the sole webserver for at least 1 site, but I haven't had to try to solve this problem myself using only Nginx (but I'm familiar with the Apache solution above).

---
Tags: multi-sites, security
---


# Question
Title: How to show contact profile and membership details in one Civicrm report?
I had a new profile called "Registration details" for contacts, and the profile fields can be edited in account page.

In my contribution page, membership form is enabled as a sign up form for my members, and the new profile "Registration details" is included in the form.

I would like to have a report to show a summary of contact details, including "Registration details" profile, and filter by membership status.

If I'm using Constituent Summary Report, I can get all the contact details summary, but I can't filter the report to show those with active membership only.

If I'm using Membership Details Report, I can filter the membership status accurately, but can't show the new profile fields of "Registration details".

Is there anyway I can configure it so that I can show both contact details and filter by membership status? Or should I make any changes to the profile?

PS: I'm using drupal 7, with CiviCRM 4.4.6.

# Answer
> 3 votes
Since you are using Drupal it can often be easier in my non-coding experience, to build a View to provide you with these kind of Reports - happy to provide more pointers if that is the direction you end up going

---
Tags: civicrm
---


# Question
Title: Embed a collection of form inside a form
With Symfony2 I can embed a collection of form inside an another form (subform inside form). http://symfony.com/doc/current/cookbook/form/form\_collections.html

I would like know if it's possible inside Drupal 8 please, The documentation (Drupal 8 - Form API) don't talk about that.

Thanks.

# Answer
Drupal forms are very different from Symfony forms.

There is no concept of sub-forms, but there is no limit to the complexity a single form can have as a form is an almost arbitrary render array structure.

A commonly used concept there is #tree. By default, the form input element names are flat.

If want to edit multiple elements in the same form, you can build a structure like this:

```
<?php
$form['#tree'] => TRUE;
foreach ($things as $id => $thing) {
 $form['things'][$id]['name'] = ['#type' => 'textfield', ...]
}

```

Without #tree, you would have multiple textfields named 'name', when set to TRUE, you get something like `name="things[5][name]"`.

In Drupal 7 and earlier, it was complicated to render those nested forms in a table, you needed custom theme functions that then built the actual table. In Drupal 8, it just works, in the above example, you would just need to add something like `$form['things']['#type'] = 'table'` and then each $id will be a table row.

Then you can get all those values in the submit method with $form\_state-\>getValue('things') and process them again in a loop.
> 2 votes

---
Tags: forms, 8
---


# Question
Title: How to access "add a card" page in Commerce Card on File?
I would like to allow users to add a "card on file" outside of the payment workflow. I have authorize.net configured and I'm able to save a "card on file" during order completion. The cards list view appears correctly at the path `user/1/cards`:

This path is provided by commerce\_cardonfile's implementation of hook\_menu():

```
$items['user/%user/cards/add'] = array(

```

So logged in as user 1, I should be able to add a card from the page at the path `user/1/cards/add`

But I get "Access denied"... How can I access a form to add a card outside of the payment workflow?

# Answer
`commerce_cardonfile` looks for a 'create callback' from the payment method modules. `commerce_authnet` does not come with the callback, but this patch adds one:

add\_card\_on\_file-2051357-21.patch

Here is the discussion: https://www.drupal.org/node/2051357

After I applied the patch, `commerce_authnet_cim_cardonfile_create()` was defined on both lines 760 and 1021. I renamed the latter so that Drupal was happy. Then "+ Add a card" became available on each user's "Stored cards" tab. And... it works!

Can I get my +250 points back? ;)
> 2 votes

# Answer
As Clive says, card on file restricted the ability to create cards outside the checkout process and the issue referred in the comments is this one: https://www.drupal.org/node/2051331

If you're using a card of file module version that includes the patch above (anything newer than 9 months as for today), you can try this workaround suggested in the issue: https://www.drupal.org/node/2051331#comment-8296497

```
   /**
    * Implements hook_form_alter().
    */
    function modulename_form_alter(&$form, $form_state, $form_id)
    {
        if($form_id == 'commerce_cardonfile_card_form') {
            if($form_state['op'] == 'create'){
                $form['credit_card']['type']['#prefix'] = '<div class="credit-card">';
                $form['submit']['#suffix'] = '</div';
            }
        }
        return $form;
    }

```

Also this issue might be related as well: https://www.drupal.org/node/2224063
> 0 votes

---
Tags: commerce
---


# Question
Title: How do I update a multi-dimensional commerce product field with Views Bulk Operation?
I'm converting from an old UPS module to the newer Commerce UPS. The old module used integer fields for height, length, width. The Commerce UPS module demands a multi-dimensional field 'Product\_Dimensions'. So I want to update the Product\_Dimensions field with the old data.

I created a View with a VBO column and I selected Execute Arbitrary PHP Script as my operation. Here is my code:

`$product = commerce_product_load($entity->product_id);
$product->field_package_dimensions = array( "und" => array(0 => array( length=>"91", width=>"22", height=>"11", unit=>"in") ) );
commerce_product_save($product);
// dpm($product->field_package_dimensions);`

...the product\_dimensions field is being updated BUT each dimension of the array is being assigned a single character '9'. ie. the length, width and height are all '9'. So clearly there is something wrong with my array assignment?

Can someone tell me what I'm doing wrong? I'm sure it's an obvious mistake... or there is a 'proper' procedure for programmatically updating commerce product fields that I'm missing.

TIA.

# Answer
> 0 votes
For any future travelers.

This may be my ignorance but it seems like you -must- use commerce\_product\_load(), even thought it kinda looks like the $entity object is the same as the $product object.

`$product = commerce_product_load($entity->product_id);
$product->field_package_dimensions = array( LANGUAGE_NONE => array( 0 =>
 array('length'=> $entity->field_length['und'][0]['value'],
 'width'=> $entity->field_width['und'][0]['value'],
 'height' => $entity->field_height['und'][0]['value'],
 'unit'=>"in") ) );
commerce_product_save($product);`

---
Tags: commerce, views
---


# Question
Title: Where I can find examples of Drupal bootstrap levels?
I recently came through some Drupal apps that I needed to send some silent Ajax requests that performs a database update, and nothing else. Every such requests bootstraps Drupal to its full level which, as far as I can see, is a waste of resources.

Where I can find examples that someone would bootstrap Drupal, but not to its full level?

One example is the statistics module in core. `./modules/statistics/statistics.php`. Do you know any others?

Please note this question is not about "how to bootstrap". Rather, in trying to see some examples of applications of it.

Thanks, and hats off everyone in advance.

# Answer
The JS module is specifically for this. It allows you to create ajax callback that only bootstrap to a level you specify via a hook\_js().

So you could either use this module or take a look at its code to see how it works.

Good blog post about it HERE
> 4 votes

# Answer
I think the best place to start answering your question its to look at Drupal's own boostrap implementation.

https://api.drupal.org/api/drupal/includes!bootstrap.inc/function/drupal\_bootstrap/7
> 1 votes

---
Tags: bootstrapping
---


# Question
Title: Is there any backport of "Grouped filters" available in Views 6.x-3.x branch?
In Views 3 (Drupal 7), there is a nice feature when you expose a Views filter, you can select "Grouped filters" option and define a set of conditions.

Is there any module that backports this feature to Drupal 6 Views 3.x branch?

# Answer
> 2 votes
Yes you can do it with Advanced Exposed Forms for views 3 version

> Advanced Exposed Forms (AEF) provides fine grained dynamic data filtering by allowing the "joining" of views exposed filters into groups. AEF provides AND/OR operators between individual exposed filters and between groups of exposed filters. Use AEF to drill down from large amounts of data to specific data sets.

---
Tags: 6, views
---


# Question
Title: Add element to the beginning of form, via hook_form_alter()
Using Drupal 7, I'm trying to utilize Drupal Form API in combination with hook\_form\_alter to place my added inputs **at the beginning** of the form.

I thought the best way to do this was to create a new form element like so:

```
$form['program_list'] = array(
    '#type' => 'select',
    '#title' => t('Select a preferred Program'),
    '#options' => $program_list,
    '#weight' => -1,
);

```

I read the documentation, and it looks like there is a `#weight` attribute. I tried setting the weight to either 0 and negative integers, but my added inputs are still at the bottom.

I then used `var_dump()` to check the weights of my Webform-generated inputs. They were as I expected: a 0-based, incremental weight index.

I also tried placing the elements in `$newform` then using `$form = $newform + $form`, but that as well placed my new inputs at the bottom of the form.

What am I doing wrong?

# Answer
> 2 votes
I've done a terrible hack JS job. Before reading this answer, please see if Clive's answer will work.

My JavaScript for getting my uncooperative selects to move to the top is:

```
jQuery(document).ready(function() {
  var inputs = jQuery('select[name=CampusID], select[name=ProgramID]').parents('.form-item');
  inputs.prependTo('.webform-client-form');
});

```

# Answer
> 5 votes
I was facing the same problem but found the answer thanks to this post: http://drupal.org/node/235354

Problem was that the field I was adding to my web form was not in a group when all the already existing fields were part of the group 'submitted' maybe because this is a webform. So setting the weight to -1000 didn't change anything.

```
function webform_boncommande_form_webform_client_form_6721_alter(&$form, $form_state, $form_id)  {

    $form['my_new_field_name'] = array (
      '#type' => 'checkbox',
      '#title' => t ('My new field is after the others'),
      '#weight' => -1000,
    );

}

```

To correctly make it work I just needed to create my new field inside the group 'submitted' like that :

```
$form['submitted']['my_new_field_name'] = array (...

```

# Answer
> 4 votes
The `#weight` property is indeed the right way to go, it might be that another module that's processed after yours is moving some of the other elements back above yours.

If this is the case you could either try changing the `#weight` to a very low number (I normally go for -1000 when what I'm doing doesn't seem to be having the desired effect), or ensuring that your module's hooks are processed after any others.

The second option basically involves setting the weight of your module to a *higher* number than the others in the `system` table. See How to update a module's weight for more information.

# Answer
> 1 votes
For the next person who comes along with this problem (specific to altering Webform nodes):

The behaviour is caused by the `webform-form.tpl.php` template. Since I wanted something to display before the webform components, I just overrode the template and `drupal_render()`'d my part of the form first.

(You *can* just stick your modifications into the `$form['submitted']` array, but then they start getting processed/stored along with the submission, which was undesirable in my case.)

# Answer
> 1 votes
For adding markup to the beginning of the form, this works (but was not easy to find):

```
 $form['#prefix'] = '<h2>A title</h2>';

```

---
Tags: forms
---


# Question
Title: Fatal Error after creating Custom Display Suite layout
I am using Display Suite and I created a custom layout called ds\_6row when I Flush Cache I get the following error

```
Call to undefined function ds_ds_6row() in /Users/myname/Sites/sitename/sites/all/modules/contrib/ds/includes/ds.registry.inc on line 570

```

I followed the method to create the layout here

My structure looks like this:

```
mytheme
--ds_layouts
---ds_6row
----ds_6row.css
----ds_6row.inc
----ds_6row.png
----ds-6row.tpl.php

```

The code for ds\_6row.inc is:

```
<?php
function ds_6row() {
  return array(
    'label' => t('6 Row Layout'),
    'regions' => array(
    'info_data' => t('Info_data')
  ),
// Add this line if there is a default css file.
'css' => TRUE,
// Add this line if you're using DS 2.x for icon preview
'image' => TRUE,
);
}

```

The code for ds-6row.tpl.php is:

```
    <?php

/**
 * @file
 * Display Suite 6 row template.
 */
?>
<<?php print $layout_wrapper; print $layout_attributes; ?> class="ds-6row <?php print $classes;?> clearfix">

  <?php if (isset($title_suffix['contextual_links'])): ?>
  <?php print render($title_suffix['contextual_links']); ?>
  <?php endif; ?>

  <<?php print $first_wrapper ?> class="group-first<?php print $first_classes; ?>">
    <?php print $first; ?>
  </<?php print $first_wrapper ?>>

  <<?php print $second_wrapper ?> class="group-second<?php print $second_classes; ?>">
    <?php print $second; ?>
  </<?php print $second_wrapper ?>>

  <<?php print $third_wrapper ?> class="group-third<?php print $third_classes; ?>">
    <?php print $third; ?>
  </<?php print $third_wrapper ?>>

  <<?php print $fourth_wrapper ?> class="group-fourth<?php print $fourth_classes; ?>">
    <?php print $fourth; ?>
  </<?php print $fourth_wrapper ?>>

  <<?php print $fifth_wrapper ?> class="group-fifth<?php print $fifth_classes; ?>">
    <?php print $fifth; ?>
  </<?php print $fifth_wrapper ?>>

  <<?php print $sixth_wrapper ?> class="group-sixth<?php print $sixth_classes; ?>">
    <?php print $sixth; ?>
  </<?php print $sixth_wrapper ?>>

</<?php print $layout_wrapper ?>>

<?php if (!empty($drupal_render_children)): ?>
  <?php print $drupal_render_children ?>
<?php endif; ?>

```

# Answer
Have a look in the code for Display Suite, specifically the block mentioned in the error message:

```
function _ds_layouts_scan_theme($theme, &$layouts) {
  $theme_layouts = file_scan_directory(drupal_get_path('theme', $theme) . '/ds_layouts', '/inc$/');
  foreach ($theme_layouts as $file => $values) {
    include_once(DRUPAL_ROOT . '/' . $file);
    $function = 'ds_' . $values->name;
    $layouts[$values->name] = $function();
    $layouts[$values->name]['path'] = str_replace('/' . $values->filename, '', $file);
  }
}

```

Note that when it goes looking for layouts is it prepending your layout name with 'ds\_'.

I imagine this is to prevent functions being included that were not intended for this purpose, a bit like using your module name in place of `hook_` when you implement hooks.

That's why changing your function name worked.
> 2 votes

# Answer
I got it to work by editing ds\_6row.inc. I changed

`<?php
function ds_6row() {`

to

```
<?php
function ds_ds_6row() {

```

If anyone can tell me why this worked. I'll be a happy man.
> 0 votes

---
Tags: display-suite
---


# Question
Title: Override default drupal_set_message() on node creation
I am creating a simple basic module that alters the text of a submit button and should change the default creation message with `drupal_set_message()`.

I've found an example about changing the message, and changed the code a little.

```
 function ask_admin_form_alter(&$form, $form_state, $form_id) {
   if ($form_id == "vragen_node_form") {
     $form['actions']['submit']['#value'] = 'Stel Uw Vraag';
     $form['buttons']['submit']['#submit'][0] = 'ask_admin_node_form_submit';
   }
 }

 function ask_admin_node_form_submit($form, &$form_state) {
   global $user;

   $node = node_form_submit_build_node($form, $form_state);
   $insert = empty($node->nid);
   node_save($node);
   $node_link = l(t('view'), 'node/'. $node->nid);
   $watchdog_args = array('@type' => $node->type, '%title' => $node->title);
   $t_args = array('@type' => node_get_types('name', $node), '%title' => $node->title);

   if ($insert) {
     watchdog('content', '@type: added %title.', $watchdog_args, WATCHDOG_NOTICE, $node_link);
     drupal_set_message(t('Uw vraag is met succes ontvangen en zal zo spoedig mogelijk beantwoord worden.', $t_args));
   }
   else {
     watchdog('content', '@type: updated %title.', $watchdog_args, WATCHDOG_NOTICE, $node_link);
     drupal_set_message(t('U heeft uw vraag met succes gewijzigd.', $t_args));
   }
   if ($node->nid) {
     unset($form_state['rebuild']);
     $form_state['nid'] = $node->nid;
     $form_state['redirect'] = 'node/'. $node->nid;
   }
   else {
     // In the unlikely case something went wrong on save, the node will be
     // rebuilt and node form redisplayed the same way as in preview.
     drupal_set_message(t('Er ging iets mis bij het verzenden van uw vraag.'), 'error');
  }
}

```

Although the form button is indeed changed to my own text, the message won't change when the node is created.

When I copy and paste the whole tutorial, my node messages won't change, but I also get no error messages.

Does anyone knows what is wrong, or how I can change the message using other code?

# Answer
Change `$form['buttons']['submit']['#submit'][0]` to `$form['actions']['submit']['#submit'][0]` in your `HOOK_form_alter()`.

I don't know why that tutorial has you modifying the `$form['buttons']` array. Very few forms will put something as important as the primary Submit button outside of `$form['actions']`, and certainly not a core form.
> 5 votes

# Answer
This: `$form['buttons']['submit']['#submit'][0] = 'ask_admin_node_form_submit';`

Should be this: `$form['#submit'] = array('ask_admin_node_form_submit');` if you want to completely override default form processing.
> 1 votes

# Answer
You can suppress the message with https://www.drupal.org/project/disable\_messages with a regex rule like:

```
Vraag .*? has been created.

```

or if translated

```
Vraag .*? is aangemaakt.

```

Then add your own custom message with Rules or with drupal\_set\_message() in a HOOK\_form\_alter()
> 0 votes

---
Tags: forms
---


title: Views profile2 views

text:
# Question
Title: Views profile2 views
I hope it's okay to ask a why question here. I've got a profile named Expert Information and a Skills field in that profile. I've got 9 users with the Expert role. Now my problem is: When I make a user type of view and make a relationship to profile, I get all 9 users but nothing shows under Skills; however when I make a profile type of view and make a relationship to user, I get results under Skills but this time I get 4 users. Why is that happening and what is the correct way to fulfill both?

Thanks,

K.

# Answer
> 0 votes
It was my bad, the person who originally made the view did not make the relationship properly. But the weird thing is, it worked properly on a Drupal 7.30 installation and broke on 7.34.

---
Tags: views, users
---


title: RewriteRule doesn't work

text:
# Question
Title: RewriteRule doesn't work
Due to request, every page (except the front page) needs to be prefixed with "training"; if the path was first /aboutus, now it needs to be /training/aboutus.

I edited almost every page I needed by rewriting mypage.tpl.php, so to change all path would be troublesome.

I tried to edit the .htaccess file, for example using the following rewrites.

```
RewriteRule ^/training/about$ /about

```

```
RewriteRule ^(.*)/training/about$ $1/about

```

Neither of them works.

Could someone point me to the right direction?

# Answer
> 1 votes
Using rewrite in .htaccess may change how external URLs are handled by Apache, but it won't change how Drupal generates URLs itself. For that you need to change the base URL. Take a look at https://stackoverflow.com/questions/5879190/how-to-set-the-base-url-in-drupal

# Answer
> 0 votes
Try this

```
 RewriteRule ^about-us$  [R=301,L]

```

# Answer
> 0 votes
Rewrite rules in a .htaccess directory are interpreted relative to the directory where the .htaccess file is found (or relative to whatever the RewriteBase directive says, if there is one). It is not relative to the base of the site, so you may need to adapt advice you find on rewrite rules intended to be used from the apache configuration files.

I'm troubled by your saying you've gone through editing your template files. That's almost certainly wrong, and I'd encourage you to add detail so someone can set you straight on that. @Alfred Armstrong's answer is worth paying attention to there, but it might need more fleshing out.

However, to the extent that your question as posed is:

> Due to request, every page (except the front page) needs to be prefixed with "training"; if the path was first /aboutus, now it needs to be /training /aboutus.

I figure what you want is something like:

```
RewriteCond %{REQUEST_URI} !^/(training|$)
RewriteRule ^training/(.*) $1 [R=301,L]

```

Note though that you should probably use R=302 at first while testing this, so the search engines will check back in again to see if the redirect has changed.

---
Tags: theming, commerce, .htaccess
---


# Question
Title: How to create a block with taxonomy terms and their corresponding nodes?
This is what I want to achieve in views:

Taxonomy vocabular "Categories":

Term 1 -\> 3 node titles;

Term 2 -\> 3 node titles;

Term 3 -\> 3 node titles;

# Answer
Well you need to use views\_field\_view module. In you views :

1. Create a view of Taxonomy type
2. Add a filter of Taxonomy Vocabulary = Categories
3. Add filed Term: tid (exclude) and Term: Name
4. Add Global View field pass argument tid (Another view in which contextual filter of tid is added and 3 items are displayed in views configuration)

Done.
> 1 votes

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


# Question
Title: Issue using Exposed filters along with contextual filters in views
I have a view page listing my stories/articles. I have a contextual filter based on the field Country which is a taxonomy term reference field. I have defined the path of the page as article-search/% to accommodate the contextual filter value.

I have an exposed filter on the field article-category which is also of type taxonomy term reference. I use better exposed filters to display the exposed filter values as links.

The contextual filter works fine and I configured the url to display taxonomy name instead of term id. This part works fine but when I click on any of the links in the exposed filter the taxonomy term name for the contextual filter value changes to %25 instead of the taxonomy name and the contextual filter fails. It works fine if I use the default dropdown option for the exposed filter instead of better exposed forms.

Any idea if there is an issue with better exposed filters when used along with contextual filters?

# Answer
> 0 votes
Sorry! I should have looked at the issue queue. There is already an issue logged for this. Here is the link to the issue https://www.drupal.org/node/2179169

The issue got resolved when I applied the patch provided by Jim Keller in the issue link https://www.drupal.org/files/issues/better\_exposed\_filters-fix\_exposed\_block\_link\_path-2179169-1.patch

---
Tags: 7, views
---


# Question
Title: Possibility to limit old content that is displayed to a new user
I am setting up a website with Drupal 7. I would like to provide premium content for subscribers on monthly basis. I would like provide ability to buy a recurring subscription.

To avoid leeching old content, that has previously been published, is it possible to limit visibility of blog posts form history?

Let me try to clarify the use case:

I would like to provide content to my Premium subscribers in December 2012. All the users that are members in December 2012 would be eligible to see all the content created then. Since I would like this type of subscription to be real time, it would need to restrict the usage of content created before one's membership. When January 2013 arrives, I would like to have recurring membership continue, but new users that arrive in January, would be restricted to content that have been published only when they are subscribers.

The best would be, that if one purchased Dec 2012, left Jan 2013 away and resubscribed Feb 2013, he or she would see material produced in Dec 2012 and Feb 2013, but not Jan 2013.

Dripping Content would be nice, but I am not providing that kind of cumulative courses but time based content instead, and would not like to provide new users the ability to leech all the old material that they've not paid for at the time.

Thank you in advance!

# Answer
> 1 votes
To do this, you probably should implement `hook_node_access($node, $op, $account)`.

You should return:

* `NODE_ACCESS_ALLOW` if content is new, or user have *premium* role
* `NODE_ACCESS_DENY` if content is old and user does not have *premium* role
* `NODE_ACCESS_IGNORE` if you do not want to control access for this content type

There are already contributed modules to sell roles, or to take payments, so this part should be easy.

Note that hook's documentation says:

> See Node access rights for a full explanation.

I strongly advise to do it.

---
Tags: 7, users
---


# Question
Title: How to change the View Mode based on theme?
I am using the ThemeKey module to change the theme for mobile users. I have a custom View Mode called Mobile to display different content. I would like to have when my mobile theme is loaded for the node to use the Mobile View Mode that I created instead of the Default View Mode.

I would like to do this in the theme. Either hooking into the theme with a module or just placing the php in a template override.

Thanks!

---

Ok I found a few items that get my closer to what I am needing. I just can't seem to get it to work. I am testing this idea with the teaser for now.

```
<?php
$rendered_teaser = render(node_view(node_load($nid), 'teaser'));
?>

```

By using the node number I am able to get it to print in the page.tpl.php file fine. But I am wanting to get the node I am on and convert the view mode from full to teaser.

```
<?php
$rendered_teaser = render(node_view(node_load(2), 'teaser'));
?>

```

I found that information be reading the links below. I am still not able to get it to work but close. For some reason I get errors. I think it has to do with me placing it in the node.tpl.php and the page.tpl.php template file.

http://drupal.org/node/985022 http://drupal.stackexchange.com/questions/36028/getting-the-auto-summary-from-a-node-bodyhttp://drupal.stackexchange.com/questions/23961/print-result-of-a-node-load

---

And I got it working. Any comments appreciated. I placed this on the top of the page.tpl.php.

```
<?php
$nid = $node->nid;
if ($nid) {
 $nid = $node->nid;
 $rendered_view = node_view(node_load($nid), 'teaser');
}
?>

```

And I placed the print rendered\_teaser where I wanted the node view to be printed.

```
<?php
if ($nid) {
 print render($rendered_view);
}
 else {
  print render($page['content']);
 }
?>

```

# Answer
Since your mobile theme is a different theme a viable alternative is to just use the same display modes everywhere and then theme that display mode differently by overriding the node.tpl.php file differently in each theme.
> 1 votes

---
Tags: theming, entities
---


title: Clone SelectQuery doesn't seem to work

text:
# Question
Title: Clone SelectQuery doesn't seem to work
I want to change the sorting of a view with something very specific which needs 2 subqueries.

So far, I tried to do something like this:

```
$sorted = false;

function mymodule_query_alter(&$query) {
  global $sorted;

  $view = $query->getMetaData('view');
  if( !$sorted && $view->name == 'my_view' ) {
    $sorted = true;

    $subquery_1 = clone $query;
    $subquery_2 = clone $query;

    // Apply sorting stuff...

    $query = $subquery_1->union($subquery_2);
}

```

Then I just realized that this desn't even work (while my view is working):

```
$subquery = clone $query;
$query = $subquery;
dpm($query->__toString());
dpm($query->arguments());

```

It doesn't return any result, but everything seems ok in the dpm dump.

Have I done something wrong? Or maybe should I handle this problem in another way?

EDIT:

I need to get a list of nodes sorted this way:

1. Sticky nodes | order by date.
2. Nodes in one of the taxonomy-term selected in user profile | order by date.
3. Other nodes | order by date.

I've already a working SQL request (actually 3 with `UNION`), but I need to make it work with Drupal.

# Answer
> 1 votes
So, I was working on a test for @Mołot to reproduce the `clone` bug, and I couldn't with a fresh view.

I tracked down the difference :

* With the filter `Published or admin`: the cloned query didn't return anything.
* No problem with the simple `Published` filter.

Don't ask me why.

As @autopoietic said, working with core `query_alter_hook` wasn't a good idea. I switched to views hook, and got the `SelectQuery` object :

```
function mymodule_views_pre_execute(&$view) {
  $query = &$view->build_info['query'];
}

```

Then I was able to do my sorting.

---
Tags: 7, views, database
---


# Question
Title: Displaying articles created by user in profile page using views
I want to display the articles created by user in user profile page. It should also display to anonymous user also.

**For example** : `twitter.com/google` displays all tweets by google.

Like that I want to display `xyz.com/john`. I want to display all articles created by john in user profile page.

I also want to know how to add that view to profile page.

# Answer
* Create a view for content of type all
* Inside the view display node title and all other fields as per your requirement.
* Add a contextual filter content : author uid
* While adding that you will have a option for provide a default value
* select that option and inside that use filter by 'currently logged in user'.
* Save it by this you will be able to see all the nodes of current logged in user.
* Inside the path you can enter just any path like '/my-nodes'. and you are done.
* If you want you can avoid providing default value and switch to manual input by placing the path as '/my-nodes/%' and then just add contextual filter as 'content : author:uid' without default value(depends as per the requirement).
* For user name you can add a relationship **content author:uid** then
in the contextual filter use **User name** with relationship **author:uid**
> 0 votes

# Answer
Add a contextual filter to your view:

User: Uid (if it is not available -\> define a relationship to User)

Now select in the section "When the filter value is NOT available" the value "Provide default value" and choose "User ID from url". Additionally you can specify a validation criteria to accept UIDs and user names.
> 0 votes

---
Tags: views
---


# Question
Title: Automatic base URL not picking up https://
My Drupal site is using https:// but the base URL is not using it.

My site therefore is not opening properly. Is there any way to make Drupal pick up the correct base URL?

I tried adding `$base_url` in settings.php but it's giving me this error:

> GET https://example.com/js/admin\_menu/cache/6599fa6c7ea0ac232a88eaa63e957878 404 (Not Found)

# Answer
Try setting the $base\_url on the protocol:

```
  $base_url = ((isset($_SERVER['HTTPS'])) ? 'https://' : 'http://') . 'www.yoururl.com';

```
> 0 votes

# Answer
You need same thing : How to get the base url?.

```
function _get_base_url(){
  $protocol = ($_SERVER['HTTPS'] && ($_SERVER['HTTPS'] != "off")) ? "https" : "http";
  return $protocol . "://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
}

```
> 0 votes

---
Tags: ssl, uri
---


# Question
Title: How to give pagination for Rest Service data
I am using Rest Service and pull the data from another non drupal db.

I wrote *custom module* with two form elements and render that data (rest service call) and display using theme table.

I wrote `$form['pager'] = array('#theme' => 'pager');` for pagination.

Pagination is working only for data which rendered using db query. In my condition it's not working.

How can I add pagination for my table.

```
 function myForm($form, &$form_state){
 pager_array_splice($final_data, 10);
foreach($final_data as $key => $value){
     $source=explode('=',$key);
     $options[]=array(
        'Token_Source'=>$source[0],
        'Tokens'=>$value,
     );
}

$form['pagerTop'] = array('#theme' => 'pager');
$form['entities'] = array(
  '#type' => 'tableselect',
  '#header' => $header,
  '#options' => $options,
  '#attributes' => array('class' => array('entity-sort-table viewTable tokensTable')),
  '#empty' => t('There are no Notification ....'),
);
$form['pagerBottom'] = array('#theme' => 'pager');
return $form;
}
function pager_array_splice($data, $limit = 9, $element = 0) {
print_r($data);
global $pager_page_array, $pager_total, $pager_total_items;
$page = isset($_GET['page']) ? $_GET['page'] : '';

// Convert comma-separated $page to an array, used by other functions.
$pager_page_array = explode(',', $page);

// We calculate the total of pages as ceil(items / limit).
 $pager_total_items[$element] = count($data);
$pager_total[$element] = ceil($pager_total_items[$element] / $limit);
 $pager_page_array[$element] = max(0, min((int)$pager_page_array[$element],     ((int)$pager_total[$element]) - 1));
 return array_slice($data, $pager_page_array[$element] * $limit, $limit, TRUE);
}

```

# Answer
```
  $row = pager_array_splice($options, 10);

$form['pagerTop'] = array('#theme' => 'pager');
  $form['entities'] = array(
  '#options' => $row,
  );

```

please assign $row value in the theme table
> 2 votes

---
Tags: 7, paging
---


title: Restrict blocks to specific pages

text:
# Question
Title: Restrict blocks to specific pages
I am using someone else's theme on a very small site.

Specifically, I want to display blocks on specific pages. I am able to display blocks on only and on all pages except .

My understanding is that I should be able to display a block only on page "what-we-do" putting what-we-do where I put .

Alternatively I code put node/7 (this page being node/7).

The result is that the block is displayed persistently on the front page and on no others.

This is clearly nonsensical and either I am doing something very silly or I need to start reading through the code.

My question, precisely: has anyone encountered this problem before and can they suggest a way forward?

# Answer
> 2 votes
Sumit Madan was spot on. Several blocks were hard coded as front page only in the page.tpl in the contributed theme.

For other newbies caught out by hard coding, the cues are:

* The visibility settings for a block behave erratically, i.e., in a pattern not consistent with your expectations
* When you inspect the regions (/Structure/Blocks - at the top), some of the regions do not appear. Yet, you can put a block into them and the show up when you inspect under Firebug. Now I understand the problem, a quirk that had puzzled me is fully explained.

To find the hard coding in page.tpl, look for ($is\_front) and change that to ($page != 0).

page=0 refers to pages like lists of taxonomies. So this edit means the relevant blocks will be available to all pages including the front page and can be managed using the block visibility as usual.

Thanks everyone.

---
Tags: blocks
---


# Question
Title: How to apply pager in a table using theme function?
I am rendering and displaying data using theme table. I'm using

```
   $form['pager'] = array('#theme' => 'pager');

```

for displaying pagination. Now my intention is to display pager in two areas of screen. One is above the theme table and another one is below. I placed this code two times but pager is coming only once.

Can anyone please help me?

# Answer
> 1 votes
Added the below lines in above and below theme table script.

```
     $form['pagerTop'] = array('#theme' => 'pager'); and
     $form['pagerBottom'] = array('#theme' => 'pager');

```

---
Tags: 7, paging
---


title: Equivalent of search_data() in Drupal 8

text:
# Question
Title: Equivalent of search_data() in Drupal 8
Is there any function equivalent to the (D7) search\_data() in Drupal 8? I would like to get the search results as a renderable array or html for a given keyword programatically.

In D8, the SearchController.php provides the view which does the same, but I'm not sure how to call that from my module?

It uses

```
$plugin = $entity->getPlugin();
$plugin->setSearch();
$plugin->buildResults();

```

to get the result.

How do I create the SearchPageInterface entity which contain the getPlugin() method? Or is there a way to create an instance of the default search plugin directly?

My requirement is to show the search results in a custom page where the search results are wrapped by the custom page content. I've implemented this in D7 using search\_data function. How can I achieve similar result in D8?

# Answer
> 2 votes
You don't create the search page entity, you load it. SearchPage::load($id). Either hardcode the id that you use on your site or make it configurable through configuration/settings/URL.

# Answer
> 0 votes
You could try hook\_search\_page to Override the rendering of search results.

You could also look into search\_data API.

# Answer
> 0 votes
Maybe, by example:

```
$query = \Drupal::entityQuery('node')
->condition('type', 'article')
->condition('title', 'cat', 'CONTAINS')
$nids = $query->execute();

```

Return a list of node ids where the field "title" contain the word "cat". After you can use:

```
$nodes = entity_load_multiple('node', $nids);

```

---
Tags: search, 8
---


# Question
Title: How can I redirect a user after adding a node that also added a new taxonomy term?
I have a content type with a Taxonomy for locations, these locations can be placed inside parent locations (f.ex United Kingdom -\> England -\> London), and it is set-up such that the end user can add taxonomy terms that do not currently exist when creating this content.

What I would like to achieve is upon creating a node that ALSO adds a NEW taxonomy term, is to redirect the page to the list of terms page so that the end user can categorise the new location appropriately.

Is this possible?

# Answer
> 1 votes
I'm not positive I understand the *why*, but the redirect-on-saving-new-node-with-new-terms bit should be reasonably straightforward.

I've suggested two possible methods below because the timing of db inserts/updates etc around node creation is a bit intricate, and you may need to shift the task to an earlier or later stage in the process. For example, the API docs mention that the db write cannot be presumed to be complete during `hook_node_insert()`, and it definitely won't be on `hook_node_submit()`. So your mileage may vary :)

You'll need to create a custom module (here's a stackexchange question on creating modules if you don't already know how) that either:

1. implements hook\_node\_submit()

This is the very likely to be the simpler/more reliable of the two methods.
2. implements hook\_node\_insert()

In this method, it is possible that `drupal_goto()` will conflict with the redirect specified in the node form's `$form_state['redirect']`, so it's probably the worse of the two possibilities.

## Method 1: implement `hook_node_submit()`

From inside `yourmodule_node_submit()`, you'll need to:

1. **Make sure that a node with this `nid` does not already exist**!
2. find out what terms (if any) are in the new node (`$node` is passed into the function)
3. load all the terms for the relevant vocabulary, probably with taxonomy\_vocabulary\_load()
4. check to see if any of the node terms are *not* in the full list
5. modify `$form_state['redirect']` if required

See drupal\_redirect\_form() for a bit more information on what happens with `$form_state['redirect']`.

## Method 2: implement `hook_node_insert()`

From inside `yourmodule_node_insert()`, you'll need to:

1. find out what terms (if any) are in the new node (`$node` is passed into the function)
2. load all the terms for the relevant vocabulary, probably with taxonomy\_vocabulary\_load()
3. check to see if any of the node terms are *not* in the full list
4. if that's true, use drupal\_goto() to redirect accordingly

---
Tags: 7, nodes, taxonomy-terms, hooks
---


# Question
Title: How to replace metatag description using views argument?
I'm having trouble while trying to use views arguments for replacing metatags description.

In the view title you can easily add the view argument for example "Blog posts in category %1" so the "%1" is the first argument and it's replaced in the view title, but it does not work for metatags.

For example I want the description of the metatag to say "Blog posts about %1 in example blog"

Is there any way so that view argument works for metatags?

# Answer
> 0 votes
I found that in the available tokens for the metatags while configuring the view, I can access the url arguments with this token \[view:url:args\]

---
Tags: 7, meta-tags, views
---


# Question
Title: How do I create a summary that is grouped by years first and then months in Views using contextual filters?
Instead of the default formatted result of «Created year + month»:

```
 - Diciembre 2014 (12)
 - Noviembre 2014 (20)
 - Octubre 2014 (23)
 - ...
 - Diciembre 2013 (13)
 - Noviembre 2013 (34)

```

I would prefer something like:

```
2014
 - December (15)
 - November (14)
 - October (12)
 - ....

2013
 - December (19)
 - November (21)
 - October (13)
 - ....

```

I'm using Drupal 7.

# Answer
In Views you can group results (e.g., by year), which can be found in the format settings. Within each group, the results are sorted according to your sorting criteria.

Although not exactly the same question, I think the answer of Views: how to ASC sort the grouping field #1 and sort DESC its content? is still applicable to your question.
> 0 votes

---
Tags: 7, views
---


# Question
Title: Set value for start/end date field labels in hook_form_alter
how can I replace the labels of start/end date for a date field via form\_alter? the code below only works for the fieldset. The "to" needs to be removed.

```
$form['field_my_dates']['und']['0']['#title'] = t('My new title');

```

Code below not working neither, please help me to figure out how to do it! I forgot to mention that I'm using the popup widget for the date field.

```
function mywebform_date_combo_process_alter(&$element, &$form_state, &$context) {
    if ($element['#field_name'] == 'field_my_dates') {
        $element['value']['#date_title'] = 'From';
        $element['value2']['#date_title'] = 'To';
        $element['value2']['#title'] = t('');
    }
}

function mywebform_date_part_label_date($vars) {
    if ('field_my_dates' == $vars['element']['#field']['field_name']) {
        return t($vars['element']['#date_title']);
    } else {return t('Date');}
}

```

# Answer
> 0 votes
Something similar to below might help,change combo field title from 'to:' to none:

```
function mymodulename_date_combo_process_alter(&$element, &$form_state, &$context) {
    $element['value2']['#title'] = t('');
}

```

To change From and To date field labels,implement

```
function mymodule_date_part_label_date(&$vars) {
    if ($vars['element']['#field']['field_name'] == 'yourfield_machine_name') {
      if ($vars['element']['#date_title'] == 'Date Start date') {
        return t('Date (From:)');
      } elseif ($vars['element']['#date_title'] == 'Date End date') {
          return t('Date (To:)');
        }
    } else {
        return t($vars['element']['#date_title']);
    }
}

```

---
Tags: datetime, entities
---


# Question
Title: How to add additional query parameters to a views page url?
I have a view with two displays as page. I need the URL of the pages as `gallery?display=grid` and `gallery?display=slideshow` and filter the views based on the additional parameter 'grid' or 'slideshow'.

Can anyone help me with this?

# Answer
> 0 votes
You can load different displays by using the views\_get\_view\_result() function.

```
$grid_view = views_get_view_result('YOURVIEWNAME', 'grid');
$grid = $grid_view[0];

```

More documentation is found here and here

---
Tags: views
---


title: Use Plugin Field inside buildForm()

text:
# Question
Title: Use Plugin Field inside buildForm()
In Drupal 8, I use this code inside my buildForm() method:

> ```
> $form['medias']['file'] = array(
>   '#title' => t('Image'),
>   '#type' => 'managed_file',
>   '#upload_location' => 'public://image_example_images/',
>   '#multiple' => true,
> );
>
> ```

(Bad) Result: https://i.stack.imgur.com/ju0ZU.png

I would like know if it's possible to use a plugin of type "field widget" inside BuildForm() for call and use a field of Image type provided by the core of Drupal:

Thanks.

# Answer
Possible?

Probably. But it would require a lot of work, as you would basically have to provide all the data and calls that such plugins need. That is very likely more work than re-implementing this functionality yourself.

And creating an entity type would only make sense if you need to manage multiple "things" that each has images attached.
> 0 votes

---
Tags: entities, 8, media
---


# Question
Title: How to create a node after one node created
How to create a node after one node created.

I have a node type of 'notifications'. I need to create an entry into that after my another content type('policy') created or updated.

I tried the `policy_entity_insert` function. Inside that I saved the 'notifications' node by the help of `node_save()`. But it is throwing the below error

```
Fatal error: Maximum function nesting level of '100' reached, aborting! in /var/www/dev/theme/includes/module.inc on line 327

```

# Answer
> 2 votes
hook\_entity\_insert is a drupal hook, not exactly a function. This hook is invoked every time an entity is created, it can be node of any type, user, comment or whatever.

I think issue might be because of infinite loop running because of probable use of node\_save() inside the hook\_entity\_insert() implementation which means every time node\_save() is called hook\_entity\_insert() will be invoked, inside which node\_save() will be called again, thus creating non terminating loop.

I would say you better use hook\_node\_insert instead of hook\_entity\_insert, this will not solve the problem but would be node specific hook\_implementation instead of broad entitywise.

for solution simple put a check something like inside your hook\_node/entity\_inert implementation.

```
  if($node->type == 'policy') {
    // your node save code goes here
    node_save($my_notification_node);
  }

```

# Answer
> 2 votes
This is very simple with Rules

1. Create a new rule, with react on event "After Saving New Content" then restrict by type "policy".
2. Add action "Create new entity", then for entity type, select "node".
3. Select content type "Notifications", add a value for title (use tokens for unique page titles), and use data selector for author.

Then either clone the rule, or add an event "After updating existing content".

---
Tags: 7, nodes
---


# Question
Title: How to insert user registration data to non-drupal table
I installed drupal 7.34 with oracle database. Now i need to save user registration data to another non-drupal table. User authentication also need to do with these non-drupal database field. Is there any method to generate the per-existing set of users in non-drupal database as drupal users.

# Answer
This looks similar to what happens when someone tries to access CiviCRM tables from Drupal when the CiviCRM tables exist in different database containers.

https://www.drupal.org/node/1569656.

Are these tables in the same database container or just on the same database server?

You may want to look at How to use separate databases for Drupal tables?

It might also be worth looking at http://wiki.civicrm.org/confluence/display/CRMDOC44/Creating+a+Drupal+user+for+every+CiviCRM+contact

That gives both a manual process of generating Drupal users from a CSV export as well as the drush method.
> 1 votes

---
Tags: 7, users
---


title: New commerce product doesn't have price

text:
# Question
Title: New commerce product doesn't have price
I am trying to figure out what's the problem with my code. It creates the product, but the price field is allways empty.

```
$cp = commerce_product_new('deposit_temp_'.$_POST['importe']);
$cp->is_new = TRUE;
$cp->revision_id = NULL;
$cp->status = 1;
$cp->created = $cp->changed = time();
$cp->sku = 'deposit_temp_'.$_POST['importe'];
$cp->title = t('Booking deposit');
$cp->language = LANGUAGE_NONE;
$cp->commerce_price['und'][0]['amount'] = 20;
$cp->commerce_price['und'][0]['currency_code'] = commerce_default_currency();

commerce_product_save($cp);

```

# Answer
The price/amount is wrong. You do not have enough significant digits. Commerce works via a base price. Example:

A product that costs $20.00 (USD) is expressed as 2000 in Commerce. Basically all prices in Commerce should have the decimal point moved to the right by two or essentially multiplied by 100 and remove all significant digits to the right of the decimal point.

So in your case the price should be 2000 not 20.

Also I would like to point out a security issue in your code. You are consuming a $\_POST global variable directly into Drupal without first cleansing the $\_POST. This could open your site up to XSS attacks. You should first past the $\_POST global variable through filter\_xss() before using the contents of that global variable. Also note that Drupal Core offers ways to consume post variables if you use hook\_menu for the page that this is running on.
> 1 votes

---
Tags: commerce
---


# Question
Title: Securing folder in Custom Module for Drupal 6
I wrote a custom module, which logs errors to an external text file. The files are kept in

```
/sites/all/modules/custom/my_module/logging/

```

The problem is, if the user know the name of the file, they can go directly to it. For example, if they go to:

```
http://localhost/MySite/web/sites/all/modules/custom/my_module/logging/

```

The will get a forbidden error. But, if they know the name of the document and go to:

```
http://localhost/MySite/web/sites/all/modules/custom/my_module/logging/myFile.txt

```

the full file is rendered to the browser. Is there a way to prevent this? Ideally, I would like to show the files to certain users but at the very least prevent it all together.

# Answer
The real problem here is that the files shouldn't be written into the module directory. There are actually two reasons for this (one of which you've run into):

1. it becomes harder to upgrade the module codebase (i.e. because you have to worry about accidentally overwriting the log files)
2. anybody can access the files (i.e. this question!)

You mention that you'd like *certain users* to be able to access the log files. You have a few options:

1. **Move the logfile directory outside of the webroot**

In other words, if your Drupal site resides at e.g. `/home/foo/public_html`, create a new directory at `/home/foo/module_logs` and write the files there instead.

This prevents **Apache** (or whatever webserver) from delivering the file, but lets it remain accessible to PHP which access it directly from the file system.
2. **Deny access to the files in their current location**

Assuming you're using Apache, you can use a `.htaccess` file in the directory where the files are written to deny access to them. Some variant on this should work:

```
<FilesMatch "\.txt$">
Deny from all
</FilesMatch>

```

As in #1, your module will still be able to read the files (this is what also happens in Drupal's default .htaccess file--you can see that it denies access to e.g. `.info` files, but Drupal can obviously still read them...)
3. **Turn on private file downloads**

I don't really suggest this to solve your problem, as it's kind of the 'nuclear option' and would affect every file controlled by Drupal. You can find this under the file system settings in the administration area.

In options 1 and 2, you will have to alter your module. In this one you probably wouldn't need to, but you might need to modify everything else in your site :-)
4. **Use file system permissions**

Again assuming this is running on an Apache webserver, you could also have your module set the **o** ('other users') bit of the log files' permissions to zero using PHP's chmod() function.

In other words, your files are probably being created with permissions `644`, so you might try creating them with permissions set to `640` instead. Your PHP scripts (i.e. Drupal) should be unaffected unless you change the first or second digit.

In addition to being Apache-specific, this item also might work differently than expected if your Apache-PHP setup is different than I'm expecting.
> 2 votes

---
Tags: 7, security
---


# Question
Title: JQuery Accordion closes unintended when ajax-link from inside gets response
I'm working on a page where a user can click on ajaxified links inside a JQuery-Accordion-Widget.

Currently every time a link is clicked and the response is loaded, the accordion gets closed and it is not possible to click it anymore - but no JS-error is raised.

Did i miss something i have to call i.e. to change the focus ?

Thanks for your help, piezo.

# Answer
> 0 votes
You can probably use one of the jQuery Accordion API functions to manually control the state of the accordion

e.g:

```
// getter
var active = $( ".selector" ).accordion( "option", "active" );
// setter
$( ".selector" ).accordion( "option", "active", 2 );

```

more info here

# Answer
> -2 votes
the event is ajaxSuccess on the child .ui-accordion-content divs

---
Tags: ajax, javascript, navigation
---


# Question
Title: Drupal Calendar highlight all days in block with views
I have calendar showing dates (start and end dates). When I create a calendar from the views template it adds several displays. The month display shows shows all days from the start to the end day highlighted with another color. But in the block display it does not highlights those days.

Below is the month display. I need the same in the block display.

# Answer
> 0 votes
This is a theming issue. Inspect the classes of the boxes in the calendar, you will probably find `.current-month` or something similar in there for the boxes in the month being shown. Then edit your theme's CSS (or SASS) with:

```
.current-month{
  background-color: [color-you-desire];
}

```

---
Tags: views, datetime
---


# Question
Title: Is Drupal internationalization development effort embracing the new "Entity Translation" method? Is it ready for use?
I'm working on standing up a new Drupal 7 site that will have content in multiple versions, and as I'm reviewing the i18n module, I see that there are now two methods for translating content: "Content Translation" and "Entity Translation."

However, the articles I've found on this are all several years old. I would have expected that, by now, there would be consensus built around the "blessed" method of doing content translation, but I can't seem to find anything except "we're moving towards entity translation, hopefully it will be done soon," and this is all in posts that are years old--so maybe by now it is done? But I just can't find the posts saying it's ready?

So, is "Entity Translation" ready for prime-time, and it's the current method recommended by Drupal (the team)? I'm looking for an authoritative reference (e.g., post by someone on Drupal or i18n team, or a respected Drupal community member), that gives the current state of affairs for Drupal internationalization.

Thanks!

# Answer
> 0 votes
Let me start by stating that I am not on the i18n team, nor very involved in the development of Drupal. But I have been working with Drupal multilingual sites for over several years, where we switched to entity translation about 2 years ago. I have done the same search as you are doing now and these are my findings.

The article you've found already covers the main things, and entity translation in my opinion is more the Drupal way. The whole translation system already went into the D7 Fields API where a value is accessed like this:

```
$field[LANGUAGE_NONE][0]['value'];

```

Most examples will use `'und'` (the value of the constant `LANGUAGE_NONE`) for the undefined index, but it can also contain a language code. Thus fields in D7 are already multilingual.

In my opinion the entity translation module uses this in a more effective way, where one piece of content, one node with one id is being linked to one field, which is used to serve content in several languages. Rather then having several nodes, each being in another language and linked to the others.

For us this solved problems when fetching certain nodes by id in an external system and finding out it had the wrong language etc.

I know entity translation is still in Beta, but over 2 years I never had an issue with it. Also note that at the bottom of the entity translation project page it states that it is in D8 Core now (although under the name of content translation). I've just tested this on a local machine and there is indeed one node for several languages, so it at least looks like entity translation is in place. Those things made me assume this is the Drupal way.

Hope this helps somewhat in making a decision.

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


# Question
Title: How to set default body message for Privatemsg embedded on page?
This is the code I used on the node template and block, I just tried it both

module\_load\_include('pages.inc','privatemsg');

$recipients = array(user\_load(arg(1)));

$subject = 'This is just a default that can be changed';

**$body = 'Again, this is just a default that can be changed';**

print drupal\_render(drupal\_get\_form('privatemsg\_new', $recipients, $subject, **$body**));

The **Bold** ones are the codes I added from the orginal code I got from here: https://www.drupal.org/node/624528

But I'm getting this message when I added the $body:

> You can not reply to this conversation because all recipients are blocked.

I've looked into the parameter of privatemsg and it says that the $body is the body text of the new message.

I would like to put some default body message on the embedded privatemsg.

I tried to edit the body via custom module, still no luck for me. I'm not sure where I went wrong.. here's the code on the custom module

```
function sassy_hook_form_privatemsg_new_alter(&$form, &$form_state, $form_id) {
   $form['privatemsg_new']['body'] = array(
    '#type' => 'textarea',
    '#title' => t('Message'),
    '#rows' => 6,
    '#weight' => 0,
    '#default_value' =>  t('Message'),
    '#resizable' => TRUE,   );
}

```

I also tried $form\_state\['values'\]\['body'\] = 'Hello World';

Is there any way to do this?

What am I missing?

# Answer
> 0 votes
Have a look at the descriptor of the `privatemsg_new` function in privatemsg.pages.inc:

```
privatemsg_new($form, &$form_state, $recipients = '', $subject = '')

```

It doesn't take a `$body` argument so you will need to alter the form once it has been created.

1. Make a custom module
2. Use hook\_form\_FORM\_ID\_alter
3. Set $form\_state\['values'\]\['body'\] to your desired value

# Answer
> 0 votes
Nice attempt with the module, but you have a bit more to learn about hooks.

1. Your module name should *replace* the word 'hook' in the function name (case sensitive).
2. Make sure you turn on the module and clear caches before testing so that Drupal knows the hook is there.

You might find that `$form['privatemsg_new']['body']` is the wrong place to be putting your new item, but once the hook registers you'll be able to play around with it until you get it right.

---
Tags: privatemsg
---


# Question
Title: Create a block with contextual filter that show related nodes based on field value, not with taxonomy
I'm no newbie to Views or Argument/Contextual Filters, but I'm having trouble getting my head around a (simple) view.

I've created a Content-type "**Event**". Which contains an 'Addressfield', which I use to store an Address and Geocode it to an value which I store in Geofield.

What I'm trying to accomplish is a 'related nodes' block, similar to an 'related articles' based on taxonomy. In that case you make a relationship, and use the NID in de URL.

I've created a View: \- a block style. \- added a 'contextual filter #1': \- When Filter value is not available: 'provide default value', content id from URL. \- Extra: exclude. This filter excludes the current node.

I'm having trouble getting to the next step: I only want to show the nodes which have the same country as the current node. How do I accomplish that?

So if I'm visiting a node from 'France', I only want to show related nodes from France.

# Answer
> 2 votes
You can try using PHP code in the contextual filter. You will be able to load the Node using arg(1) - node ID and provide the field value based on the node. Refer screenshot.

---
Tags: views
---