# Question
Title: Make the Main Menu have dynamic links based on url
My main menu has links to common things: HOME | PHOTOS | VIDEOS ... etc. Home points to `/`, PHOTOS points to `/photo-galleries` and VIDEOS points to `/videos`

The client has added a new feature request and I'm trying to figure out how to handle this. The site has a couple of general topics, let's say `baseball`, `football` and `soccer`.

When I browse to the main home page `/`, then the menu should point to `/photo-galleries` and `/videos`.

However, when I browse to the "baseball filtered" home page `/baseball` then I'd like the photo galleries menu link to point to `/photo-galleries/baseball` and the videos link to point to `/videos/baseball`.

This "filtering" should follow them through out the site, so once they are on `/videos/baseball` then all of the menu links should continue to have the `baseball` element on them.

I'm unsure how to approach this problem and I feel like there should be an elegant way to handle this and I'm not the first person to have this problem.

I understand how to setup my various Views on the different pages so they have contextual filters and only show the content items with the `baseball` tag, but my big question is about how to handle re-writing all of the URLs of the menus and the content URLs.

Help? :)

# Answer
> 2 votes
3 (updated) options (or a combination thereof) for you to consider:

1. The drupal module Menu Token provides the ability to put *variables* in your menu options -- and used in conjunction with your existing context filtered views, may work for you if it allows you to construct the menu options you need based on other tokens that it makes available to you.
2. The other option is to consider an alternative approach (sorry! :) ). This would be faceted filtering. Follow the tutorials here: http://webwash.net/tutorials/intro-search-api-part-1-how-create-search-pages This is possible on even the most modest of hosting as it does not require Solr (but it *can* use it if you need that functionality later).
3. (added in update) Drupal module Menu Trail By Path

I think option 1 (perhaps in conjunction with option 3) might be the closest to what you are looking for though.

# Answer
> 1 votes
Hope this will help you,

In Drupal 7, for your requirement you can use **ThemeName\_links\__system\_main\_menu** function in your template.php file. This function works only for Main menu.

```
function ThemeName_links__system_main_menu($variables) {
  $links = $variables['links'];
  $html = "<div><ul>";
  foreach ($links as $link) {
    if(baseball filtered) {
      if(home menu) {
        $link['href'] = 'baseball';
      }
      if(photo menu) {
        $link['href'] = 'photo-galleries/baseball';
      }
      if(video menu) {
        $link['href'] = 'videos/baseball';
      }
    }
    elseif(filter is football) {
      if(home menu) {
        $link['href'] = 'football';
      }
      if(photo menu) {
        $link['href'] = 'photo-galleries/football';
      }
      if(video menu) {
        $link['href'] = 'videos/football';
      }
    }
    elseif(filter is soccer) {
      if(home menu) {
        $link['href'] = 'soccer';
      }
      if(photo menu) {
        $link['href'] = 'photo-galleries/soccer';
      }
      if(video menu) {
        $link['href'] = 'videos/soccer';
      }
    }
    else {//for normal
      if(home menu) {
        $link['href'] = 'node';
      }
      if(photo menu) {
        $link['href'] = 'photo-galleries';
      }
      if(video menu) {
        $link['href'] = 'videos';
      }
    }
    $html .= "<li>" . l($link['title'], $link['href'], $link) . "</li>";
  }
  $html .= "  </ul>";
  $html .= "</div>";
  return $html;
}

```

---
Tags: 7, routes
---


title: My account as a block

text:
# Question
Title: My account as a block
I am using Drupal 7. I want to show my account page as a block, where user can edit their personal information. Does anybody have an idea regarding this. Do I need to write custom module? Thanks

# Answer
> 5 votes
Possibly you can try this :

1. Create a views block with current uid in contextual filter & have all the account fields in that views block
2. Use 'editablefields' module & make use of it for Inline Edit
3. Enable the block where you need

Hope it helps

---
Tags: 7, theming
---


title: Generating Content Type at once

text:
# Question
Title: Generating Content Type at once
It is very time consuming to define fields, set their types and validation while creating a content type. It's a nightmare if the fields are exceeding in numbers (say more then 10).

Is there any way to define all the fields, their types, structures, validations one time on a page and generate the whole content type at once?

# Answer
There is none, and there probably will not be one. Drupal is modularised, pluggable system. Each and every module can provide it's own field types, validators, widgets. They have custom settings defined in their modules. There are per field settings, and settings specific for a field in a given content type. Module to provide it all on one screen would need to know about all these modules and their form elements, and there are no hooks for that now. It would be a big job to hack it together with what's provided.
> 0 votes

---
Tags: nodes
---


# Question
Title: Drupal 7: How to insert site's Main Menu and also use my custom style on it?
I've a menu like this-

```
<!-- Main Menu -->
<ul class="nav sf-menu clearfix">
    <li><a href="about.html">About Us</a></li>
    <li><a href="index.html">Artists</a><em></em></li>
    <li class="sub-menu"><a href="index.html">Works</a><em></em>
    <ul>
            <li><a href="#">Dolore ipsu</a></li>
            <li class="sub-menu"><a href="#">Consecte</a>
            <ul>
                    <li><a href="#">Dolore ipsu</a></li>
                    <li><a href="#">Consecte</a></li>
                    <li><a href="#">Elit Conseq</a></li>
            </ul>
            </li>
            <li><a href="#">Elit Conseq</a></li>
    </ul>
    </li>
    <li><a href="index.html">Blog</a><em></em></li>
    <li><a href="contact.html">Contacts</a><em></em></li>
</ul>
<!-- End Main Menu -->

```

There's a whole section of CSS style information for that plain HTML section. I've tried to add the site's Main Menu to `page.tpl` but it isn't showing up When I add the following PHP code-

```
<?php
    $menu = menu_navigation_links('menu-main-page');
    print theme('links__menu_main_page', array('links' => $menu));
?>

```

What am I doing wrong here?

Also when it DOES show up, I'd like to **which elements are printed exactly when trying to include the menu** and **how to assign the generated ul / li to some classes**, as required for the CSS to apply style to those elements?

# Answer
In Bartik, menu is added like that:

```
    <?php if ($main_menu): ?>
      <div id="main-menu" class="navigation">
        <?php print theme('links__system_main_menu', array(
          'links' => $main_menu,
          'attributes' => array(
            'id' => 'main-menu-links',
            'class' => array('links', 'clearfix'),
          ),
          'heading' => array(
            'text' => t('Main menu'),
            'level' => 'h2',
            'class' => array('element-invisible'),
          ),
        )); ?>
      </div> <!-- /#main-menu -->
    <?php endif; ?>

```

Except the fact that `$main_menu` was not provided in `page.tpl.php` nor in `template.php`, apparently created by menu module, it looks like your code, just more elaborate. This indicates that either in `menu_navigation_links` or in `theme` you passed an argument that happens not to work. Except that it should be all right. Use `dpr()` or `var_dump()` to see which one fails.

If you need better control over your menus, I suggest using Menu block module to put them. This module allows you to treat menus or their parts as a blocks, so in your template all you need to do is to output proper region.

To get classes on menu items, you can simply use Menu attributes module:

> The module currently allows you to set the following attributes for each menu item:
>
> * Id
> * Name
> * Target
> * Rel
> * Class
> * Style
> * Accesskey
> 1 votes

---
Tags: theming, routes
---


# Question
Title: How to do I stop product URLs changing each time I delete and re-import?
Kickstart 2. I'm importing products using Feeds Importer. Every time I delete a product and re-import I get a sequential number appended to the end of the product's URL. For instance, I import MyProduct and its URL is mysite.com/products/MyProduct. I delete that product and import again and now the URL is mysite.com/products/MyProduct-0. Next time -1, etc.

I tested removing all products, truncating the commerce\_product and commerce\_product\_revision tables and that didn't help.

So, how do I keep the URLs from changing? I'd prefer to fix the actual problem, not just use PathAuto or some other process afterwards to change the URLs.

Thanks.

# Answer
There are two ways:

1. Don't delete them. Import them and let Feeds update them.
2. If you can't use above (for example no proper UUID on them), after node deletion, go to http://example.com/admin/config/search/path/delete\_bulk and delete old aliases as well - that will free addresses for reuse.

Flipping "published" on and off is the way Drupal is designed to work, not deleting and re-uploading. On the other hand, path module implements `hook_node_delete()` \- hook called for each node deletion by `node_delete_multiple()` and `node_delete()` to delete aliases of deleted nodes. If it isn't, it's a core bug , or incompatibility between modules. You can fight to have it fixed, or try to implement `hook_node_delete()` on your own. Code of original implementation is very simple:

```
function path_node_delete($node) {
  // Delete all aliases associated with this node.
  path_delete(array('source' => 'node/' . $node->nid));
}

```

Of course to get it to work you may need to use some code from inside `path_delete()` to get query work properly, or to omit call to `hook_path_delete()` if one of it's implementation is buggy.
> 2 votes

---
Tags: uri, commerce
---


# Question
Title: Adding variable to user profile page in drupal 6
I have a custom module let say mymodule. One of the function in this module generates or returns some contents. Forget about what the content is. My question is how could i add this content to user profile page. I tried to override using user-profile.tpl.php file. I could override the theme. But how to add a variable to this page that contains the required content so that i can echo the variable. Is there any preprocessing function that will help

# Answer
Use the `hook_menu` in your custom module and use `MENU_LOCAL_TASK` as the type, and the path in your custom module needs to start with user/

```
function HOOK_menu() {
      $items['user/%user/yourpage'] = array(
        'title' => t('My Tab'),
        'type' => MENU_LOCAL_TASK,
        'page callback' => 'yourmodule_page', //your module page should be a function
        //'page arguments'
      );
      return $items;
    }

function yourmodule_page()
{
   $uid = arg(1);
   $user = user_load($uid);
   //use user to get particular content belonging to them
   //return content
}

```
> 1 votes

# Answer
You can use the theme preprocess function template\_preprocess\_user\_profile to provide your variables.
> 0 votes

---
Tags: users
---


title: After migrating D6 only homepage works

text:
# Question
Title: After migrating D6 only homepage works
I've migrated a D6 site to a new server and now it's working in a very strange way:

