# Question
Title: Condition plugins: two on the same form?
I'm working on porting the CAS module to Drupal 8. On the main configuration form, users can list paths that will activate a feature of the module.

I read about using the new condition API recently, which has a condition for matching request paths, and decided to try and incorporate it into the module settings since it seems perfect for what I'm doing.

On the form submit handler, I have code like:

```
$this->myPathCondition->submitConfigurationForm($form, $form_state);

```

And the actual `submitConfigurationForm` code from the `RequestPath` class looks like this:

```
public function submitConfigurationForm(array &$form, array &$form_state) {
  $this->configuration['pages'] = $form_state['values']['pages'];
  parent::submitConfigurationForm($form, $form_state);
}

```

Couple problems though:

1. I have two instances of the condition plugin, so they would trip over each other in the form submission
2. For that reason, I would typically "namespace" each to a section, like: `$form_state['values']['forced_login']['paths']`

But since the condition plugin looks at a specific array structure for the value, this won't work. This appears to be a limitation of the plugin, but perhaps there's a reason for this, or a method around it?

I understand D8 isn't even in beta yet, but I didn't want to comment on the closed issue where this was implemented: https://www.drupal.org/node/1921544

# Answer
> 2 votes
You are responsible for only passing a sub-key of the form to each plugin configuration method.

Have a look at BlockBase::buildConfigurationForm() and the corresponding validate and submit methods. Note that this itself is already a partial form of BlockForm::form().

For a more flexible approach, have a look at https://drupal.org/project/page\_manager, which has an UI that allows to add conditions and configure them in separate forms, but those forms also pass only a part of the form to those methods.

The main advantage of the page\_manager approach is that BlockBase only works in a useful way with condition plugins that have a no-op mode, meaning, that you can configure them so they don't do anything (and that is the default configuration) because all condition configurations are saved and all plugins are invoked.

Yes, this is sometimes limiting and inconsistent, but that's how it works and I don't really have an idea to improve it...

---
Tags: 8
---


# Question
Title: What does features_exclude mean in a features info file?
I found this line in the \*.info file of one of my feature modules.

```
features_exclude[field_base][field_block] = field_block

```

I did find a number of drupal.org issues dealing with this, but no documentation about the intended purpose.

The context of my example does not really matter; I am asking about the general meaning and implications of the features\_exclude key.

# Answer
`features_exclude` is generated by the Features UI when creating a Feature. It is not created by `drush fu FEATURE_NAME`. See https://www.drupal.org/node/1064472#comment-7196064.

> The features\_exclude lines are purely for the new UI to determine if an auto-detected dependency should be checked or if you have specifically unchecked it.
> 9 votes

---
Tags: features
---


# Question
Title: Give a basic page a different appereance by rendering it with views
I'd like to render a basic page to look somewhat different for my mobile site. Now I have come up with a combination of `views-view--mobile-aboriginalartsfestival.tpl.php`, `page--mobile-aboriginalartsfestival.tpl.php` & `html--mobile-aboriginalartsfestival.tpl.php` to change the appareance of my `mobile-aboriginalartsfestival` view. Now, the page contains certain elements that I would like to alter, in particular I would like to get rid of the `<h2>` title on top of the content (but not all h2 elements on the page!) and I would like to replace the image, too. How do I best go about it?

**edit 1**

So far, I have a couple of arrays on top of my page. One contains strings to search for `$searchstr` and the other one `$contentstr`contains strings to replace the search strings with. Then, where to content gets rendered in my `page--mobile-aboriginalartsfestival.tpl.php`, I implemented a few lines like:

```
        <?php $i = 0;
              $contentstr = render($page['content']);

              foreach ($searchstr as &$value) {
                $contentstr = str_replace($value,$replacestr[$i],$contentstr);
                $i++;
                }
              print $contentstr;
        ?>

```

and even thought, that approach seems to work fine, I doubt that it's the best way to go about it, does any one have a better idea for this?

# Answer
The **Theme Key** module enabled me, to do what I was looking for: enable a different theme per page based on certain criteria (like mobile browser e.g.).
> 0 votes

---
Tags: theming
---


# Question
Title: Views: How to list "files" view for their own files?
I'm working on Workbench module on Drupal 7. There is a "File List" tab and showing all images and files from the site. I would like to change this to be showing their uploaded files only.

PS: the "File List" Tab is from the "workbench\_files" Views

# Answer
First open the workbench file tab, then from the contextual menu on the right select edit view.

Add the relationship 'The user that uploaded the file.' if it does not already exist. Above Relationship, you will see Contextual Filters (these are dynamic contextual parameters you pass to views). Add a contextual filter 'The User ID' and set the relationship to 'User who Uploaded'.

In the same window just below that there is a section 'When the filter value is not in the URL'. You select 'Provide default value'. This opens a select list, from which you choose 'Use ID from logged in user'
> 1 votes

---
Tags: views, files, workbench
---


# Question
Title: How to change OG "subscribe to group" link text?
I want to customize the link text, don't want to use string overrides module for this small job.

In my template\_preprocess\_node() function I tried to change the #title element of the render array. But it doesn't change the link. Any ideas?

```
//change the "subscribe link for tribes
if ($variables['type'] == 'tribe'){
    if (isset($variables['elements']['group_group']['0']['#title'])){
        $variables['elements']['group_group']['0']['#title'] = 'Join this Tribe';
    }
}

```

# Answer
You don't necessarily need to use the string overrides module. You can add string overrides directly in your settings.php.

```
$conf['locale_custom_strings_en'][''] = array(
  'Subscribe to group' => 'Join this Tribe',
);

```

For more information, see Change default strings (text) without using full translation system.
> 5 votes

# Answer
I just figured this out.

In Drupal 7 after you've added the Group Content Visibility to the Organic Group Field Settings (admin/config/group/fields) for the bundle of the content type you're wanting to change this within then you simply go to Manage Fields for that content type and Edit the Field where you can change the Title as well as the language in the options.

In my case I made the title "Share with" and the allowed values list to:

1|Public - visible to all site users 2|Private - visible to only my followers
> 1 votes

# Answer
If you don't want to change code, the stringoverrides module does a great job. Install it, enable it, go to configuration -\> string overrides and add a new line with 'subscribe to group' and 'Join this Tribe'.
> 1 votes

# Answer
I ran into this problem just now. It looks like the best way to determine which message is being displayed to the user is by the class name applied to the output. I found five distinct messages that can be displayed to the end user in the `og_ui_field_formatter_view` function and decided to replace them all. I also decided to `unset` all the element `title` attributes, instead of updating the duplicate text in each `title` attribute.

```
<?php
function MODULE_preprocess_node(&$variables) {
  if ($variables['type'] == 'NODE TYPE') {
    $field_value = &$variables['content']['group_group'][0];
    $is_link = $field_value['#type'] == 'link';
    $class = $is_link ?
      reset($field_value['#options']['attributes']['class']) :
      $field_value['#attributes']['class'];
    switch ($class) {
      case 'group subscribe':
        $field_value['#title'] = t('I am an employee here');
        unset($field_value['#options']['attributes']['title']);
        break;
      case 'group unsubscribe':
        $field_value['#title'] = t('I no longer work for this company');
        unset($field_value['#options']['attributes']['title']);
        break;
      case 'group other':
        $field_value['#value'] = t('You are already subscribed to other groups');
        unset($field_value['#attributes']['title']);
        break;
      case 'group closed':
        $field_value['#value'] = t('This is a closed listing. Only an administrator can add you.');
        unset($field_value['#attributes']['title']);
        break;
      case 'group manager':
        $field_value['#value'] = t('This is my company');
        unset($field_value['#attributes']['title']);
        break;
    }
  }
}

```
> 0 votes

# Answer
You can use this code to check if current user is subscribed to group and check link text according to that.

```

if (module_exists('og')) {
  if (og_is_member('node', $variables['nid'])) {
    // We do not alter "You are the group manager" text.
    // Assuming that group admin will only have permission to administer group.
    if (!og_user_access('node', $variables['nid'], 'administer group')) {
      $variables['content']['group_group'][0]['#title'] = t('Leave this group');
    }
  }
  else {
    $variables['content']['group_group'][0]['#title'] = t('Join this group');
  }
}

```

Write this code in template\_preprocess\_node(). This code snippet works for Drupal 7.
> 0 votes

---
Tags: organic-groups
---


title: Create sub-menus from views data

text:
# Question
Title: Create sub-menus from views data
I'm using Views 7.x-3.8 and Drupal 7.

I've created cutom tables :

* youtube\_video (with fields : vid, vtitle, description...)
* youtube\_playlist (with fields : pid, ptitle, description...)
* youtube\_video\_playlist (with fields: vid, pid, weight)

I define my tables in Views with this hook\_views\_data() :

