# Question
Title: How to create checkbox instead of radio for just 1 allowed value?
Because of this major Drupal 7 bug (http://drupal.org/node/811542), I cannot use radio options in my form.

I have three options in my form and I want them to be checkboxes, but the user can only select one checkbox. By Drupal 7's auto form design, it converts single value items to become radios. How can I get the below to become checkboxes that users can only select one without having to write my own module to override the form?

beef|I prefer beef

chicken|I prefer chicken

veggie|I am a vegetarian

# Answer
Simply create three fields. One for each of your beef, checken and veggie with type: `Boolean` widget: `Single on/off checkbox`

The use the Conditional Fields module to create a relationship between the three, so that when one is checked off the other two disappear.
> 3 votes

# Answer
Since checkboxes are multi-value options by nature. It would be detrimental to usability to override this default and expected behavior. You could change the validation as jimajamma suggests, but this would definitely lead to mass confusion amongst your users, as checkboxes are specifically intended for use for multi-value selections.

A slightly better, but still sub-optimal, option would be to use javascript to make sure that only one checkbox option is selected. Using javascript would at least mean that users have immediate feedback rather than finding out after submitting the form (and it failing validation) that the completely expected behavior of multiple values for checkbox form items is no acceptable in this situation.

Since the Drupal core issue that you linked to specifically refers to sets of radio options that are not set as required, why not re-phrase the radio options so that you can make the form item be required?

For example, instead of the three options

```
beef|I prefer beef
chicken|I prefer chicken
veggie|I am a vegetarian

```

create a forth option,

```
none|No preference
beef|I prefer beef
chicken|I prefer chicken
veggie|I am a vegetarian

```

and set that fourth option as the default. In this way, you can successfully work-around the existing Drupal bug without confusing your users with non-standard behavior of form items and without creating any additional work for them. Not only is this better for users, but it requires no code customizations and is more easily maintainable (and easier to change once the bug is fixed).

In a situation with a yes/no question, you could use checkboxes and only provide one option, "Yes." Then you could evaluate "Yes" in its unchecked state the same way you would have evaluated "No" in its checked state.
> 3 votes

# Answer
You could also allow for multiple values to force the checkboxes and then create a custom validation function that makes sure only one is actually checked.
> 0 votes

---
Tags: 7, forms
---


title: Syntax Error or Access Violation

text:
# Question
Title: Syntax Error or Access Violation
I am hoping this is a simple problem. I have Drupal 7.12 and MySQL 5.1.61 running on CentOS 6. I get the following error upon saving an article with Taxonomy. Has anyone run into this problem? I am hoping it is fairly simple to fix. The only Drupal module I've added is LDAP.

```
PDOException: SQLSTATE[42000]: Syntax error or access violation: 1064
You have an error in your SQL syntax; check the manual that
corresponds to your MySQL server version for the right syntax to
use near '))' at line 2: SELECT base.tid AS tid, base.vid AS vid,
base.name AS name, base.description AS description,base.format
AS format, base.weight AS weight, v.machine_name
AS vocabulary_machine_name FROM {taxonomy_term_data} base
INNER JOIN {taxonomy_vocabulary} v ON base.vid = v.vid WHERE
(base.name LIKE :db_condition_placeholder_0 ESCAPE '\\')
AND (base.vid IN ()) ; Array ( [:db_condition_placeholder_0] => Exxon )
in DrupalDefaultEntityController->load() (line 196 of /var/www/html/includes/entity.inc).

```

# Answer
> 2 votes
As this Drupal core issue shows, this error has made an appearance from time to time. From a reading of the thread, it looks like it is often related to a content type that is referencing a missing taxonomy vocabulary. I recommend checking your vocabularies against your content types to make sure everything is correct and consistent.

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


# Question
Title: Set up Drupal to use alternative nodes for different incoming urls?
I have a Drupal website set up selling a single product. Currently the transactions are being processed with paypal with simple buttons set up on a specified node (e.g. *www.website.com/buy*).

I want to start a referral or affiliate system so that drupal will notice the different incoming links (*www.website.com/referral*) and will then always route (*www.website.com/buy*) to (*www.website.com/buy\_referral*) once it detects the different incoming links. This is because I will set up different PayPal buttons for different referrals on different buy\_referral nodes.

Is there a module available to do so? or is there an easier way to do things?

Thanks for the help.

# Answer
You could use the `mod_rewrite` features in your site's `.htaccess` to redirect before Drupal even gets started. This would increase performance vs. using JavaScript.

Implementation details:

https://stackoverflow.com/questions/5151385/redirect-on-the-basis-of-referer-http-referer-htaccess

More about Drupal's `.htaccess`:

http://drupal.org/getting-started/clean-urls

Contents of Drupal's `.htaccess`:

http://drupalcode.org/project/drupal.git/blob/HEAD:/.htaccess
> 1 votes

# Answer
I'd look into using jQuery/javascript if all you have to do is change the href of a link. For example, let's say you have:

```
<a href="http://www.website.com/buy">Buy Me</a>

```

You could change that (and any others) to:

```
<a href="http://www.website.com/buy_referral">Buy Me</a>

```

with the following jQuery:

```
$("a[href=http://www.website.com/buy]").each(function(){
  this.href="http://www.website.com/buy_referral";

```

Of course, you have to figure out when to do that, but I'd do that based upon a class in the body of the node coming in:

```
if $('body').hasClass('referral') {
  $("a[href=http://www.website.com/buy]").each(function(){
    this.href="http://www.website.com/buy_referral";
}

```

but you could also scan through the DOM for hrefs with referral in them if you have no control over the node content itself.

Anyways, it's late here and I am just freethinking so this may or may not be a good idea, or even totally accurate js but hope it helps out or gives you some ideas...
> 0 votes

---
Tags: commerce
---


# Question
Title: Drupal Commerce payment transaction: execute script and pass variables
When you need to create a new transaction method for Drupal Commerce, you need to dive into the code. And that's something I have zero experience with. BUT the following couldn't be hard. I already created a new payment module (just copied and edited the payment example module so I have a new payment method).

In `commerce_payment_example.module` you have the function `commerce_payment_ideal_transaction` that is been executed by the submit button of the checkout form. The only thing I need to do is to execute a script on submit (in HTML you can do this with `<form method="post" action="script.php">`, and pass three variables with it: the amount `($charge ?)`, the order ID `($order->order_id ?)` and a description `($order ?)`. Could someone help me on the right way?

# Answer
> 1 votes
the transaction is meant to be created on a successful response of your provider (this could be payed, denied or whatever), usually an IPN. meaning you have to provide a **MENU\_CALLBACK** item in `hook_menu`. most likely information about the order will be posted, make sure you get the order id back.

if you really want that on the payment form submission, just call the method (`commerce_payment_ideal_transaction`) in the `hook_redirect_form`. the question here is, how do you decide if a payment was successful or not ;)

---
Tags: commerce
---


title: Alternative to current_user

text:
# Question
Title: Alternative to current_user
I have modified user-picture.tpl.php the follow way:

```
$employeeid = token_replace('[current-user:field_employeeid]');
?>
<?php if ($user_picture): ?>
<div class="user-picture">
    <?php print $user_picture; ?>
</div>
<?php elseif ($employeeid): ?>
<div class="user-picture">
    <img src="../../sites/default/files/pictures/<?=$employeeid?>.jpg"/>
</div>
<?php endif; ?>

```

by adding a token\_replace to manage the current-user avatar for a company directory. I have left the original options in place because there is the possibility for non employees to be logged in.

THE PROBLEM:

The above code works, provided you are the current user, I need the employee avatar to show for everyone. I have tried replacing

```
curent-user:

```

for

```
user:

```

with no success. The whole reason for this is so that the employee avatar is automatically pulled from an IMCE managed folder and NOT left up to the employee to "get creative".

Any constructive thoughts or suggestions would be appreciated. Thanks!

SOLUTION:

```
if (isset($account->field_employeeid['und'][0]['safe_value'])) :
    $employeeid = $account->field_employeeid['und'][0]['safe_value']; ?>
    <div class="user-picture">
        <img src="<?=base_path()?>sites/default/files/pictures/<?=$employeeid?>.jpg"/>
    </div>
<?  else: ?>
    <div class="user-picture">
        <?php print $user_picture; ?>
    </div>
<?  endif; ?>

```

# Answer
> 1 votes
i would say remove the `if/else` and only leave the `else` code, as you never want to show `$user_picture`

```
$employeeid = token_replace('[current-user:field_employeeid]');
?>
<div class="user-picture">
    <img src="<?=base_path()?>sites/default/files/pictures/<?=$employeeid?>.jpg"/>
</div>

```

---
Tags: tokens, media
---


title: Omega Theme and Superfish Menu

text:
# Question
Title: Omega Theme and Superfish Menu
I am trying to use superfish menu with Omega 7.x-3.0-rc3 and so far from bits and pieces on the internet I did the following.

1. Create sub-theme from the '\omega\starterkits\omega-xhtml' folder.
2. Add 'regions\[superfish\_menu\] = Superfish Menu' in sub-theme info file.
3. Add the following in the sub-theme info file: (the paths are correct - sf folder is in my sub-theme folder.

```
;Superfish Stuff
stylesheets[all][] = sf/css/superfish.css
stylesheets[all][] = sf/css/superfish-navbar.css
scripts[]          = sf/js/superfish.js

```
4. Add a Menu called 'Top Navigation' to the region with an expandable Menu Item/Sub-Items.

This is where it seems I got stuck...to add the following to page.tpl.php: (I have renamed the div in the code so that it matches the correct Omega region div - region-superfish-menu)

```
<script type="text/javascript">
  $(document).ready(function() {
   $("#region-superfish-menu ul.menu").superfish();
  });
</script>

```

I cannot seem to make it work as page.tpl.php does not exist in omega theme. Any clues? Thanks for helping!

Kevin

# Answer
I would also recommend just using the Superfish module. It handles the block and has a nice admin. That said, 2 problems I see in your approach:

1) $ style jQuery does not work in Drupal 7. You can either replace '$' with 'jQuery' or use a wrapper like

```
(function ($) {
  // Original JavaScript code.
})(jQuery);

```

See http://drupal.org/update/modules/6/7#javascript\_compatibility

2) The template you want for omega is probably html.tpl.php, not page.tpl.php.
> 1 votes