* Homepage loads OK
* Update.php and install.php loads OK
* Any other page (including /admin, /user...) doesn't work. They load but they all show the homepage content instead of the content of that page.

You can see it live in http://www.efetic.com/

I'm not able to access /user, so I can't change any configuration, clear cache, etc. I've ran update.php but it doesn't change anything.

I've read some related issues and most seem to point it should be an Apache/htaccess error. I'm not using apache, but nginx. I don't know much about nginx, but I have other drupal sites working correctly in this same server (although they are all D7, not D6 like this one).

What do you think? It's a Drupal problem or an Nginx problem? Should I ask in Stackoverflow or Serverfault?

# Answer
> 0 votes
http://www.efetic.com?q=online/cursos-de-recursos-humanos-y-laboral returns `301 Moved Permanently` and redirects to http://www.efetic.com/online/cursos-de-recursos-humanos-y-laboral. That's how SEO modules like Global Redirect work to prevent duplicated content issues. http://www.efetic.com?q=node/432 redirects to http://www.efetic.com/universidad/plan-acceso/cancelado \- so your nodes are there all right and Drupal core recognizes them, if you are using access method independent on Apache's `mod_rewrite` (or similar technology if you are using another http server).

Now, there are 3 options:

1. During migration you omitted .htaccess file. It happened to me with exactly the same results. File is hidden, so it's easy to make that mistake. If so, just extract one from fresh Drupal download.
2. Your server does not support `mod_rewrite` (Clean URLs in Drupal) or requires specific configuration for it to work. If so, contact their customer support for feedback.
3. You are using nginx as a server, not only a cache / proxy, and failed to comply with instructions on Drupal.org. You need to add (or have sysadmin to add for you) this to your settings:

```
 server {
     listen       80;
     server_name  example.org;

     location / {
         root   /path/to/drupal;
         index  index.php;
         error_page 404 = @drupal;
     }

     location @drupal {
         rewrite ^(.*)$ /index.php?q=$1 last;
     }
}

```

Full config for Drupal is here on nginx wiki \- read comments carefully, as D6 and D7 needs different approach, especially in rewrite section. Now your site behaves like D6 with nginx configured for D7.

# Answer
> 1 votes
Check if your server supports Clean URLs. It is most likely the culprit.

You can consult the following threads on how to enable Clean URLs on Nginx.

---
Tags: 6, migrations
---


# Question
Title: How add new tab in structure when manage it?
I try to do own User Graffic Interface. That interface must help to managers do they are own form displays. By drug\`n drop elements in space. Then when they push save. I will save coordinats of elements. I need to show my module in other (new one) tab when manage in structure. I have little exp. working with drupal. But deadline is coming close. I sware i will give this module for avryone. So i need help. (pls. didn't write about Display Suit.)

```
<?php
/**
 * Implements hook_form_FORM_ID_alter().
 */
function admt_form_node_type_form_alter(&$form, &$form_state) {
  $default_value =TRUE;// auto_nodetitle_get_setting($form['#node_type']->type);

  $type = $form['#node_type'];
  $form['#theme'] = 'admt_form_theme_function';
  $form['admt'] = array(
    '#type' => 'fieldset',
    '#title' => t('Graffic User Interface'),
    '#weight' => 0,
    '#collapsible' => TRUE,
    '#collapsed' => false,
    '#group' => 'additional_settings',
    //'#theme' => 'admt_form_theme_function',
    '#attached' => array(
      'js' => array(drupal_get_path('module', 'menu') . '/menu.admin.js'),
    ),
  );

    if (isset($type) && $type->has_title) {
    $title = $type->title_label;
    }
    $fields = array();
    $arrFieldsType=array(
    "number"=>"textfield",
    "text_textfield"=>"textfield",
    "options_select"=>"select",
    "taxonomy_autocomplete"=>"textfield",
    "text_textarea_with_summary"=>"textare",
    "image_image"=>"file",
    "checkboxes",
    "radios"
    );
  $instances = field_info_instances('node', $type->type);
  $extra_fields = field_info_extra_fields('node', $type->type, 'form');

  // Fields.
  foreach ($instances as $name => $instance) {
    $form['admt'][$name] = array(
    '#type' => $arrFieldsType[$instance["widget"]["type"]],
    '#title' => t($instance["label"]),
    '#default_value' => array('value' => '...'),
    //'#options' => $type2,
     );
        if($arrFieldsType[$instance["widget"]["type"]]!="select") $form['admt'][$name]['#size']= '20';
  }

  // Non-field elements.
  foreach ($extra_fields as $name => $extra_field) {
    if(!empty($extra_field["type"]))
    $typ=$arrFieldsType[$extra_field["type"]];
    else
    $typ="textfield";
    $form['admt'][$name] = array(
    '#type' => $typ,
    '#size' => '20',
    '#title' => t($extra_field["label"]),
    '#default_value' => array('value' => '...'),
    '#description' =>  t($extra_field["description"]),
    //'#options' => $type2,

     );
  }
  return $form;
}
function admt_theme($existing, $type, $theme, $path,$form)
{
  return array(
    'admt_form_theme_function' => array(
      'render element' => 'form',
      'template' => 'admt',
      'form' => $form,
    ),
  );
}

```

# Answer
> 1 votes
You need to create a menu with type as MENU\_LOCAL\_TASK. Can refer to menu 'node/%node/edit' in node.module.

Hope it helps

---
Tags: theming, routes
---


# Question
Title: How do you give permissions to certain roles to get certain menu items to display in the admin_menu toolbar?
Currently I'm using the admin\_menu module and have certain roles restricted todo certain things. As an admin I can see the full admin\_menu bar in full, but as a restricted user I can only see **Add content**. Since I'm running the commerce module, I only want certain roles to get the **Store** dropdown menu. Right now I only see Add content and I'm not sure where to go to enable it to show up in the admin\_menu toolbar.

# Answer
> 1 votes
Select People or users in admin bar, the user section on the right side there is permissions tab click it. then scroll down to store section, there u can set the permission for each type of user in your site.

Just to be clear user account ur are using as restricted go to his account page and see what type of user he is? ex admin or user or author.

then tick yes the setting u want for your restricted user in the permission tab.

---
Tags: 7, commerce, users, toolbar
---


# Question
Title: when mouseover on username display popup views
How to display popup ajax information of user when user mouseover on username or picture of users with views. i want fetch information from profile user with ajax no hidden. such as Facebook or LinkedIn

# Answer
Hope this will help you

In Drupal 7, for your requirement you can use **qTip (Stylish jQuery Tooltips)** module with **Views**.

* After installing and configuring qTip, go through the qtip examples(refer **qtip README.txt**).
* For this example I have created a view with some user fields, these fields will popup on hovering user picture
* Create a new view and add fields which you want to show on the popup.
* For showing user information in popup, you need to give the proper structure(read qtip README.txt).
* I have added the HTML structure for **profile\_image** view field
* On mouse hover of the user picture, user information will popup. And make **CSS** changes as per your requirement.
* You can also refer BeautyTips, for example you can refer this link

Drupal 7 : Ajax load

Steps

* To show user details on hover you need to add attributes to the username, it can be done using preprocess function template\_preprocess\_username in your active theme tempalte file. ````

function themeName_preprocess_username(&$variables) {
  $variables['attributes_array'] = array('class' => array("user-info"), 'data-uid' => $variables['account']->uid);//adding more attributes for your requirement
}

````
* Create a view with the fields you want to show on popup.
* Create a menu to get user details like get/user\_details/%, where % is the user-id. This menu will returns user details.

```
function test_menu() {
...
$items['get/user_details/%'] = array(
'title' => t(''),
'type' => MENU_CALLBACK,
'page callback' => 'get_user_details_ajax_callback',
'page arguments' => array(2),
'access arguments' => array('access content'),
);
...
return $items;
}
//Implement the ajax callback to get user details
function get_user_details_ajax_callback ($uid) {
$html = '';
$html = views_embed_view('VIEWNAME','display_id', $uid);
return $html;
}

```
* For showing the user details on hover, you need to make a ajax call using $.ajax
* Once the user hover the username get the **data-uid attribute** and make a ajax call to get user info.
* Once you get the user details append it and show as popup.

Drupal.behaviors.getUserDetails = {
    attach: function (context, settings) {
      var replace_wrapper = 'user-'+$(this).attr('data-uid')+'details';
      //add html to show user details
      $( "a.user-info" ).each(function( index ) {
        if(!$(this).closest('div').hasClass('user-details-wrapper')){

```
      $(this).append("<div class='user-details-wrapper'><div class'"+replace_wrapper+"'></div></div>");
    }
  });
  $('a.user-info').mouseenter(function(){
    if($(replace_wrapper).is(':empty')){//if empty then make ajax call and
      var url = Drupal.settings.basePath + 'get/user_info/'+ $(this).attr('data-uid');
      $.ajax({
        url: url,
        type: 'GET',
        success: function (data) {
          //create html and append to replace_wrapper
          var user_detail_html = '';
          //code to get user html here
          $(replace_wrapper).each(function( index ) {
            $(this).html(user_detail_html);
          });
        }
      });
    }else{
      //show popup here
      $('user-details-wrapper').show();
    }
  }).mouseleave(function() {
    //hide popup here
    $('user-details-wrapper').hide();
  });
 }
}

```

* Make changes as per your requirement

Note : views\_embed\_view
> 7 votes

# Answer
I would create a new path in a custom module.

```
function MODULE_menu() {
  $items['get/profile/%/ID'] = array(
    'page callback' => 'get_info',
    'page arguments' => array('$nid', 1),
    // …
  );
}

```

In your page callback use the following code.

```
function  get_info($nid) {
  $userInfo = user_load($nid);

  // Create your HTML.

  return $output;
}

```

When the user is hovering the mouse on the username, you make an AJAX call to that URL.

```
 $.ajax({
   type: "POST",
   url: "<?php echo url('get/profile'); ?>/"+NID,
   async: false,
   cache: false,
   timeout: 30000,
   success: function(resp) {
     $('popUp').html(resp);
   }
 });

```

I don't need to create a view for that, but if you need to use it you can create a view and in your page callback use the following code.

```
function  get_info($nid) {
  views_embed_view('VIEWNAME');
  return $output;
}