```
function mymodule_map_views_data() {
  //The group name
  $data['youtube_playlist']['table']['group'] = t('Youtube playlist');
  $data['youtube_video']['table']['group'] = t('Youtube video');
  //The base table
  $data['youtube_video']['table']['base'] = array(
    'field' => 'vid',
    'title' => t('youtube video'),
    'help' => t('youtube video should be related to youtube playlist.'),
    'weight' => -10,
    'defaults' => array(
      'field' => 'vtitle',
    ),
  );
  //The join
  $data['youtube_playlist']['table']['join']['youtube_video'] = array(
    'left_table' => 'youtube_video_playlist',
    'left_field' => 'pid',
    'field' => 'pid',
  );
  // Allow this field to be used as a contextual filter.
  $data['youtube_playlist']['pid'] = array(
    'title' => t('playlist id'),
    'help' => t('playlist id'),
    'field' => array(
      'handler' => 'views_handler_field_numeric',
      'click sortable' => TRUE,
    ),
    'argument' => array(
      'handler' => 'views_handler_argument',
      'name field' => 'title',
    ),
  );
  $data['youtube_video_playlist']['table']['join']['youtube_video'] = array(
    'left_field' => 'vid',
    'field' => 'vid',
  );
  //the fields description
  $data['youtube_playlist']['ptitle'] = array(
    'title' => t('youtube playlist title'),
    'help' => t('youtube playlist title.'),
    'field' => array(
      'handler' => 'views_handler_field',
      'click sortable' => TRUE,
    ),
    'sort' => array(
      'handler' => 'views_handler_sort',
    ),
    'filter' => array(
      'handler' => 'views_handler_filter_string',
    ),
    'argument' => array(
      'handler' => 'views_handler_argument_string',
    ),
  );
  //the fields description
  $data['youtube_playlist']['description'] = array(
    'title' => t('youtube playlist description'),
    'help' => t('youtube playlist description.'),
    'field' => array(
      'handler' => 'views_handler_field',
      'click sortable' => TRUE,
    ),
    'sort' => array(
      'handler' => 'views_handler_sort',
    ),
    'filter' => array(
      'handler' => 'views_handler_filter_string',
    ),
    'argument' => array(
      'handler' => 'views_handler_argument_string',
    ),
  );
  $data['youtube_video']['vtitle'] = array(
    'title' => t('youtube video title'),
    'help' => t('youtube video title.'),
    'field' => array(
      'handler' => 'views_handler_field',
      'click sortable' => TRUE,
    ),
    'sort' => array(
      'handler' => 'views_handler_sort',
    ),
    'filter' => array(
      'handler' => 'views_handler_filter_string',
    ),
    'argument' => array(
      'handler' => 'views_handler_argument_string',
    ),
  );
  $data['youtube_video']['vhash'] = array(
    'title' => t('youtube video vhash'),
    'help' => t('youtube video vhash.'),
    'field' => array(
      'handler' => 'views_handler_field',
      'click sortable' => TRUE,
    ),
    'sort' => array(
      'handler' => 'views_handler_sort',
    ),
    'filter' => array(
      'handler' => 'views_handler_filter_string',
    ),
    'argument' => array(
      'handler' => 'views_handler_argument_string',
    ),
  );
  return $data;
}

```

I've created a page view with my video informations, then \- added the playlist title to the contextual filter \- set the path to 'playlist/%'

This allows me to have a view that displays all videos from a playlist (filtered with a contextual filter). But to be usable, i would like to have a menu item "Playlist" and the submenus being AUTOMATICALLY all the playlists, when i create the view. Something like :

```
- Home
- Playlists
--playlist 1
--playlist 2
...

```

and when i click on playlist 1, i've got all the videos from that playlist 1

In menu section in views, I've tried to add menu tabs (and all the others, actually), but i have the message "A display whose path ends with a % cannot be a tab.". So it seems problematic to create (even only) menus with contextual filter.

Is it possible using only the standard view UI, or do i have to add some hooks or other logic ? If so do you have any lead.

# Answer
> 0 votes
I've managed to find a solution for it, but it is not "perfect" : i will post another question for the remaining problem, since it's not directly related.

* I set my view (page) with contextual filter (playlist id : 'pid')
* I set my path name : playlist/%

Then i added in my module the items in the hook\_menu :

```
function mymodule_menu() {
  //Create parent menu item
  $items['playlist'] = array(
    'title' => 'Playlists',
    'menu_name' => 'main-menu',
    'expanded' => TRUE,
    'enabled' => 1,
    'access callback' => TRUE,
    'page callback' => '_mymodule_menu_page',
  );
  //Get all the playlists
  $result = db_select('youtube_playlist', 'p')
    ->fields('p', array('pid'))
    ->orderBy('title', 'ASC')
    ->execute();
  foreach ($result as $record) {
    //Create the menu items, children of "Playlist" menu item
    $items['playlist/' . $record->pid] = array(
      'title' => $record->title,
      'access callback' => TRUE,
      'expanded' => TRUE,
      'page callback' => 'views_page', //'views_embed_view',
      'page arguments' => array('ytv', 'page_2', 1),
      'file path' => drupal_get_path('module', 'views'),
      'file' => 'views.module',
    );
  }
  return $items;
}
with 'page arguments' : 1) view name, 2) view displayid, 3) position in the path the arg appears (from 0)

```

I now have my menu "Playlists" with all the playlists as submenus, and when i choose one i've got all the videos from that playlist chosen.

The only problem left is the fact the contextual filter is 'pid' and not 'ptitle' (problem of cleaning the ptitle name). But for this question, this is ok.

---
Tags: views, routes
---


title: Node access to anonymous user

text:
# Question
Title: Node access to anonymous user
Is there any way to make some nodes accessible to anonymous users in drupal and rest of the nodes content accessible to only authenticated users . I have a site which offers questions for practice . I want to keep some nodes(questions) accessible to anonymous users to see a sample before they can decide to be a premium user . Any pointers on this is highly appreciated .

Regards Meenakshi

# Answer
Try Content Access module Content Access

```
   This will allows you to manage permissions for content types by role and author.this will allow you to manage permission for node that you want to access to anomyous and authenticated users.

```
> 0 votes

---
Tags: users
---


# Question
Title: How to create a machine name for custom table field with transliteration available
I think the title is pretty explanatory. I have a custom table in which i retrieve human readable titles in 'title'. This title could be any language, and since i'm french it could have accents for instance. I would like to change a title like : "**L'océan indien, l'Asie et la végétation**" into the 'cleanurl' field : "**l-ocean-indien-l-asie-et-la-vegetation**".

I've seen this topic that seemed interesting, but neither machine name nor safeword seems to be usable with transliterate (or i don't see how).

I've tried some "custom" function but does not work completely as expected (and is not a serious replacement for transliterate i guess :

```
function clean_name($string)
{
  $string = html_entity_decode($string);
  $string = str_replace(''', '\'', trim(strtolower($string)));
  $search  = 'àáâãäåçèéêëìíîïðòóôõöùúûüýÿ';
  $replace = 'aaaaaaceeeeiiiioooooouuuuyy';
  $string = strtr($string, $search, $replace);
  $string = preg_replace('/[^a-z0-9-]/', '-', $string);
  $string = trim($string, '-');
  $string = preg_replace('/-{2,}/', '-', $string);
  return $string;
}

```

What can you suggest to achieve this goal ? I would obviously prefer to use core functions if possible.

EDIT -- @Clive I tried to use the pathauto/transliteration modules and i've manage to get what i want, but i'm not sure this is the right way.

```
module_load_include('inc', 'pathauto', 'pathauto');
module_load_include('module', 'transliteration', 'transliteration');
$cleantitle = pathauto_cleanstring(transliteration_get($string));

```

This might not be the optimal way since as you emphasised : Process the string through the transliteration module, but i'm not at ease enough with Drupal code. From the code in pathauto\_cleanstring(), transliteration\_get should be processed automatically if

```
variable_get('pathauto_transliterate', FALSE) && module_exists('transliteration')

```

Both are enabled in my Drupal, but if i do `pathauto_cleanstring($string);` the transliteration is not aplied.

But again, if nobody tells me why, this works with `pathauto_cleanstring(transliteration_get($string));`

# Answer
I don't think core has any such function, but the Pathauto module does.

`pathauto_cleanstring()`:

> Clean up a string segment to be used in an URL alias.
>
> Performs the following possible alterations:
>
> * Remove all HTML tags.
> * **Process the string through the transliteration module.**
> * Replace or remove punctuation with the separator character.
> * Remove back-slashes.
> * Replace non-ascii and non-numeric characters with the separator.
> * Remove common words.
> * Replace whitespace with the separator character.
> * Trim duplicate, leading, and trailing separators.
> * Convert to lower-case.
> * Shorten to a desired length and logical position based on word boundaries.

Emphasis mine.
> 2 votes

---
Tags: uri
---


# Question
Title: Drupal views UI, is it possible for the user to limit the number of row of the result?
I created a view that display some content. I would like to allow the user to change the number of result (row).

By example, the view display ten row. The user can set (in text field?) 5, and the view display only the first five result.

Is it possible via view ui ? I didn't find... If not, I guess that I must create a custom module with view alter..

Thanks for help =)

# Answer
> 1 votes
Go To view .Set pager options and do the change given in above screen shot

---
Tags: views
---


title: How to replace text in many nodes?

text:
# Question
Title: How to replace text in many nodes?
We're upgrading from Bootstrap 2 to 3. Now I need to replace CSS classes in the body fields of many nodes. This needs to be done in at least 5 sites. What is a good way to replace text in all nodes of a site?

Ideally I'd do it with something like `drush replace old_str new_str`. Found one thing from 2009 that didn't work at all and then I found `drush sar`, which didn't do the job either.

# Answer
The Drush Search and Replace plugin may be of some use

> This drush plugin performs a text search & replace on all content and content revisions in all text fields and all custom blocks on a Drupal site.
>
> It does this directly in the database, not by loading, editing and then saving entities, so it is very fast. This also means you should clear the Drupal caches after you run this command.

Hopefully it goes without saying you should give this a dry run before applying it to a live site, how well it works will depend on exactly what data you have in the fields.
> 2 votes

---
Tags: drush, search
---


# Question
Title: drupal 7 webform add classes to submit button
I am trying to add classes to my webform. In

**hook\_webform\_element**

I can do this

```
if ($element['#type'] == 'checkboxes') {
  $wrapper_classes = array(
    'form-item',
    'webform-component',
    'large-16 medium-8 small-24 columns',
    'webform-component-' . $type,
  );
}
else {
     $wrapper_classes = array(
    'form-item',
    'webform-component',
    'large-8 medium-8 small-24 columns',
    'webform-component-' . $type,
  );
}

```

But I do not seem to have access to the submit button. I need to add a couple of classes and also only do it on a certain form so suppose I need the $form\_id.

# Answer
You can do this hook\_form\_alter(). As all the form element are available in hook\_form\_alter.

```
function mymodule_form_alter(&$form, &$form_state, $form_id){
    if ($form_id == 'webform_client_form_YOUR_NODE_ID') {
        $form['actions']['submit']['#attributes']['class'][] = 'newclass';
    }
}

```
> 3 votes