# Answer
Why don't you just use the Superfish module that already integrates Superfish into Drupal. It automatically creates a block to add to any region you wish.
> 1 votes

# Answer
The best way to add code to a jQuery ready function is through Drupal behaviors. You can add a javascript file to your .info, let's call it loadsf.js.

```
scripts[] = js/loadsf.js

```

The contents of loadsf.js would be something like this:

```
(function ($) {

  Drupal.behaviors.superfish = {
    attach: function (context, settings) {
      if ($("#region-superfish-menu ul.menu").length > 0) {
        $("#region-superfish-menu ul.menu").superfish();
      }
    }
  };
})(jQuery);

```
> 0 votes

---
Tags: routes, theming, navigation
---


# Question
Title: Is it possible to set the user picture as the value of an image field from a node?
Use case: On my site, I need a workflow that allows user pictures to be approved. Users submit images using a special content type. Of these images, they must designate one as their user picture. I use the Rules module to manage the approval workflow.

I managed to get everything set up in Rules so that the picture they designate shows up in their profile appropriately. However, many modules (such as Privatemsg) make use of Drupal's default user picture. Is there a way to set the Drupal user picture value with the value from the uploaded field?

# Answer
> 2 votes
A quick grep through privatemsg shows that it is using `theme('user_picture'...)` so you should be able to copy `user-picture.tpl.php` from "drupalroot"/modules/user to your theme and edit it to your specifics...just flush caches :)

---
Tags: 7, media
---


title: admin content filter

text:
# Question
Title: admin content filter
is there a way in Drupal-7 to add form search in the content page filter or add text box in the filter form for filter the nodes by node title beside the type of node and publishing property

# Answer
The Admin menu module has a nice sub-module called 'Administration views" which replaces Drupal core content management page with a view. It also adds extra filters and a search function.
> 3 votes

# Answer
I was looking for something similar to this.. I ended up just putting a JS hack into the template file. It's pretty dodgy, but it works well and I don't know how to "compile" the code into a module (I could never get my head around that stuff). Anyway, here is the code that I dropped into the bottom of page.tpl.php of my admin theme.

```
<?php ///THIS IS A HACKY SOLUTION TO PROVIDE SEARCH FUNCTIONALITY
    if(implode('/',arg())=='admin/content'):
?>
<script type="text/javascript">
jQuery(document).ready(function($){
    $("#edit-filters").append('<div id="hacky-search"><legend><span class="fieldset-legend">Search</span></legend><input type="text" /></div>');

    var titlesArray = new Array();
    var wordsArray = new Array();

    $("#node-admin-content tbody tr").each(function (e) {
        titlesArray[e] = $(this).find('td:eq(1)').text().replace(/^\s+|\s+$/g, "");
    });
    /**/
    $("#hacky-search input").bind('keyup blur change', function () {
        var theSearch = $(this).val().replace(/^\s+|\s+$/g, "");
        if (theSearch > "") {
            $("#node-admin-content tbody tr").addClass('hidden');
            for (i = 0; i < titlesArray.length; i++) {
                theItem = titlesArray[i].toLowerCase();
                if (theItem.search(theSearch.toLowerCase()) > -1) {
                    $('#node-admin-content tbody tr:eq(' + i + ')').removeClass('hidden');
                }
            }
        } else {
            $("#node-admin-content tbody tr").removeClass('hidden');
        }
        $("#node-admin-content tbody tr").removeClass('even').removeClass('odd');
        $("#node-admin-content tbody tr:not(.hidden)").each(function(e){
            if(e%2==0){
                $(this).addClass('odd');
            }else{
                $(this).addClass('even');
            }
        });
        //$('h2').text(theSearch);
    });
});
</script>
<style type="text/css">
    #hacky-search{
        position: absolute;
        right: 15px;
        top: 0;
        text-align:right;
    }
    #hacky-search legend{
        position:relative;
    }
    #hacky-search legend span{
        right:0;
    }
    #hacky-search input{
        border: 1px solid #CCCCCC;
        margin-top: 33px;
        padding: 2px 4px;
        width: 200px;
    }
    #node-admin-content tr{

    }
    #node-admin-content tr.hidden{
        display:none;
    }
</style>
<?php
    endif;
?>

```
> 1 votes

# Answer
Drupal 6 had a "content management filter" module but it's not ported to 7. You can always build your own with a view and some exposed filters.

If you like the "bulk operation" option you can do that too with the VBO module.
> 0 votes

---
Tags: search, nodes
---


# Question
Title: How to add custom attributes to a field?
I would like to be able to add a handful of custom attributes to a filefield. The attributes will be used by other modules to manage the uploaded files.

For example: Admin creates a filefield and adds a "youtube" attribute, meaning that videos uploaded to this filefield should get transferred to youtube.

I see that the database table `content_node_field` (which contains a row for each defined field) has a `general_settings` column that stores serialized data. I am assuming this is a good place to store my custom field attributes.

Question #1:
How to set/get custom attributes stored under the "general\_settings" column?

Question #2: How to customize the filefield widget so that when admin defines a particular filefield, she can also select values for these custom attributes.

(I am using Drupal 6.)

Thank you!

# Answer
> 1 votes
The database table "content\_node\_field\_instance" has a "widget\_settings" column which can be used to store field attributes. Use hook\_widget\_settings\_alter() to associate attributes with a field. Admin will then be able to set attribute values from the cck UI. For example, to associate a binary attribute "my\_attribute" with every filefield:

```
function mymodule_widget_settings_alter(&$settings, $op, $widget) {

  // Apply to all FileFields
  $widget_types = _content_widget_types();
  $widget_type = isset($widget['widget_type']) ? $widget['widget_type'] : $widget['type'];
  if (!in_array('filefield', $widget_types[$widget_type]['field types'])) {
    return;
  }

  switch ($op) {
      case 'form':
        $settings['my_attribute'] = array(
          '#type' => 'checkbox',
          '#title' => t('my attribute'),
          '#options' => array(0 => t('Disabled'), 1 => t('Enabled')),
          '#default_value' => !empty($widget['my_attribute']),
        );

        break;
      case 'save':
        $settings[] = 'my_attribute';
        break;
  }
}

```

In this example, the filefield form will contain a checkbox labeled "my attribute". Admin checks the box to set my\_attribute to true, for the particular filefield.

To get the attribute value of a particular field:

```
$attribute_value = $field['widget']['my_attribute'];

```

---
Tags: entities, files
---


# Question
Title: Popup with the content of the exposed date field
I am using "Webform Views Submitted Data" module to show webform submissions report with views. I have one expose filter name "Webform submissions: Submitted" which will give two date options; start date and end date. How do I select the date i want to filter by in a popup calender?

# Answer
> 1 votes
How about writing a custom jquery code with the help of http://docs.jquery.com/UI/Datepicker. I am not sure whether you are proficient with jquery , but still i would prefer to have a go at this.

# Answer
> 0 votes
We've been using Better Exposed Filters to have a datepicker in exposed filters. It's fairly straightforward to set up as well. This replies the first question you have, but I am unsure about how the Webform submission is affecting the scenario.

---
Tags: views, 6
---


title: Hook for altering secondary local tasks

text:
# Question
Title: Hook for altering secondary local tasks
`hook_menu_local_tasks()` works for the top level tabs, but the secondary tabs don't seem to have an equivalent. Does anyone know how I can modify those?

# Answer
```
$primary = menu_local_tasks(0);

$secondary = menu_local_tasks(1);

```

See: http://api.drupal.org/api/drupal/includes%21menu.inc/function/menu\_local\_tasks/7

It's actually not a hook, it's just a function that gathers the items while in context.

There is a hook to alter the items: http://api.drupal.org/api/drupal/modules%21system%21system.api.php/function/hook\_menu\_local\_tasks\_alter/7
> 1 votes

---
Tags: 6, routes, hooks
---


title: Menu local tasks and hook preprocess

text:
# Question
Title: Menu local tasks and hook preprocess
I just want to remove a secondary menu local task from a preprocess function such as

```
function mymodule_preprocess_menu_local_tasks(&$vars, $hooks) {
    $vars['secondary'] = '';
}

```

I'm using D7, **sky** theme for front-end and **seven** theme for admin. The above code works in **seven** but not in **sky**.

The sky theme page.tpl.php has a variable `$secondary_local_tasks` which I might be able to remove from `hook_preprocess_page()`. I also tried this :

```
function mymodule_preprocess_page(&$vars, $hooks) {
    $vars['secondary_local_tasks'] = '';
    unset($vars['tabs']['#secondary']);
}

```

My hook is invoked correctly, but the secondary local task is still rendered to the template. Where local tasks are prepared to be rendered after my hook ?

# Answer
Finally, I've done with `hook_process_page()` and removed the variable `secondary_local_tasks` upon logged-in user role before rendering to the template.

```
function mymodule_process_page(&$vars, $hooks){
    global $user;
    if(array_key_exists(6, $user->roles) && arg(0) == 'user' && arg(2) == 'edit'){
        $vars['tabs']['#secondary'] = array();
        if(isset($vars['secondary_local_tasks'])){
            $vars['secondary_local_tasks'] = array();
        }
    }
}

```

I have also tried this from `hook_preprocess_page()`, but it did not work on the sky theme.
Related question is here : Profile2 and profile fields by user role
> 1 votes

# Answer
Or use: hook\_menu\_local\_tasks\_alter()
> 1 votes

# Answer
You could use hook\_menu\_alter to remove any menu entry. This would be completely indipendent of the theme.

Just implement `hook_menu_alter` in a custom module and look at the given menu items with a dubugger or dpm(). Then do something like this:

```
unset($items['menu/item/to/delete'];

```
> 0 votes

---
Tags: routes, hooks, theming
---


title: DD-Block resizes images

text:
# Question
Title: DD-Block resizes images
I'm developing a website in Drupal 6, and I've employed Dynamic Display Block for a slideshow that displays in a panel.

Unfortunately, even though the images show in the slideshow, they are not rendered in their full size as I described in the configuration page of the Dynamic Display Block settings.

I used firebug, and I realised that a class called `ddblock-processed` has been added which is the cause of the issue i'm facing, as it has different dimensions compared to the one I specified.

I've tried overriding that effect in the style sheet - css, but to no avail.

Someone should kindly help me hack this stuff under the hood.