```
> 0 votes

# Answer
I found this sandbox module from October 2012 that might be helpful: https://drupal.org/sandbox/zeet/1801738:

> simple module to display the users profile information in popup balloon
> 0 votes

---
Tags: 7, views, users, ajax, theming
---


# Question
Title: Can't change my custom logo for Bartik-theme. How to fix this?
Have newly installed Drupal 7 . Tried to change my logo to a custom logo. Worked the first time. Theme Bartik was activated. Now wanna change the logo a second time, can't do it. Can't disable it. Appearence-\>Settings-\>Custom Logo won't change or when i uncheck Logo nothing happens. Switched appearance to Stark, everything worked as expected. Switched back to Bartik no logo-change-feature anymore / still the old logo.

Any suggestions/help? Thank you in advance.

# Answer
> 2 votes
Silly me. There exists global settings / bartik settings etc. I was convinced i used global settings all the time but nope, and if you specify a bartik logo, it overrides the global one. Thank you for trying to help me.

---
Tags: 7, files
---


# Question
Title: retaining upload file information in form when validation fails on other fields
If there are required fields in a form (ie '#required' is set to TRUE), and the user sets a file to be uploaded but not provide all the required fields, validation fails on the required fields and the validation hook does *not* get called; the specified file does not get uploaded (if that is where the upload code is placed) and the form is refreshed without the previously provided filename wiped out. Is there a way to either upload the file during validation, or reset the filename in the form field, so that the user doesn't have to reselect it again?

thanks

# Answer
I believe using the File\_Managed fieldtype will fix your problem. This Drupal FAPI field type uploads the file to a temp directory BEFORE the form is submitted, and so you can access the file during/after validation. You can see an example of it being applied in the "image\_example.pages.inc" in the Examples module. Hope this helps.
> 1 votes

---
Tags: files, forms
---


# Question
Title: Autocomplete widget - save id of suggested and accepted value
I'm writing a custom text field and widget module with ajax autocomplete from scratch. I want the lookup to work on one column, but I want another column's value (the looked-up item's id) to be saved as the field value in the node.

So, for example, user types for example `Sams`, they accept suggestion `Samsung`, but Drupal save its database identifier, say `145`.

Conversely, when opening the node for editing, the saved value of `145` should be again looked up, converted and displayed as `Samsung`.

What is the key to get it working the Drupal way?

# Answer
Use the Entity and Entity Reference modules to create the link between the two items, using this method means your selections will be available to other modules such as Views, Rules, etc.
> 0 votes

---
Tags: ajax, entities
---


# Question
Title: When using the workbench core module, how can one assign a node to a new author and it show up in their list of content?
I'm using workbench core, which so far is providing the workflow that I need (well, almost).

The workflow is:

* Primary editor writes a new node, and leaves it unpublished.
* When the Primary editor is finished, he edits the node and changes the 'author' field to the new editor who will continue editing.
* The New editor accesses his workbench page to (should be able to) see the unpublished node in his article list, where he continues to edit.
* The New editor publishes the node after he has finished.

The problem is that the article never shows up in the New editor's article list on his Workbench page. However, when viewing the Content list, the article shows correctly and shows that he is indeed the owner / author. There is something wrong with Workbench that doesn't recognize new ownership of nodes (via the author field).

Is this a bug? Configuration setting? All I want to do is change the author of this node and it show up in his workbench. I am hoping I can do this without having to add any more workbench related modules.

To me it feels strongly like a configuration issue with the view that was supplied by the Workbench core module, but no amount of fiddling with it has proved productive. I think I'm just missing something. Plus, I'd prefer not to have to hack a module.

Here is a Drupal.org thread about it, however, no one has looked at the issue for months.

https://drupal.org/node/1921798

# Answer
> 3 votes
Workbench uses Views to render it's data. The trick - whilst new user is now considered author of a node, last edit was not his. So it will not be seen in "my edits".

Go to http://example.com/admin/structure/views/view/workbench\_edited/edit. You will see:

This filters by revision's author. Not what you want. What you need is to filter by node's user. But this view does not have a relationship to content author:

Add missing relationship:

Filter is still using wrong relationship:

Make it use proper one:

Done. Repeat for other views as needed.

---
Tags: 7, views, workflows, workbench
---


# Question
Title: How to add user upload files to git when the node is pulished?
my requirements is:

* some users are adding application file drupal system adding node.
* initially that node is in unpublished state. Once the admin is publishing the node that uploaded file need to be pushed to into github repo.
* If there any module available for git interaction Please suggest.

# Answer
> 1 votes
You can take advantage of the Version control api

> Version Control API is an engine for Drupal integration with a variety of version control systems. The focus is primarily on working with canonical, server-side repositories. It provides basic tools that allow for things like history listings, commit access controls, triggered actions when new code comes in, and direct on-disk repository management.
>
> This module is a core engine and does nothing on its own without a "backend" module that provides integration with a specific VCS (e.g. git, bzr, svn). This module provides a consistent base interface (UI and API) for interacting with all the different backends.

You will also need the version control git backend as the module does not work on it's own

> This module provides an implementation of the Version Control API that makes it possible to use the Git version control system. It can retrieve commit information by parsing commit logs.
>
> The Git backend depends on the Version Control API module. It also requires Git \>=1.7.2 to be installed on the server.

---
Tags: 7, files, version-control
---


title: How to add field to fieldset by ajax?

text:
# Question
Title: How to add field to fieldset by ajax?
I have a fieldset with one field by default. I want to add new fields by ajax (button "new item"). I can do it for usual field, but I have a problem with fieldsets. How to do that?

For usual fields I do it like below:

```
$form['add_item'] = array(
    '#type' => 'button',
    '#value' => t('Add item'),
    '#ajax' => array(
        'wrapper' => 'content',
        'callback' => 'add_more_ajax',
        'method' => 'append',
        'affect' => 'fade',
    ),
);

function add_more_ajax($form, &$form_state) {
    $form['image'] = array(
        '#title' => t('Image'),
        '#type' => 'managed_file',
        '#default_value' => '',
        '#upload_location' => 'public://images/',
    );
    return $form['image'];
}

```

# Answer
First - ajax callback should **not** make any persistent changes to `$form`. It's only duty is to return proper part of form array. Render all elements in form creation function:

```
mymodule_form($form, &$form_state) {
  $form['image'] = array (
    '#type' => 'fieldset',
    '#title' => t('images'),
    '#collapsible' => TRUE,
    '#collapsed' => FALSE,
    '#prefix' => '<div id="product_images">',
    '#suffix' => '</div>',
  );
  if (empty($form_state['image']['count'])) {
    // Keep number of fields either in form or form state, both works.
    $form_state['image']['count'] = 4; // Default number of elements
  }
  elseif( isset($form_state['triggering_element'])
      and $form_state['triggering_element']['#machine_name'] == 'more_images_button' ) {
    // If form was triggered by proper form element, increase counter
    $form_state['image']['count']++;
  }
  // Loop to create elements
  for ($i = 0; $i < $form_state['image']['count']; $i++)
  {
    $form['image'][$i] = array (
      '#markup' => "<p>$i</p>",
    );
  }
  // And our button
  $form['image']['more'] = array (
    '#type' => 'button',
    '#value' => t('More'),
    '#ajax' => array (
      'callback' => 'product_more_images',
      'wrapper' => 'product_images',
      'method' => 'replace',
      'effect' => 'fade',
      'prevent' => 'submit',
    ),
    '#machine_name' => 'more_images_button',
  );
}

// Now callback function is trivial
function product_more_images($form, $form_state) {
  return $form['image'];
}

```

Of course it's only a sketch, with all off topic parts removed.
> 1 votes

---
Tags: forms
---


# Question
Title: Conditionally assign a custom role on user registration
I've written a custom module that uses hook\_form\_alter() to set some default values from GET-parameters when the user registration form is called with certain GET values. That is, if you call mysite.com/user/register?firstname=Derp you'll find that the form field "Firstname" is magically filled with "Derp".

Now here it comes: When a specific GET value is given, then and only then I'd like to automatically assign an existing custom role to the new user. That's not to be achieved with Rules and the like. (Yes, I know that anyone with even small insight in programming may exploit this to get the role, but the role is not really important).

I've tried to update the register form values with:

```
$form['#user']->roles[] = 'customRole';

```

A var\_dump($form) gives:

```
    ["#user"]=>
  object(stdClass)#111 (4) {
    ["uid"]=>
    int(0)
    ["hostname"]=>
    string(14) "myhost"
    ["roles"]=>
    array(2) {
      [1]=>
      string(14) "anonymous user"
      [2]=>
      string(9) "customRole"
    }
    ["cache"]=>
    int(0)
  }

```

...but it seems that this data gets sorted out during the processing of the form. Thus the role is not assigned.

Alternatively I could assign the role directly using user\_multiple\_role\_edit(), but I need the uid for that, which in turn is assigned during user\_register\_submit(). That function however seems to be beyond the reach of any API function I've found so far.

I'd be glad to read about your thoughts how I could assign the role on registration (to say it again: Rules doesn't do the job). Thank you.

# Answer
You need to use hook\_user\_presave. like below,

```
function mymodule_user_presave(&$edit, $account, $category) {
  if ($account->is_new) {
    $roles = user_roles(TRUE);
    $rid = array_search('Test', $roles);
    if ($rid != FALSE) {
      $edit['roles'][$rid] = 1;
    }
  }
}