---
Tags: theming, webforms
---


# Question
Title: Added items to registration form and get "Notice: Undefined property: stdClass"
I added 2 items to the user registration form Phone Number and Carrier. When I register a user or edit one i get the following error. Notice: Undefined property: stdClass::$phone in user\_account\_form() (line 1066 of /var/www/capaug/modules/user/user.module). Notice: Undefined property: stdClass::$carrier in user\_account\_form() (line 1076 of /var/www/capaug/modules/user/user.module).

Here is the code for the user registration:

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

  $account = $form['#user'];
  $register = ($form['#user']->uid > 0 ? FALSE : TRUE);

  $admin = user_access('administer users');

  $form['#validate'][] = 'user_account_form_validate';

  // Account information.
  $form['account'] = array(
    '#type'   => 'container',
    '#weight' => -10,
  );
  // Only show name field on registration form or user can change own username.
  $form['account']['name'] = array(
    '#type' => 'textfield',
    '#title' => t('Username'),
    '#maxlength' => USERNAME_MAX_LENGTH,
    '#description' => t('Spaces are allowed; punctuation is not allowed except for periods, hyphens, apostrophes, and underscores.'),
    '#required' => TRUE,
    '#attributes' => array('class' => array('username')),
    '#default_value' => (!$register ? $account->name : ''),
    '#access' => ($register || ($user->uid == $account->uid && user_access('change own username')) || $admin),
    '#weight' => -10,
  );

  $form['account']['mail'] = array(
    '#type' => 'textfield',
    '#title' => t('E-mail address'),
    '#maxlength' => EMAIL_MAX_LENGTH,
    '#description' => t('A valid e-mail address. All e-mails from the system will be sent to this address. The e-mail address is not made public and will only be used if you wish to receive a new password or wish to receive certain news or notifications by e-mail.'),
    '#required' => TRUE,
    '#default_value' => (!$register ? $account->mail : ''),
  );

  //Phone Number Entry
  $form['account']['phone'] = array(
    '#type' => 'textfield',
    '#title' => t('Phone Number'),
    '#maxlength' => PHONE_MAX_LENGTH,
    '#description' => t('A valid Telephone number. Numbers only, no parentheses or dashes.'),
    '#required' => TRUE,
    '#default_value' => (!$register ? $account->phone : ''),
  );

  //Carrier Selection
  $form['account']['carrier'] = array(
    '#type' => 'select',
    '#title' => t('Carrier'),
    '#options' => array(t('--- NONE ---'), t('AT&T'), t('NTelos'), t('Sprint'), t('Straight-    Talk'), t('T-Mobile'), t('Tracfone'), t('Verizon'), t('Virgin Mobile')),
    '#description' => t('Your phone service provider. Select "None" for home phones.'),
    '#required' => TRUE,
    '#default_value' => (!$register ? $account->carrier : ''),
  );

```

Where do I have to define those variables to get them to work?

Thank you all!

# Answer
Never, *ever* patch core like that. This is not how Drupal works. That said, you didn't specify whether you are using Drupal 7 or not; I presume you do. Instead of doing this, use the field UI module to add the relevant fields to users under Administer \> Configuration \> People \> Profiles.
> 2 votes

---
Tags: users
---


# Question
Title: How to display or hide a Views field based on it's length?
I have 2 fields in Views the first of which is always displayed, and the second I would like to display only if the first field has more than 70 characters. I have tried to do this using Views Conditional module but for some reason it does not work.

I have also tried this using Views PHP module by using drupal\_strlen and replacement patterns, but this isn't working yet either. Below is the code that I am using:

```
<?php

if (drupal_strlen($row->comment_body) >= 70) {
  print $row->php;
} else {
  print $row->nothing_1;
}
?>

```

How can this be done?

# Answer
In the views conditional field you are comparing the string value to the value 70, not the length of the string.

And the $row variable in views is very limited.

For the field that you want to do a length comparison on, if it is a PHP field already, then before you do the print statement set the following:

```
<?php
$data->custom_len_70 = strlen($output);
?>

```

$output is whatever you are going to print as the value of the field, so your naming is obviously different.

Then create another PHP field after that one, exclude it from display, and set its output code to:

```
<?php print $data->custom_len_70;?>

```

You have now created a hidden field which has the value of the length of the field you require.

Now you can use the Views Conditional field to do a comparison.
> 1 votes

---
Tags: views, entities
---


title: Page transitions

text:
# Question
Title: Page transitions
I am interested in using https://github.com/dgileadi/zepto-page-transitions for page transitons in Drupal 7.

I am not a coder but have some experience with setting up Drupal sites with themes from Theme Forest.

I want different on-page links or menu links to have different transitions and if the user clicks back it reverses the transition.

# Answer
1) Load the javascript library into your theme. (put it in your themes javascript folder and then see this page for help loading it)

Because Drupal is not a static website you will have to do some work to get page transitions working the way you would like. Furthermore, it is always so simple to add code to dynamically generated menus.

You have three ways someone will navigate.

1) Links manually created inside node or region content - These are easy, just add the transition to the `a` tag.

2) Menus - This are a little tricky. You either need to write some jQuery or Javascript to manipulate the DOM or write a theme pre-proecess template as noted here. I would try the template option first as it will be the most reliable solution and shouldn't be too hard to implement, even for an inexperienced coder.

3) User's browser buttons - For these the most reliable way I am aware of to capture browser behavior is with JavaScript or jQuery. This is not that difficult, but you will have to enact the page transitions within jQuery as there will not be any page event to fire off. This will require you parse the DOM to learn which transition you should use or pass it in a get parameter to pickup on page load.

Last, you say you want to "reverse" the transition. If this is not already built into this library, you will have to dig into the code to figure out how to make that happen.
> 0 votes

---
Tags: 7
---


# Question
Title: Node theming through Views or tpl.php files - which one is better for performance?
As an example, let's take a node with 5 fields and two blocks between those fields. E. g. you want an article do be displayed like this:

First field

Second field

Block with related nodes

Third field

Fourth field

Block with ads

Fifth field

In D7, such display is quite simple to create with Views - you use contextual filters to output fields and just put two blocks between them.

Another option is to use node.tpl.php and create the same template.

Which of these two (Views with context. filters and tpl.php files) is better performance-wise, especially when it comes to MySql performance?

# Answer
> 1 votes
The two are essentially doing the same work and are going to degrade over load very similarly from my experience. If you look at how views works and builds its content, contextual filters is just aiding the discovery by passing in all the data the view needs. This has to be done one way or another. After that, the view builds the same regardless.

However, tpl files are greatly useful for code management. If you are really worried about performance, then you need to look into memcached and/or Varnish \- both are open source and can be implemented easily on most \*nix servers.

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


title: Add tabs on node edit page

text:
# Question
Title: Add tabs on node edit page
How can i add a new tab in node tabs ( with edit, view tabs ) and show a page on this new tab ? i am working on a shopping cart where i need to add a new configuration tabs with nodes and ubercart products.

# Answer
You need to define a new URL by using hook\_menu.

There, 'type' is set as MENU\_LOCAL\_TASK and URL is like 'node/%node/CUSTOM\_CONFIG'.

Code snippet from the hook\_menu in node.module:

```
 $items['node/%node/edit'] = array(
    'title' => 'Edit',
    'page callback' => 'node_page_edit',
    'page arguments' => array(1),
    'access callback' => 'node_access',
    'access arguments' => array('update', 1),
    'weight' => 0,
    'type' => MENU_LOCAL_TASK,
    'context' => MENU_CONTEXT_PAGE | MENU_CONTEXT_INLINE,
    'file' => 'node.pages.inc',
  );

```
> 4 votes

---
Tags: 7, nodes, ubercart, routes
---


title: Views menu tabs with a dynamic view

text:
# Question
Title: Views menu tabs with a dynamic view
I have built a DYNAMIC VIEW to display city data, broken out as tabs on the page -- it is a modified verion of the taxonomy term page view. It uses view menu tabs for this segregation, and Taxonomy Menu (of city names) to trigger the view.

The tabs all work correctly. The problem is the VIEW tab, which shows all results for the subject city (this is not a view display that I created). I don't want an "all results" tab, and I would like the Overview to be the active tab. However, it does not work to set the Overview as the default menu tab -- counterintuitive. (Have fiddled with this a lot! This year, and a project last year in D6.) All the desired tabs are set as "menu tabs". The paths are of this format: taxonomy/term/%/travel/guide/overview

The so-called menu parent path (default tab) doesn't really exist. It appears that the default taxonomy term page behavior creates the VIEW tab. Have the Taxonomy Term Page view enabled also with different path than my city view:

I can hide the VIEW tab with CSS, but then there is no active tab. Would like the Overview to be the active tab, hence first visual info.

NOTE: This issue is similar to this one (unresolved), but trickier because of taxonomy page behavior. Using Menu Tabs with Views 3 (Drupal 7)

> Confirmed. I have a similar issue: the default tab always seems to use the parent menu item's path, instead of its own. I guess, what we'd really like, is that the parent menu item required by default tab item, exist only virtually but never be used on its own. Gonna file an issue for that. – Artur Apr 21 at 9:24

# Answer
> 3 votes
You need to understand that the default tab is not used for anything but the title and the weight of it. For an example, check `node/%node/view` in node\_menu. Also check how `node/%node` is not a tab and yet when you are on example.com/node/1 you see the `View` because it's the default.

So. Since Drupal already provides a page on `taxonomy/term/%` all you need to add is a dummy Views display contents irrelevant, path should be `taxonomy/term/%/does_not_matter_what` with the title 'Overview' and a nice, negative weight and "default menu tab". All other displays are going to be "menu tabs" plain and these can get paths like `taxonomy/term/%/travel`.

You can play the same game with a Views display of your own instead of a Drupal provided page if you set that display as a page and the dummy as a children.

To summarize

1. Have a page, a Views display or a Drupal page at `foo/bar`.
2. Add a display at `foo/bar/dummy` with the title of the default tab and set it as type default tab.
3. Now add any number of `foo/bar/baz` displays with the relevant titles as a normal tab.

# Answer
> 0 votes
So, if i understand correctly, you would like to replace the default local task "View" with your own default local task "Overview".

a few things to try:

1. change the view page path for overview to taxonomy/term/%/view . If you can do this, it will override drupal core's menu router and use your view instead.
2. implement hook\_menu\_alter to hide or remove taxonomy/term/%/view, and assign your own path taxonomy/term/%/travel/guide/overview as the default local task.

e.g.

```
function MYMODULE_menu_alter($items) {
  $items['taxonomy/term/%/view']['type'] = MENU_CALLBACK;
  $items['taxonomy/term/%/travel/guide/overview']['type'] = MENU_DEFAULT_LOCAL_TASK;
}