Thank you.

# Answer
`ddblock-processed` class is added to your div when the Javascript event is attached to it by Drupal. This is normal behavior, but it shouldn't be too hard to override the style with CSS.

To show you a simple example of CSS overrides (even though this is considered an inefficient selector, it doesn't matter too much in cases such as yours):

If on the original style, the CSS is declared as follows:

```
.ddblock-processed {
  width: 100px;
}

```

You can easily override it in your own stylesheet by including the "parent" element in the CSS selector. So if `ddblock-processed` div's parent is a div with an ID of `myregion` then doing this will override it:

```
div.ddblock-processed {
  width: 200px;
}

/* OR */

#myregion .ddblock-processed {
  width: 200px;
}

/* OR */

body .ddblock-processed {
  width: 200px;
}

/* OR */

div .ddblock-processed {
  width: 200px;
}

```

This is called CSS specificity if you want to read up about it.
> 0 votes

---
Tags: theming
---


title: Sort field items

text:
# Question
Title: Sort field items
what is proper moment of drupal execution to sort fields in node display? One of content types has this list which points at other nodes, showing links with their titles. Problem is, they're not sorted alphabetically. I don't wanna use views. Should I do the sorting in node--content-type.tpl.php or rather some field hook? Examples appreciated!

# Answer
```
function my_theme_preprocess_field(&$variables, $hook) {
 if($variables['element']['#field_name']=="field_project_release_packages"){
 usort($variables["items"], "_my_theme_sort_package_list");
 }
}

function _my_theme_sort_package_list($a, $b) {
    return $a["#title"] > $b["#title"];
}

```
> 2 votes

# Answer
There are several options: \-
> 0 votes

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


# Question
Title: How do the $node modifications in hook_node_presave persist?
I was looking at `hook_node_presave()` and I tested it out and it works as described. The thing I'm puzzled about is that it doesn't take the `$node` parameter by reference, nor does it return anything from the function, however when I modify `$node` in this hook, the changes get saved. I'm really confused. Can anyone shed some light and make sense of this? How do I implement something like this?

# Answer
Objects are (mostly) passed by reference in PHP. The `$node` variable is a `stdClass` object so any changes you make will be reflected on the original object in memory.

You don't need to do anything special to implement this yourself, just accept an object as an argument to a function as usual and let PHP take care of the rest.
> 8 votes

---
Tags: hooks
---


# Question
Title: How to boost search relevance based on certain values using Search API
I'm using the Search API with a database back-end.

I would like search results that are tagged Editorial to be favoured over results not tagged Editorial. So, for example, if two articles match a search query, and one is tagged Editorial, I'd like to see the Editorial one listed first.

Can this be done?

Thanks.

# Answer
It would be insanely complex to do this properly, since you need to alter some very core Search API mechanics, much of which is handled by the database backend and not search api itself.

What you could do as a hack, it to

1. Create two fields: A and B.
2. Select a non existing word like `ethsrtsghtpofksd`
3. Add the word in field A when it's an editorial and in field B when it's not an editoral.
4. Set the searcg weight for field A to be higher than field B
5. Add the word to all searches before search API sends it to the DB.

Since the word is used in all searches and it always is matches (either in field A or B) it won't effect the results, but the weight they get will be different since field A will get a boost. I haven't tried this before, but it should work. But like I said it's a hack so it's not a pretty solution, but it's a clever way of avoiding to mess with the internal workings of Search API module.
> 2 votes

---
Tags: 7, search
---


# Question
Title: Executing PHP code only once, when the node is created
I am using Drupal 7 with the Token module.
I wrote PHP code using the token field that can satisfy loading a specific node, updating some field values, and saving the node (using node functions).

When editing this node the code run again; I just want to run this code when creating this node. How can I do that?

# Answer
You should use `hook_node_insert` in a custom module to run your code when the node is created.

```
function hook_node_insert($node) {
  // To include @marcvangend's comment.
  if ($node->type == 'type') {
    // Run code here only for node of type 'type'.
  }
  // Run code here for all nodes...
}

```
> 14 votes

---
Tags: nodes, tokens
---


# Question
Title: multistep registration from in drupal 7 need to add a user and role
Here is my method

```
test_two_submit($form, &$form_state) {
  $page_one_values = $form_state['page_values'][1];
  drupal_set_message(t('The form has been submitted'));
  $page_one_values = $form_state['page_values'][1];
  drupal_set_message(t('The form has been submitted. name="@username @email", password=@password', array('@username' => $page_one_values['username'], '@email' => $page_one_values['email'], '@password' => $page_one_values['password'])));
}

```

What i am trying to do is to add a user to my multi-step form.

I guess my two questions are how to add a user and also assign that particular user to a role.

Would it be possible for someone to give a short example.

# Answer
```
   // Register this new user.
    $roles = user_roles();
    $userinfo = array(
      'name' => $name,
      'pass' => user_password(),
      'init' => $name,
      'status' => 1,
      'access' => REQUEST_TIME,
      // This is where we are different from the default function.
      'roles'        => array(array_search('campus_student', $roles) => 1),
      // the field_* values come from custom columns added through
      // thhe admin ui under manage fields for users.
      'field_first_name'   => array(LANGUAGE_NONE => array( 0 => array('value' => $get_ldap_details['first_name']))),
      'field_last_name'    => array(LANGUAGE_NONE => array( 0 => array('value' => $get_ldap_details['last_name']))),
      'field_perm_number'  => array(LANGUAGE_NONE => array( 0 => array('value' => $get_ldap_details['campus_perm_number']))),
      'mail' => $get_ldap_details['mail'],
    );
    $account = user_save(drupal_anonymous_user(), $userinfo);

```

**EDIT:** You can see how drupal itself typically creates in a user via drupal\_external\_login\_register(). The above example uses some API calls to get all Roles and assigns very clearly X additional roles, it also sets up additional drupal Fields tied to the user entity.
> 1 votes

---
Tags: users
---


# Question
Title: Can anyone help me translate this Javascript code line the Drupal Way?
I need to convert this code line (it focuses the cursor to the first input of a form) to Drupal behaviourism. Can anyone help me put it the Drupal bushido way?

```
jQuery("input:text:visible:first").focus();

```

# Answer
> 3 votes
```
jQuery("input:text:visible:first").focus();

```

Becomes

```
Drupal.behaviors.focustextfield = function(context) {
  $("input:text:visible:first:not(.focustextfield-procd)", context).addClass("focustextfield-procd").focus();
}

```

---
Tags: javascript
---


# Question
Title: Can I add a custom link to "Main Menu" via hook_menu?
I'm trying to add a new link to the Main Menu from inside my module.

Currently, this code:

```
function custom_food_orders_menu() {
  $items['order_food'] = array(
    'title' => 'Order Food',
    'page callback' => 'page_creator_function',
    'access callback' => TRUE,
        'menu_name=' => 'main-menu',
    'type' => MENU_NORMAL_ITEM,
  );

  return $items;
}

```

...adds the 'order food' link to the 'Navigation' menu. I tried setting the menu name to main-menu, but that does not seem to work.

Is this a limitation in Drupal? If it is, I'll adjust by creating a link to that page manually.

# Answer
The correct code would be the following one; notice the commented line.

```
function custom_food_orders_menu() {
  $items['order_food'] = array(
    'title' => 'Order Food',
    'page callback' => 'page_creator_function',
    'access callback' => TRUE,
    'menu_name' => 'main-menu',  // This is the changed line.
    'type' => MENU_NORMAL_ITEM,
  );

  return $items;
}

```

There aren't properties returned from `hook_menu()` (and generally from any hook used from Drupal core code) that uses the equal character.
> 16 votes

---
Tags: 7, routes
---


# Question
Title: How can I display a picture from a field as the user picture rather than the drupal default with user-picture.tpl.php?
Because my site requires user pictures to be approved, the default Drupal user picture is not suitable.

Instead, I want to show a picture from a field in each user's profile as the user's profile picture.

The field is "field\_profile\_picture".

The image style is "profile\_picture".

Based on this tutorial, I put the following code in user-picture.tpl.php in my theme's templates folder:

```
if (!empty($user->field_profile_picture['und'][0]['filename'])) {
  echo theme('image_style', array('style_name' => 'profile_pic', 'path' => file_build_uri($user->field_profile_picture['und'][0]['filename'])));
}

```

This doesn't result in any PHP errors but no picture is displayed. It appears that field\_acc\_profile\_picture is evaluating as empty because even if I put a `print "Hello world";` inside the {} it doesn't appear. However, I am sure that the field has a value because I can see the picture displayed in views.

# Answer
I don't think `$user->field_profile_picture['und'][0]['filename']` would be set by default, you normally only get the `fid` column (this does vary depending on context, but you should *always* get the `fid` column either way).

This sort of code always works for me:

```
if (!empty($user->field_profile_picture[LANGUAGE_NONE][0]['fid'])) {
  // Load the file
  $file = file_load($user->field_profile_picture[LANGUAGE_NONE][0]['fid']);

  // Note the style name is "profile_picture" as explained in your question,
  // not "profile_pic" which was in your original code
  echo theme('image_style', array('style_name' => 'profile_picture', 'path' => $file->uri));
}

```

If you're worried about the extra overhead involved with potentially loading the file twice, don't be, Drupal caches the object the first time round.

It the above doesn't work it's likely that the `$user` object is not fully loaded and so the fields haven't been attached. If that's the case, load the user like this:

```
$account = user_load($user->uid);

```

And then use the `$account` object to test for the field value.
> 5 votes

---
Tags: 7, media, users
---


title: Combine fields – images and text

text:
# Question
Title: Combine fields – images and text
I want to have content type tutorial, with descriptions step by step, consisting of text paragraphs and pictures as an explanation (like clickable thumbnails or just picture).

I know how to add field like text text and image, add set a possibility of make it's number unlimited. But how allow user to arrange order of pictures and text?

Example:

TITLE of PAGE

PARAGRAPH 1

PICTURE 1

PARAGRAPH 2

PICTURE 2

PICTURE 3

PARAGRAPH 3

PARAGRAPH 4

# Answer
You can use field collection it allow you to make a subform inside a form so you can add more than subform and arrange them
> 5 votes

# Answer
Draggable Views does exactly that : ordering contents arbitrarily by hand. If you dare, you can even use this, which is more lightweight but probably much less flexible and stable. I can tell, I wrote it ...
> 3 votes

---
Tags: entities, media, nodes
---


# Question
Title: How can I limit users to one account each? (Or, how can I detect users who have multiple accounts?)
For various reasons I would like to limit each individual user to registering/using only one account. I realize that there is no perfect way to do this, but what can I do within Drupal to detect cases where users have registered and are using multiple accounts?

I plan to set up a view using uiplog to check whether the same IP address is logging out and then immediately logging in to another account, but what else can I do?

Additional information: The site I am working on requires users to complete a fairly lengthy registration form and then additional information on the first time they log in. As such, I'm primarily concerned about users with multiple accounts trying to game the ratings system within the site. (Abusive users will be handled through an abuse reporting system.)

# Answer
> 1 votes
You can not. Only limitation is Useraccount with one Emailadress. But if the same User Logs in with a different name and a disposable email adress, you can not verify if it is the same User. Something like undisposable will help. But it's not the solution.

Also if 200 Users use the same Proxy/same IP, you will limit them.

---
Tags: 7, users
---


# Question
Title: Using panels everywhere... without Panels Everywhere
I recently discovered how awesome Panels is and I want to use it as a replacement essentially for the default theming mechanism that comes with Drupal (I'm using version 7). In fact, I want to use it just about everywhere. Unfortunately, it looks like the Panels Everywhere module for Drupal 7 is completely dead.

I noticed that any panel that you create is just dropped into the content area. So, with an out-of-the-box Drupal installation that is going to leave all the heading information at the top of the page intact, even if you've defined a header section in your panel.

So, right now I'm thinking that the best way to deal with this is to tell Panels to disable output to regions, and to also override page.tpl.php so that it doesn't include any extraneous junk with the exception of wrapper HTML and the content region.

Does this approach make sense or is there a better way to go about accomplishing this?

# Answer
I believe the answer to your question is "Use Panels everywhere". :)

As one of the maintainer of Panels Everywhere, I wonder what you mean with "completely dead"? Yes, I'm a bit slow in the issue queue, but that's because 1. Both me and merlin are crazy busy with the Panels queue (318 issues vs 15), and 2. I'm also not aware of any serious issues. Any help from the community in the Panels queue will greatly help with any PE issues as well.

You should use Panels Everywhere because:

1. There only thing that's preventing a stable release is a bug on d.o. (I just now updated the module page to say so.)
2. Merlin is also planning to redo the UI to be much more user friendly.
3. I build websites with Panels everywhere every single day at work. It works great. *If* any serious issues were to come up, they will most definitely be fixed. At NodeOne, we build nearly every single site with PE. We need it to work well. :)