```

Replace the Test with your role name. $account-\>is\_new will be set to 1 during the registration process alone, so your code will not execute when a user updates the profile.
> 0 votes

---
Tags: users
---


title: How to change the error system messages

text:
# Question
Title: How to change the error system messages
is it possilbe to use string overrides module for system messages? What i need is to change the order of the words and add some more. For example i have a webform with some required fields. When user forget to fill a field it gets this message: "Surname field is required.". I need to change this to "The field Surname is required for this form". How can i do this?

Thank you

# Answer
You can use String Overrides module. Also you can override strings through settings.php, look this post.

For example that you listed above, there is one string that contains variable !name. So "Surname field is required." is "!name field is required.", when you changing use "The field !name is required for this form" and you overrides all similar messages.
> 5 votes

---
Tags: 7, string-overrides
---


title: Why does drupal create revision table?

text:
# Question
Title: Why does drupal create revision table?
From database design perspective, Why does Drupal even create these tables? They are so much alike. There are modules & methods for getting rid of these tables, But why are they there?

```
MariaDB [park]> describe field_data_body;
+--------------+------------------+------+-----+---------+-------+
| Field        | Type             | Null | Key | Default | Extra |
+--------------+------------------+------+-----+---------+-------+
| entity_type  | varchar(128)     | NO   | PRI |         |       |
| bundle       | varchar(128)     | NO   | MUL |         |       |
| deleted      | tinyint(4)       | NO   | PRI | 0       |       |
| entity_id    | int(10) unsigned | NO   | PRI | NULL    |       |
| revision_id  | int(10) unsigned | YES  | MUL | NULL    |       |  ONLY DIFFERENT ONE
| language     | varchar(32)      | NO   | PRI |         |       |
| delta        | int(10) unsigned | NO   | PRI | NULL    |       |
| body_value   | longtext         | YES  |     | NULL    |       |
| body_summary | longtext         | YES  |     | NULL    |       |
| body_format  | varchar(255)     | YES  | MUL | NULL    |       |
+--------------+------------------+------+-----+---------+-------+
10 rows in set (0.00 sec)

MariaDB [park]> describe field_revision_body;
+--------------+------------------+------+-----+---------+-------+
| Field        | Type             | Null | Key | Default | Extra |
+--------------+------------------+------+-----+---------+-------+
| entity_type  | varchar(128)     | NO   | PRI |         |       |
| bundle       | varchar(128)     | NO   | MUL |         |       |
| deleted      | tinyint(4)       | NO   | PRI | 0       |       |
| entity_id    | int(10) unsigned | NO   | PRI | NULL    |       |
| revision_id  | int(10) unsigned | NO   | PRI | NULL    |       |  ONLY DIFFERENT ONE
| language     | varchar(32)      | NO   | PRI |         |       |
| delta        | int(10) unsigned | NO   | PRI | NULL    |       |
| body_value   | longtext         | YES  |     | NULL    |       |
| body_summary | longtext         | YES  |     | NULL    |       |
| body_format  | varchar(255)     | YES  | MUL | NULL    |       |
+--------------+------------------+------+-----+---------+-------+
10 rows in set (0.00 sec)

MariaDB [park]>

```

# Answer
The revision table has been set up to track the revisions of a node. Like Triskelion noted, there already is a thread up on D.O. Furthermore the reason the table is populated is for denormalization purposes, per The aforementioned issue. Inevitably. this has some drawbacks. The first of which is bloat. Write speed is also affected, especially under a load. The community has seemed to coalesce around using contrib to deal with this issue e.g. Field SQL norevisions. At some point it would be nice to have this in core, but a rock solid contrib module is the next best thing.
> 1 votes

---
Tags: database
---


title: How to create a packing slip?

text:
# Question
Title: How to create a packing slip?
We want to be able to print a packing slip from a completed order.

I see that the line items is a view but how can I create a new page or tab on the order page to display a clean packing slip?

# Answer
> 0 votes
Check out this list of order printing and order invoicing modules.

I think Commerce Billy looks promising, but I haven't tried it out.

Commerce Order2Pdf is another promising module, but I'm not sure how customizable it is.

I am currently building a custom module to handle my own packing slip requirement. I'm building to a template, and have found FPDF to be quite useful for this.

If you're comfortable with custom module development, I'd think that FPDF is the way to go, but you'll just need to write a lot of PHP to build a template, and then use Drupal Commerce API and/or custom database queries to load in the order data. If you don't like the sound of that check out the aforementioned modules.

Let us know what you end up using! I'm curious about those modules but in this case I am going the custom route.

---
Tags: 7, commerce
---


# Question
Title: What is the correct procedure to restore database in Drupal 7?
Reverting to a former database has been a tricky business with error messages and problems cropping up when I try to re-install modules that were installed or re-create content types, or re-do anything that was done since the back-up was made. In an attempt to avoid these problems I've been deleting the database using phpmyadmin before reinstalling the backup. Better, maybe(?) but now I've had other problems. Should I delete all the contributed modules also? Anyone direct me to the *correct* procedure for restoring database using phpmyadmin and ftp?

\-

# Answer
Deleting the database and re-importing an earlier backup is the correct procedure. Module states (enabled/disabled/version), content types, and other settings are stored in the database, so if those changes are not part of the backup you have, they will be lost. That said, you should be able to re-create them without any problems.

Modules you've added since the backup will remain there as files, and you can re-enable them at will. There is no need to delete the files themselves.
> 1 votes

---
Tags: database
---


# Question
Title: Adding a block to the page but not declaring it in hook_block_info()
I have inherited some code from a contractor. This code adds a block to `page_content` but it is not defined in `hook_block_info()`.

We then have the following code:

```
/**
 * Implements hook_block_view().
 */
function erepair_blocks_block_view($delta = '') {
  $block = array();
  switch ($delta) {
    ...
    case 'page_content':
      $block['content'] = page_content();
      break;
    ...
  }
  return $block;
}

```

This block is then displaying on some certain pages but I can't work out how.

So I have looked into the database and have found an entry for the block in the table.

It is safe to presume that they have either:

* executed some sql to add the block (but did not do it in an install file)
* had an entry in `hook_block_info()` added the block to the page then deleted the deceleration in `hook_block_info()`

I imagine what ever they have done is not best practice. Is there anything else they could have done (we are not using features).

# Answer
The block may be positioned using the Context module, or via custom code in about a million places. What you can do is temporarily modify the template\_preprocess\_block() function in block.module, identify the block you're looking for by looking at the data in $variables\['block'\], and then looking at the output of debug\_backtrace() to see the callstack and find the place the block is coming from.
> 0 votes

---
Tags: 7, blocks
---


# Question
Title: How to make panels with a node reference argument
I have a multi-user site. When a new user registers, several nodes (such as gallery node, etc.) are automatically created for him/her.

There is a panel page for each user that displays a profile of its owner. The panel is composed of various view panes.

Very much like in other community sites, a visitor to the profile page will be able to leave comments (text + pictures.)

To that effect, **and hoping this is the right approach,** I am trying to include in the panel a comment form. Comment forms are attached to their respective nodes so that comments left on John's panel page do not show on Jack's panel page. Comments will be displayed under the form in a view. The view is obviously universal and the same for all panel pages.

Now, on to the comment form. There is a node, specially for comments, created at the time the user registers.

How do I include the comment form of that node in a panel context knowing that it has to be different for each user?

I see that a node context can be passed into the panel. However, it requires a node ID. So that limits it to one node. Does it support some kind of token so that a different node ID loads on different users pages? If so, how would I write it?

If i am using the wrong approach on this, how should I go about it?

Any idea anyone?

Thank you. :)

# Answer
I implemented a similar feature on my site: when a user registers, several nodes of different content types are created specifically for that user. I also use Panels.

To (somewhat) easily link the content with the user, I used the Relation module, which integrates with Rules. After I created the content upon account registration, I created relations between the user and the content (all using Rules-- if you do this, you'll need to make a rule set and create the content in one rule before creating the relations in a following rule; otherwise, you'll get some weird errors).

Then, without using Panels contexts, I simply created content panes in Views that pull in the content by adding relations (from the Relation module) as relationships (in the Views UI).

The challenge of this approach is that setting up rules to fetch the relations and loop through them is pretty complex. It might be easier to use the Entity Reference module, which has Rules integration, but when I was building my site a year ago it was broken so I used the more complex Relation module instead.
> 1 votes

# Answer
I have to use this because the site doesn't allow editing of comments for more than five minutes!

Anyway...

I tried everything. I followed the tutorial for the Entity Reference, created an Entity Reference field for the the user profile and added the referenced entity relationship to the view.

As soon as I make the relationship required, regardless of the contextual filter, nothing shows. I tried this in the pane view and the (newly created) Entity Reference view.

I also tried it in reverse, adding an Entity Reference field to the comment node and repeated the procedure, but nothing. Maybe it doesn't work because one is a node and the other a user? I have no idea. I am back to square one.

It's very discouraging. I am back to square one. Anyway, I really appreciate what you've tried to do. Thank you. :)
> 0 votes

---
Tags: nodes, panels, comments, views
---


title: Image style results in wrong image

text:
# Question
Title: Image style results in wrong image
I had a very odd error where the image showed as style'ed but was using the wrong source image. When I deleted the style'ed image and reloaded the page, the correct image displayed and was style'ed.

I haven't figured out how to reproduce the error, but I am positive the source image didn't change.

# Answer
> 2 votes
This was likely a file-naming conflict of sorts. ImageCache (the module responsible for generating the image styles) generates a file name for each image style, and then checks for the presence of that file. If the file exists, it is served to the browser, otherwise it is generated and then served.

If you had a file called fruit.jpg that resulted in an image style of /files/styles/some/folder/fruit.jpg, and then deleted the source file, it is possible that the derivative style file wasn't removed (keep in mind, this a theory). If you then uploaded a different image with the same fruit.jpg filename and tried to generate the same image style again, ImageCache would find the previous /files/styles/somes/folder/fruit.jpg and serve that, resulting in the confusion you're seeing.

That said, I do believe derivative image styles get deleted when the source image is deleted, but I'm not sure of the specifics (ex. timing - it may happen during a cron run which wasn't ran).

For the most part, I wouldn't worry about it. Sounds like a onece in a million edge-case.

---
Tags: media
---


# Question
Title: How to create a custom content type region template?
I built a sub theme based on Omega's adaptive Alpha theme. I made a content type called "project". For that content type I need to edit what gets displayed on the project detail page. What is the best way to do this?

I currently have a page--type--project.tpl.php file that I can edit, but Ideally I would like to just edit the region, like with using something like region--content--project.tpl.php file or something. Is that possible? I haven't found anything online with modifying a region based on the content type.

# Answer
There is a lot of ways to accomplish your goal. I'll point some of them:

**Using template files**

One of them is to add the new region to your current theme and just use the modules suggested by Sohail (Delta and Context) to make the blocks to be shown in the *project* detail page. This means that your current theme will be a new site wide region to be used as you need.

There is some other questions that cover this:

How do I create custom regions in a theme?

Render a custom region inside node template

**Using GUI**

Another way to do this is by using the Display Suite module. Here goes a summary of the module description:

> Display Suite allows you to take full control over how your content is displayed using a drag and drop interface. Arrange your nodes, views, comments, user data etc. the way you want without having to work your way through dozens of template files.

You can also use the Panels module suite and also the Panelizer module to achieve this goal.
> 1 votes

# Answer
You should theme the node per content type instead of the page. Refer to this article - http://drupal.org/node/17565

Hope this helps you!
> 0 votes

# Answer
I guess the best way to approach this is using Delta and Context module in omega.
> 0 votes

---
Tags: theming, nodes
---


# Question
Title: Show block if user has never completed Ubercart checkout
Part of my website's signup process is the purchase of a product via Ubercart. The signup process directs the user to the checkout page with the product already in their cart. The problem I am having is when users get to the cart and then abandon their cart.

I'd like to add a block to the user profile pages that says "Your profile is not yet complete. Please click here to enter your payment info", and I only want that block to show up for users who have not completed that order process. How can I filter users in that way to make that block show up only for those select users?

# Answer
I've got it figured out, at least for my own use-case:

1. I use a webform to collect info on the newly-signed-up user. That webform then redirects to the checkout page with the product in the cart. I used the Webform Rules module to auto-assign a "pre-customer" role to the user when they finalize the webform. Then, when they complete the cart checkout process, that user role is removed and the "customer" user role is assigned to their account.
2. I've got a block that is visible only to users with the role "pre-customer". That block is the one where they will be prompted to click a link to finalize their order/payment info.

Hope this can help someone else at some point! :)
> 1 votes

---
Tags: 7, ubercart, blocks
---


# Question
Title: How to add links in the title for a profile text field
so i have this as a check box for profiles and it is being shown on the registration page as well "I accept the Terms & Conditions and Privacy Policy." and i need to make Terms & Conditions and Privacy Policy links that point to their respective pages. also i'm using Drupal 6

# Answer
> 0 votes
It sounds like you should be looking at the Terms of Use module, which will place the check box on the user registration page. It provides a link to a node, which you create, outlining the terms the user must agree to to register on the site.

On the project page they also mention the Legal module, which provides similar, but more extensive options.

Check both, and see which best satisfies your needs.

---
Tags: users
---


# Question
Title: Why Drupal won't remember "use search" permission settings for roles?
I want to make search available to everyone who uses the site, including anonymous users.
Now, if i go to */admin/people/permissions* and and try to enable "use search" for anonymous and authenticated users, the systems seems to act okay, but when I look at it again, nothing's changed. The settings seemingly won't remember my settings. Any ideas? I hope that there's something totally simple I forgot

EDIT: in fact, it does not keep any changes in the permission system.

EDIT 2: I made it work by editing permissions through /admin/people/permissions/roles. Does anyone has any ideas why it was possible in one way but not the other?

# Answer
> 1 votes
PHP has a default setting of 1000 for max\_input\_vars, and once you have a significant number of modules and/or roles defined, you end up with an excess number of permissions boxes on the page.

In your php.ini file add max\_input\_vars = 1500 and keep incrementally increasing it until it saves.

---
Tags: users, search
---


# Question
Title: Why doesn't the overlay background show?
I created a fancybox gallery as block using the Views module and inserted that block into the node using the Insert Block module. Everything works fine, but the overlay background doesn't show.

How do I fix this?

Edit: The problem has been resolved: The 'Overlay helper' was disabled.

# Answer
> 0 votes
The problem has been resolved: The 'Overlay helper' was disabled.

---
Tags: theming, media, javascript
---


title: Fancybox gallery

text:
# Question
Title: Fancybox gallery
I have one button in node body called 'Gallery' and I need to show fancybox with thumbnails when button is clicked.

What is the simplest way to do that?

# Answer
I create gallery using Views. I create block and insert that block in node's body using Insert Block module.

My first image in gallery is button because I need to show full gallery only when button is clicked, I use this solution to hide other images (but to view that images in fancyBox)...
> 0 votes

---
Tags: media, javascript
---


# Question
Title: Jquery ticker in a drupal block isn't working
I'm trying to add this ticker type to my site: http://cektkp.com/twittermarquee/.

I've created a new module to do so, and this is my module dir structure:

```
 module stocksTicker:
       1. stocksTicker.info
       2. js/
       3. images/
       4. stocksTicker.module

    js/:
       1. marqueeTicker.js

    images/:
       1.fade-trends2.png
       2.trendtip-pointer.gif