```

ymmv.

You may run into problems with this because Drupal really wants to find local tasks at the same depth as one another. ie. %/view, %/edit, %/devel instead of %/travel/guide/overview, %/travel/guide/etc. In the latter case, Drupal expects to find sets of actions at %/travel, and %/travel/guide, but it sounds like you want to collapse all 3 levels. You might want to consider refactoring your url paths to put all your menu items at the same level.

---
Tags: views, routes
---


title: Put html in variable_get and Email

text:
# Question
Title: Put html in variable_get and Email
I am using custom form to store email content using variable\_set. Using drupal\_mail and hook\_mail to send that content using variable\_get. Now in email I want to add image using html.

```
$pre_body = '<img src="http://sitename.com/sites/all/images/logo.gif" /><div style="padding-top: 10px;">'
$body = variable_get('email_content');
$post_body = '</div>';
$full_body = $pre_body . $body . $post_body;
$message['body'][] = t('@body', array('@body' => $full_body));

```

but in email it shows me...

```
<img src="http://sitename.com/sites/all/images/logo.gif" />
<div style="padding-top: 10px;">Hello obv
You have placed a bid on lot 'AA' of auction 'Test Curator Email'.
You currently the highest bidder.</div>

```

how to achieve it...???

# Answer
> 0 votes
What you basically need to do is add headers to your email. You can implement a solution like the one that can be found in this Drupal.org's comment. The code is pretty much straightforward:

```
$body = '<html><body><img src="http://sitename.com/sites/all/images/logo.gif" />';
$body .= variable_get('email_content');
$body .= '</body></html>';
$my_module = 'foo';
$my_mail_token = 'bar';  // A key to identify the e-mail sent
$from = 'tanvir@gmail.com';
$message = array(
  'to' => '"'.addslashes(mime_header_encode('Winnie Pooh')) .'"<james@gmail.com>',
  'subject' => t('Example subject'),
  'body' => $body,
  'headers' => array(
    'From' => $from,
    'MIME-Version' => '1.0',
    'Content-Type' => 'text/html;charset=utf-8',),
  );
$system = drupal_mail_system($my_module, $my_mail_token);
  if ($system->mail($message)) {
    // Success.
  } else {
    // Failure.
  }

```

Keep in mind that if your needs for html mailing become more complex and you need to theme your mails using template files or filter the mails' contents after the theme has applied, you can check the HTML Mail module.

---
Tags: 7, emails
---


title: Replacement module for Image FUpload

text:
# Question
Title: Replacement module for Image FUpload
Last week the Image FUpload module got the "no longer supported" status because "its dependencies swfupload are not maintained and not safe anymore".

**Are there any Drupal 6 modules that can replace the Image FUpload module, allowing uploading multiple files/images at once?** An HTML5 solution would be great. Thanks!

# Answer
ImageField module is the perfect solution for your requirement. It is dependent on `CCK` and `FileField` modules. Some of the additional benefits provided by `ImageField` are it works fine with AJAX upload and removal, HTML5 and you can also restrict its behavior.
> 0 votes

---
Tags: 6, media, updating
---


# Question
Title: How to Rename "Request new password" link?
We want to rename the "Request new password" text on a Drupal's login page to some custom text.

In the user.module file, I see that this text is hard coded

```
if (variable_get('user_register', 1)) {
    $items[] = l(t('Create new account'), 'user/register', array('attributes' => array('title' => t('Create a new user account.'))));
  }
  $items[] = l(t('Request new password'), 'user/password', array('attributes' => array('title' => t('Request new password via e-mail.'))));
  $form['links'] = array('#value' => theme('item_list', $items));

```

Is there any other way of renaming this text rather than modifying the Drupal core?

# Answer
> 5 votes
Have you tried the String Overrides module?

> Provides a quick and easy way to replace any text on the site.
>
> **Features**
>
> * Easily replace anything that's passed through t()
> * Locale support, allowing you to override strings in any language
> * Ability to import/export \*.po files, for easy migration from the Locale module
> * Note that this is not a replacement to Locale as having thousands of overrides can cause more pain then benefit. Use this only if you need a few easy text changes.

# Answer
> 12 votes
The String Overrides module is a good suggestion if you have many strings, or need to constantly alter them, but you can also achieve this by editing the string overrides section of your settings.php file.

Simply uncomment the section so it looks like this:

```
$conf['locale_custom_strings_en'] = array(
  'Request new password' => 'MY CUSTOM TEXT FOR A NEW PASSWORD',
);

```

# Answer
> 4 votes
I just tried this in Drupal 7 but it wasn't quite right. It needs an extra \[''\] bit added. This works:

```
$conf['locale_custom_strings_en'][''] = array(
  'Request new password' => 'MY CUSTOM TEXT FOR A NEW PASSWORD',
);

```

# Answer
> 1 votes
I found two more ways of doing it:

Use your module name instead of 'mymodulename':

```
/*
 * Implements hook_menu_alter(). Change link text of 'Request new password' link.
 */
function mymodulename_menu_alter(&$items) {
      $items['user/password']['title'] = t('Reset password');
}

```

# Answer
> 0 votes
You can also do it in `template.php` of your theme, solution more flexible for my purpose (*I wanted the text in French and English side by side*):

```
/**
 * Implements hook_form_alter(&$form, &$form_state, $form_id)
 */
function YOURTHEME_form_alter(&$form, &$form_state, $form_id) {

  switch ($form_id) {
    //Modify the User Login Block Form
    case 'user_login_block':
      $item = array();
      $items[] = l( t('Request new password') . ' |  <span class="en">' . t('Request new password', array(), array('langcode' => 'en')) . '</span>', 'user/password', array('html' => TRUE) );

      $form['links']['#markup'] = theme('item_list', array('items' => $items));

    break;
  }
}

```

Originally inspired by Geoff Hankerson. Thanks to him.

---
Tags: 7, theming, navigation
---


title: How to parse definition lists ckeditor?

text:
# Question
Title: How to parse definition lists ckeditor?
I want to write definition lists with , and tags with drupal commons 3 in CKEditor. I am writing code directly (while I am in source mode) then switch to WYSIWYG and go back to source. CKEditor change this tags to paragraphs.

How to not transform definitions tags (dl, dt, dd) ?

# Answer
I just had this issue myself.

The way I got around it was to add them to the Extra Allowed Content in the profile edit form.

You'll also be pleased to note that while the definition list tags are being presented as p tags they are still stored as the original tags in the db. You won't need to rebuild your definition list.
> 0 votes

---
Tags: wysiwyg, 7
---


# Question
Title: Problems while migrating drupal website from localhost to server
I am trying to migrate my Drupal website from localhost to server, but I am having some problems. I tried many guides from Google, but with no luck.

***What I did:***

First I did a fresh drupal installation on server

Once installation was complete I edited the `.htaccess` file as

```
RewriteBase /site-name

```

Then I used mysqldump to dump my database from localhost to server I found that I had total 126 tables in localhost while in server I had 128 tables

Then I copied my complete "sites" directory from localhost to server

**My problem:**

Now when I enter `www.mysite.com/site-name` I get proper home page of my website but if I go to any other link such as `www.mysite.com/site-name/user` it is not able to open the page but if I enter `www.mysite.com/?q=user` then it works perfectly and this happens for all pages such as `/content`, `/config` etc.

What should I do to solve this issue? I think it is a problem of `clean-urls` So I went to configuration but it said **clean URL enabled but test failed**!

I need to make website live by tomorrow so need your help!

Note: I am using ubuntu on localhost as well as server

Thanks!

# Answer
This is because you need to configure the virtual host in your server. Also with proper permissions. `clean-urls` are associated with mod\_rewrite.so file. So in your apache configuration you need to enable `mod_rewrite.so` and restart httpd or apache2 process.

Depending on the distribution you are using (you should have mentioned that in your question) I'm giving you 2 links to look to.

How To Set Up Apache Virtual Hosts on CentOS
How To Set Up Apache Virtual Hosts on Ubuntu

**EDIT # 1** As this is a Drupal only discussion forum, please consult http://askubuntu.com for the server related issues. But for your help I'm giving you a link in how to enable mod\_rewrite.so. Every deployment process should be consistent with the development server to the production server. So as of me, you should make a complete zip/tar of your local installation and upload it to Production. The archive should consist of your local Drupal installation database as well. This table difference may have caused due the recent updates of Drupal core or due to some contrib module installation. The links I provided is to tell you how to setup virtual host in servers that are fully managed by the user. If you face any issues, then its better to consult with the server support team and I hope they will help you because you are paying them ;).
> 0 votes

# Answer
* To avoid requiring `?q=user` or `?q=some/page/path` you should assure `ModRewrite` is enabled on your Apache webserver. If you're on shared hosting you made need to ask your host provider to enable this module of Apache.
* Moving a Drupal site is essentially moving all the PHP + MySQL data from 1 computer to another. Pick you're tools: mysqldump + zip, rsync, scp, ftp ... Drush whatever ... but the procedure is essentially the same -- move everything in it's entirety.

Why you have 2 less tables between your Drupal installs is unfortunately simply bad project management on your behalf -- good luck tracking down the differences.

Comparing `drush pm-list` between the 2 Drupal installs should help to find any modules on 1 system and not on the other. I like using `drush archive-dump` and `drush archive-restore` to move Drupal sites around -- but under your time constraint I recommend using SQL migration tools and code migration tools your comfortable and most familiar with.
> 0 votes

# Answer
In the command line:

```
sudo nano /etc/apache2/sites-available/[your-vitualhost].conf