I will take the opportunity to shamelessly suggest that anyone interested in Panels and/or Panels everywhere could contribute a bit of time to the issue queue. The current number of contributors, 2, is vastly outnumbered by the number of questions being asked. This slows down development considerably. My d.o profile has the necessary info for contacting me about this. :)
> 9 votes

# Answer
I have done it on one website . I disabled all the blocks .All I have is panels pages. I don't think there is anything wrong with this approach.
> 2 votes

# Answer
It is not true that every Panel you use is falling inside the content area. Check on the Panel admin page that is `admin/structure/panels` and you'll notice on the left side the option to create Panel page or Panel node.

Panel pages can be used as landing pages. Thus, they are provided with a URL path, accept arguments and can have menu entries. For Panel nodes (you must activate the panel node module for this functionality) you can manage them the way you manage blocks. In fact if you get some experience with Panels you'll never touch blocks anymore.

Another thing to keep in mind is that Panels are relying on ctools so you can create whole pages patterns using Pages: `admin/structure/pages` and then fill them with the panels you want.

I never used Panels Everywhere (they have an alpha release for Drupal 7) but honestly I don't understand their utility.

Another tool you might consider not only as alternative to Panels but also you can use together with them (as I often do) is Context module.

Context module have a more simple interface but powerful they handle pages and sections and manage blocks for each sections. You can also handle Panels inside them creating very complex layouts.
> 2 votes

# Answer
Lester, when you write:

"I noticed that any panel that you create is just dropped into the content area. So, with an out-of-the-box Drupal installation that is going to leave all the heading information at the top of the page intact, even if you've defined a header section in your panel."

The problem is that you are defining regions in both your panels and your theme. Take a look at this old support issue from the Panels Everywhere queue: http://drupal.org/node/1256000. You need to change your theme to do what you want.

Hope that helps.
> 1 votes

---
Tags: theming, panels, 7
---


# Question
Title: Integration between js and php code in custom module
I'm writing a custom module which outputs blocks with various deltas. Later, a jQuery code has to be attached for every generated block, aware of their id's, as in `$('#mymodule-block-delta')`. How is that accomplished?

# Answer
> 5 votes
You would use `drupal_add_js()` to pass the data from PHP to JS:

```
$block_ids = array('blockid1', 'blockid2');
$settings = array('myModule' => array('blockIds' => $block_ids));
drupal_add_js($settings, 'setting');

```

Then in JS you can pick these up like so:

```
var blockIds = Drupal.settings.myModule.blockIds;

```

---
Tags: blocks, javascript
---


# Question
Title: How do I install modules using a module?
I wanted to install few modules when my module is installed. How can this be achieved?

I am creating a module which requires few other modules to be installed. I want to install them when my main module is installed.

I have placed all those module folders inside one main folder, and I want to create an install file to install those modules when this main install file is executed.

# Answer
Just in addition to kiamlaluno's (correct) answer, if you want to get stuck in and do-it-yourself you can use the core `module_enable` function, perhaps in your module's `hook_enable()` function:

```
function MYMODULE_enable() {
  $modules = array('module_1', 'module_2');
  module_enable($modules);
}

```

The code is purely for demonstration purposes, I wouldn't actually recommend using it; if you want to make sure certain modules are enabled along with yours, the safest way is to use `dependencies[]` in your .info file as has already been described.
> 1 votes

# Answer
If there are modules from which your module depends, your module should declare them as dependencies, in its .info file. Supposing that your module is my\_secret\_module.module, and it depends from first\_module, and second\_module, my\_secret\_module.info should contain the following lines.

```
// Drupal 5
dependencies = first_module second_module

// Drupal 6, Drupal 7, and next releases
dependencies[] = first_module
dependencies[] = second_module

```

In this way, your module cannot be enabled of the other modules are not enabled too.
> 2 votes

---
Tags: installation
---


# Question
Title: How to get the active #comment-cid when a comment permalink is clicked?
I am trying to get the comments on my website to change color when they are active. More specifically, I am looking to do something very similar to what StackExchange sites do when you click on a notification in your inbox (like this). So what I initially tried to do, was to wrap the comment class in another div class called `comment_active` using an `if` statement to see whether the current page url contained the string "#comment-". (being that the permalink for a comment is `/node/nid#comment-cid` I am trying to get drupal to know what the current cid is) I am having some problems figuring out how to do this. Is placing, for example `#comment-1` even part of the url? or does it just bring you to the part of the page that contains that element id? is there a way that I can have the comment.tpl.php know whether a comment is active? Or should I be doing it some other way entirely?

# Answer
Try to add a custom javascript file to in theme.info file

```
 jQuery(document).ready(function() {
    //get the current path
    var pathname = window.location.hash;
    jQuery(pathname).next().addClass('active-comment');
    //here add your custom animation
    jQuery('.active-comment').fadeOut().fadeIn().fadeOut().fadeIn().fadeOut().fadeIn().fadeOut().fadeIn().fadeOut().fadeIn().fadeOut().fadeIn().fadeOut().fadeIn().fadeOut().fadeIn();

});

```

here is a plugin to animate the background color of the wrapper :here

Hope this will Help You
> 1 votes

---
Tags: 7, comments, uri
---


# Question
Title: No data returned when SSL enabled for REST server via services module
I am running a LAMP stack on CentOS with Drupal 6 and the latest Services module. Over HTTP the REST server I have running works fine and behaves as expected.

When I installed an SSL certificate I forced all port 80 traffic to 443 (SSL). This worked fine for Drupal but has caused the REST server to return no data. Naturally I have removed the force SSL and allowed both HTTP and HTTPS for the time being.

I am testing via Fiddler, which when used to access the endpoint over HTTP, returns the expected data. Testing over HTTPS I receive no data. Do I need to make a configuration change to the REST server?

# Answer
OK so I had some help in where to look on StackOverflow but ultimately I discovered my problem myself.

The issue was that I was using a name based Virtual Host rather than an IP one.

So to be clear, I had:

```
<VirtualHost MyDomain:443>

```

and I needed

```
<VirtualHost *:443>

```
> 1 votes

---
Tags: services, ssl
---


# Question
Title: Drupal 7 Forms API radios value not saving to the $form_state array after submitting
I have a form where I am using radio buttons and when I use integers as the index, the form is saving and passing the value just fine. However if I use a string as the index it is saving nothing in the $form\_state\['storage'\]\['values'\].

**Example - This works as expected:**

```
$testArray = array(0 => 'test1', 1 => 'test2', 2 => 'test3');

$form['step0']['testthis'] = array (
    '#type' => 'radios',
    '#options' => $testArray
);

```

After submitting this example the $form\_state will look like (with array index 2 selected):

```
- Form Storage -
Array
(
    [values] => Array
        (
            [step0] => Array
                (
                    [testthis] => 2
                )

        )

)

```

**Example - This does not work as expected... for me!**

```
$testArray = array('test01' => 'test1', 'test02' => 'test2', 'test03' => 'test3');

$form['step0']['testthis'] = array (
    '#type' => 'radios',
    '#options' => $testArray
);

```

After submitting this example the $form\_state will look like (with array index test03 selected):

```
- Form Storage -
Array
(
    [values] => Array
        (
            [step0] => Array
                (
                    [testthis] =>
                )

        )

)

```

I expect it to output

```
- Form Storage -
Array
(
    [values] => Array
        (
            [step0] => Array
                (
                    [testthis] => test03
                )

        )

)

```

Any insight would be most appreciated!

Thank you.

Edit: I forgot to mention that the HTML element is output just fine. So using the string index the element looks like:

```
<input type="radio" id="edit-step0-testthis-test3" name="step0[testthis]" value="test03" class="form-radio">

```

# Answer
> 1 votes
My mistake!