```

This is my stocksTicker.module file:

```
/**
 * Declare what blocks are provided
 * by this module.
 */
function stocksTicker_block_info() {
  $blocks['bseTicker'] = array(
    'info' => t('BSE'),
    'cache' => DRUPAL_NO_CACHE,
  );
  return $blocks;
}

/**
 * Return a rendered view of the block.
 */
function stocksTicker_block_view($delta) {
  $block = array();
  switch ($delta) {
    case 'bseTicker':
      $block = getBSETicker();
      break;
  }
  return $block;
}

/**
 * This function does the real work of getting
 * the stocks info and marking it up & produces
 * it in a renderable format.
 */
function getBSETicker() {
  $path = drupal_get_path('module', 'stocksTicker').'/js/marqueeTicker.js';
  $content = "<div id=\"header\"><div id=\"trends\"><div class=\"inner\"><ul class=\"trendscontent\"><li class=\"trend-label\">Trending topics</li>";
  $stockEntry = array("Stock1","Stock2","Stock3", "Stock4", "Stock5", "Stock6", "Stock7", "Stock8", "Stock9", "Stock10");
  foreach ($stockEntry as &$stock) {
       $content = $content . "<li><a href=\"search?q=". $stock. "\" class=\"search_link\" name=\"". $stock. "\" rel=\"nofollow\">" . $stock. "</a><em class=\"description\">This
is description.</em></li>";
  }

$content = $content . "</ul></div><span class=\"fade fade-left\"> </span><span class=\"fade fade-right\"> </span></div></div><div class=\"trendtip\"><div class=\"trendtip-content\"><div>Trending right now:</div><a class=\"trendtip-trend\"></a><div class=\"trendtip-why\">Why?<span class=\"trendtip-desc\"></span><span class=\"trendtip-source\">Source: <span>What the Trend?</span></span></div></div><div class=\"trendtip-pointer\"> </div></div><script src=\"https://ajax.googleapis.com/ajax/libs/jquery/1.3.0/jquery.min.js\" type=\"text/javascript\"></script><script type=\"text/javascript\">";

  $content = $content. "//<![CDATA[";
  $content = $content. "var page={};";
  $content = $content. "$(function() {";
  $content = $content. "new FrontPage().init();";
  $content = $content. "});";
  $content = $content. "//]]>";
  $content = $content. "</script>";
  $block['content'] = array('#markup' => $content,
                            '#attached' => array('js'  => array($path),),);'
  return $block;
}

```

When I try to view the changes, I do get the list and I do see the css working just fine but none of the jquery feature works (scrolling/ tooltip anything..) which is the main aim of this exercise. Please tell me how can I fix this.

I'm new to drupal so please excuse any silly mistake that I might have done.

# Answer
> 1 votes
In your js file, you are depending on the `$(document).ready(function () {} );` to initialize your jquery stuff, but your content is being added via ajax ( if I understand correctly ), so this code will never fire, as the document is already loaded at that point.

This is the reason behaviors have been implemented in drupal.

If you change this to initialize your code in a drupal attached behavior, like so:

```
(function ($, Drupal, window, document, undefined) {
    Drupal.behaviors.stockTicker = {
        attach: function( context, settings ) {
            page.trendDescriptions = {};
            loadTrendDescriptions();
        }
    }
})(jQuery, Drupal, this, this.document);

```

or something of the sort, that may fix your problem. You'll need to look into the `once()` function, to prevent the code from running every time any content is added to the page, but for now, try a behavior and see if you get js behavior

---
Tags: ajax, javascript, blocks
---


# Question
Title: need you advice how to build this website has the same views
`The search info module is the common feature for all the airport1,2,3`

with this requirement do I need to set up multisite for ariport1,2 ,3?

Could any give some tips what should I use (drupal) to develop this kind of website.

Thanks

# Answer
> 1 votes
With the info that you've given, I'll suggest you to use quicktabs module for tabs and views exposed filter for search. If you're asking what CMS to use I guess that is inappropriate to ask here.

---
Tags: views, multi-sites, routes
---


# Question
Title: drupal 7: How do I add individual css elements to an existing module css
drupal 7: How do I add individual css elements to an existing module css so that if later on when this module css is updated when the module is updated my individual css are not deleted?

# Answer
You don't. You are supposed add your individual CSS files in your custom themes (possibly sub-themes of existing ones) or in your custom module.

In both cases, do it using `stylesheets[all][] = your.css` clausule in module's .info file or theme's .info file.
> 0 votes

---
Tags: theming
---


# Question
Title: DatabaseSchemaObjectExistsException: Table products already exists
I try to install my module, and everything goes ok, without an error while enabling

> DatabaseSchemaObjectExistsException: Table products already exists. in DatabaseSchema-\>createTable()...

I checked it and there wasn't the products table.

My install function is:

```
function products_schema() {
    $schema['products'] = array(
        'description' => 'The base table for products.',
        'fields' => array(
            'pid' => array(
                'description' => 'The primary identifier for a product.',
                'type' => 'serial',
                'unsigned' => TRUE,
                'not null' => TRUE,
            ),
            'name' => array(
                'description' => 'The title of this product, always treated a non-markup plain text.',
                'type' => 'varchar',
                'length' => 255,
                'not null' => TRUE,
                'default' => '',
            ),
            'created' => array(
                'description' => 'The Unix timestamp when the product was created.',
                'type' => 'int',
                'not null' => TRUE,
                'default' => 0,
            ),
            'changed' => array(
                'description' => 'The Unix timestamp when the product was most recently saved.',
                'type' => 'int',
                'not null' => TRUE,
                'default' => 0,
            ),
            'description' => array(
                'description' => 'The product description.',
                'type' => 'text',
                'not null' => FALSE,
            ),
        ),
        'indexes' => array(
            'node_changed' => array('changed'),
            'node_created' => array('created'),
        ),
        'primary key' => array('pid'),
    );

    return $schema;
}