```

then put, AllowOverride All into your `<Directory>`, like this:

```
<Directory /var/www/>
        # ...
        AllowOverride All # this allow use the .htaccess file.
        # ...
</Directory>

```

Lastly, ensure mod\_rewrite is enabled:

```
sudo a2enmod rewrite

```

Then, restart apache:

```
sudo /etc/init.d/apache2 restart

```

Greetings.
> 0 votes

---
Tags: migrations, uri
---


# Question
Title: How can I make Drupal/MySql accept special characters in ANSI (without changing the file's encoding)?
I'm developing a custom module where a user (actually an admin of sorts) can upload a CSV file. Based on the contents of this file, certain rows are inserted into a table.

I'm now having problems with special characters, like `é`. These give the following error:

```
SQLSTATE[HY000]: General error: 1366 Incorrect string value: '\xE9initi...' for column 'remarks' at row 1

```

I've tried changing the collation of the table and of the specific field, but this didn't help. The only thing that did help is changing the encoding of the file. But this puts the burden of solving the problem in the hands of the (non-technical) admin. Something I don't want.

What's more, this used to work. Before this module, things were done with a (non-Drupal) php script. The difference is that the old php script used `mysql_query` to insert the records, whereas I am now using `db_insert`.

How can I make Drupal/MySql accept the special characters in ANSI?

# Answer
Found it. I just needed to encode the values with:

```
$encodedval = mb_check_encoding($val, 'UTF-8') ? $val : utf8_encode($val);

```
> 2 votes

---
Tags: database
---


# Question
Title: Printing current node workflow state name as the page body classes
I have a workflow system in my site using workflow module, and I need to print the node current state name as body class.

I did the same with user current role in template.php with this snippet:

```
function sattari_preprocess_html(&$vars) {
  foreach($vars['user']->roles as $role){
    $vars['classes_array'][] = 'role-' . drupal_html_class($role);
  }
}

```

I'd really appreciate your help.

# Answer
> 1 votes
you can use the same hook\_preprocess\_html() hook to add the node current workflow state name as body class. there is workflow module api workflow\_node\_current\_state which will return the current ID of workflow state of a node. i am just providing pseudo code.

```
function mymodule_preprocess_html(&$variables) {
  // Compile a list of classes that are going to be applied to the body element.
  // This allows advanced theming based on context (home page, node of certain type, etc.).
  $current_state = workflow_node_current_state($node);
  $variables["classes_array"][] = $current_state;

}

```

As workflow\_node\_current\_state return the state id, If you want current state name rather then current state id, then you can do one more query to get the state name with this state id.

# Answer
> 1 votes
I think once you get the node object in your preprocess function then you will be able to add the class. Body classes are only applied in `template_preprocess_html` so you can do the following,

```
function sattari_preprocess_html(&$vars) {
  // If on an individual node page, add the node type to body classes.
  if ($node = menu_get_object()) {
    // debug($node);
    // Change as per your node object values added by workflow module.
    $variables['classes_array'][] = drupal_html_class('node-status-' . $node->status);
  }
}

```

For more reference have a look at template\_preprocess\_html

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


# Question
Title: Drupal Commerce Rules if Paypal Payment Method is Selected
What's the best event trigger for the following:

* Remove all Taxes if Payment method selected is Paypal.
* Add %3 to Total if Payment method selected is Paypal.

Thanks.

# Answer
> 1 votes
You can use the event

```
'After updating an existing commerce order'

```

on condition

`'Selected payment method comparison'` under commerce Payment and select its value to `'Paypal'`

Now in action add `'Remove taxes applied to a line item'` and another action 'Add an item to list' to add %3 amount to total .

It will perform accordingly.

Hope it will work for you!

---
Tags: commerce
---


# Question
Title: How to not hide a taxonomy term if it has no content
I have a view that shows content. The issue is that I needed to still show a taxonomy term even if it has no content under it. Is that possible?

Here's the screenshot

# Answer
You can add output to be displayed even if the taxonomy term has no content related to it by adding a field under the settings "No results behavior".

Try adding "Global: Unfiltered text" and add the text that should display when there is no content assigned to the term.
> 0 votes

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


title: Form doesn't submitted

text:
# Question
Title: Form doesn't submitted
```
        <?php

        //https://www.drupal.org/node/1806758
        function mhzipcode_block_info() {

          $block = array();
          $block['mhzipcode'] = array(
            'info' => t('mhzipcode'),
          );
          return $block;
        }
        /*
        Implement hook_block_view
        */

        function mhzipcode_block_view($delta= ''){
          $block = array();
          switch($delta) {
           case 'mhzipcode' :
             $block['content'] = drupal_get_form('mhzipcode_storage_form');
           break;
          }
          return $block;
        }
        /*
        Implement zipcode_view function
        */

        function mhzipcode_storage_form($form, &$form_state) {
          if ($form_state['rebuild']) {
            $form_state['input'] = array();
          }
          // Initialize
          if (empty($form_state['storage'])) {
            if (empty($form_state['input'])) {
              $_SESSION['constructions'] = 0;
            }
            // Put the initial thing into the storage
            $form_state['storage'] = array(
              'thing' => array(
            'zipcode' => '',
            'phonenumber' => '',
              ),
            );
          }
          // Count how often the form is constructed.
          $_SESSION['constructions']++;
          //drupal_set_message("Your form has been saved.");

          $form['zipcode'] = array(
            '#type' => 'textfield',
            '#title' => 'Zip Code',
            '#size' => 15,
            '#default_value' => $form_state['storage']['thing']['zipcode'],
            '#required' => TRUE,
          );
          $form['phonenumber'] = array(
            '#type' => 'textfield',
            '#size' => 15,
            '#title' => 'Phone Number',
            '#default_value' => $form_state['storage']['thing']['phonenumber'],

          );
           $form['continue_submit'] = array(
            '#type' => 'submit',
            '#value' => 'Continue submit',
            '#submit' => array('mhzipcode_storage_form_submit'),
          );

          if (isset($_REQUEST['cache'])) {
            // Manually activate caching, so we can test that the storage keeps working
            // when it's enabled.
            $form_state['cache'] = TRUE;
          }

          return $form;
        }
        function mhzipcode_storage_form_submit($form, &$form_state) {
          $zipcodeAlias = $form_state['values']['zipcode'];
          $zip_code = db_query("select PhoneNumber from {Phone_number} where Zipcode='".$zipcodeAlias."'")->fetchField();
          die;
          $form_state['storage']['thing']['phonenumber'] = $zip_code;
          $form_state['rebuild'] = TRUE;
        }

```

Form doesn't submitted and mhzipcode\_storage\_form\_submit isn't working .doesn't load this function code , and die is not load .

# Answer
> 1 votes
I have tested it in my module, i didn't get any issue. It worked fine for me. The output i received after using **print\_r();** and **die();** in my submit function is

```
Array
(
    [zipcode] => 23423423
    [phonenumber] => 423423423
    [continue_submit] => Continue submit
    [form_build_id] => form-zVFjX4fMorTyOI6m3JE0SL3w0_rSCTsVzEho63Qb1u4
    [form_token] => Pg3erepuKQvtsCSQT-3G7FWLivsSWDH69P0Z3YfRD6M
    [form_id] => mhzipcode_storage_form
    [op] => Continue submit
)

```

Just try it in a separate module where no extra code exists and then debug the issue. It can be conflict with some module or any other issue. Hope it will help.

# Answer
> 1 votes
I have checked your code and its perfectly working for me. The form is getting validated if the 'zipcode' field is left empty and it also getting submitted. Please check whether you have written any jQuery 'preventDefault()' function. You can easily identify this by disabling the Javascript of your brower. Once after disabling your browser and check the form submission.

Please clear the browser and Drupal cache too... :) Good Luck

---
Tags: forms
---


# Question
Title: How do I get Drupal to recognize my 404 page override?
I am using a custom 404 page. I also have a theme installed.

This is what I did:

1. I created a node 95761 which contains my 404 error page.
2. I set node/95761 to be my 404 error page I've created a template in my theme node--error.tpl.php
3. I cleared my cache after uploading node--error.tpl.php to the server.
4. I've verified that node--error.tpl.php exists on the server and has my custom code in my theme's templates folder.
5. I go to \[mydomain\]/pathThatDoesNotExist

Actual result: The contents of node/95761

Expected result: The modified version that is contained in node--error.tpl.php

I also tried node--95761.tpl.php and that doesn't override node/95761 either.

Any ideas why Drupal 7 is not picking up the override and how to fix it?

While we're at it, should the name of the template actually be node--error-404.tpl.php so that it doesn't override 403 or other non-404 errors?

# Answer
> 1 votes
Have you check this link http://example.com/admin/config/system/site-information. Visit the above link in your site and set the 404 error page for your site.

# Answer
> 0 votes
If you have assigned 95761 node id as you error page and its not picking your override.

I think you need to add these lines in your template.php file of your active theme.

```
function YOURTHEMENAME_preprocess_page(&$variables) {
if ($variables['node']->type != "") {
$variables['template_files'][] = "page-node-" . $variables['node']->type;
  }
}