I am using AJAX to submit the form and selecting the radio button using the .attr() function.

I was using an improper name in the element selector thus nothing was technically being selected.

Hope that helps someone else!

---
Tags: forms
---


title: Need block context in hook_form_alter

text:
# Question
Title: Need block context in hook_form_alter
I'm trying to get my module to work: it replicates an exposed filter of a view into a block to display on other pages. Altering the form generally works, but it unfortunately works globally, ie. my changes are also applied to the original filter form on the views page. That's because I use a simple checking of $delta which does not give me a context - sort of module signature that embedded the form.

I tried both `hook_form_alter` and `hook_form_FORMID_alter` \- the variables passed to those functions don't seem to carry that info though.

Is there a way to get this kind of context?

# Answer
> 0 votes
If you are displaying this block on only certain pages, looking at `$_GET['q']` or `arg(#)` will tell you that path or one of its arguments, so maybe you can switch on that? eg, `path/to/my/page` is in `$_GET['q']` and `arg(2)=='my'`. Note that paths to nodes are system paths, not aliases, so the path might be just `node/#` but you can do a `drupal_get_path_alias()` to find it if need be. If you are displaying the block only on certain node types, you can grab `$node=menu_get_object()` and then switch on `$node->type` as an example as well. In fact, if you do it that way, `$node->path` should already point to the aliased path, and it's already cached for your performance pleasure :)

Oh, and failing all the above, you could do all of this in a custom module block, too, eg, in there do something like:

```
$block['subject']='// subject goes here';
// do the hook form alter
$content=views_embed_view( // the view in question );
$block['content']=$content;

return $block;

```

All of the php above presumes D6, minor changes apply to D7, but since it is being called in the block itself, the form alter should only change the view there (unless it is also being displayed elsewhere on the same page)

---
Tags: forms, blocks, 7, views
---


# Question
Title: Translating pages, only the last version remains
I am setting up my first Drupal site, with Drupal 7, which is multilingual; I thought after surprisingly much work I had set it up correctly.
I can choose a language for each page, and translate pages, but when I translate a page, all translations of that page will have the same text: the last one I entered. So the text of the other language versions is overwritten by the last edited one. Did I do anything wrong? Is there a bug?

You may have a look here.

The login credentials, if you want to test it are: test, test.

# Answer
The problem is the 'synchronize translations' submodule of i18n was enabled.
I took the privilege of disabling it on your test site.
I know multilanguage is a tricky part in D7 but you should start with the basics of multilanguage by enabling locale, content translation, Internationalization, block languages, multilingual content and string translation. Just to get a feeling of what you're doing.
Later on you can activate some other submodules of the i18n module but in my opinion it is never a good idea to activate all at once.
Activating to many modules at once can result in losing control of your installation like you're having right now.
> 1 votes

---
Tags: i18n-l10n
---


# Question
Title: Putting subsites outside of the sites directory
When number of subsites increase, is there a way to put subsites in a directory outside of *sites* directory or even outside of drupal base directory, like */var* ?

Are *symlinks* the only solution?

# Answer
The location of subsites is hard-wired in function conf\_path().
> 2 votes

---
Tags: 7, subsites
---


title: add a user and role programatically

text:
# Question
Title: add a user and role programatically
I am using the following code to add a user:

```
  $roles = user_roles();
  $userinfo = array(
  'name' => 'user2',
  'pass' => '123456',
  'init' => 'user2d',
  'status' => 1,
  'access' => REQUEST_TIME,
  // This is where we are different from the default function.
  'roles'        => array(array_search('student', $roles) => 6),

);
$account = user_save(drupal_anonymous_user(), $userinfo);

```

I am getting this error message:

```
PDOException: SQLSTATE[23000]: Integrity constraint violation: 19 column name is not        unique:
INSERT INTO {users} (uid, name, pass, created, access, status, init) VALUES (?, ?, ?, ?, ?, ?, ?); Array ( [0] => 15 [1] => user2 [2] => $S$DrkIg0KuBFO12eQ9nQ5ViSx4ydfcWS0nS1TMvaTjYyZyfmVniGgh [3] => 1333135061 [4] => 1333135061 [5] => 1 [6] => user2d ) in drupal_write_record()
(line 6975 of

```

I am wondering if someone can explain what is going wrong with me trying to add a role. ......

# Answer
> 5 votes
`drupal_anonymous_user()` gives you an object with a `uid` that is considered *empty* by PHP. This means, your call to user\_save() will try to insert a new user into the database. The insert operation fails, because a user with the name *user2* already exists in the database.

---
Tags: 7, users
---


title: Proper way to handle ajax request

text:
# Question
Title: Proper way to handle ajax request
I know the way that I'm currently implementing ajax page loads is not the best way to do it. It goes like this:

I have a module (that I created) that has a path to send all ajax request though. based on the urls parameters, it's able to figure what actual page (node) needs to be loaded. It just returns a json\_encoded string for processing (rendering is done client side).

The trouble with Drupal is that it wants to decorate EVERYTHING with all the templates. So I get json intermingled with html. I obviously don't want that. I don't want any rendering done at all in fact. So far, the only thing I've come up with on my own is to implement hook\_page\_alter and just unset as much data as possible until it renders with only the json. That was working for a while.