function products_install() {
    drupal_install_schema('products');

    cache_clear_all(NULL, NULL, '*');
}

function products_uninstall() {
    drupal_uninstall_schema('products');

    $result = db_select('file_usage', 'f')
            ->fields('f')
            ->condition('type', 'product')
            ->condition('module', 'products')
            ->execute()
            ->fetchAll();

    foreach ($result as $row) {
        $file = file_load($row->fid);

        if ($file) {
            file_usage_delete($file, 'products', NULL, NULL, 0);
            file_delete($file);
        }
    }
}

```

# Answer
From your previous questions it looks like you're using Drupal 7, but the above code is partly for Drupal 6.

You don't need to add/remove the schema manually any more in Drupal 7; implementing `hook_schema()` is enough. Drupal installs the schema for you, and then when you it hits your implementation `hook_install()`, the table does already exists so it throws an error.

Just remove the calls to `drupal_install_schema()` and `drupal_uninstall_schema()`, uninstall the module and try again - it should work fine.
> 2 votes

---
Tags: 7, database
---


# Question
Title: Create directory in file system per organic group
I am using Drupal 7 and I am creating a content type which is a content of an Organic Group. This content type has a file field and all the Organic Group Members can create a node of that. I want to grouping the files in the file system with directories automatically named by Organic Groups names and some sub directories named by current date and current user uid. User can be member of 2 or more groups, so the file should be copied to all the groups directories that user selects in the create node form. Any suggestion?

# Answer
It looks like the Filefield Paths module will do what you ask, in particular there is an over view on how to Mix public and private files with Organic Groups and File (Field) Paths

The part I can see it doing is copying the file - but you may not want that behavior as it will quickly bloat your storage.
> 3 votes

---
Tags: 7, organic-groups, files
---


# Question
Title: why are form ids being displayed above forms?
I have taken over some work and have not got much documentation on what has been done. I have turned off error message reporting in the Development module but this does not turn off the form id being displayed.

What I've been seeing is messages like this... `Form ID is : search_block_form` on every page with a form. They are green, rather than the usual red of an error message.

# Answer
OK, never mind - always find the answer as soon as I've posted a question!

This is what I'd done...

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

    drupal_set_message("Form ID is : " . $form_id);

    ...

```
> 0 votes

---
Tags: forms
---


# Question
Title: Hide certain views fields only on particular content type
I am working in Drupal 7. I have a view that filters on 'Is one of' content type 'blog post' or 'member news story'. I need to adjust the output of the view so that when the content returned in the view is a blog post the author and the author company are shown, but when the returned content is a member news story the author and author company are hidden. My view has a relationship 'Content: Author'.

First of all I tried using Global PHP. I am using the realname module and was able to return the realname of the author by adding the following code to the output field of a Global PHP field:

```
    <?php
    if ($row->type == 'member_news_story'){
         print ("Author: ");
         print($row->realname);
    }
    ?>

```

I would have thought that I could just as easily use the replacement pattern for my field for the authors company, but adding the following code beneath 'print($row-\>realname);' simply prints a number i'm guessing this is a NID.

```
     print($row->field_guest_blogger_company_or_o);

```

I tried following advice like that give in questions like returning nod ID in views php and global php in view using `print_r($data);` to return the available data and then trying to drill down into it to get the variable I need. Unfortunately I was not able to return the company name. I expect this was more complex as the the company name is not in the returned node, but is a user field. After spending ages on this and getting no where I decided to try a different approach -

I thought that it might be better to work with the template.php file and create a hook for the company name views field. In template.php I added:

```
    function amrc_new_views_view_field__news_blog_front__block__field_guest_blogger_company_or_o(&$vars) {
       return "views theme view field working";
    }

```

I could see the text 'views theme view field working' in the correct place showing the hook was working. I was able to use `dpm($vars);` instead of the return statement above to return a devel/krumo display of the available variables. However I struggled to be able to print any of the variables to the screen, which I would like to be able to do before I try using them to only print the company name if the returned node is of the type 'blog post'.

To recap, my question is: When the content returned in the view is a blog post I need to show the author and the author company, but when the returned content is a member news story the author and author company are hidden. I would like to know whether using global php in views or a hook in template.php would be the best way of going about achieving this. I would also like suggestions on how to access the company name variable so I can work with it. I have been struggling with this for a long time, so your input would be really appreciated.

If required I can easily supply the output of the using `print_r($data)` in the view and the `dpm($vars);` in the hook, but left these out for brevity.

# Answer
> 0 votes
To solve this first i used `dpm($data);` in the output field of the Global PHP. This gave me the data value through devel/krumo (unsure that the devel module is installed for this). Interestingly this gave me a different name to reference the field with than when I did `print_r($data);`

Using `print_r($data);` suggested i needed `field_guest_blogger_company_or_o`

but `dpm($data);` indicated that i needed to use `field_field_guest_blogger_company_or_o`

So the working Global PHP to only print the author and company name when the content type returned is a blog post (article) was:

```
    <?php
    /* dpm($data); */

    if ($row->type == 'article'){
         print ("Author: ");
         print($row->realname);

         if (isset($data->field_field_guest_blogger_company_or_o[0]['raw']['value'])) {
            print (", ");
            print($data->field_field_guest_blogger_company_or_o[0]['raw']['value']);
         }
    }
    ?>

```

Uncomment the `dpm($data);` to see all the available variables. Note you won't have the realname field if you aren't using the realname module. For the values to be available to this code you will have to include them in your view fields and then hide them if necessary.

The above code uses an isset to check that there is a company name before printing the comma after the author name.

# Answer
> 1 votes
Controlling the rendering of information at the views level is preferable. If you control it at template.php it's just one step before the information is going to be displayed to the end user. So, it will be an overload. Just try to render the $data object, you can easily get the required information. Yes, $row has issue of returning nid in D7.

Hope it helps

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


# Question
Title: How to get custom product line item text field value?
by using commerce customisable products module, I created a custom product line item type to which I added a text field (Machine name field\_license\_details). By following this excellent video tutorial http://commerceguys.com/blog/commerce-module-tuesday-commerce-customizable-products-screencast