```

Hope it will work for you!

---
Tags: 7, theming
---


# Question
Title: How do I implement cookieless subdomain?
Cookieless subdomains are considered beneficial for a number of purposes:

* They save some network overhead \[1\], and
* they are required for certain types of caching \[7\] (e.g. reverse proxy like Varnish).

The most straight-forward way to implement is to create a sub domain of the main domain (A or CNAME host record in DNS), then set up a virtual host on the webserver and lastly configure a CDN with shared sub domains. \[2\] suggests to configure the cookieless Vhosts in Apache like this:

```
<VirtualHost *:8081>
  ServerName cdn.example.com
  <Directory /var/www/example >
    RequestHeader unset Cookie
    Header unset Set-Cookie
    […]
  </Directory>
</VirtualHost>

```

In Drupal, a CDN with shared sub domains can be implemented with the 'CDN' module and a CDN mapping like suggested in \[3\]:

```
http://css.example.com|.css
http://js.example.com|.js
http://img.example.com|.jpg .jpeg .gif .png .ico

```

At this point, CSS, JS, and images are delivered through the respective subdomains; however, according to firebug, these objects still have cookies attached to them, so Varnish can't cache them efficiently (or not at all).

These are some sample cookies I'm getting attached to an image that is delivered through the CDN sub domain img.example.com:

```
__utma=192369400.1671803289.1403302173.1403302173.1403302173.1;
__utmz=192369400.1403302173.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none);
__utmv=192369400.|1=User%20roles=anonymous%20user=1;
__utma=164879789.945246956.1281184906.1403129675.1405102008.2582;
__utmc=164879789; __utmz=164879789.1396142298.2568.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none);
__utmv=164879789.authenticated%20user%2CSysop|1=User%20roles=anonymous%20user=1

```

All these cookies are set from/belong to the main domain www.example.com; I don't know what application/module sets the other cookies, but those including an Drupal user role are clearly set by Drupal. How do I get rid of them on images and what am I doing wrong here?

Some of the other cookies are probably set by the 'Google Analytics' module which are "usually set on a domain-wide basis to cover all subdomains" \[6\]. However, this module allows to configure `./admin/settings/googleanalytics`, if GA is supposed to track one domain, or multiple sub domains (of course I chose "single domain").

Is an additional functionality required to allow Drupal (in my case Pressflow) to actually allow cookieless subdomains? For example, there is an 'Cookieless Subdomain' module at drupal.org \[4\] (undocumented; dev release; very few users). Do I need this, or is there another way *outside* of Drupal, e.g. in the Apache or Varnish configuration (\[5\] suggests that "varnish really isn't made to do redirects")?

\[1\] developer.yahoo.com/performance/rules.html#cookie\_free
\[2\] webmasters.stackexchange.com/questions/1772/how-do-i-set-up-a-cookie-less-domain
\[3\] www.drupal.org/project/parallel
\[4\] www.drupal.org/project/cookieless\_subdomain
\[5\] serverfault.com/questions/275728/varnish-serving-static-files-from-subdomains-for-better-page-load-speed
\[6\] serverdown.ttwait.com/que/275728
\[7\] www.ravelrumba.com/blog/static-cookieless-domain/ (Wordpress)

# Answer
> 2 votes
> *All these cookies are set from/belong to the main domain www.example.com;*

Check your `$cookie_domain` value in `settings.php`

```
/**
 * Drupal automatically generates a unique session cookie name for each site
 * based on its full domain name. If you have multiple domains pointing at the
 * same Drupal site, you can either redirect them all to a single domain (see
 * comment in .htaccess), or uncomment the line below and specify their shared
 * base domain. Doing so assures that users remain logged in as they cross
 * between your various domains. Make sure to always start the $cookie_domain
 * with a leading dot, as per RFC 2109.
 */
# $cookie_domain = '.example.com';

```

the leading '.' means the cookies also apply to subdomains.

You could try something more specific, to restrict the drupal cookie domain, like:

```
$cookie_domain = '.www.example.com';

```

---
Tags: cookies, subsites
---


# Question
Title: Delete content in a user registration field after X number of days
I am looking for a way to delete the data in a custom registration field (field:transaction\_code) after 30 days. How can this be achieved?

Let me explain better. I want users to get the registration code from me. When they have that registration code, their accounts will be valid for 30 days. Once those 30 days are over, the user will then be required to enter a new transaction code. Thus they will need to revisit the registration page

# Answer
> 0 votes
Are you sure this is the right way to proceed? I think it would be better if you use a custom field with 2 properties: the registration code and a timestamp which holds the time until the value is valid.

And every time when you want to use the value, you check the timestamp. Also with this version you could easily set up a cron or advancedqueue job to delete old values.

---
Tags: views, rules
---


# Question
Title: How to alter the default font displayed INSIDE CKeditor
I would like to be able to alter the font in the CKeditor (version 7.x-1.15) module so that it does not show Times New Roman, but rather the font that the rest of the site uses, Helvetica. I'm using Drupal 7.30.

When CKeditor loads when content is edited it always shows Times New Roman!

I have altered 'Custom Javascript configuration' in:

admin/config/content/ckeditor \> Advanced options to read:

```
config.extraCss += "body{font-family:Helvetica, serif;}";

```

Cleared all Drupal caches AND browser caches - nothing.

I've also altered:

ckeditor.config.js - line 36:

```
config.extraCss = 'font-family:Helvetica;color:#726F6F;';

```

Again, cleared all caches - nothing!

Please could someone explain what I'm doing wrong!

# Answer
The font is set in ckeditor/ckeditor/contents.css, although it is generally inadvisable to alter a module, it can be done safely so long as you document the changes (in the event that updates are required and would overwrite your work).
> 1 votes

# Answer
Thanks to Geoff for providing the path to the content.css file.
> 0 votes

---
Tags: wysiwyg
---


# Question
Title: What is the difference between Referenced Entity and Referencing entity in views
I just wanted to know what is major difference between

> Entity Reference: Referenced Entity
>
> A bridge to the Content entity that is referenced via field\_FIELD\_NAME

AND

> Entity Reference: Referencing entity
>
> A bridge to the Content entity that is referencing Content via field\_FIELD\_NAME

While using relationship in views or when I prefer to Entity Reference: Referencing entity

# Answer
> 6 votes
Say you have a content type called course that has a entity reference field that targets a content type called school.

In views you could now add a relationship using "Entity Reference: Referenced Entity" and fetch values from the school that the course belongs to.

You list of courses could now show something like: Course X - School X

So far so good.

Now let's say you want to list schools and which courses they provide. Since the entity reference field points from course to school you need to fetch the reference the other way. Now you can instead use "Entity Reference: Referencing entity". This way you could list schools and courses:

School X - Course X.

You will end up with duplicate rows in some cases if several courses points to the same school, but that's another story :)

Hope this made the relationship bit clearer.

---
Tags: views, entities
---


# Question
Title: Is a DB transaction executed when it is committed?
`cache_get()` is not working as expected when called in a request initiated by `drupal_http_request()` on the same server. Is it true that the `cache_set()` immediately before `drupal_http_request()` doesn't actually take place in the database until the first database transaction is committed?

Given the sequence:

* `cache_set($cid, $data)`
* `cache_get($cid)` // returns data
* external request using `drupal_http_request()`
    + `cache_get($cid)` // same $cid, returns FALSE
* `cache_get($cid)` // of course, returns data

To make the cached item available to the request initiated by `drupal_http_request()` I wrapped the cache\_set call in a function like this, but it had no effect.

```
function cache_set_wrapper($cid, $data, $bin = 'cache', $expire = CACHE_PERMANENT) {
  $txn = db_transaction();
  return cache_set($cid, $data, $bin, $expire);
}

```

Why is there a discrepancy in the cache between the initial request on the second request?

# Answer
> 2 votes
Copied from my comments:

That depends on where and how you are calling cache\_set(). A transaction only exists if someone explicitly started it. If you're in a node, user or other entity insert/update hook for example, then yes, then you are in a transaction.

If there is an active transaction that it will only get committed at the end. Nested transactions are supported but only to rollback to a certain step. Does the external request need to happen immediately? Doing external requests from a entity crud hook is always a bit problematic for performance (imagine a bulk resave or import of nodes) too. Consider moving the HTTP request to a shutdown function or a queue.

---
Tags: caching, database
---


title: Better Exposed Filters

text:
# Question
Title: Better Exposed Filters
I have created a view block to display filter options. But in BEF settings I dont get check box options. Can anybody help me out.

Thank you in advance embeeke

# Answer
I tried on my local with

* drupal 7.30-dev
* views 7.x-3.7
* better exposed filter 7.x-3.0-beta4

Added term reference field in article content type. Created a view, added this term reference field as exposed filter i was able to get the checkboxes for tid.

**Make sure the term reference field setting is set to "Dropdown" and Use Ajax options is set to "yes".**

After setting term reference field setting to "Dropdown" i was able to see the "Checkbox/radio buttons" options in better exposed filter setting.
> 0 votes

---
Tags: views
---


title: better exposed filters for block view

text:
# Question
Title: better exposed filters for block view
I have created a block view for filter options and tried to display the filter options as check boxes using Better Exposed Filters(BEF) but in the BEF settings i don't get check box option in select option list of "display tid as" drop down. now how to solve dis problem?

# Answer
Make sure that the term reference field settings is set to "Dropdown" and Under views Other settings Use Ajax option is set to "Yes"
> 1 votes

---
Tags: blocks, views
---


# Question
Title: How to add IE specific stylesheet in drupal 7 in drupal way
I want to add this into my Drupal site in a Drupal way!

```
<!--[if IE]>
<link type="text/css" rel="stylesheet" href="IE.css" media="all" />
<![endif]-->