Then I added the devel\_themer module (or whatever it's called). That automatically appends some javascript to the end of every response. That is breaking the json I'm sending via these ajax requests.

This has brought up the issue of my method of processing the ajax.

What is considered best practice for this type of thing? Ultimately, there may be minimal server side rendering, but I want the data to be sent in chunks that I can inject in various parts of the page. I don't want to have to put in all in one spot. To the ajax\_response.title would go in the div with id="title" and the ajax\_response.body would go in the div with id="body". There may be info between those two that I don't want to replace/re-render between requests.

Mostly my question is this: How can I tell drupal to send exactly the text that I want as a response instead of insisting on decorating the response with templates and allowing modules to add information?

# Answer
Simply print your json stuff in your page callback instead of returning it, then Drupal isn't going to add anything around it. In fact, there is a helper function for that, called drupal\_json\_output(), see user\_autocomplete() for an example of that.

That's the official way to deal with this currently, Drupal 8 will hopefully add proper handling for different types of content directly into the routing system (which will be heavily reworked and built upon Simfony2 components).
> 3 votes

# Answer
Use

```
 // do your processing
 print $json_object

```

This keeps all the Drupal rendering and template stuff away.
> 1 votes

---
Tags: ajax
---


# Question
Title: How to add {less} files to Omega HTML5 subtheme?
I would like to use **less.js** and the **less** module to work with my **Omega**-based HTML5 themes. How to add \**.css.less\* files to the Omega-based subtheme .info file ?

My current set up is:

1. /sites/all/themes/omega - the Omega master theme directory
2. /sites/all/themes/custom-html5 - Omega-based HTML5 subtheme directory
3. /sites/all/themes/custom-html5/css/custom-html5-alpha-default.css - my default css file

This question is related to

my previous one: How to use CSS preprocessor LESS.js with Drupal 7?

# Answer
> 6 votes
Install the LESS module and then in your custom-html5.info file just add your LESS CSS files like you would normally add stylesheets:-

```
stylesheets[all][] = css/custom-html5-alpha-default.less

```

The module will detect the LESS files (those with a .less file extension) and process them so that they are output as standard CSS.

Processing the LESS files on the server rather than via the browser using JavaScript will give the end user a better experience and ensures that the look of your site isn't dependent on JavaScript. If you really must include the less.js file then perhaps you could consider using the drupal\_add\_js() method in your template.php file.

# Answer
> 2 votes
From #10 @ http://drupal.org/node/928292

> Using stylesheets\[all\]\[\] = example.css.less is problematic. This usage, while \>generally correct, causes example.css.less to load before Omega's stylesheets.
>
> You can use LESS stylesheets in place of regular CSS files using Omega directives, \>however:
>
> Create global.css.less in your theme's css folder (important!).
>
> Create a stanza like this in your theme.info file:
>
> ```
>     css[global.css.less][name] = My Project styles
>     css[global.css.less][description] = LESS CSS stylesheet for My Project.
>     css[global.css.less][options][weight] = 10
>     settings[alpha_css][global.css.less] = 'global.css.less'
>
> ```

Take a look @ http://drupal.org/node/1233904 for a good start to a LESS file.

---
Tags: theming
---


# Question
Title: Views display settings are in the database but don't show up in views UI
I'm trying to create a copy of a live site and use it as test site, but I have troubles with a view whose settings are in the database, which does not show up correctly in the UI.

I copied the site by installing Drupal, the required modules, including some custom features, and exporting the database.

The view is defined in a feature, and also exists in the *views\_view* and *views\_display* database tables. I have not reverted the feature, so I believe the feature code should be ignored in favor of whatever is in the database.

In the database and in the feature, the view has display with some settings that overrides the default display, for example *Header: PHP Code* overrides *Header: None*. In the UI, the added display exists, but, except for *Name*, all of its overridden settings, relationships, arguments, fields, and filters are gone.

That is the case for some of the other displays on the view too. A display lost its relationships, arguments, and sort criteria, but not its fields and filters.

I've tried running `drush cc all`, clearing the cache from *Admin \> Site Building \> Views \> Tools*, and deleting all rows from the *views\_object\_cache* table; None of them helped.

# Answer
> 0 votes
The test running on a 32-bit system, and the Role Export module did not support 32-bit systems. (See 32-bit overflow in role\_export\_generate\_id, a bug report that is still open and it will never be fixed, since Drupal 6 is no longer supported.)

Once MAMP has been upgraded to a 64-bit version, the view worked as expected.

# Answer
> 0 votes
FWIW - you might want to install drush and use the drush archive-dump command which will extract your entire site (database, drupal instance and files) into a single tarball file. You can then use drush archive-restore to import that site into a different site on the same or different machine.

There are other ways, of course, but this seems to be one of the easiest as there is nothing to remember or think about other than doing it.

Good luck - B

# Answer
> 0 votes
Memcache seems like a possible cuplrit. Try clearing out memcache cache manually. Drupal generally dislikes DB edit's and may not understand to requery the actual DB, but instead is getting the values from Memcache.

/etc/init.d/memcached restart

---
Tags: views, 6, features
---


title: How to pass fields values

text:
# Question
Title: How to pass fields values
How to pass float field value from node(content type A) to another node(content type B)?
which content type B referenced to content type A by using reference from url widget.
thanks

# Answer
> 2 votes
First of all: This introduces redundant data into your DB. Generally this isn't a good idea.

If you must for some reason:

You can implement hook\_node\_presave for content type B. You get the fully populated $node. This gives you the possibility to load the referenced node type A and grab the value you want to set in B.

Maybe you want to consider to implement the same for content type A. This gives you the possibility to propagete this value every time it changes.

---
Tags: nodes
---


# Question
Title: Linking External Javascript with drupal_set_html_head
I want to add the below external javascript file to the head of my Drupal 6 site.

```
<script type="text/javascript" src="http://w.sharethis.com/button/buttons.js"></script>
<script type="text/javascript">
stLight.options({
    publisher: "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
});
</script>

```

I want to know if it's OK to do somethng like this, as it's not working at the moment.

```
function template_preprocess_page(&$vars){
  drupal_set_html_head('<script type="text/javascript" src="http://w.sharethis.com/button/buttons.js"></script>');
  drupal_set_html_head('<script type="text/javascript">stLight.options({publisher: "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"}); </script>');
}

```

Someone should kindly assist me feature the links of the external file in the header of every page of my site.

Thank You.

# Answer
I think all you need to add is `$vars['head']=drupal_get_html_head();` after your code above so that the $head variable passed to your page.tpl.php is updated. If you are doing anything "interesting" with your header, you may need to change that to a `.=` instead so that it is added to $head instead of just replacing it.
> 6 votes

---
Tags: javascript
---


# Question
Title: ShareThis in header rather than content type?
I am adding Drupal ShareThis to a header mini-panels, but the buttons are not displayed. Firebug tells me that the corresponding code is not there at all. How can I display ShareThis buttons outside of content types?

# Answer
Please try the following:

* Go to menu Structure\>Blocks.
* find the ShareThis block.
* set the block region settings for the theme you are using
* go to block configuration and make sure the block is visible for all required pages, content types, roles, users
* go to menu Configuration\>Web Services\>ShareThis
* go to 'Advanced' section
* find 'Location' settings
* select 'Block' to select the ShareThis widget should appear as a block and not in a node content.
> 1 votes

---
Tags: 7, social-network
---


title: Google+ in ShareThis module

text:
# Question
Title: Google+ in ShareThis module
How can I add the Google+ option in the ShareThis module? They posted a blogpost on the 6th of July where they stated the Google+ and Facebook options are added to the module. But when I download the module, there is no such thing as a Google+ button...

However they say it's easy to implement, I didn't find any way how to do this. So if anyone would like to help me out here, it would be much appreciated!

# Answer
> 1 votes
Now you can use ShareThis with both Google+ and Facebook Like.

Go to Menu\>Configuration\>Web Services\>ShareThis

* Go to *Choose services* to pick Google Plus One or Facebook

or

* Go to *Extra services* to pick Google Plus One or Facebook Like

You can also see details how to set this up directly in the html code here.

---
Tags: social-network
---


title: 2 sites sharing one user table

text:
# Question
Title: 2 sites sharing one user table
How can I make 2 Drupal websites share the same user table so when a user is logged in on one they are automatically logged in on the other?

# Answer
Your question seems to be all over the place. However, the Bakery Single Sign-On System module sounds like what you need.

> Bakery provides a "single sign on" feature for Drupal based sites that are on the same second-level domain (i.e. example.com, subsite.example.com, subsite2.example.com). It could also provide support for any other website that implements the same web cookie, xmlrpc, and POST methods.
>
> This module started at the 2009 Drupal.org redesign sprint in San Francisco as a way to manage single sign-ons across \*.drupal.org infrastructure.
>
> Read the bakery documentation for more information.
> 5 votes

# Answer
tl;dr Try using the Domain module suite. I allows you to run a site that "pretends" to be more than on domain, and helps you with relevant access rules and content sharing.

My experience with sharing tables is that you are in for a world of pain. I've tried it twice in the past and it has had various odd effects, due to various modules becoming confused. I no longer remember any specifics though, but if I did it today, I would take my own advice from above. :)
> 1 votes

---
Tags: 7, users
---


title: Redirect a node to it's custom view

text:
# Question
Title: Redirect a node to it's custom view
I've created a `view` *"myview"* for a custom `content-type`.

Now I want: Any node of that `content-type` to be automatically redirected to that view page.

For example, if a user types: http://my-drupal-site/node/4 and that node is of my desired `content-type`, it needs to be redirected to http://my-drupal-site/myview/4

**What I can do:**

What I can do now is writing in my theme's `template_preprocess_node()` function following lines:

```
function myCustomTheme_preprocess_node(&$variables) {
    $arg1 = (int) arg(1);
    $isArg1Int = (is_int($arg1) && $arg1) ? (true) : (false);

    if (isset($variables['node']->type) && $isArg1Int) {
        if ($variables['node']->type == "MY-DESIRED-CONTENT-TYPE") {
            // REDIRECT!
            drupal_goto('myview/' . $variables['node']->nid);
        }
    }
}

```

That's pure hard-code, and I don't like it. Is there some elegant solution, may be using URL aliases or something like that?

# Answer
> 5 votes
You can use Panels like Patrick suggests, but Panels requires a lot of resources and it's a bit of a waste to only use it for this simple case.

There are different approaches to this, one could be to react to the full view of the node:

```
/**
 * Implements hook_node_view().
 */
function hook_node_view($node, $view_mode, $langcode) {
  if ($node->type == 'type' && $view_mode == 'full' && arg(0) == 'node') {
    drupal_goto('url/' . $node->nid);
  }
}

```

The if statement if true if the node is of the correct type, is being view in full view and the url is `node/...`, which should limit to node being view the standard way.

Another way of doing this, would be to use the redirect module or something similar to setup redirects for all nodes of the type to the view. A weakness to this approach could be path alias. But that way you would make a permanent redirect which is more SEO friendly.

# Answer
> 2 votes
You can definitely do this in Panels by adding a variant to the default node display override and then a selection rule for "content type = my\_content\_type."

You may also be able to just use Page Manager, part of Ctools and a dependency of Panels, to set this up but I'm not sure how to do it off the top of my head.

Node One has an excellent screencast on learning Page Manager and Panels.

---
Tags: 7, views, uri, redirection
---


# Question
Title: In Panels, how are the 2 given arguments in System's node_view created?
In the Panel pages for System node\_view (Node template) and term\_view (Taxonomy term template), there is a variant that is already defined. This variant has 2 arguments, "Node being viewed" and "Depth". How are these arguments created?

thanks,

Eric J.

# Answer
> 1 votes
Panels has by default some operations on url arguments which can create variables used in Panels. The short explanation is that Panels for nodes does a `node_load` on the node id which is part of the url: `node/[nid]`. It does something similar for taxonomy terms, only depth isn't the term itself, but rather information about it.

You can do this yourself if you create a custom url with placeholders, like `my-panels-url/%node` and assign the variable to be a node or taxonomy term.

---
Tags: panels
---


# Question
Title: Can I use a token within a custom token?
I am trying to create a custom token that modifies another token.

```
$theDomainName = "[domain-name-raw]"; //Pull in the other token
$removeCounty = str_replace(" County", "", $theDomainName); //Replace " County" with nothing
$countyPlus = str_replace(" ", "+", $removeCounty); //Replace " " with "+"
return $countyPlus; //Return modified token as new custom token to be used through out site

```

If I use *\[domain-name-raw\]* for `$theDomainName`, my result is the original token (e.g. "Cerro Gordo County"). If I type what *\[domain-name-raw\]* should output for `$theDomainName` (e.g. "Cerro Gordo County"), my code works fine (it outputs "Cerro+Gordo"). What is going on?

I am using Drupal 6.

# Answer
You could use something like `token_replace()` to get the other token value within your own token, but you shouldn't try to alter an already created token, as that will mess up when you really want to use that token.

You need to define you own token, and handle the output of that token. But in doing so, you will most likely find that it will be easier to get the raw values from the PHP values supplied instead of using `token_replace()` or something similar.

You need to look at `hook_token_list()` and `hook_token_values()` to define your custom token.
> 1 votes

---
Tags: tokens
---


# Question
Title: Fatal Error: PDOException: SQLSTATE[42000] [1049] Unknown database
I have a development site (site1) and created a second (site2) using drush, copied over all modules/themes and continued development. Both were working and I continued module updates in both. When I returned to site1, I found an error message as follows:

> PDOException: SQLSTATE\[42000\] \[1049\] Unknown database 'mydevelopmentDB' in lock\_may\_be\_available() (line 167 of mywebsite/includes/lock.inc).

There features and nodes I would like to use in site2 but I cannot access it. So I created a new site (site3) using drush, copied the contributed modules & themes from site2, and imported the database from site1 into site3, only to get the same error message as from site1.

As I interpret this, situation, the core and contributed module files in site3 should be good, the core is a fresh copy and contributed modules are taken from site2, which is working fine. The settings.php files are identical except for the database, username and password settings match the individual database name. The only difference is the database itself. Can anyone help identify the table(s) that might have a setting that might cause this problem?

# Answer
> 5 votes
This isn't a problem with tables, it's a problem with the name of the database.

Drupal is successfully connecting to your database server, but it isn't finding a database with the name `mydevelopmentDB` (which must be the name of the database specified in settings.php).

To isolate the problem:

1. Open up PHPMyAdmin for the server in question and run this query:

```
SELECT * FROM mydevelopmentDB.users

```

If you get a similar error then you know that you've definitely got the wrong database name.
2. Make sure that the name of the database on the server matches the *case* of the database name in settings.php. Depending on your MySQL settings the server may or may not be enforcing case sensitivity on database/table names.

---
Tags: 7, database
---


# Question
Title: How to quickly create multiple Drupal 7 features?
I use Features and Strongarm to manage configuration of my Drupal 7 systems.

Until now I was creating features manually but even with Features Tools installed and ajax features status disabled it is a mundane process.

I want a separate feature for each contrib module and a separate feature for each view.

Is there a way to create features automatically or at least more quickly, maybe using drush ?

# Answer
You can use the Drush features add/export commands (add was removed in the latest version of Features (rc1)). As there have been a lot of changes recently with features rc1 and drush 5.0, the exact commands will differ depending on your setup, but `drush help` will list the features commands and `drush help fe` will show you the details (in this case, how to export \[e.g., create\] a feature).

If you really needed to create a lot of features, you could script Drush (either extend Drush itself or run Drush via bash script, etc.)
> 2 votes

---
Tags: 7, features
---


title: Auto increment in views table

text:
# Question
Title: Auto increment in views table
I have views with table display, the table consist of two column(name\[string\], salary\[float\]).
How can i set a auto increment for the table rows?
like this want i want .
Thanks.

# Answer
> 10 votes
You need to add a new field to the view, and choose the "Global" filter from the available drop down.

Then choose the "Global: View result counter" type:

That wiill give you a counter as a field which you can put into whichever column in the table is appropriate for what you need.

---
Tags: views
---


# Question
Title: how can i specify certain block for specific content type to get in there?
In Drupal 7 every content type gets in the "Main page content" block, so I want every node with "Product" content type to sits in some other block. How could I?

# Answer
> 2 votes
It sounds like you're looking for the Views module; it's essentially a query builder with a simple-to-use UI.

You can make a View that lists all the content of type 'product', displayed in a choice of different formats (HTML list, table, unformatted list of content, etc.). You can create different display modes for the View, including a block which you can assign to a region in the blocks admin page as normal.

The best part is, though, that you also get the benefit of being able to easily choose the sort order of the list, set filters on certain criteria, add AJAX pagers automatically, and a lot more.

Check out Working with Views to get started; you'll be glad you did!

---
Tags: blocks, nodes
---


# Question
Title: How do I group two nodes on the frontpage in a div?
I want to have every two articles on the homepage within a div structure.

However, I can't get this done in my node.tpl.php file: if I use the zebra variable to print a tag before the node when zebra is odd, and a closing tag after the node when zebra is even then this only works when there are an even number of articles, or otherwise the last div won't be closed.

In code:

```
<?php if($zebra=='odd'): ?>
     <div class='row'>
 <?php endif; ?>

 <div id="node-<?php print $node->nid; ?>" class="[..]">
 [rest of node here]
 </div><!-- /#node-x -->

 <?php if($zebra == 'even'): ?>
     </div><!-- /.row -->
 <?php endif; ?>

```

To make this work, I must be able to know when a node is the last one. But there isn't a variable $last in the node template file, neither is there a $count variable that hold the total number of nodes.

Does anyone has done something similar before?

# Answer
The node template is not (usually) aware of the context in which it's been called; when you list nodes as teasers each node is themed individually, and has no awareness of the other nodes in the list.

What you need to do is find out what template/function is responsible for outputting the list of nodes in question and override that in your own theme/module to add the extra divs.

The Theme Developer module might come in quite handy here, it provides an in-page way of isolating which theme functions have been responsible for rendering which areas of the page.
> 1 votes

---
Tags: nodes
---


# Question
Title: What is the Internationalization Views module for?
In what kind of use cases would one want to use the Internationalization Views module? I just discovered this module for the first time today, but documentation on it is sparse.

Since it is already possible to translate the fields and rewrites that are used in Views with the standard i18n module, what does this add?

# Answer
> 2 votes
Looking at the module code it seems to do the following:

* Adds a Translate operation to the ctools export UI (see the `i18nviews_ctools_plugin_post_alter()` function in the module file).
* Supports translation for views strings: title, header, footer (this is in the `i18nviews_help()` function).

The comment at the top of the module file is:

> This module translates some views strings on the fly using i18n string system

So I would guess the module is just providing internationalisation for some elements of the Views module that don't have it built in yet.

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


# Question
Title: Can I publish something in my wall of facebook?
I need to publish something in the user's facebook wall, when you entered the site, automatically.

This is the code that I actually use.

```
function publish(){
    global $user;
    $attachment = array(
            'name' => 'Name app',
            'href' => url('http://....', array('absolute' => TRUE)),
            'description' => 'Use this application.',
          );

    $user_message = t('Check out the latest application on !site...', array('!site' => t('My Drupal for Facebook powered site')));

    $actions = array();

    $actions[] = array('text' => t('Read More'),
                       'href' => url('http://....', array('absolute' => TRUE)),
                      );

    fb_stream_publish_dialog(array('user_message' => $user_message,
                                  'attachment' => $attachment,
                                   'action_links' => $actions,
                            ));
}

```

This code work, but it publish again the text when I edit the page, or I go to a different page.

Is there a module (for publish), or another way to do this?

# Answer
Set a session variable, or a cookie, when sent the first time; check that always.
> 0 votes

# Answer
If you are looking for a module to publish nodes on Facebook, there is the Drupal for Facebook module.

> This set of modules and themes turns Drupal into a platform for developing Facebook Applications. This allows you to embed your content and features within facebook, or allow facebook users onto your site via Facebook Connect.
>
> With Drupal for Facebook, you can harness all the power of Drupal in you Facebook App. **If you already have content in Drupal, you can expose it on Facebook.**

Read the online documentation for the Drupal for Facebook module to understand which libraries are required, and need to be installed; enable the Facebook API, and the FB Streams modules.
> 0 votes

---
Tags: 7, social-network
---


# Question
Title: How can I allow the user to choose their language upon registration?
There is a solution for showing the site language selection field on the user/register form in Drupal 6 here: https://stackoverflow.com/questions/5556895/how-to-add-language-switcher-in-user-register-form-in-drupal-6

However, I'm personally not able to convert this to Drupal 7. Is there another way to do this?

EDIT: When multiple languages are enabled via locale, the "Language Settings" with the list of user languages is shown on /admin/people/create. This is what I want-- except I want this to be shown on /user/register, where it is not (at least by enabling locale alone) shown by itself.

# Answer
As Drupal 7 doesn't show the language selector for the users who create their own account, you need to implement `hook_form_user_register_form_alter()` (see the documentation for hook\_form\_FORM\_ID\_alter()) using the following code.

```
function mymodule_form_user_register_form_alter(&$form, &$form_state) {
  // Only alter user forms if there is more than one language.
  if (!isset($form['locale']) && drupal_multilingual()) {
    locale_language_selector_form($form, $form_state, $form['#user']);
  }

  if (isset($form['locale']) {
    $form['locale']['#access'] = TRUE;
  }
}

```

The code is generic, and works even in the case a module removed the language selector field (which is something a module should never do, though).

"user\_register\_form" is the form builder used for the "user/register" path. The code works if the Locale module is enabled. The code will show the language selector if there are more than one language enabled; differently, `drupal_multilingual()` would return `FALSE`.

```
  $items['user/register'] = array(
    'title' => 'Create new account',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('user_register_form'),
    'access callback' => 'user_register_access',
    'type' => MENU_LOCAL_TASK,
  );

```

The code used from the Locale module is the following one.

```
function locale_form_alter(&$form, &$form_state, $form_id) {
  // Only alter user forms if there is more than one language.
  if (drupal_multilingual()) {
    // Display language selector when either creating a user on the admin
    // interface or editing a user account.
    if ($form_id == 'user_register_form' || ($form_id == 'user_profile_form' && $form['#user_category'] == 'account')) {
      locale_language_selector_form($form, $form_state, $form['#user']);
    }
  }
}

```

In general, the equivalent for `hook_user('register')` in Drupal 7 is `hook_form_user_register_form_alter()`; the equivalent of `hook_user('form')` is `hook_form_user_profile_form_alter()`.
> 2 votes

# Answer
Yes you can add any kind of field in user registration form using Profile2.

First download the required module and enable the profile 2 module.Then go to "admin/structure" There you will find a option like "Profile types".Click on that, then you will get a form like content type manage field.There you can create selectbox option.

If you need this selectbox should come on the user registration page follow the below steps

1. Go to "admin/structure/profiles/manage/main"
2. There you will get a Checkbox, check it to visible the field in registration form
> 0 votes

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


# Question
Title: How can I grant anonymous users access to the locale language select form without hacking core?
I am attempting to override the user registration from at user/register to allow users to select their own language upon login.

Based on this helpful answer, I came up with this override:

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

  $form['locale']['language'] = array(
    '#type' => (count($names) <= 5 ? 'radios' : 'select'),
    '#title' => t('Language'),
    '#default_value' => $user_preferred_language->language,
    '#options' => $names,
    '#description' => $mode ? t("This account's default language for e-mails, and preferred language for site presentation.") : t("This account's default language for e-mails."),
  );

```

However, it doesn't work because of the following code in locale.module:

```
  $form['locale'] = array(
    '#type' => 'fieldset',
    '#title' => t('Language settings'),
    '#weight' => 1,
    '#access' => ($form['#user_category'] == 'account' || ($form['#user_category'] == 'register' && user_access('administer users'))),
  );

```

Simply deleting `&& user_access('administer users')` from locale.module and clearing the cache makes it work, but if I do that I'm hacking core.

How can I remove the bit about `&& user_access('administer users')` without hacking core?

# Answer
You should be able to just replace the `#access` property for the element added by the locale module in your form alter:

```
function MYMODULE_form_user_register_form_alter(&$form, &$form_state, $form_id) {
  // Use exactly the same access logic as the original,
  // without checking for the 'administer users' permission
  $form['locale']['#access'] = ($form['#user_category'] == 'account' || ($form['#user_category'] == 'register'));
}

```

That's essentially the same as taking the `&& user_access('administer users')` part out of the core file.

All you need to make sure of is that your module hooks are run after those of the locale module (so the element actually exists when you try to alter it), which you can see how to do here.
> 5 votes

---
Tags: 7, hooks
---


title: filter vocabulary from vocabulary

text:
# Question
Title: filter vocabulary from vocabulary
I have several vocabularies; let's assume they are the following ones:

* v1, with terms v11,v12,v13
* v2, with terms v21,v22,v23
* v3, with terms v31,v32,v33

I have a product category. When you hit the product category, I want that a page appears showing drop down menus of the above vocabularies, and the drop down containing their terms.

1. How can this page be called from the click on the product category?
2. Now the main problem I want to solve is when the page containing the drop down menu appears, and the user clicks on a particular term of a vocabulary, that action filters some terms in the other drop down menu. For example, if v11 is selected in vocabulary v1, then with v2 only terms v22 and v23 are allowed, and in v3 only v31 is allowed so when you select term v11 the other menus should only show the allowed term. Also when a term is selected, the below section of the page should show only those products (teaser or table) satisfying the attributes as selected in the terms. And we have two choices in vocabulary v2 we can select either v22 or v33 which will further filter the search criteria of products in that category.

An example can be seen on this site.

In the left side menu, go to detection and ranging, and hit on laser measurement technology. The page which appears has several drop down menus; I want to acheive the same functionality.

# Answer
> 1 votes
Essentially, you want a hierarchical 'drill down' through taxonomy to narrow a search? If I'm interpreting this correctly, you're looking for something like Hierarchical Select, a module that does just that in the form of an input widget. I don't have personal experience with the exposed filter implementation, but it sounds like it exists.

http://drupal.org/project/hierarchical\_select

http://drupal.org/node/720268

# Answer
> 0 votes
I have never used Hierarchical Select, and I might be underestimating the difficulty of this challenge, but smells like each term in v1 should have a term reference field linking to a term from v2, and a similar binding should be established between terms of v2 and v3. This would define allowable relationships that we see in your example site. Without those relationships you won't be actually able to say what you should see on your pages.

And then - well - Views (Term) for a good start.

There are tons of taxonomy related modules out there, so it's perhaps premature to recommend you any particular ones. Let us hear from you how you're doing. I'm sure you'll hear a lot of recommendations as you precisely outline your issues.

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


# Question
Title: mysql server gone away while loading drupal site in the shared environment
i am getting serious error in the production server when i deploy for the first time. Please find the below PDO exception which i am getting.

```
PDOException: SQLSTATE[HY000]: General error: 2006 MySQL server has gone away in variable_set() (line 977 of /var/www/htdocs/includes/bootstrap.inc).

```

I am not allowed to increase allowed packet size and wait timeout in the mysql end, because multiple sites are running on the DB and such a way we are not allowed to change php.ini also.

Is there any other solution for this problem I am facing this issue with the client for past one week not it has been very critical for me.

Could anyone please help me out to get ride of this issue? Thanke in advance.

# Answer
> 2 votes
Increase max allowed packet size is the only proper way of doing this.
If your host doesn't allow you to change values in your multi-site environment simply change the host because you could experience a lot more problems overtime if you're not allowed to change anything!
A quickfix solution could be to limit the number of activated modules and by this limit the number of queries executed on page loads.

---
Tags: database
---


# Question
Title: Keep Footer at the Bottom of the Page w/ Andromeda Theme
I recently setup a site using the Andromeda theme and love it! However the only issue I have is that when a page doesn't have much content in it the footer does not stick to the bottom of the page. I have tried to implement some of the css answers I have seen on this site with no luck. Does anyone else know how to implement this?

# Answer
> 1 votes
You should be able to do this with CSS using

```
position: fixed;

```

On the footer and placing it on the bottom of the screen.

---
Tags: theming
---


# Question
Title: Multisite setup on local development environment
I've been around the block with this one. and I'm back at my front door!

I am trying to setup a multisite configuration on my local dev server, which currently looks like this. I'm using Xampp in a windows environment so my root is "Xampp\htdocs\\"; then any site I'm working on is created under a folder here.

This gives me the follwing Drupal stucture.

> \sites\all\themes\devsite

In my browser, I can go to http://localhost/devsite, and it launches my Drupal site without problems; If I go to http://localhost, I get redirected to XAMPPS installation page.

So now I embark on the multisite config.

First, my hosts file is altered to include these two entries.

* 127.0.0.1 devsite.com
* 127.0.0.1 m.devsite.com

Browsing to the following URLs launch my site.

I now copy my \devsite\sites\all structure to a \devsite\sites\m.devsite.com folder and setup a \devsite\sites\sites.php file with these entries.

```
$sites = array(
    'devsite.com' => 'all',
    'm.devsite.com' => 'm.devsite.com',
);

```

If I browse to either hostname, both load the site configuration which is in All. I can't seem to get it to load anything within m.devsite.com? I've tried copying the settings.php file into each stucture which produces an error message. I've tried renaming All to devsite in folder and sites.php but then I get a blank page when browsing.

Do you have any idea on what is wrong?

# Answer
> 2 votes
Not sure what exactly you want to do.

Multi-site is usually used to create *separate* drupal installation from the same drupal folder. To create one, you need to copy default/default.settings.php to yoursite.com/settings.php, make it writable and then visit the site, which should present you with the installer.

You only need to something with sites.php if you want to override the default domain mapping and e.g. also server siteB.com from sites/siteA.com. Also, Drupal doesn't search for a settings.php in 'all' but 'default'.

Your naming scheme sounds more like you want a mobile version of your site, which usually just implies that a different theme is used and some other mobile specific things. There are modules which can automatically changing the theme when the site is requested by a mobile browser.

# Answer
> 0 votes
You need to configure httpd-vhosts.conf as well, along with hosts file Add an entry like this to your vhosts file,if this is the first time you are using this file then its probably commented in httpd.conf file, uncomment it and restart apache.

```
<VirtualHost *:80>
    ServerName m.foo.com
    DocumentRoot "C:/xampp/htdocs/drupal_folder"
</VirtualHost>

```

inside sites folder create a folder called m.foo.com and make sure you have a valid settings.php file in it. You should be able to see your site now when you open `m.foo.com` And as suggested by Berdir if you want a mobile site , then no need of another sub site you can create a mobile theme and make use of mobile tools module or something similar to switch between m. and www. for your sites.

---
Tags: multi-sites
---


# Question
Title: How can I generate similar sets of fields in views quickly from within the views ui?
I have several views that I have made of the users on my site. Each view has different contextual filters, pages, and fields. However, certain "groups" of fields are the same.

In particular, I have a series of four checkboxes on the user profile that I use the views module's rewriting ability to display, and this "group" of four fields is the same among all views.

Is there a way to somehow save this as a reusable unit within the views UI so I don't have to input it manually all the time?

# Answer
The easiest thing to do it to add all of the common fields to the Master display, and then a few displays to the view that get customized for the individual uses using overrides.
> 1 votes

---
Tags: 7, views
---


# Question
Title: How to Use Ajax in form alter in Drupal 7?
I have created a content type named "main menu". I have few select lists which depend on one another. I wanted to display a different list when different checkboxes are selected. I figured out that I need to use Ajax to edit the form in order to achieve that but can anyone tell me how to use Ajax with hook\_form\_alter?

The form id of the form I am supposed to edit is "main\_menu\_node\_form". When I try to access this form using `hook_form_alter()`, and add the `#ajax` property of the form fields, it seems that I am not able to do that since the fields are already rendered before the handle is passed to `hook_form_alter()`. Can anyone please help me solve this?

Note : I have created the content type using `hook_install()`.

```
function main_menu_content_type_form_main_menu_node_form_alter(&$form, &$form_state, $form_id) {
  dpm($form);
  dpm($form_state);

  $form['field_mlnk'] = array(
    '#ajax' => array(
      'callback' => 'main_menu_content_type_form_main_menu_node_form_alter_callback',
      'wrapper' => 'link-div',
      'method' => 'replace',
      'effect' => 'fade',
    ),
  );
}

```

# Answer
> 7 votes
I would be able to give you some detailed information about what you are doing wrong with hook\_form\_alter if you included some actual code from your custom module. However, since you are not giving any specifics, you can watch the video: How to build beautiful forms in Drupal 7 (note that I entered the URL so that it starts at the moment where the ajax is described). About 5 minutes of watching this will probably give you the answer to your question (since it describes exactly how to use ajax with hook\_form\_alter), but if you are really impatient, the actual code is shown somewhere around here.

If you want to see a live, well-tested and documented example of a form being altered using ajax, there is one in the Examples module. You can find the actual hook here and the callback function here.

I hope this helps. If it doesn't, give us some more background about your code and we will be able to tell you exactly what you are doing wrong.

---
Tags: forms, ajax
---


# Question
Title: Let users download entire folders (zip first) or individual files?
Is there a module or a series of modules that will allow users to download a folder of files (e.g. construction blueprints and sketches) or just individual files via the browser?

The files for user A should be only accessible to user A.

# Answer
> 1 votes
I suspect that the functionality that you are looking for exist in the elFinder file manager module. It allows downloading individual files and whole folders after compressing them first.

You can manage the roles that you allow to download specific files with the native drupal permission system. Just make sure that you don't give your users access to sensitive files in drupal installation.

---
Tags: files
---


title: How do I modify the "group" label?

text:
# Question
Title: How do I modify the "group" label?
I would like to use Organic Groups in a way that would make each group a company. Is there an expeditious way to do a mass modification of the label "group" wherever it appears on the UI? I'd like the references to "group" to be changed to "company".

# Answer
I think the String overrides module would be the quickest way. The module:

> Provides a quick and easy way to replace any text on the site.
> 2 votes

---
Tags: organic-groups
---


# Question
Title: How can I put a checklist button in a views table to run some code on selected rows?
I want to select some rows in views table and run some code for selected rows(nodes) by submit button.
How can i do that?

# Answer
> 3 votes
It sounds like you want to use the views bulk operation module.

---
Tags: 7, views
---


# Question
Title: how to add a terms to a vocabulary by form?
I'm using drupal 7
I need to create a form that can add new terms to specific vocabulary.
Which function can do that?
Thanks

# Answer
> 1 votes
Check this link taxonomy\_term\_save($term)

---
Tags: taxonomy-terms
---


title: Making a basic block in Drupal 6

text:
# Question
Title: Making a basic block in Drupal 6
I am trying to make a simple block to put out some HTML. However, my block is not showing. This is what I have from putting it together from different pieces of code.

```
function blue_block_info() {
  $blocks['blue_block'] = array(
    'info' => t('Blue'),
  );

  return $blocks;
}

function blue_block_view($delta = '') {
  $block = array();

  switch ($delta) {
    case 'blue_block';
      $block['subject'] = t('Blue');
      $block['content'] = blue_content();
      break;
  }

  return $block;
}

function blue_content() {
  return '<div>this is a test</div>';
}

```

# Answer
> 4 votes
The code you are using above is for Drupal 7, not Drupal 6. In Drupal 6, it would be the following one.

```
function blue_block($op = 'list', $delta = 0, $edit = array()) {
  switch ($op) {
    case 'list':
      // code from your blue_block_info()

    case 'view':
      // code from your blue_block_view()

  }
}

```

---
Tags: 6
---