I was able to create a node/page which include the text field I mentioned before. However, what I find impossible to do, is to get the value that the user entered to that field. For example, when the user has entered something in the text field and clicks the add to cart button, I want the text he typed , to be 'placed' to a variable so i can do whatever i like with it for example display it back to the user or write it down to a file etc. I understand that in order to achieve that I would need to write my own module , but I am not sure which hook I should implement, and how exactly extract the string to a variable. As you probably already understood by the nature of the question ,I am just getting started on drupal, so any suggestions would be more than welcome. Thanks in advance PS I am using drupal 7.22 (the latest stable version and I have installed the drupal commerce module, the commerce file and commerce customisable products modules.

# Answer
> 0 votes
I ended up doing the following :

```
    function my_Module_form_alter(&$form, &$form_state, $form_id){
           if ($form_id == 'commerce_cart_add_to_cart_form_12'){
                  dpm($form, 'cart form'); //to use with deve module
                  $form['#submit'][]=('my_Module_commerce_add_to_cart_form_12_submit');
                  }
            }

       function my_Module_commerce_add_to_cart_form_12_submit($form, &$form_state){

             $user_text_temp=$form_state['values']['line_item_fields']['field_license_details'][LANGUAGE_NONE][0]['value'];
             dpm($user_text_temp, 'extract value is ');
            // whatever else you want to do with that user_text_temp value
          }

```

I think that's the easiest way to do what i want. I posted it because it may be of use to people new to drupal.

---
Tags: commerce
---


# Question
Title: Global Variable with a dynamic value set by variable_get() in multisite
My question is, if I have a multisite environment what is the expected behaviour of global variables set like:

```
define('GLOBAL_VARIABLE' , variable_get('myvar'));

```

**'myvar'** is set in a module configuration page, all the sites share the same module. Will each site use an independent value for **'GLOBAL\_VARIABLE'**? Which is what I want, each site to have different values for these global variables.

I can't seem to find any documentation on how this would work, or any previous questions either. It's something that would significantly affect how my module is structured, as there's a rather large amount of customization settings.

Any input is greatly appreciated.

# Answer
> 3 votes
If you are running true multisite, then your sites are sharing the same *code*, but not the same *database catalogs*.

If you are in a situation where you only have access to a single database catalog, then you can use prefixes to keep all of your instances separate.

It is also possible to share tables in the same database catalog between multiple sites. This is primarily meant for the `{users}` table, and cousins. Sharing anything else, is likely a recipe for disaster.

So, to answer your question, the `{variables}` tables in a true multisite instance will be distinct unless you went out of your way to share them.

If you are using the Domain Access module to share some content between sites, then everything is really in the same database, and you will have a single `{variables}` table.

Now, you have the sample code

```
define('GLOBAL_VARIABLE', variable_get('myvar'));

```

This is not really a good idea; just use `variable_get('myvar')` wherever you need it. If you have a lot of settings, then I would consider wrapping everything up in a singleton with a getter function that uses `drupal_static()`.

---
Tags: multi-sites, configuration
---


# Question
Title: Only ask for a shipping address if a real product is ordered
I'm using the Drupal Commerce module with Shipping 7.x-1.0. I created a webshop with both real and virtual products.

My problem is that the shipping address is required even if all the products are virtual (so there is no shipping). How can I make sure that the shipping address is only asked for if the shoppingcart contains real products?

# Answer
Here's a solution that doesn't require a custom module:

* Install Commerce Rules Extra
* Create a rule for Event: Process checkout pane
* Add Action: Change pane properties
    + Value: Shipping information
    + Page to move to: `<do not change>`
    + Enabled: uncheck
* Add Condition: e.g. by `Order contains products of particular product types`, or based on `Commerce order contains shippable products` supplied by Commerce Physical Product.

You may have to clear caches before this takes effect.
> 3 votes

# Answer
you could use hook\_commerce\_checkout\_pane\_info\_alter and do

unset($checkout\_pane\['customer\_profile\_shipping'\]);

only if all line\_items contains physical products:

```
function mymodule_commerce_checkout_pane_info_alter(&$checkout_pane) {
  global $user;

  foreach ($checkout_pane as $pane_name => & $pane_data) {
    if ($pane_name == 'customer_profile_shipping') {
      $order = commerce_cart_order_load($user->uid);
     if ($order) {
       $order_wrapper = entity_metadata_wrapper('commerce_order', $order);
       $lines = $order_wrapper->commerce_line_items->value();

       $ask_shipping = FALSE;
       foreach ($lines as $line) {
         if ($line->type == 'product') {
           $line_wrapper = entity_metadata_wrapper('commerce_line_item', $line);
           $product = $line_wrapper->commerce_product->value();
           if ($product->type == '---> you physical product type <---') {
             $ask_shipping = TRUE;
           }
         }
       }

       if (!$ask_shipping) {
         unset($checkout_pane['customer_profile_shipping']);
       }
     }
   }
 }
}

```
> 5 votes

---
Tags: commerce
---


# Question
Title: What is the variable format to reference Views field data in a Global PHP that resides in a footer/header?
Currently its annoying to have to manually parse through the views results data by either doing a print\_r() or a dsm() via devel. Does anyone know how to reference a field via PHP when you put in a Global PHP field in either the header or footer of the View?

# Answer
##

To reference a Views field result here's the format of the variable when using a PHP Global in the footer/header in a Views display:

```
$results[0]->field_**<FIELD NAME>**[0]['raw']['**<VARIES DEPENDING ON TYPE OF FIELD>**']

```

This is in reference to a taxonomy id (tid) reference:

```
$results[0]->field_field_device_type[0]['raw']['tid']

```

This is in reference to a text field called full\_name:

```
$results[0]->field_field_full_name[0]['raw']['value']

```

The \[0\] represents each result row and the last array value usually changes depending on the field type (text,reference,image, etc.) So its better to dsm or print\_r() if you really need to reference something that your not sure of.

Here's a sample output of the array structure so you can get an idea of how its laid out:

---

**Here's a better view of the array output of a view's result when you do a print\_r() within the header. I had to apply this to another view and forgot how to reference the variables. So here's the full output when you do a print\_r($result\[0\]-\>field\_field\_machine\_type): (keep in mind it has to be "field\_field" when you reference a field.**

```
     Array
(
    [0] => Array
        (
            [rendered] => Array
                (
                    [#markup] => Tablet
                    [#access] => 1
                )

            [raw] => Array
                (
                    [tid] => 105
                    [taxonomy_term] => stdClass Object
                        (
                            [tid] => 105
                            [vid] => 9
                            [name] => Tablet
                            [description] =>
                            [format] => plain_text
                            [weight] => 0
                            [vocabulary_machine_name] => machine_type
                            [rdf_mapping] => Array
                                (
                                    [rdftype] => Array
                                        (
                                            [0] => skos:Concept
                                        )

                                    [name] => Array
                                        (
                                            [predicates] => Array
                                                (
                                                    [0] => rdfs:label
                                                    [1] => skos:prefLabel
                                                )

                                        )

                                    [description] => Array
                                        (
                                            [predicates] => Array
                                                (
                                                    [0] => skos:definition
                                                )

                                        )

                                    [vid] => Array
                                        (
                                            [predicates] => Array
                                                (
                                                    [0] => skos:inScheme
                                                )

                                            [type] => rel
                                        )

                                    [parent] => Array
                                        (
                                            [predicates] => Array
                                                (
                                                    [0] => skos:broader
                                                )

                                            [type] => rel
                                        )

                                )

                        )

                )

        )

)

```
> 0 votes

---
Tags: 7, views
---


# Question
Title: Per-item commerce shipping rules working but charging for same item twice
I've read similar looking posts, but nothing addresses my particular problem.

I have 2 shipping rates and rules setup and no longer confusing each other (thanks to rfay's excellent vimeo tutorials and the discussion here: https://drupal.org/node/1415638)

One is for domestic and I'm trying to add a 50 cent per item shipping charge to a $3 base.

The other is international and I want it to add a $3 per item shipping charge to an $11 base.

I have things basically setup like rfay documents in https://drupal.org/node/1415638

And it's sort of working. The problem is it appears to be double-counting one of the items - I'm probably saying this wrong.

e.g., 4 domestic items should be base ($3) + 3\*50 cents = $4.50, but it is currently computing $5.00

My international rule is behaving in the same way. How do I avoid this double-dipping?

# Answer
OK - I figured it out. I don't know if this is the best way to do it, but I added an action to my rule, but not as part of the Loop - just beneath it (not indented). This new action is "Subtract an amount from the unit price." For data selector I entered commerce\_line\_item. For amount, I entered the amount of one additional item (50 for the 50 cents in my domestic shipping example).

So now my rule basically takes the base rate of $3, adds 50 cents for each item including the base item, so then the subtraction action removes that extra 50 cents. Hope this makes sense.
> 0 votes

---
Tags: rules, commerce
---


# Question
Title: How do I preserve file permissions after compressing and moving as tarball?
I seem to be frequently encountering a situation when I compress files of a Drupal site as a tarball from a production server to the `public_html` folder of my local machine.

The permissions seem to get messed up and I usually end up with a filesystem not readable error and deleting a few files in the `sites/default/files` directory during the process of changing the permissions.

How can I preserve these permissions when the folder is compressed and copied to a new folder or is it an issue with the permissions of the destination folder?

# Answer
I move sites as tarballs between servers fairly often when I can't deploy with rsync or git.

According to the man page:

> -p, --preserve-permissions
> extract information about file permissions (default for superuser)

is the proper option to use. However, this never works well for me.

Typically, I will just use normal tar options, and then run a script after the fact to fix things up.

The Securing file permissions and ownership article has a very good script. As that gets adjusted from time to time, I am not going to reproduce it here. It essentially does some find/chown/chmods on the tree to fix things up.

I would use this script as a starting point for your needs. One thing that it doesn't address is having the private:// filesystem outside of docroot, which I always use. I will also use 2775 as the permission for the public:// path, as well as a separate use for core/contrib and the site specific code.
> 3 votes

---
Tags: 7, files
---


title: Drush post command hook not executed

text:
# Question
Title: Drush post command hook not executed
I need to run a hook after a drush command in another module has been run to clean up a file on the server, and so based on what I've read here and here I'm trying to implement a post command hook on the node-export-import command. In mymodule.drush.inc I have a function defined as

```
function drush_mymodule_post_node_export_import(){
  // Do my magic here
}

```

but it isn't called at all after running the node-export-import command. I've played around with other naming variations, but none are getting called. My module is enabled, and I've cleared cache. I'm using version 5.9. Is there something I'm missing?

Thanks.

# Answer
> 10 votes
To see all of the hooks available to you, run your command with --show-invoke, like this:

```
$ drush status --show-invoke 2>&1 | grep mymodule
drush_mymodule_core_status_pre_validate
drush_mymodule_core_status_validate
drush_mymodule_pre_core_status
drush_mymodule_core_status
drush_mymodule_post_core_status

```

However, when we do this on node\_export commands, we see no results. Why is that? Well, unfortunately, some commands do not go through the drush invoke hook process. If you look at the definition of the node-export-import command, you will see this:

```
$items['node-export-import'] = array(
  'callback' => 'drush_node_export_callback_import',

```

In Drush's command.inc, there is this comment in the function drush\_get\_commands():

```
    // If command callback function name begins with "drush_$commandfile_",
    // then fix up the command entry so that drush_invoke will be
    // called by way of drush_command.  This will cause all
    // of the applicable hook functions to be called for the
    // command when it is invoked.  If the callback function does
    // -not- begin with its commandfile name, then it will be
    // called directly by drush_dispatch, and no hook functions
    // will be called (e.g. you cannot hook drush_print_file).

```

If a command provides a callback, then Drush calls that function instead of drush\_command, so \_drush\_invoke\_hooks is never called. This means that, even though you named your hook function correctly, Drush will not call it, and you are stuck.

From here, you have two options:

1. Post an issue to the node\_export issue queue, and request that they stop using the 'command' callback parameter, and let Drush choose the function name to call. This will make hooks work again. Using 'callback' is deprecated unless it is necessary (e.g. many commands calling the same function, such as drush\_print\_file), so hopefully the maintainers will be willing to do this.
2. Post a feature request to the drush issue queue, and request that Drush call the invoke hooks even if the Drush command uses the callback feature. This is theoretically possible if the parameters to \_drush\_inovke\_hooks were enhanced to include a replacement function name to call in place of the primary hook function. This would have to be set up in drush\_get\_commands(), and then detected and uses in drush\_command() where it calls \_drush\_invoke\_hooks. This didn't seem like a good idea at the time, but if it is common for contrib module maintainers to ignore subtle Drush conventions, it might be worthwhile to go to the extra effort to let folks hook their functions anyway.

**Update:** I made a patch for you. See: https://drupal.org/node/2041109. You might still want to do #1, as I don't think that we will necessarily backport this enhancement to Drush 5.

**Update 2:** Above-referenced patch has been committed to Drush-8.x-6.x-dev. This happened after the rc1 release, but it will be in the next release.

**Update 3:** This is now available in Drush-8.x-6.0-rc2.

---
Tags: hooks, drush
---


title: How do you theme the node edit page?

text:
# Question
Title: How do you theme the node edit page?
What filename do you use to theme the node edit page in Drupal 7?

# Answer
If you are asking about theme()ing the page on which the node edit form is displayed, you would use `page--node--edit.tpl.php`.

More information on Drupal 7 Template Suggestions can be found here.
> 2 votes

---
Tags: 7, theming, nodes
---


# Question
Title: programmatically taxonomy update node DrupalDefaultEntityController error
When I programmatically create a taxonomy term and update node, in `hook_node_presave()` I have the following code:

```
$node->field_status_tags[LANGUAGE_NONE][]['tid'] = $value->tid;

```

I get the following error:

> Notice: Array to string conversion in DrupalDefaultEntityController-\>cacheGet() (line 369 of includes\entity.inc).

This is the code I am using. I'm sure the value for tid is right.

```
/**
 * Implements hook_node_presave().
 */
function love_layout_node_presave($node) {
  /*
   *if ($node->nid && $node->moderate) {
   *  // Reset votes when node is updated:
   *  $node->score = 0;
   *  $node->users = '';
   *  $node->votes = 0;
   *}
   */
  if($node->type == 'status') {

   $pattern = '/#([^\\#|.]+)#/';
   preg_match_all($pattern, $node->title, $matches, PREG_SET_ORDER);
   $node->field_status_tags[LANGUAGE_NONE] = array();
   foreach ($matches as $key => $value) {

      $term_name = $value[1];
      $term = taxonomy_get_term_by_name($term_name);
      if(!count($term)){
       $term = new stdClass();
       $term->vid = 1;
       $term->name = $term_name;
       taxonomy_term_save($term);
       $term = taxonomy_get_term_by_name($term_name);
       foreach ($term as $value) {
          //dpm($value,$key);
          $node->field_status_tags[LANGUAGE_NONE][]['tid'] = (int) $value->tid;
        }
      }else{
        foreach ($term as $key => $value) {
          //dpm($value,$key);
          $node->field_status_tags[LANGUAGE_NONE][]['tid'] = (int) $value->tid;
        }
      }
   }
   //dpm($node,'love_layout_node_presave-node');
  }
}

```

# Answer
> 0 votes
Basically I would think that $value-\>tid when you are using it is not a number but an array. Because I do the same assignment and it works.

So I suspect you are misusing the taxonomy term you created. This is how I created the taxonomy in a function:

```
function create_new_term($term_name, $vocabulary_id, $language = LANGUAGE_NONE, $i18n_tsid = 0){
  $tid = db_insert('taxonomy_term_data')
  ->fields(array(
    'name'=>$term_name,
    'vid'=>$vocabulary_id,
    'language'=>$language,
    'i18n_tsid'=>$i18n_tsid,
  ))->execute();
  db_insert('taxonomy_term_hierarchy')
    ->fields(array(
      'tid'=>$tid,
      'parent'=>0,
  ))
  ->execute();
  print "Created new taxonomy term tid #".$tid." $term_name in $vocabulary_id<br>"."\n";
  return $tid;
}

```

And here is how I add that term:

```
$my_new_node->field_my_term['LANGUAGE_NONE'] [] ['tid'] = $returned_tid;

```

I hope this helps.

# Answer
> -1 votes
This appears to be the same as one the existing core issues (https://drupal.org/node/1525176).

As of 2013-09-11, there are patches in the issue, but it still remains open.

---
Tags: entities
---


# Question
Title: Contextual filters with Entity reference
I have two content types called Basic Page and Contact Info.

* There are around 5 nodes from Contact Info with some contact info (phone/fax/email/IM) in the body field.
* In Basic Page content type there's an Entity Reference field that refers to Contact Info. So that for each page there would be a main contact person. When someone create a Basic Page node they can pick a Contact Info node from the dropdown (out of the 5 Contact Info nodes).

> Basic Page -\> Contact Info (Basic Page content type refers to Contact Info content type)

Then I created a block view (added to the sidebar of Basic pages) which displays the contact info associated with that node.

Added a Relationship in the view (Entity Reference: Referenced Entity)

Right now it's displaying all 5 contact info nodes, not just the one associated with that particular basic page node. I tried to tweak the Contextual filter and relationships but couldn't get it to work.

I have a feeling that the solution lies in the php code that goes in Provide default value -\> php code section.

Any help appreciated. Thanks

# Answer
> 8 votes
The contextual filter should be "content:nid"

The options should be set as follows...

> The Relationship should be your "Entity Reference: Referenced Entity" relationship
>
> Under "When the filter value is NOT available" check "provide default value" and select "Content ID from URL"
>
> Apply changes and save view.

I think this is the same thing Renee was saying, just in other words.

Hope this helps - I recently lost a weekend to figuring this out ; )

---
Tags: views, entities
---


# Question
Title: How to: Multilanguage site, but single language backend?
I have almost completed my first Drupal 7 multilanguage test site. As long as I'm not logged in, I can browse through all pages and switch languages. When logged in, my first issue was that the backend language would switch, when switching the frontend language. I.e., the admin menus are translated, but should stay English (or whatever the editors preferred language is).

Then I found that in Configuration \> Languages \> Detection and Selection, I can select how the language is chosen. So: User first, then the backend stays in the user language. Fine. But then, the frontend stays in that language, too! So when logged in, I cannot browse all pages anymore, only the English ones ...

There must be a way to select front and backend languages independently. How?

# Answer
I know this post is getting old and the OP probably has this sorted by now but I came here looking for the same answer and thought I'd post a follow up for anyone looking for details. I've made this as easy and basic as possible in case you're new to Drupal.

My version is 7.21.

Ok, here's what I just did to get the back end in English and the site content in Spanish. I'm assuming you have all the translating modules installed and set up, etc.

Go to your admin profile and set your languages, for me its this:

Administration Language = Default administration language, currently English

Language Settings Language = English

Then go get the Administration Language module that Patrick linked to. (its currently the Dev version but works fine for me, look in the red area for the DL). Install and enable.

Then go to Administration \> Configuration \> Regional and language \> Languages:

Scroll to the bottom and you'll have an option of "Use administration language in the administration menu". Set that to Enabled

Save it and now everything should show in what ever language while the back end stays in the language you set for your admin profile.

I hope this helps!
> 5 votes

# Answer
There is an easier way to do this, if we say that the Admin language should be the same language, that the logged in user wants it to be.

This is how you do it.

---

1. Go to » /admin/config/regional/language
2. Choose the "Detection and Selection" tab » /admin/config/regional/language/configure
3. Activate the "User detection" and drag it to the top of the detection methods.

**OBS! It is important, that it is above the "URL detection".**

Now login and go to your user account. Here you can choose which language, you prefer the site to be. And the admin pages will now show up in your language, even if you choose for the site content to change to let's say German, while your building your page.
> 3 votes

# Answer
There is the Administration Language module, though it doesn't even have an alpha release yet for D7 and I haven't used it on D7.

The difficulties in this kind of set up were also touched on in this Drupalcon Denver 2012 presentation by Suzanne Kennedy and Florian Loretan.
> 2 votes

# Answer
Maybe you could try using TranslateThis Button for your site. It uses Google translate which translates every page on load. Also you will not have to worry about the backend language.
> 1 votes

---
Tags: i18n-l10n, users
---


# Question
Title: Uncaught TypeError: Cannot call method 'extend' of undefined
I'm trying to use a jquery ticker in my website and this is the code: http://cektkp.com/twittermarquee/twitmarquee.js and I'm getting these errors:

1) Uncaught TypeError: Cannot call method 'extend' of undefined:

```
window.twttr.bounds = window.twttr.bounds || {};
   $.extend(twttr.bounds, {
      Bounds: function (b, d, c, a) {
        this.x = b;
        this.y = d;
        this.width = c;
        this.height = a
      }
});

```

2) Uncaught TypeError: Property '$' of object \[object Object\] is not a function (line 37)