```

I know it can be done easily by adding the above tag directly into html.tpl.php but I don't want hack the Drupal core and I want to follow a Drupal way for this.

What would be the best possible solution?

# Answer
You don't hack Drupal core if you add that to your **THEME's** html.tpl.php but anyway you can try implementing hook\_html\_head\_alter() in your theme's template.php
> 0 votes

---
Tags: theming, hooks
---


# Question
Title: Let user join an organic group during site registration
I would like my users to be able to select a preexisting Organic Group to join when they are registering to use my site. Is this possible? How should I do this?

I already have the groups set up, and the permissions are set so that so that non members can 'Subscribe to group (no approval required)'.

# Answer
> 0 votes
Organic groups register 7.x-2.2 was already installed.

I worked out that my problem was that while I had created a content type which in the Organic Groups tab I set to be an OG ' Group', I had not created a second content type to be the Group Content for that group. By following the D7 OG instructions on this I was able to add a field in the user account settings to reference the Group I had created.

It appears to me that for each Group type and there must be a second content type which is designated to be 'Group Content' for that group.

# Answer
> 0 votes
You must enable the module:

Organic groups register (Allow subscribing to groups during the user registration)

# Answer
> 0 votes
You could set group audience field in you user entity first go to admin/config/group/fields page and choose "user" in your bundle select list then click the add field button now you added the group audience field in your user profile form. Please see the image for configuration

---
Tags: 7, organic-groups, users
---


# Question
Title: How to bypass/skip payment after checkout in Ubercart?
I've tested Ubercart with Sagepay sandbox and it's very inconvenience to enter every time the payment. Another disadvantage is that when working on internal hosts, the redirection URL from external payment gateways never works, therefore when testing, payment is never completed.

How it's possible to bypass payment after checkout and make the order completed for testing purposes? Is there any option or module?

# Answer
**Drupal 6 & 7**

You may add free payment method called 'No payment required' and set-up the right Rules conditions to these payments, e.g.

* Condition: Order balance comparison; Parameter: Order: \[commerce\_order\], Operator: = 0
* Based on specific user role (e.g. for admin).
> 0 votes

# Answer
One way to do this using the combination of ubercart custom payment module and ubercart discount coupon module, i.e creating a coupon of `100%` discount and to bypass the payment process you will need the `ubercart custom payment` module (by default it provides the rule that can use it).

Ubercart Discount Coupons: Coupons can apply either a fixed price discount or a percentage discount to the order subtotal or to selected product prices.

> Coupons are configured at Store administration \> Coupons. Global settings for the module are configured at Store administration \> Configuration \> Coupon module settings.

Ubercart Custom Payment module:

> provides a "Free Order" payment method, and a default Rules configuration is provided to enable this.
> 2 votes

# Answer
**Drupal 6**

I've defined some custom bypassing function as below:

```
/**
 * Implementation of hook_menu().
 */
function foo_menu() {

  // URL for user to be directed to on test order completion
  $items['test/order/%/complete'] = array(
    'title' => 'Fake payment bypass.',
    'page callback' => 'foo_test_order_complete',
    'page arguments' => array(2),
    // 'access callback' => variable_get('my_environment', 'live') <> 'live', // disabled on live
    'access callback' => 'user_access',
    'access arguments' => array('administer site configuration'), // Only admin can test that
    'type' => MENU_CALLBACK,
  );

  return $items;
}

/**
 * Test order completion page
 */
function foo_test_order_complete($order_id) {

  if (empty($_SESSION['cart_order'])) {
    $_SESSION['cart_order'] = $order_id;
  }

  $order = uc_order_load($_SESSION['cart_order']);

  // This lets us know it's a legitimate access of the complete page.
  $_SESSION['do_complete'] = TRUE;
  module_load_include('inc', 'uc_cart', 'uc_cart.pages');
  uc_cart_checkout_complete();
  drupal_goto('cart/checkout/complete');

}

```

So when submit your Review order, after that you can go to:

`test/order/12345/complete` where 12345 is number of your order or just:

`test/order/current/complete` to load the order from the session.

These URLs are accessible only by admin, but you can free to extend the permissions as you wish.
> 1 votes

# Answer
**Drupal 6**

You can use the following PHP code:

```
<?php

  // See: http://www.ubercart.org/forum/development/17963/programmatically_submit_entire_ubercart_order_using_drupal_execute_debugging

  /*
   * Node IDs for the products:
   *   4844 - My product
   */

  $nid = 4844;

  $form_state = array(
    'values' => array(
      'nid' => $nid,
      'qty' => 1,
    ),
  );
  $node = node_load($nid);
  drupal_execute("uc_product_add_to_cart_form", $form_state, $node);

  // Load the relevant include files for checkout, as normally done by hook_menu
  module_load_include('inc', 'uc_cart', 'uc_cart.pages');

  $uc_cart_checkout_form_state = array();

  // Define billing information in the form_state variable
  // Note: When using Sagepay in test mode, to simulate successful payment the first line of the address must be '88' and the postcode should be '412'.

  // Customer e-mail
  $uc_cart_checkout_form_state['values']['panes']['customer']['primary_email']         = 'email@example.com';

  // Billing details
  $uc_cart_checkout_form_state['values']['panes']['billing']['billing_first_name']     = 'Test';
  $uc_cart_checkout_form_state['values']['panes']['billing']['billing_last_name']      = 'Order';
  $uc_cart_checkout_form_state['values']['panes']['billing']['billing_address_select'] = '0';
  $uc_cart_checkout_form_state['values']['panes']['billing']['billing_company']        = 'Company LTD';
  $uc_cart_checkout_form_state['values']['panes']['billing']['billing_street1']        = '88 Test Street';
  $uc_cart_checkout_form_state['values']['panes']['billing']['billing_street2']        = '';
  $uc_cart_checkout_form_state['values']['panes']['billing']['billing_city']           = 'London';
  $uc_cart_checkout_form_state['values']['panes']['billing']['billing_country']        = '826';
  $uc_cart_checkout_form_state['values']['panes']['billing']['billing_zone']           = '2806';
  $uc_cart_checkout_form_state['values']['panes']['billing']['billing_postal_code']    = '412';
  $uc_cart_checkout_form_state['values']['panes']['billing']['billing_phone']          = '0123';
  $uc_cart_checkout_form_state['values']['panes']['uc_termsofservice_agreement_checkout']['tos_agree']['agreed'] = 'agreed';

  // VAT and Discounts
  $uc_cart_checkout_form_state['values']['panes']['vat_number']['vat_number']                  = '';
  $uc_cart_checkout_form_state['values']['panes']['uc_discounts']['uc-discounts-codes']        = '';
  $uc_cart_checkout_form_state['values']['panes']['uc_discounts']['uc-discounts-placeholder']  = '';
  $uc_cart_checkout_form_state['values']['panes']['uc_discounts']['uc-discounts-button']       = '';

  // Payment details
  $uc_cart_checkout_form_state['values']['panes']['payment']['current_total'] = NULL;
  $uc_cart_checkout_form_state['values']['panes']['payment']['payment_method'] = 'free_order';
  // $uc_cart_checkout_form_state['values']['panes']['payment']['payment_method'] = 'uc_sagepayserver'; // enable when testing SagePay payments
  // Etc etc etc

  // Define the credit card information in the $_POST directly.
  // See uc_payment_method_credit($op = 'cart-process') for why this is necessary.
  $_POST['cc_type']      = 'uc_credit_visa';
  $_POST['cc_owner']     = 'Test Order';
  $_POST['cc_number']    = '4929000000006';
  $_POST['cc_exp_month'] = '12';
  $_POST['cc_exp_year']  = '2018';
  $_POST['cc_cvv']       = '123';

  // Programmatically emulate the hitting of the 'Review order' button
  $uc_cart_checkout_form_state['values']['op'] = t('Review order');
  drupal_execute('uc_cart_checkout_form', $uc_cart_checkout_form_state);

  if ($uc_cart_checkout_form_state['redirect'] == 'cart/checkout/review') {
    // We're good to move forward!!
    $uc_cart_checkout_review_form_state = array();

    // Define the session's sescrd info in the $_POST directly
    // See uc_credit_cart_review_pre_form_submit() for why this is necessary.
    $_POST['sescrd'] = base64_encode($_SESSION['sescrd']);

    //Programmatically emulate the hitting of the 'Submit order' button
    $uc_cart_checkout_review_form_state['values']['op'] = t('Submit order');
    drupal_execute('uc_cart_checkout_review_form', $uc_cart_checkout_review_form_state);

    if ($uc_cart_checkout_review_form_state['redirect'] == 'cart/checkout/complete') {
      // The order checks out -- go ahead and complete it using uc_cart_checkout_complete()!
      drupal_set_message(uc_cart_checkout_complete());
    }
  }

?>

```

The above file can be pasted into: order-6.php and then you can use it as a drush command as below:

```
drush -v scr order-6.php

```

Optionally you can use `-u user` to testing the orders using different user. For **Drupal 7**, mainly you have to change drupal\_execute() with drupal\_form\_submit().

---

**Commerce**

For Commerce example, please see:

Programmatically creating an order in Drupal Commerce for anonymous users redirecting to payment page
> 1 votes

---
Tags: ubercart, payment-gateways
---


# Question
Title: A page to display various membership types to choose from?
I am completely newbie to Drupal, currently using Drupal 7.x

Though I am experience hard-core IT professional, I am trying to learn Drupal.

I have a simple requirement to display a page when user clicks on "Create new account".

The page should display three columns giving details of three types of memberships, basic, premium and enterprise. Three memberships should be display in three columns and at the bottom of column there should be button "Register" which should take user to fill registration details.

Please could you guide me how to do that.

Regards TD

# Answer
You will need to create a custom module to do it exactly as you desire, and you probably won't find anyone here to do it for you, so you need to do more research if you go that approach.

A simpler approach does not require a custom module:

* create a block with the three "tables" as images (to be prettier in my opinion)
* add that block to the content-top of whichever theme you have
* restrict the content to only show on the user/register page
* under admin/config/people/accounts/fields add a new field of type list(text) that includes the three types of account, required at registration
* if desired - set a Rule to act on new account registration to take care of role changes or other account differences based on the value of the drop-down selection

This will show the three options at registration and require the user to choose one of them - the Rules will then act on that choice to change the account as desired
> 0 votes

---
Tags: users
---


title: Comment count for different language

text:
# Question
Title: Comment count for different language
I have a blog section on a bilingual page that I'm working on and I'd like to show the total number of comments below each teaser. Not to confuse users, the total should be total number of comments for the language that user is in. So, let's say if I have Spanish and English version of the website. If the user is on English, it should only show total number of comments in English not the grand total. Likewise, if the user is on Spanish, it should only show total number of comments in Spanish. Right now, it shows grand total and confuses users. How do I resolve this issue? Any help would be appreciated.

Drupal 7.x

# Answer
This is untested but you could override the comment\_count variable in a template\_preprocess\_node.

```
/**
 * Implements template_preprocess_node().
 */
function MYTHEME_preprocess_node(&$variables) {
  // Not sure if you wanted to limit to teasers but here goes.
  if ($variables['view_mode'] == 'teaser') {
    // Get the node object.
    $node = $variables['elements']['#node'];
    // Fetch the language the user is browsing the site in.
    global $language;

    // Query against the database all comments for the node in language the user
    // is browsing the site in.
    $result = db_select('comment', 'c')
      ->fields('c', array('cid', 'language', 'nid'))
      ->condition('language', $language->language, '=')
      ->condition('nid', $node->nid, '=')
      ->execute();
    $comment_count = $result->rowCount();

    // Now we override the comment count from the comment module with our result.
    $variables['comment_count'] = $comment_count;
  }
}

```

Observe that Views for example fetches $node-\>comment\_count which is set in a node\_load by the comment module.

So if you are using Views to display the comment count will still be wrong. One idea could be to add your own hook\_node\_load and populate $node-\>comment\_count. This needs to be done after the comment module has run it's hook\_node\_load.

But if you are displaying nodes using the teaser view mode the code above (maybe with some modifications) should work :)

**Edit** On second hand it might make more sense to setup a new variable called something like comment\_count\_active\_language instead of overriding comment\_count. In theory the comment\_count is correct for the node. You are more asking for another count.

Change the example above but setup a new variable.

```
$variables['comment_count_active_language'] = $comment_count;

```

Then print that in node.tpl.php instead of $comment\_count.
> 1 votes

---
Tags: 7, comments
---


# Question
Title: How to set up Google+ authorship in Drupal 7
How do you set up Google+ authorship in Drupal 7?

So I can link my drupal website to our Google+ account so that our Google+ profile pic can appear in the search engines next to our site.

# Answer
> 3 votes
The easiest way is with the Metatag module:

> The Metatag module allows you to automatically provide structured metadata, aka "meta tags", about your website. In the context of search engine optimization, when people refer to meta tags they are usually referring to the meta description tag and the meta keywords tag that may help improve the rankings and display of your site in search engine results.

After you install/enable the module, you can edit the metatags at admin/config/search/metatags The Google+ Author is under Advanced.

---
Tags: google-search-console
---


# Question
Title: How to remove default form tag while rendering output in hook_theme
I am customizing the login form. I have to put all the three forms(login, register, forgotpassword) into one page. **I don't want that unwanted root form tag, how can i remove that one? I am using drupal 7.** This is my code.

## template.php

function bartik\_theme() {

```
$items = array();

$items['user_login'] = array(
    'render element' => 'div',
    'arguments' => array('form' => NULL),
    'variables' => array('form' => NULL),
    'path' => drupal_get_path('theme', 'bartik') . '/templates',
    'template' => 'user-login',
    'preprocess functions' => array(
          'bartik_preprocess_user_login'
    ),

```

);

return $items;

}

## user-login.tpl.php

```
        <div id="signupbox">
            <?php
                $login_form = drupal_get_form ( 'user_login_block' );
                echo drupal_render ( $login_form );

                $forgot_password_form = drupal_get_form ( 'user_pass' );
                echo drupal_render ( $forgot_password_form );

                $register_form = drupal_get_form ( 'user_register_form' );
                echo drupal_render ( $register_form );
            ?>
        </div>

```

My problem is that all the 3 forms are rendering in one more form tag.

## My Output:

\<form action="/drupal728/user" method="post" id="user-login"\>

```
 <form>Login</form>
 <form>Password....</form>
 <form>Registration....</form>

```

\</form\>

I don't want that unwanted root form tag, how can i remove that one? I am using drupal 7.

# Answer
You're attacking the problem at the wrong level - if you want to modify forms/functionality, the theme layer's too late. Specifically what's happening here is that by default forms have a theme wrapper of `theme_form()` which adds the form tag. The form template itself should only contain the form's children elements. (And shouldn't contain for example calls to `drupal_get_function()`).

Here are some ways of adding the forms:

1. Implement `hook_menu_alter()` and alter the page callback for the login page to be your own callback. This callback returns the three forms. Don't forget to check for whether the user's logged in like core does.
2. Create a couple of custom blocks for the other two forms and add them to the login page.
3. Implement `hook_page_build()` and add the forms there (quick and dirty!).
> 0 votes

---
Tags: theming
---


title: Homepage has redirect loop

text:
# Question
Title: Homepage has redirect loop
One of my sites has started to have a redirect loop that just happens on the homepage. Not the secondary pages though. (Drupal 7 - Commerce Kickstart)

```
Error 310 (net::ERR_TOO_MANY_REDIRECTS): There were too many redirects.

```

Some days it does this, some days it doesn't. I feel like it magically fixes itself during the week and on the weekend it breaks. Is there any way to can find out where it is trying to redirect itself to and remedy it? Would the redirect location/error be logged somewhere I could check?

# Answer
Found follow errors in php logs:

```
PHP Warning:  Unknown: Input variables exceeded 1000. To increase the limit change max_input_vars in php.ini

PHP Fatal error: Unsupported operand types in public_html/dev/profiles/commerce_kickstart/modules/contrib/search_api_db/service.inc on line 970

```

Got the redirect loop to stop after increasing the max\_input\_vars to 9000. I feel it's more of a bandaid fix though. So I'm taking this further into the Commerice Kickstart community.
> 0 votes

---
Tags: 7, redirection, commerce
---


# Question
Title: Why does user column name has UNIQUE Constraint?
I got aware that the column `name` in TABLE `users` has a UNIQUE Constraint, when I tried to register a 2nd user with the same username : it returned a \`*integrity constraint violation 1062 duplicate entry '' for key 'name'*.

Lets' say 2 of my customers called "John Doe" want to create an account : Ths 2nd one could not then ?!

So I made a quick SQL fix

```
ALTER TABLE `users` DROP INDEX `name`

```

**I'd like to be sure it's not a very bad idea for some reasons ?**

Config : this is a Drupal Commons distro

# Answer
> 3 votes
It's a bad idea, your are modifying a core feature of Drupal that others module (and the core itself) may relay on. That's the reason why that column has 'UNIQUE' option, because Drupal requires unique username. Think on user login: how you can login with different users if the have the same username?

Check this answer where you may find more info: Is it possible to allow duplicate usernames ?

---
Tags: database, users
---


# Question
Title: Bootstrap 3 sub theme - missing header for banner?
I am new with Drupal Bootstrap 3 sub theming, and I checked the view source and noticed:

```
<div class="main-container container">

  <header role="banner" id="page-header">

      </header> <!-- /#page-header -->

```

I wanted to move header outside main-container - how or where can I edit that?

thanks

# Answer
I think you are using the Bootstrap 3 subtheme and in that case you have to modify the corresponding templates. So to do that create a new directory "templates" in your subtheme directory and then there you have to place a `page.tpl.php` then edit as per your needs.

For further reference you can follow, Theming Guide & Bootstrap sub-theming "how to"
> 1 votes

---
Tags: theming, bootstrap-theme
---


title: using User Import module with date

text:
# Question
Title: using User Import module with date
I was planning on using the user module to import more than 300 new users into my website. However, the birth date fields cannot be imported. Even before the actual import has started, I get these errors and warnings.

```
Warning: Creating default object from empty value in _user_import_settings_save()
(line 574 of /sites/mywebsite.nl/dev/sites/all/modules/user_import/user_import.module).

Field Birthdate is not supported

```

Apparently the User Import module can't handle date fields. Can this be solved with the User Import module? Or is there another module that I can use to import my users? Or do I have to php this manually?

thanks in advance

# Answer
> 0 votes
You can use feeds module to import User. It can handle external fields also. For more information go through the module documentation.

---
Tags: users, importing-exporting
---


# Question
Title: How to order nodes with a number like 1.1.1
I have a long list of files to be downloaded with different categories.

So I created a node for each file.

And assigned a term field for the categories

A file can be used in different categories so I cant sort by posted date or the order might be wrong.

Is it possible to create a text field on nodes and then order them in a view based on that number? Example

* 1.1.1
* 1.1.2
* 2.1.1
* 2.1.2

Views Natural Sort might work for this but I can only get it working on titles.

# Answer
> 4 votes
You can do this with hook\_views\_query\_alter(). I had a similar requirement few time ago where i have to sort nodes where title those have numbers should display before the nodes those have alphabets. Here is a snippet i created at dropbucket.rog

http://dropbucket.org/node/1484

Steps:

* Add one new text field to the content type you using for files. use textfield because integer or float type field will not allow you value in format 1.1.1.
* Create a view.
* Add a sort criteria the field you added either desc or asc. because you are going to alter this in hook\_views\_query\_alter().

**I tried with textfield name "sort". Change the field name whatever you use in content type, in query alter. You can get field name in view query display if query display is enabled in views settings.**

Create a custom module.

```
function custom_views_query_alter(&$view, &$query) {
  if($view->name == 'your_view_name'){
      // Remove all the sort order fields.
      $query->orderby = array();
      // Show number before the alphabets in titles.
      // This is trick which add 0 to the field to cast it to number then check the not equal to condition.
      $query->orderby['0']['field'] = 'field_data_field_sort_field_sort_value+0<>0';
      $query->orderby['0']['direction'] = 'DESC';
      $query->orderby['1']['field'] = 'field_data_field_sort_field_sort_value';
      $query->orderby['1']['direction'] = 'ASC';
  }
}

```

---
Tags: views
---