```
 function loadTrendDescriptions() {
    $("#trends a").each(function () {
        var A = $(this);
        var C = A.parent().find("em");
        if (C.length) {
            var B = A.text();
            var D = C.text().replace(new RegExp(B.replace(/([^\w])/gi, "\\$1"), "gi"), "<strong>" + B + "</strong>");
            var E = A.attr("title").length ? A.attr("title") : A.attr("name");page.trendDescriptions[E] = [B, D]
        }
    })
}

```

I've fixed many other problems I was getting but these are the ones I just can't understand how to fix. Please help me out!

# Answer
> 1 votes
You are attempting to use jQuery before it's loaded.

You should place that code inside your ready function:

```
$(document).ready(function () {
    // place code here
});

```

Although to be really Drupal-friendly, you should use Drupal's behaviors.

---
Tags: ajax, javascript
---


# Question
Title: Is it bad practice to track all in the configuration module
I am taking over a site that was built without configuration management, I installed the configuration module for the first time (I am used to using features). I am wondering if it is bad practice to just select all in all the categories and track all the available configurations instead of trying to cherry pick the applicable ones. What are the effects of performance, etc.

# Answer
> 3 votes
I have tried it in Drupal7 (not on Drupal8).

Logically it should be good practice to track all the configurations. However, not all the "configurations" are actually configurations. For example there are persistent variables or cached values that have nothing to do with the configuration. So, tracking all of them would undermine the aim of configuration tracking.

Besides this, the UI becomes infinitely slow and unresponsive when you select all the configurations. I guess it is because it tries to find out dependencies of each configuration and does it in an inefficient way. You can try to handle them from the command-line (with drush) but I doubt that it would be more efficient.

So, I think that the best option is to cherry pick the relevant configurations. But once you start cherry-picking them, you might as well use features, configuration management loses its meaning.

This is basically what I did on a project of mine: I started with configuration management, and ended up using features, which by the way was a tedious process.

---
Tags: configuration
---


# Question
Title: Show Webform confirm message in my custom panel page
I'm new to Drupal. I have created a web form in my page using Webform module. I added my contact web form in a custom panel page. I use the Clientside Validation module to validate the web forms.

If the form validation is okay, I want to show the confirmation message at the top of the web form in my panel page instead of the default message location used in the page.tpl.php. I use the single page web site.

Can anyone help me to solve my problem?

# Answer
> 1 votes
I guess the problem is that the Clientside Validation module shows the message in the default location defined in the template.

You can check Clientside Validation Usage. Then you can see **Error Message placement** and **Default location**. I hope you can tweak your default message location from this:

> Here you can select the default location to display your error messages. You can choose between the following options:
>
> * jQuery selector: This option will place a div containing all the error messages inside the div that matches the jQuery selector
> entered in the "jQuery selector" field below this option.
> * Top of form: This option will place a div containing all the error messages above the form the error messages are for.
> * Before label: This option will place the error before the label of the matching element
> * Afterlabel: This option will place the error after the label of the matching element
> * Before input: This option will place the error before the matching element
> * After input: This option will place the error after the matching element
> * Top of first form: This option will place a div containing all the error messages above the first form. This means that when there are multiple forms on a page, the errors of the second form will be added to the error div of the first form and will be displayed above the first form
> * Custom function: (Advanced) Selecting this option requires you to enter a javascript function name in the textfield "Custom function name" below this option. This function name will be given to the errorPlacement option of jQuery.validate()

You could use jQuery selector or Custom function.

---
Tags: webforms
---