# Question
Title: Logging into Drupal from a non-Drupal site
I would like to create an interface on a non-Drupal site that will allow me to login to my Drupal site?

How can I accomplish this, either with custom code or with an existing Drupal module?

# Answer
> 2 votes
Use Token authentication

> Token Authentication provides a token for use in the URL to authenticate users to your site. It only works on paths configured in the settings page.
>
> Originally this module was intended to offer simple authentication for RSS feeds to allow feed readers to pull customized content listings. You can now use it to provide a simple browsing experience of any Drupal content.

You would need to code a bit behind the scene - namely inject new token to proper table on successful off-site login, but it should be possible.

But maybe for your case opposite approach would be better? You can add custom submit handler to Drupal's login form to get arbitrary PHP code executed.

# Answer
> 1 votes
My solution to your issue; is to read/get Drupal login page as HTML using `file_get_contents` PHP function or cURL. Then parse through the HTML string and extract login form with its fields and submit button, using DomDocument.

Add the following code to your none Drupal login page/block:

```
$url = 'http://example.com/user/login';

$html = file_get_contents($url);

$dom = new DOMDocument();

// to support HTML5 doctype
libxml_use_internal_errors(true);

$dom->loadHTML($html);

libxml_use_internal_errors(false);

// get Drupal login form
$login = $dom->getElementById('user-login');

// reset action attribute to absolute URL
$login->setAttribute('action', $url);

// save form node
$form = $login->ownerDocument->saveHTML($login);

print $form;

```

**Note:** Drupal messages will only appear on Drupal side in case of successful login or invalid login.

---
Tags: users
---


title: Feed Import Error

text:
# Question
Title: Feed Import Error
This import was working, now I'm stumped on why it's breaking.

> An AJAX HTTP error occurred. HTTP Result Code: 200 Debugging information follows. Path: /batch?id=79&op=do StatusText: OK ResponseText: Please register to continue....\[lots more\]

just a standard import: mylocal.com:8080/import select import file: ~downloads/myexport.xml click \[Import\]

Everything is being done on local osx laptop.

* Drupal 7.22
* Feeds 7.x-2.0-alpha8

Since it seems to be an authentication issue for the batch, I assigned all permissions to all roles, including anonymous, for feeds and the relevant content create (on this local instances).

This can't be a big problem, I just don't see it...

# Answer
> 0 votes
When upgrading Feeds, I have found that settings often get lost. It is not an extremely stable module.

Go to `/admin/structure/feeds` and edit your feed importer. Re-check all of your importer settings, and make sure they are correct. In particular, under processor settings make sure the *Author* is set to a user with sufficient permissions (usually *admin*).

# Answer
> 0 votes
Feeds is fine. The error reported above was caused by an unrelated custom module. When that module was disabled, then the feed import succeeded. Long live feeds.

---
Tags: 7, feeds
---


# Question
Title: Round Commerce Price: in tpl.php or template.php
Currently I'm using Commerce and Commerce Multicurrency to our currency in Indonesia.

Sometimes there is a price to numbers that are not rounded.

With print render ($ content \['product: commerce\_price'\]) I get the original price.

I've tried to edit the tpl.php file and the results are as desired.

```
number_format (round ($ price, -4), 0);

```

2,511,000 into 2,500,000 2,565,000 into 2,600,000

But after some reading and hopefully not misread. That is not good in tpl.php, but should be in template.php or modules.

Please advise to help me.

# Answer
> 1 votes
A better way to adjust currency formatting, using the relevant Commerce currency hooks, is with

hook\_commerce\_currency\_info\_alter

and adding your own commerce\_currency\_format handler

e.g:

```
/**
 * hook_commerce_currency_info_alter
 *
 * Add custom currency format to selected currencies
 */
function MY_MODULE_commerce_currency_info_alter(&$currencies){
  $currencies['IDR']['format_callback'] = 'MY_MODULE_commerce_currency_format';
}

/**
 * Currency format callback
 *
 * Remove decimal places from output
 * while keeping commerce_amount_to_decimal formatting the same
 *
 * See: commerce_currency_format
 */
function MY_MODULE_commerce_currency_format($amount, $currency, $object = NULL, $convert = TRUE) {

  // Format the price as a number.
  // In our case, we remove decimal places
  $price = number_format(commerce_currency_round(abs($amount), $currency), 0, $currency['decimal_separator'], $currency['thousands_separator']);

  // Establish the replacement values to format this price for its currency.
  $replacements = array(
    '@code_before' => $currency['code_placement'] == 'before' ? $currency['code'] : '',
    '@symbol_before' => $currency['symbol_placement'] == 'before' ? $currency['symbol'] : '',
    '@price' => $price,
    '@symbol_after' => $currency['symbol_placement'] == 'after' ? $currency['symbol'] : '',
    '@code_after' => $currency['code_placement'] == 'after' ? $currency['code'] : '',
    '@negative' => $amount < 0 ? '-' : '',
    '@symbol_spacer' => $currency['symbol_spacer'],
    '@code_spacer' => $currency['code_spacer'],
  );

  return trim(t('@code_before@code_spacer@negative@symbol_before@price@symbol_spacer@symbol_after@code_spacer@code_after', $replacements));
}

```

# Answer
> 0 votes
As per your comment you have done it by making some module. But still I will tell you my way to doing it.

As you want to print the value after rounding it in your node.tpl.php, you can go for implementing THEME\_preprocess\_node(&$variables) function in your template.php file of the theme which you are using. Replace THEME with your theme name in there.

Now implement something like this,

```
function indiareads_preprocess_node(&$vars){
  if ($node = menu_get_object()){
    if($node->type == 'YOUR_PRODUCT_DISPLAY_TYPE'){
      $product_id = $node->FIELD_PRODUCT_REFERENCE['und'][0]['product_id'];
      $product = commerce_product_load($product_id);
      $price = $product->commerce_price['und'][0]['amount'];
      $rounded_price = number_format(round($price,-4), 0);
      $vars['rounded_price'] = $rounded_price;
    }
  }
}

```

Replace YOUR\_PRODUCT\_DISPLAY\_TYPE with the name of content type which is displaying your product & FIELD\_PRODUCT\_REFERENCE with the name of field of that content type which reference the commerce product.

After this when you will go to **node.tpl.php**, you will have `$rounded_price` variable available to print where ever you want.

I am writing this for better understanding of the system even if you have done that, so that if somebody comes searching can get help.

---
Tags: theming, commerce
---


# Question
Title: How to use Apache Solr as data source for a view
Is it possible to use data indexed in Solr as the data source for a specific view? I already tried installing the search api, search api page, entity api, ctools, search api solr and the views api.

I already created a server and an index which uses solr:

But the only fields that I get are node fields:

I'm expecting to get the fields from documents that I indexed in Solr. How do I do that in Drupal, is there a specific module that would allow me to make use of the fields that already exists in Solr as the fields for a view?

# Answer
All you need is Apache Solr Views module.

> This module provides Views implementation for the Apache Solr Search Integration Project 7.x-1.x branch. Requires Views 3.
>
> This module will provide facet navigation combined with searching to make a powerful user experience.

After installing this module, you can able to create a Apache Solr view, which list all the fields which are available in the indexed documents in the solr.
> 1 votes

---
Tags: views, 7, search
---


# Question
Title: Programmatically displaying a view into a colorbox
Love the module. My use case is to take programatically take the result of a view and load it into a colorbox. I can use views\_get\_view or views\_embed\_view to get a result array or a large html string. But how can I pass that to the colorbox?

Any help is greatly appreciated.

https://drupal.org/node/1991948

# Answer
> 1 votes
Put your view into a div with a *wrapper* that is hidden (ie, display:none;). Then you can use the following javascript:

```
$.colorbox({
    'inline' : true,
    'href' : $('.views-view-my-view'),
});

```

You must replace the 'href' attribute with the appropriate jQuery collection representing your view. Other customisations to the way your colorbox appears can be found here.

If you need some advice on placing a view on your page, here is a clean implementation:

```
function MODULE_preprocess_page(&$vars) {
  $vars['page']['bottom']['my_view'] = array(
    '#type' => 'container',
    '#attributes' => array(
      'id' => 'my-view-container',
    ),
    'children' => array(
      '#markup' => views_embed_view(...),
    ),
  );
}

```

In this case your selector for colorbox would be `#my-view-container .view`

---
Tags: views, javascript
---


# Question
Title: Optional field in admin panel to filter nodes in view
Is there a way to add a optional field that filters nodes in a view?

I'm fairly new to drupal but I have a view that renders nodes depending on their categories. I can edit the view and manually add the filter but that affects all the nodes with that view. So is there a way to add filed to the "edit" screen of a page so I can have a field, that when filled it will filter the nodes it picks up and when it is empty it shows all the nodes?

Sorry if I'm using the wrong vocabulary, really new to Drupal

# Answer
Not a problem... Drupal does have its own jargon but after a while you will get it. Very simple solution whenever you want to offer user an option of refining the view or sort... Expose the relevant filter(s), in this case the vocabulary or taxonomy term... You might also think about using the global null function so as to reduce load on your server ... This will basically produce no results until the user chooses a vocabulary or taxonomy term (category)... Here is an excellent walkthrough on how to do this: How to prevent views from loading the results upfront

Cheers, gg
> 0 votes

---
Tags: views
---


title: File field emptied on node_save

text:
# Question
Title: File field emptied on node_save
I know that similar questions have been asked before but none of the suggestions there have helped me at all. I've been trying all day to get this node to save file data and nothing has worked. I'm not sure whether I am missing something, but if anyone could help I appreciate it a whole lot.

This is the code, which seems accurate but when the node save happens the file field is emptied. So I don't understand what is happening. I have tried different approaches to this and haven't figured it out yet.

```
$file_object = file_save_upload('node_file', NULL, $dest, FILE_EXISTS_RENAME);
    if ($file_object !== 0) {
     $node->field_file_upload[$node->language][0]['value']=(array)$file_object;

        node_save($node);
    }

```

# Answer
> 0 votes
Well I answered my own question eventually. The issue was the format for saving to this particular type of field 'file'. I changed

`$node->field_file_upload[$node->language][0]['value']=(array)$file_object;`

to

```
$node->field_file_upload[0]['fid']=$file_object->fid;

```

For some reason the formatting that was given in other answers was not functional for me. The file field type seems to be very particular about it's format, but it only NEEDS, the fid. Once the node is loaded the full file array is loaded.

To answer longboardnode what I wanted was the array of data about the file that is stored when the file is uploaded. Unfortunately node fields seem very picky about formatting.

---
Tags: nodes
---


# Question
Title: Mass image upload with Storage API and Services API
I am trying to set up a site that will be storing a large amount of images (roughly 50,000 to start with). The strategy for this was to use Storage API and S3 storage to deal with the costs of hosting, and Services API to provide an interface for a offline converter/uploader to get the images to the site.

This is working pretty good. If I upload an image manually by creating a node and filling in the image field, it gets sent to Storage API and good things happen. I can also upload files and create nodes from the offline uploader via the XMLRPC Services API.

The problem is that the files uploaded with the offline uploader don't get handled by Storage API. Currently the script uses the Services API method 'file.create' to create and object, then the details returned are used to fill in the image field on the node that is created next. I expect there is a better way to do this, but I am not sure.

# Answer
Still in early dev, but checkout Storage API Populate:

> Storage API Populate provides a mechanism to move existing files within file/images fields into storage. The module requires the Storage API module.
>
> For a scenario where you have an existing site, without any Cloud/CDN support for assets and would like to use Storage API to manage the storage and serving of files.
> 3 votes

---
Tags: 7, services, media, files
---


title: Multisite and apple touch icons

text:
# Question
Title: Multisite and apple touch icons
In a typical multisite D7 installation, I would like to set up apple touch icons. So that, when an agent requests `http://example-1.com/apple-touch-icon.png` then he receives the image appropriate for site **example-1**. And for site **example-2**, it should be a different image with the same name (and unfortunately at the exact same url, which is the multisite root directory). How can this be solved?

# Answer
> 1 votes
It doesn't totally help with the default paths, but I explicitly define them for each theme:

```
/**
 * Implements hook_preprocess_html().
 */
function MYTHEME_preprocess_html(&$variables) {
  $path = drupal_get_path('theme', 'MYTHEME');

  drupal_add_html_head(array(
    '#tag' => 'link',
    '#attributes' => array(
      'href' => $path . '/images/favicon.png',
      'rel' => 'icon',
      'type' => 'image/png'
    ),
  ), 'MYTHEME-favicon');

  drupal_add_html_head(array(
    '#tag' => 'link',
    '#attributes' => array(
      'href' => $path . '/images/touch-icon-iphone.png',
      'rel' => 'apple-touch-icon',
    ),
  ), 'MYTHEME-touch-icon-iphone');

  drupal_add_html_head(array(
    '#tag' => 'link',
    '#attributes' => array(
      'href' => $path . '/images/touch-icon-ipad.png',
      'sizes' => '72x72',
      'rel' => 'apple-touch-icon',
    ),
  ), 'MYTHEME-touch-icon-ipad');

  drupal_add_html_head(array(
    '#tag' => 'link',
    '#attributes' => array(
      'href' => $path . '/images/touch-icon-iphone-retina.png',
      'sizes' => '114x114',
      'rel' => 'apple-touch-icon',
    ),
  ), 'MYTHEME-touch-icon-iphone-retina');

  drupal_add_html_head(array(
    '#tag' => 'link',
    '#attributes' => array(
      'href' => $path . '/images/touch-icon-ipad-retina.png',
      'sizes' => '144x144',
      'rel' => 'apple-touch-icon',
    ),
  ), 'MYTHEME-touch-icon-ipad-retina');
}

```

---
Tags: 7, multi-sites
---


title: Change base URL of multi-site install

text:
# Question
Title: Change base URL of multi-site install
I've searched a bit for the answer to this, but all the answers seem to refer to single sites, or they just don't work (or I'm doing them wrong).

I have an out-of-the-box Bitnami image setup on Amazon EC2, and when I point my domain to the server, then visit the domain, I need to put a `/drupal` on the end to get to the drupal sites.

I need to figure out how to make `example.com` and `example2.com` point to the drupal installation instead of `example.com/drupal` and `example2.com/drupal`.

Is this a drupal configuration that I need to change, or an Apache configuration, or what?

# Answer
This is more than likely an apache configuration. Changing it to the RewriteBase /drupal like above will simply allow drupal to know that /drupal is where the site is installed. You need to either look into moving the files into the original directory that the domain is pointed to, or look into finding the apache virtual host file and point it to the /drupal folder.
> 1 votes

# Answer
Inside your site's `.htaccess` file you should see this:

```
# Modify the RewriteBase if you are using Drupal in a subdirectory or in a
# VirtualDocumentRoot and the rewrite rules are not working properly.
# For example if your site is at http://example.com/drupal uncomment and
# modify the following line:
# RewriteBase /drupal

```

You should be able to fix the problem you're having by uncommenting the last line, so it now looks like this:

```
# Modify the RewriteBase if you are using Drupal in a subdirectory or in a
# VirtualDocumentRoot and the rewrite rules are not working properly.
# For example if your site is at http://example.com/drupal uncomment and
# modify the following line:
RewriteBase /drupal

```

Hope that helps... Let me know if you're still having an issue though. :)
> 0 votes

---
Tags: uri, multi-sites
---


# Question
Title: How can i change RealName / User account link destination?
I'm using RealName module in D7 to show real names on nodes and in comments and would like to link the real name `[user:first-name] [user:last-name]` to a custom content type (a 'profile' page), instead of the standard 'user account'.

It is easy to use RealName in D6, but I've been searching for ages for a solution in D7.

I have read "Have username link to profile rather than regular userpage by default", but I am not using Content Profile.

I wondered if I need to 'preprocess' the user name, but can only read php and have no idea what to change there.

I have set the URLs for account pages to be `[user:first-name]-[user:last-name]-account` using URL alias patterns and the URLs of the custom content type I am trying to link to look like `[user:first-name]-[user:last-name]`.

What is the simplest way to change the 'View user profile' link, which appears in comments and in node 'Authored by' to point at my custom user profiles instead of the standard 'user account's pages?

# Answer
Did you try `hook_username_alter()`?

> Alter the username that is displayed for a user.
>
> Called by format\_username() to allow modules to alter the username that's displayed. Can be used to ensure user privacy in situations where $account-\>name is too revealing.

I've used this occassionally, but I find sometimes there are instances where I felt it should have been called/used already and then wasn't (the Webform module submission report tables come to mind ...)
> 0 votes

---
Tags: 7, users, navigation
---


# Question
Title: How to creat a page display comments list of users
I try to make every users of my site can view their own and others' posted comments (like "profile:user comments history").

Although the Tracker module can do it, it is not the way I want: It doesn't display the comment but the title of the article to which the comment belongs to.

I am trying with the Views module 7.x-3. I created a comment type view to display comments and add a relationship "Comment: Author". I am stuck here: user1 can view user2's, user3's "profile:user comments history" so the value of "Comment: Author uid" (Filter criteria) should change with the profile pages.

The path of user profile page is /user/% and the arg(1) is the id of users. So I want to make "Filter critera" -\> "Comment: Author uid (= `< ? php echo arg(1) ; ?>`)", but it does not work.

If the Views module can't do this, please tell me some other modules (small and simple is best) that could make it.

# Answer
My solution was to configure the view as

* "Advanced" =\>
* "CONTEXTUAL FILTERS" =\>
* Add "Comment: Author uid" =\>
* Chose "Skip default argument for view URL" =\>
* "WHEN THE FILTER VALUE IS IN THE URL OR A DEFAULT IS PROVIDED" =\>
* "Override title" =\>
* %1
> 0 votes

# Answer
This is just a simple view: Set up a relationship with comment:node not author; then in your filter criteria add "User: Name exposed" and set your fields.
> 1 votes

---
Tags: views, users, comments
---


# Question
Title: Need an exposed filter field as select box with values like "Last x days" etc
I'm trying to filter my nodes on the basis of last 7 days & last 30 days but the below code is not working for me when I tried this in my custom module, its working as a conversion for text-field to select but not working as a filter

```
function dreamzen_form_views_exposed_form_alter(&$form, &$form_state, $form_id) {
    $fromdate = &$form['created'];
    $fromdate['#type'] = 'select';
    $fromdate['#options'] = array(
      'All' => 'All',
      'Last 7 days' => '-7 days',
      'Last months' => '-30 days',
    );
    $fromdate['#default_value'] = '';
    $fromdate['#size'] = 1;
}

```

# Answer
> 0 votes
are you checking, value is equal to '-7 days', it must match to the value of select box.

Hope this may help full.

---
Tags: views, 7
---


title: Add/attach a field to all content types

text:
# Question
Title: Add/attach a field to all content types
I know that I can attach a field to any content type. I have to attach a field to all content types in a my site which are more than 40 content types. It is hard for me to attach this field manually. I'm seeking for an automated way to do this. Is there any module to do that?

# Answer
> 2 votes
Use your favourite SQL client and amnually populate `{field_config_instance}` table:

1. In Drupal, create field in one content type.
2. In your favourite editor create set of 39 queries (40 content types minus that one you worked out manually), with the same field values. Just leave id empty so autoincrement can work, and populate `entity_type` with your conetnt type names. I use spreadsheets to do that, first spreadsheet column is first query part, second is for the names of content types (obtained by querying `{node_type}`, third is for last part of the query.
3. Paste that query set into your SQL client and execute.

---
Tags: 7, entities
---


# Question
Title: Form Default Values missing on theming form
Long story short when doing some basic theming on a drupal form the default / previously saved values refuse to display within the form fields (works without theming of course). In the code exerpt below we are simply taking some for fields and sticking them into a drupal table to better organize the overall page. This is within the hook\_form\_alter() framework.

```
$form['top'] = array(
  '#theme' => 'table',
  '#header' => array(array('data' => $form['#node']->title, 'style' => 'text-align: center; font-size: 1.6em; color:#333399; margin:1em 0; background: transparent; border: 1px solid #FFF; border-bottom: 3px solid #CCCCCC;', 'colspan' => 2,),),
  '#rows' => array(array(drupal_render($form['title']), drupal_render($form['field_order_id']),),),
  '#weight' => -8,
);

```

The form correctly outputs the form items and submits correctly, all that is missing is the default / previously saved values. Nothing around the internet seems to have a workable solution either.

# Answer
See examples for developers. You should not theme form in form alter hook. Do it in hook\_theme(). In a module it looks like that:

```
function yourmodule_theme() {
  return array(
    'yourmodule_form' => array(
      'render element' => 'form',
      'file' => 'forms/yourmodule_form.inc',
    ),
  );
}

```

If you move elements around in form\_alter(), they became different fields. If `#tree` is set to `false` (default), it does not interfere with submit, but it may interfere with defaults and validation.
> 1 votes

---
Tags: forms, theming
---


# Question
Title: Create a footer menu from primary links and should be able to control what should appear
I have a menu at the top on hover it expands. I want a menu at bottom of page with same links, but i may choose what should appear here. Is there any module available for it.

# Answer
For this functionality, try Footer Sitemap

It allows you to choose which menus and/or menu items will be included in the footer sitemap.

You can then customize the template included to manipulate the markup if you need to.
> 2 votes

# Answer
You need a region in footer, of course, but I guess that's not a problem. You have 2 viable ways to display a copy of menu (without actually duplicating it's data):

1. Menu block module. It's pretty simple - you create a block displaying menu items, and it gives you broad control of what, how, how deep et cetera.
2. Views. You need to expose `{menu_links}` table to views using your own custom module. Or you can search for ready made one, I'm sure there was one in 6.x times, but I can't find it now. With menu links available as views fields, you can do pretty much everything.
> 1 votes

# Answer
Depending on what your installed Drupal theme supports in terms of regions, you should be able to position your menu at the footer of your pages. When logged in as an admin, go to the admin/structure/block section (append this to your site domain for a direct link). Here you'll be able to choose where to position your menu.

Other menu systems to consider: http://drupal.org/project/megamenu
> 0 votes

# Answer
You can achieve this with Menu Clone module.
> -1 votes

---
Tags: 7
---


# Question
Title: hide "Submitted by ADMIN on THU, xx/xx/xxxx - 00:00" in a view
I created a view listing a type of content.

This list shows the title of the content, publication information, images, link... I would like to get ride of the publishing information but I don't find the wright parameteres. Thank's to any of you who could help

# Answer
> 1 votes
You don't change that in view.

To perform this step, make sure you are logged on as an administrator, choose the content type you would like to edit by going to » Administration » Structure » Content types.

and under display settings tab, uncheck the display author and date information. Once you are done, save the content type

---
Tags: views
---


title: Deadlock issue on my server

text:
# Question
Title: Deadlock issue on my server
I am getting the following error:

> PDOException: SQLSTATE\[40001\]: Serialization failure: 1213 Deadlock found when trying to get lock; try restarting transaction: INSERT INTO {domain\_source} (nid, domain\_id) VALUES (:db\_insert\_placeholder\_0, :db\_insert\_placeholder\_1); Array(\[:db\_insert\_placeholder\_0\] =\> 101712 \[:db\_insert\_placeholder\_1\] =\> 0)

This happens `hook_node_update()`. Do you have an idea on how to solve the issue?

# Answer
After applying this Patch, these errors are reduced however not fully rectified. This patch prevents empty delete queries being run and thus reducing the load on the domain\_source table.
> 0 votes

---
Tags: domain-access
---


title: Smiley icons in the comments

text:
# Question
Title: Smiley icons in the comments
I installed the Smiley module for drupal 7. Filtered enabled smileys for plan text format.

I want to enable the smile in the comments field where the body of the comments is a plain text.

# Answer
> 2 votes
You need to rearrange text filters - make smiley filter last. If you put it before "strip HTML tags", it will add tags but they'll be stripped.

---
Tags: comments
---


# Question
Title: how to automatically retrieve selected value
is there a way to automatically retrieve selected value from dropdown or radio to form below? example in the image below, if i select radio button "randy", then the value "randy" automatically fill in the form Nama below

```
$header1 = array('Name'); // Prepare table header
$query = db_select("homo", "r"); // Select table
$query->fields("r", array("nama")); // Select fields
$result = $query->execute(); // Execute query
$rows = array();
while($data = $result->fetchObject()){ // Looping for filling the table rows
$rows[] = array( // Fill the table rows
  $data->nama,
  );
}
$form['table'] = array (
 '#type' => 'tableselect',
 '#header' => $header1,
 '#options' => $rows,
 '#multiple' => FALSE,
);
$form['f1'] = array(
 '#title' => t('Detail Anggota'),
 '#type' => 'fieldset',
);
$form['f1']['namaa'] = array(
 '#title' => t('Nama'),
 '#type' => 'textfield',
 '#required' => TRUE,
);

```

# Answer
You need to use Form API Ajax. There you can see how to use it, Examples for developers include good ajax forms too.

Just remember, to set value to display, use `$form_state['input']`, not `$form_state['values']`.
> 0 votes

---
Tags: forms
---


# Question
Title: Filtering my products on drupal commerce
I have imported 5.000 products to my drupal-commerce website.I want the user to be able to navigate fast on all of these products,so I just figured out that I need to make somehow a filter or a search that when the user chooses/selects some of the features of the product the result will be only the products with these features.How can I manage to do this on Drupal 7 and Drupal Commerce(Commerce kickstart?)

# Answer
> 1 votes
You can do it in the view.

Select a filter criteria for example "size", then click on expose filter.

This permit you create a custom search box as well clicking on "exposed filter in block" under Advanced in view.

First part of a tutorial http://www.youtube.com/watch?v=9-sKG1bplx0

# Answer
> 0 votes
I've always used Views to reach filter functionality.

But, it seems, there is a simpler solution.

See video from module desription. http://commerceguys.com/blog/commerce-module-tuesday-commerce-search-api

---
Tags: commerce, search
---


title: 2 Questions 2 Radio buttons no Loading

text:
# Question
Title: 2 Questions 2 Radio buttons no Loading
I have a website with a webform module. It has got 2 questions with 4 radio buttons each and then a break-page so when someone clicks on one of the radio buttons, it automatically takes them to the next question. However, when someone clicks on the first questions radio button it loads the whole page and then when someone clicks on the second one, then it loads again.

I tried using a ajax page module but it doesn't work I m using this jquery code at the moment

here is the form below

http://goo.gl/bUqvZ

this is the jquery form I am using

```
(function ($, Drupal, window, document, undefined) {
$(document).ready(function() {
$('.form-radio').click(function() { $('#edit-next').click(); });
});
})(jQuery, Drupal, this, this.document);

```

How do I get rid of the loading after every selection of the questions

# Answer
> 0 votes
Don't write your own jQuery. Use Form API Ajax for your callbacks.

# Answer
> 0 votes
I hope this Basic Ajax form submit example may help you.

```
/**
 * @file
 * Demo module, Basic Ajax form submit (Ajax framework).
 */

 /**
  * Implements hook_menu().
  */
function demo_menu() {
  return array(
    'demo/newsletter' => array(
      'page callback' => 'drupal_get_form',
      'page arguments' => array('demo_demo_form'),
      'access callback' => TRUE,
      'type' => MENU_CALLBACK,
    ),
  );
}

 /**
  * A simple newsletter subscribe form.
  */
function demo_demo_form($form, &$form_state) {
  return array(
    'email' => array(
      '#type' => 'textfield',
      '#title' => t('Join our Newsletter'),
      '#required' => TRUE,
      '#attributes' => array(
        'placeholder' => t('mail@example.com'),
      ),
    ),
    'submit' => array(
      '#type' => 'submit',
      '#value' => t('Subscribe'),
      '#ajax' => array(
        'callback' => 'demo_form_ajax_submit',
        'wrapper' => 'demo-demo-form',
        'method' => 'replace',
        'effect' => 'fade',
      ),
    ),
  );
}

/**
 * Ajax callback function.
 */
function demo_form_ajax_submit($form, $form_state) {
  // Dummy/dumb validation for demo purpose.
  if (!empty($form_state['input']['email'])) {
    return 'Subscribed !';
  }
  else {
    return $form;
  }
}

```

Source

---
Tags: ajax, webforms, javascript
---


# Question
Title: Get Contacts from social networking sites
I am trying to import contacts from Social networking sites to Drupal using OpenInviter. Its working fine with Web mail Providers but when i am trying to get contacts from Social networking sites it is throwing error as

* Unable to get contacts.
* No contacts could be retrieved from your account.

Any help is appreciated.

# Answer
I would use Contact Importer in conjunction with OpenInviter. It could be that you do not have an app for the specific social network to give permissions to allow access to users' data.

While I was configuring HybridAuth, there were options to allow your site to access contacts of users. This requires you acquire an API key for each social network you want to access, which means creating an app. If you're still having issues I could set up an app on the social networks you would like to access, then configure hybridauth and see if you can access the contacts through its API.
> 1 votes

---
Tags: 7
---


# Question
Title: How can I add two 'add to cart' ubercart buttons in a product page
I would like to have two 'add to cart' buttons on my ubercart drupal site. I've set up two views, but only one button will show at a time. Why is this? You can see it on https://www.thepetwiki.com/mg-testsite.com/ubercart/painting/please There should be an 'add to cart' button next to both 'BUY: $2,400'

# Answer
> 0 votes
I would recommend creating a view:block that displays the product's price and an add to cart button, you can then duplicate the view:block and have in the block admin page, add the two new view blocks to the regions you would like them displayed in.

---
Tags: ubercart
---


# Question
Title: Preserve term association when migrating nodes
Actually I can migrate nodes depending on their type, and the author comes with node import like this in d2d :

```
$this->addFieldMapping('uid', 'uid');

```

but I don't know how to do the same to keep terms attached to nodes..I believe that in Drupal6 source, terms are frequently assigned from the core system, not via the content taxonomy module that represent the Drupal7 way.

Do you think I can do that actually, or do I need to modify the source and adopt the content taxonomy way before migrating nodes or generally upgrading from Drupal 6 to Drupal 7 ?

Thanks

EDIT: my migration class code

```
class NodesPageInnovationsMigration extends DrupalNode6Migration {
/* ==============================================================================
* -- Pour limiter l'import aux nodes créés aprés la date indiquée --
*
* ==============================================================================
*/
//protected function query() {
//    $query = parent::query();
//    $query->condition('created', strtotime('28-03-2013'), '>');
//    return $query;
// }
public function __construct(array $arguments) {
    parent::__construct($arguments);
    //Le nom machine de la migration de nodes associée comme dépendances
     // $this->dependencies[] = 'D2D_RostandNodes_PageInnovations';

    //On défini la source et la cible depuis les infos de base
      $this->source = new MigrateSourceSQL($this->query(),
      $this->sourceFields,NULL, $this->sourceOptions);

// We're replacing the legacy field_published, which was a text field, with a new date field
    $this->addFieldMapping('field_publish_date', 'field_published');

    //Préservation du NID des nodes importés
     $this->addFieldMapping('field_legacy_nid', 'nid')
         ->description('We have a common field to save the D6 nid');

    /* ==============================================================================
     * -- Mappage de la taxonomie --
     * Assigned terms are represented in Drupal 6 by their vid, migrate to the new term
     * reference field, translating the tid from the legacy value.
     * ==============================================================================
     */
     //$this->addFieldMapping('field_NomduChampCible', 'VidSource')
    //La taxonomie via champs custom ou du core (D6)
   // The first param is for the D7 field name.
    // The second param is for the old site's vocab ID.
    $this->addFieldMapping('taxonomy_vocabulary_1', '1')
        // ->sourceMigration('Tags') // This is the machine name of the tags migration.
         // This tells the migration to match on the term ID instead of the default, which is the term name.
         ->arguments(array('source_type' => 'tid'));

    $this->addFieldMapping('taxonomy_vocabulary_2', '2')
        // ->sourceMigration('Tags') // This is the machine name of the tags migration.
         // This tells the migration to match on the term ID instead of the default, which is the term name.
         ->arguments(array('source_type' => 'tid'));

   //$this->addFieldMapping('field_taxo_vdl', 'field_taxo_vdl'); inutile car dans D7 taxo est un champ

    /* ==============================================================================
     * -- Mappage des champs custom CCK --
     * $this->sourceFields['NomChampSource'] = t('DescriptionChampSource');
     * ==============================================================================
     */
//   $this->sourceFields['field_fichier_joint_lycee'] = t('Joindre un fichier');
//   $this->sourceFields['field_lien_page_lycee'] = t('Liens utiles');
//   $this->sourceFields['field_video_lycee'] = t('Ajout galerie Flickr');

   $this->addFieldMapping('field_video_externe', 'field_video_externe');
   $this->addFieldMapping('field_fichier_joint_innovation', 'field_fichier_joint_innovation');
   $this->addFieldMapping('field_fiche_action_innovation', 'field_fiche_action_innovation');
   $this->addFieldMapping('field_date_evenement', 'field_date_evenement');

   //Les champs custom pour les contenus VDL
   $this->addFieldMapping('field_illus_vdl', 'field_illus_vdl');
   $this->addFieldMapping('field_video_vdl', 'field_video_vdl');
   $this->addFieldMapping('field_galerie_image_vdl', 'field_galerie_image_vdl');
   $this->addFieldMapping('field_choix_galerie_vdl', 'field_choix_galerie_vdl');
   $this->addFieldMapping('field_liens_vdl', 'field_liens_vdl');

   //Correspondance des utilisateurs
   $this->addFieldMapping('uid', 'uid');
   //$this->addFieldMapping('tnid', 'tnid'); traduction du terme

}
/* ==============================================================================
     * -- Manipulation et mise en forme des données des champs mappés --
     *
     * ==============================================================================
     */
public function prepareRow($row) {
// Always include this snippet, in case our parent class decides to ignore the row
if (parent::prepareRow($row) === FALSE) {
   return FALSE;
}
//ici le code pour formatter les data
}
}

```

# Answer
Check out all the examples for migrations in the migrate d2d handbook.

There is documentation on taxonomy term migrations and node migrations.

Put these together with the documentation for migrate.

Also, the migrate, migrate extras, and migrate d2d modules all have example modules in them, which have very useful example code. Specifically check out the example module in migrate\_d2d, it has an example of this.

There is a lot of documentation there but that is because migration is a complicated task. The more you read and the better understanding you have the easier it is and the better the result.

After you have done a couple of migrations it gets much easier.

For nodes and their taxonomies, you migrate the terms first, then the nodes. The migrate module will keep track of the mapping of the old term id to the new term id, then when it comes to the nodes it will use that mapping for the terms attached to the nodes.

This is how you map a taxonomy field:

When you register your hooks:

```
// Each migration being registered takes an array of arguments, some required
// and some optional. Start with the common arguments required by all - the
// source_connection (connection key, set up in settings.php, pointing to
// the Drupal 6 database) and source_version (major version of Drupal).
$common_arguments = array(
  'source_connection' => 'legacy', // This is the name of a connection in your settings.php file.
  'source_version' => 6, // This is the source drupal version.
);

// Other migration registration here, like users & files.

// For vocabulary migrations, source_vocabulary and destination_vocabulary are
// required arguments. Note that in Drupal 6 vocabularies did not have machine
// names, so we use the vocabulary ID to uniquely identify them.
$vocabulary_arguments = array(
  array(
    'description' => t('Migration of Tags terms from Drupal 6'), // Description for this migration
    'machine_name' => 'Tags', // Migration machine name
    'source_vocabulary' => '5',  // Source vocabulary ID
    'destination_vocabulary' => 'tags', // Destination vocab machine name.
  ),
  array(
    'description' => t('Migration of Category terms from Drupal 6'), // Description for this migration
    'machine_name' => 'Category', // Migration machine name
    'source_vocabulary' => '6',  // Source vocabulary ID
    'destination_vocabulary' => 'category', // Destination vocab machine name.
  ),
  // More migrations for other vocabs.
);

// We're using the migrate_d2d class directly for all of the above.
// You can put other common params here.
$common_vocabulary_arguments = $common_arguments + array(
  'class_name' => 'DrupalTerm6Migration',
);
foreach ($vocabulary_arguments as $arguments) {
  $arguments += $common_vocabulary_arguments;
  // Register the migrations.
  Migration::registerMigration($arguments['class_name'], $arguments['machine_name'], $arguments);
}

// Node migrations.
$node_arguments = array(
  array(
    'class_name' => 'PageMigrationClassName', //  The class name for this migration as we are extending a built in one.
    'description' => t('Migration of page nodes from Drupal 6'), // Description for this migration.
    'machine_name' => 'Page', // Machine name of this migration.
    'source_type' => 'page', // The node type in the old site.
    'destination_type' => 'page', // The node type in the new site.
    // Dependencies. This means this won't run until after the Tags & Category migrations have run.
    'dependencies' => array('Tags', 'Category'),
  ),
  // Other nnode migrations here.
);
foreach ($node_arguments as $arguments) {
  $arguments += $common_arguments;
  // Register the migrations.
  Migration::registerMigration($arguments['class_name'], $arguments['machine_name'], $arguments);
}

```

Now in your page node migration code you would do:

```
class PageMigrationClassName extends DrupalNode6Migration{
  public function __construct(array $arguments) {
    parent::__construct($arguments);

    // Note that we map migrated terms by the vocabulary ID.
    // This is for the Tags vocab.
    // The first param is for the D7 field name.
    // The second param is for the old site's vocab ID.
    // This is how it is stored on the row, eg. $row->5
    $this->addFieldMapping('field_tags', '5')
         ->sourceMigration('Tags') // This is the machine name of the tags migration.
         // This tells the migration to match on the term ID instead of the default, which is the term name.
         ->arguments(array('source_type' => 'tid'));

    // And for the category vocab.
    $this->addFieldMapping('field_category', '6')
         ->sourceMigration('Category')
         ->arguments(array('source_type' => 'tid'));
  }
}

```

If you want to map the data to data that is already in the new system and wasn't migrated with the migrate module, there is probably a bunch of ways to do it. One way is to use the migrate API methods.

You can implement prepareRow() in your node migration class and do this:

```
public function prepareRow($row) {
  // Always include this fragment at the beginning of every prepareRow()
  // implementation, so parent classes can ignore rows.
  if (parent::prepareRow($row) === FALSE) {
    return FALSE;
  }

  // The node's terms are in an array under their vocab ID.
  if (!empty($row->{5})) {
    foreach ($row->{5} as &$tid) {
      // Code here to map term IDs from old to new.
      // Set $tid to the corresponding new site tid.
      // You could call a separate mapping function to do this if you have
      // a lot of terms or complex mapping requirements or something.
    }
  }
  return TRUE;
}

```

Alternatively, you can put the new tids somewhere else on the $row, like:

```
$row->mapped_tids_tags = array(3, 7, 4, 8, 6);

```

Then for your field mapper you have:

```
$this->addFieldMapping('field_tags', 'mapped_tids_tags')

```

Instead of:

```
$this->addFieldMapping('field_tags', '5')

```
> 5 votes

---
Tags: updating, migrations
---


# Question
Title: Theme suggestions for blocks in a region which has a dash in the name
I have a Region in the theme called `header-top`. As you may notice this region has a dash in the name instead of an underscore.

This theme is a sub-theme of a master theme called `Framework`. I wanted to apply a certain template file to blocks in that region, so according to Drupal 7 Theme Hook Suggestions page I've created a template file called `block--header-top.tpl.php` and cleared the cache. After re-loading the page a few times, I inspect the HTML to see if this particular template file is being applied, but all evidence suggests that it's still using `block.tpl.php`. I've tried using `template_preprocess_block` and `dpm`-ing out the `$variables` and in there I see an array `theme_hook_suggestions` which has the following values: `array(block__header-top, block__block, block__block__21)`. I've checked the existing template files and there's no template file named `block--block.tpl.php` or `block--block--21.tpl.php`. I've even tried to swap the dash with an underscore to be `block--header_top.tpl.php` but still no luck.

Finally I've switched the region name to become `header_top` and the renamed template `block--header_top.tpl.php` suddenly starts to take effect.

I'm wondering is there a certain naming convention for regions with dashes in the name? If so what would be the ways to try and find out what exactly the template name for this region should be? I'd like to not resort to renaming the region, as that may have a knock-on effect on modules and other template files which I may miss and mess up the production website.

# Answer
Per the Theme suggestion docs you linked to the format for region-specific block templates go like this:

> An example of a region-specific template would be "block--sidebar\_first.tpl.php"

It looks like Drupal flips `_` and `-` in theme suggestions so

> block\__header-top

becomes

> block--header\_top.tpl.php

(I knew it replaced `_` with `-` but I didn't know it was the other way round too; there may be more to it than that).
> 2 votes

---
Tags: 7, theming, blocks
---


# Question
Title: Why is my Multi-Step form going back to the first page instead of moving to the third?
I've buit a multi-step (3 steps) form in form api, and going from step one to two works fine, but going from 2 to three just brings me back to step one.

```
function multi_step_menu() {
  $items = array();

  $items['multi-steps'] = array(
    'title' => 'Multi Steps',
    'description' => 'Multi Steps',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('step_one_form'),
    'access callback' => TRUE,
  );

  return $items;
}

function step_one_form($form, &$form_state) {

  // Display page 2 if $form_state['page_num'] == 2
  if (!empty($form_state['page_num']) && $form_state['page_num'] == 2) {
    return step_two_form($form, $form_state);
  }

  // Otherwise we build page 1.
  $form_state['page_num'] = 1;

  $subschoices = array(1 => t('Day'), 2 => t('Month'), 3=> t('Year'));
 $form['subscription_choice'] = array(
   '#type' => 'radios',
   '#title' => t('Subscriptions'),
   '#options' => $subschoices,
  '#description' => t('Choose your subscription type.'),
  '#required' => TRUE,
 );

  $form['next'] = array(
    '#type' => 'submit',
    '#value' => 'Purchase >>',
    '#submit' => array('step_one_next_submit'),
    '#validate' => array('step_one_next_validate'),
  );

  //  syslog(1, print_r($form, true));

  return $form;
}

function step_two_form($form, &$form_state) {

  // Display page 3 if $form_state['page_num'] == 3
  if (!empty($form_state['page_num']) && $form_state['page_num'] == 3) {
    return step_three_form($form, $form_state);
  }

  $form['description'] = array(
    '#type' => 'item',
    '#title' => t('Purchase Subscription'),
  );

  $form['clientReference'] = array(
    '#name' => 'clientReference',
    '#type' => 'hidden',
    '#value' => $account->uid,
  );

  $form['clientType'] = array(
    '#name' => 'clientType',
    '#type' => 'hidden',
    '#value' => 'individual',
  );

  $form['recurrentDebitExecutionDate'] = array(
    '#name' => 'recurrentDebitExecutionDate',
    '#type' => 'hidden',
    '#value' => date('m/d/Y'),
    '#attributes' => array(
      'id' => array('recurrentDebitExecutionDate'),
    ),
  );

  $form['recurrentDebitAmount'] = array(
    '#name' => 'recurrentDebitAmount',
    '#type' => 'hidden',
    '#value' => $recurrentDebitAmount,
    '#attributes' => array(
      'id' => array('recurrentDebitAmount'),
    ),
  );

  $form['recurrentDebitLabel'] = array(
    '#name' => 'recurrentDebitLabel',
    '#type' => 'hidden',
    '#value' => $recurrentDebitLabel,
    '#attributes' => array(
      'id' => array('recurrentDebitLabel'),
    ),
  );

  $form['name']['firstName'] = array(
    '#name' => 'firstName',
    '#type' => 'textfield',
    '#title' => t('First Name'),
    '#maxlength' => 20,
    '#size' => 21,
    '#required' => TRUE,
  );

  $form['name']['lastName'] = array(
    '#name' => 'lastName',
    '#type' => 'textfield',
    '#title' => t('Last Name'),
    '#maxlength' => 20,
    '#size' => 21,
    '#required' => TRUE,
  );

  $form['phoneNumber'] = array(
    '#name' => 'phoneNumber',
    '#type' => 'textfield',
    '#title' => t('Phone Number'),
    '#maxlength' => 13,
    '#size' => 13,
    '#required' => TRUE,
  );

  $form['address']['line1'] = array(
    '#name' => 'line1Inv',
    '#type' => 'textfield',
    '#title' => t('Address'),
    '#required' => TRUE,
  );

  $form['address']['line2'] = array(
    '#name' => 'line2Inv',
    '#type' => 'textfield',
  );

  $form['city'] = array(
    '#name' => 'cityInv',
    '#type' => 'textfield',
    '#title' => t('City'),
    '#required' => TRUE,
  );

  $form['postalCode'] = array(
    '#name' => 'postalCodeInv',
    '#type' => 'textfield',
    '#title' => t('Postal Code'),
    '#required' => TRUE,
  );

$form['countryCode'] = array(
    '#name' => 'countryCode',
    '#type' => 'textfield',
    '#title' => t('Country Code'),
    '#required' => TRUE,
  );

  $form['displayedCost'] = array(
    '#title' => t('Cost'),
    '#markup' => $recurrentDebitAmount . "</br>",
  );

  $form['back'] = array(
    '#type' => 'submit',
    '#value' => t('<< Back'),
    '#submit' => array('step_two_back'),
    '#limit_validation_errors' => array(),
  );

  $form['next'] = array(
    '#type' => 'submit',
    '#limit_validation_errors' => array(

    ),
    '#value' => 'Checkout >>',
    '#submit' => array('step_two_next'),
    '#validate' => array('step_two_validate'),
  );

  return $form;
}

function step_three_form($form, &$form_state){

  $form['slimpay'] = array(
    '#type' => 'submit',
    '#value' => t('Slimpay'),
    '#submit' => array('step_three_one_submit'),
  );

  $form['ogone'] = array(
    '#type' => 'submit',
    '#value' => t('Ogone'),
    '#submit' => array('step_three_two_submit'),
  );

  $form['back'] = array(
    '#type' => 'submit',
    '#value' => t('<< Back'),
    '#submit' => array('step_three_back'),
    '#limit_validation_errors' => array(),
  );

  return $form;
}

function step_one_validate($form, &$form_state) {

}

function step_two_validate($form, &$form_state) {

}

function step_one_next_submit($form, &$form_state{
  $form_state['page_values'][1] = $form_state['values'];

  if (!empty($form_state['page_values'][2])) {
    $form_state['values'] = $form_state['page_values'][2];
  }

  // When form rebuilds, it will look at this to figure which page to build.
  $form_state['page_num'] = 2;
  $form_state['rebuild'] = TRUE;
}

function step_two_next_submit($form, &$form_state) {
  syslog(1, $form_state['values']);
  $form_state['page_values'][2] = $form_state['values'];
syslog(1, "page_values" . print_r($form_state['page_values']));
  if (!empty($form_state['page_values'][3])) {
    $form_state['values'] = $form_state['page_values'][3];
  }

  $form_state['page_num'] = 3;
  $form_state['rebuild'] = TRUE;
}

function step_two_back($form, &$form_state) {
  $form_state['values'] = $form_state['page_values'][1];
  $form_state['page_num'] = 1;
  $form_state['rebuild'] = TRUE;
}

function step_three_back($form, &$form_state) {
  $form_state['values'] = $form_state['page_values'][2];
  $form_state['page_num'] = 2;
  $form_state['rebuild'] = TRUE;
}

function step_three_one_submit($form, &$form_state) {

  $page_one_values = $form_state['page_values'][1];
  $page_two_values = $form_state['page_values'][2];

  $form_state['redirect'] = 'node';
}

function step_three_two_submit($form, &$form_state) {

  $page_one_values = $form_state['page_values'][1];
  $page_two_values = $form_state['page_values'][2];

  $form_sate['redirect'] = 'node';//ogone
}

```

# Answer
Once you correct a few of the obvious submit handler names in that code and run it, the issue eventually boils down to checking if your $form\_state\['page\_num'\] is 2 in step\_one\_form(). When you attempt to go to step 3, the condition in step\_one\_form() fails (because page\_num is 3), so step\_two\_form() never gets called (to eventually call step\_three\_form).

A few other comments about your code:

* You should be prefixing all functions in your module with the module name. This is to avoid namespace collisions, which can sometimes be obvious to fix and other times, be very frustrating.
* With a multistep form, it may be easier to read by having one function that calls the function of each step. See this blog post for an example of a multistep form.
* instead of using the syslog PHP functions, install the devel module and use dpr(). It's more drupaly, and easier to read the output of arrays and objects with that function.
> 3 votes

# Answer
In your code you can make a fix with step\_one\_form function.

```
function step_one_form($form, &$form_state) {

 // Display page 2 if $form_state['page_num'] == 2
 if (!empty($form_state['page_num']) && $form_state['page_num'] == 2) {
   return step_two_form($form, $form_state);
 }
 if (!empty($form_state['page_num']) && $form_state['page_num'] == 3) {
   return step_three_form($form, $form_state);
 }

```
> 1 votes

---
Tags: 7, forms
---


# Question
Title: How to properly add JavaScript to drupal
I'm trying to create a module that will make use of Google Maps to display the current places indicated in the search results via markers. The problem that I'm having is that I'm getting the following error when I add the Google maps script:

```
Uncaught ReferenceError: jQuery is not defined

```

The map wouldn't work if I don't include my own version of jQuery, but the error stays there whether or not I include jQuery.

```
function gmapsnrew_block_view($delta = ''){
    $block['subject'] = 'Google Map Test';
    $block['content'] = '<div id="map-canvas"></div>';
    return $block;
}

drupal_add_css(drupal_get_path('module', 'gmapsnrew') . '/css/gmapsnrew.css');

drupal_add_js('http://maps.googleapis.com/maps/api/js?key=google_key&sensor=false&libraries=places');

drupal_add_js(drupal_get_path('module', 'gmapsnrew') . '/js/load-map.js');

```

And the `load-map.js` looks something like this:

```
(function ($) {
  Drupal.behaviors.gmapsnrew = {

    attach: function(context, settings){

      console.log(context);
      var base_lat = 51.322377;
      var base_lng = -0.1358427;

      var latlng = new google.maps.LatLng(base_lat, base_lng);
      var options = {
          zoom: 10,
          center: latlng,
          mapTypeId: google.maps.MapTypeId.ROADMAP,
          mapTypeControl: false
      };
      var map = new google.maps.Map(document.getElementById("map-canvas"), options);
    }
  }

})(jQuery);

```

Any ideas what I'm doing wrong here? Thanks in advance.

# Answer
> 3 votes
If your code sample is accurate, and you are calling drupal\_add\_js() from outside a function in a module file, then that will be the problem.

You would want to add your js from within your hook\_block\_view(). This way it loads after drupal has done all it needs to do with its js and jQuery will exist.

Also, you might not want to put your map initialisation in a behavior, because you would usually only ever want your map to load once, on page load. I don't know all the details of your setup though so I can't know exactly what is best in your case.

---
Tags: 7, javascript, google-maps
---


# Question
Title: Security issues after authenticated user has been logged out
I have a `profile information` page that is being displayed for an `authenticated users`. But after I `log-out` as that specific user,and then i click the `back button` of the browser,I could find the `anonymous user` landing on the profile information of the previously `logged-in user`.

How could I prevent such a behavior as I do have some `confidential information` on those profile information page.

Could someone please help me.

# Answer
Once page is stored in browser's cache, there is nothing you can do about it. It's responsibility of an user who logs in and views confidential information to remove it from device he was reading it on.

You could try to prevent caching (as described in this question), but all you send to browsers and proxies in that regard is just an suggestion, not an order. It's a good idea to do this, but sadly you can't be sure of it.

You could use javascript to go to another page if logged out user tries to go back to page with sensitive data.

And you can and should use Secure Pages to enforce encryption and thus prevent proxies from reading you data.

At the end of the day once user will get that data, data security is his problem.
> 3 votes

---
Tags: 6, security
---


# Question
Title: How do I check the entered quantity before the checkout phase in Drupal Commerce?
How to check product quantity before checkout ?

I want to avoid the order if a required quantity is not reached.

Nota : I use Commerce Physical Product module.

# Answer
You can use rules to change the quantity in a line item... so you could force the quantity up and output a system message. I don't know of a way to prevent them from checking out using rules.

So: Condition: Data Comparison: Line item: Product: SKU equals XX Condition: Data Comparison: Line Item: Quantity less than X Action: System message explaining why we're increasing quantity Action: Data Set Value: Set quantity to X+3

Update: this strategy might work for you.
> 0 votes

# Answer
Just created a similar rule. Product minimum quantity must be \>=100 only for selected product.

Hope this helps...
> 0 votes

---
Tags: commerce
---


# Question
Title: Hide a block depending on the value of a field?
* I have put a block in the taxonomy pages.
* I have added a new field to the vocabulary with two states: shown, hidden.
* I want that when in taxonomy term I select hidden, the block to be hidden.

So I can display or not a block depending on the categories.

I've tried with this code in the block visibility options, but it does not works:

```
global $field_show_block;
return ($field_show_block == "show");

```

Any ideas? Can it be done with Views?

Thank You

# Answer
> 1 votes
As Letharion points out you can use Panels to do this, but panels does indeed have a bit of a steep learning curve. It might be quicker to learn something like the Context Module with Context Entity Field.

To do this with context, create a new context with whatever name you like. Then in the Conditions area add the "Entity field" as a condition and select entity type as taxonomy term. Then select the field you created in your vocabulary e.g. "field\_show\_block" and uncheck the "empty field" checkbox and put in "show" into the field value. Then in Reactions select which blocks you want to show, and assign them to the relevant regions.

If you don't want to do things using a Drupal contributed module though, the following visibility code (with the core PHP filter module on) may work with a bit of tweaking to match your exact field name:

```
<?php
// assumes the user is visiting taxonomy/term/<tid>
if (arg(0) == 'taxonomy' && arg(1) == 'term' && is_numeric(arg(2))) {
  $term = taxonomy_term_load(arg(2));
  if (isset($term->field_show_block[LANGUAGE_NONE][0]['value'])) {
    return $term->field_show_block[LANGUAGE_NONE][0]['value'] == "show";
  }
}
return FALSE;
?>

```

The reason why using the PHP filter for block visibility is bad practice is because, when the PHP code is written incorrectly, it's a little awkward to fix it (e.g. clearing database columns). It's also a potential security risk, allowing database stored PHP code to be executed unchecked.

---
Tags: entities, taxonomy-terms
---


title: How to rename GCC paths

text:
# Question
Title: How to rename GCC paths
I'm using Groups, Communities and Co (7.x-1.0-beta2) and I'd like to rename the paths that are used. As currently it uses the format:

```
#node#/gcc
#node#/gcc/members
#node#/gcc/role
#node#/gcc/permissions

```

and I'd prefer it to be:

```
#node#/group
#node#/group/members
#node#/group/role
#node#/group/permissions

```

Can this be done without going into the module code and renaming the variables directly?

# Answer
There are 2 parts to this question:

1. How to make Drupal accept second paths? Go to http://example.com/admin/config/search/path and set aliases for them. You can use Pathauto to automate this process, or try one of the modules that allows wildcards in aliases.
2. How to make Drupal generate proper paths? Well, if above will not assure this, use Global Redirect \- it'll make sure only aliases are visible to your users.
> 2 votes

---
Tags: 7
---


# Question
Title: how to disable a class in migrate module
I have already deleted a migrate class in the .inc file and also deleted it in the .install file but i still get an error saying:

```
Class ForumTermMigration no longer exists
Class ForumUserMigration no longer exists

```

whenever i access the migrate UI in drupal site.

how to fix this?

```
<?php

/**
 * @file
 * Set up the move2drupal module module.
 */

function move2drupal_enable() {
  //Migration::registerMigration('ForumTermMigration');
  //Migration::registerMigration('ForumUserMigration');
  Migration::registerMigration('ForumNodeMigration');
  Migration::registerMigration('ForumCommentMigration');
  }

function move2drupal_uninstall() {
  //
}

function move2drupal_disable() {
  //Migration::deregisterMigration('ForumTermMigration');
  //Migration::deregisterMigration('ForumUserMigration');
  Migration::deregisterMigration('ForumNodeMigration');
  Migration::deregisterMigration('ForumCommentMigration');
}

```

the above is my .install file. see ive commented the class i deleted in the .inc file.

I have also tried clearing the cache. uninstalling the module and reinstalling it again.

# Answer
> 4 votes
I'm currently using Drupal 7.22.

For my migration class, in my migrate\_mypages.install file I have:

```
function migrate_mypages_enable() {
  Migration::registerMigration('MyPagesMigration');
}

function migrate_mypages_disable() {
  Migration::deregisterMigration('MyPages');
}

```

I haven't looked into the actual Migrate module, but it seems that when registering a migration in code, you have to use the full class name, whereas when de-registering the migration in code, you use only the name of your migration (machine-name).

If you are stuck with old classes, you can either add the de-register lines back in, and enable/disable your module, or, manually clear the class lines out of the table "migrate\_status" in your database (as per Neograph734's comment).

As well, if you use drush, there is also:

```
drush migrate-deregister --orphans

```

# Answer
> 1 votes
You can use Drush for achieving this: Use `drush migrate-deregister --orphans`.

---
Tags: migrations
---


# Question
Title: project/configuration sync from shell (not from ./admin)
With project/configuration (core 7.22 and configuration 7.x-2.0-alpha2), we can sync a new database to the exported .inc files via the admin gui, but need to be able to do it from drush.

Specifically, we trying to get to where we can run drush site-install, and then drush sync config, to get content types and other meta-data built, from the project/configuration exported .inc files.

It looks like the heavy lifting is implemented in configuration.module, function configuration\_import\_directory. Do we still have to roll our own, to be able to invoke this from the shell?

# Answer
> 0 votes
drush csyn does the job.

we're putting the config files in a non-default location, so need to specify the path: drush csyn --source=/path/to/config

---
Tags: drush, configuration
---


# Question
Title: How can I edit the string "Send this user a private message" in Privatemsg
Is it possible in the Privatemsg module (7.x-1.3) to edit the string "Send this user a private message" to something else without directly editing the modules code?

# Answer
> 3 votes
Have you tried String Overrides module? Here is a quote about it (from the module's project page):

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

---
Tags: privatemsg
---


title: Field translation works randomly

text:
# Question
Title: Field translation works randomly
I have a 3 language website and translated bunch of field labels, the thing is that it works just for some of them not all of them. I created the forms with Entity form module and even when I check the translation for other languages it's there, it just doesn't show the proper translation and keep showing the default language instead.

Any ideas what may have caused it?

# Answer
> 2 votes
The module used for translating fields (title, help text, description, allowed values) is i18n\_field.

Internationalization 1.8 shipped with a broken i18n\_field module, so in many cases nothing would get translated.

The first issue that fixed most of the failures was \[7.x-1.8 regression\] Field translation fails in numerous situations It has now been committed and is a part of the latest -dev release.

Contrib field types such as commerce\_price might need the following patch: Extend support for contrib field types

With those patches applied I had no problem with translating any part of a field. For translating allowed values (radio or select fields), my process was this: 1) Go to manage fields, click edit next to my list(text) field. 2) Click the Translate tab on the next page. 3) In the table, find my language and click "translate". 4) I can translate the values under the "Field settings" vertical tab.

Also keep in mind that when showing one of those values on a rendered entity, you need to use the "Default translated" formatter (set under "Manage Display").

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


# Question
Title: What is the CCK module? Is it a core module in drupal 7 or do I have to install it?
When I go to download the CCK module I see that it is available for Drupal in the recommended release. I want to know why it is not available for Drupal 7 or whether I can use the development release.

# Answer
> 2 votes
Most of the CCK code is part of Drupal 7. Actually, the code in Drupal 7 is quite different from the code used from the CCK module in Drupal 6. That is the reason why there is a Drupal 7 version of CCK; the other reason is that not all the code that is part of the CCK module was ported to Drupal 7 core.
In short, you need CCK for Drupal 7 to upgrade a Drupal 6 site using CCK to Drupal 7.

As for using the Drupal 7 development snapshot, the usage statistics say there are 36007 sites using CCK for Drupal 7 out of 222100 sites using CCK, while 3081 sites are using the Drupal 5 version.

---
Tags: entities
---


title: Override contrib module's theme

text:
# Question
Title: Override contrib module's theme
I've been turning the internet upside down trying to find out how to simply override a contrib module's `theme()` file. Although I have find many ways that *should* work, no result pops up and I can't really troubleshoot why.

To be more specific, I want to override the output of the file `(/sites/all/modules/contrib/commerce/modules/cart/theme/commerce-cart-block.tpl.php)` through `theme('commerce_cart_block')`.

Now, I've tried many things. I have tried something called *suggestions* trying trying to make a file named `block--commerce--commerce_cart_block.tpl.php` in my theme directory plus several other varies of names. I've also tried setting new path through `custom_checkout_theme_registry_alter`'s passed array. But now changes are visible, with or without clearing the cache each attempt.

I'm clearly missing something since this should in my eyes be both easy to do and needed to be editable.

So the question in short; How can I with as good practice as possible override the theme file of a contrib module and use it's passed variables?

# Answer
> 1 votes
Copy `commerce-cart-block.tpl.php` file to your theme and edit that copy. Remember to clear your cache before you reload the page. That's all. Don't rename. Don't play with suggestions.

# Answer
> 1 votes
Use theme developer.
Theme Developer relies on the Devel module as a dependency. Once enabled, you may click on any part of the page and a sexy popup display shows which theme function/template outputted the HTML, and what other files could have done so. Armed with this info, a themer may quickly and accurately override the presentation. Further, all the variables passed into the template/function are presented for review.
With devel\_themer you can see which template, process and preprocess are currently used for all different regions / blocks / fields etc and in your case, which candidate template files and functions can be used.
Only caution is to only activate the module when needed and disable it afterwards because it injects markers into the DOM, which can break the lay-out.

---
Tags: 7, commerce, theming
---


# Question
Title: Problem configuring the MailChimp module
I am having an issue installing the MailChimp module. I have installed the module and the extra library under `/sites/all/libraries/mailchimp/MCAPI.class.php`. I have copy and pasted my API key into the form on `admin/config/services/mailchimp`. There are no errors coming up in the apache log. The module is not functional and my lists are not syncing!

In the `MCAPI.class.php` Readme file says this:

> 2) Try running mcapi\_lists.php from the command line. Something like this:
>
> ```
> `# php -f mcapi_lists.php`
>
> ```

But that command is not recognized.

# Answer
Turns out mailchimp was working fine. The confusion arose in that the mailchimp api doesnt populate the `Lists and Users` tab on my Drupal installation from mailchimp. Instead it pushes Druapl's mailchimp lists to sync with mailchimp. The `refresh lists from mailchimp` title can be quite deceiving.
> 0 votes

---
Tags: emails
---


# Question
Title: How to add a new calculated field by using `hook_views_query_alter`?
I have three node types that I have created relations between using the Relation module. Seaon --\> Player --\> Week

The player node has a numeric field called cost. The relationship between the player and the week has a numeric field called score.

The following is a views query (with some alias changes to make it a tad more intelligible) that I use to summarise data per season. The view works fine but I need to add a calculated field that takes the sum of the weekly scores and divides it by the player cost.

```
SELECT  PLAYER.title AS PLAYER_title
        ,PLAYER.nid AS PLAYER_nid
        ,PLAYER_COST.field_cost_value AS PLAYER_COST_field_cost_value
        ,MIN(PLAYER.nid) AS PLAYER_nid_1
        ,'node' AS field_data_field_cost_node_entity_type
        ,MIN(PLAYER2WEEK.rid) AS PLAYER2WEEK_rid
        ,'relation' AS field_data_field_score_relation_entity_type
        ,SUM(PLAYER2WEEK__field_data_field_score.field_score_value) AS PLAYER2WEEK__field_data_field_score_field_score_value
FROM    {node} SEASON
INNER JOIN
        {field_data_endpoints} FDE
ON      node.nid = FDE.endpoints_entity_id
AND     (FDE.bundle = 'player_in_season'
AND     FDE.endpoints_entity_type = 'node'
AND     FDE.endpoints_r_index = '1')
INNER JOIN
        {field_data_endpoints} FDE2
ON      FDE.entity_id = FDE2.entity_id
AND     (FDE2.endpoints_entity_type = 'node'
AND     FDE2.endpoints_r_index !=  FDE.endpoints_r_index
AND     1 = '1')
INNER JOIN
        {node} PLAYER
ON      FDE2.endpoints_entity_id = PLAYER.nid
AND     FDE2.endpoints_entity_type = 'node'
LEFT JOIN
        {field_data_endpoints} PLAYER_FDE
ON      PLAYER.nid = PLAYER_FDE.endpoints_entity_id
AND     (PLAYER_FDE.bundle = 'has_weekly_score'
AND     PLAYER_FDE.endpoints_entity_type = 'node'
AND     PLAYER_FDE.endpoints_r_index = '0')
LEFT JOIN
        {relation} PLAYER2WEEK
ON      PLAYER_FDE.entity_id = PLAYER2WEEK.rid
LEFT JOIN
        {field_data_field_cost} PLAYER_COST
ON      PLAYER.nid = PLAYER_COST.entity_id
AND     (PLAYER_COST.entity_type = 'node'
AND     PLAYER_COST.deleted = '0')
LEFT JOIN
        {field_data_field_score} PLAYER2WEEK__field_data_field_score
ON      PLAYER2WEEK.rid = PLAYER2WEEK__field_data_field_score.entity_id
AND     (PLAYER2WEEK__field_data_field_score.entity_type = 'relation'
AND     PLAYER2WEEK__field_data_field_score.deleted = '0')
WHERE   (( (node.nid = '3' ) )
AND     (( (node.type IN  ('SEASON')) AND (node.status = '1') )))

```

From all the reasearch I've done, it looks like the correct option is to use `hook_views_query_alter()` to add the new field. This is where I lose it, I have no idea how to write the code to build the new field. Essentialy, based on the query above the field needs to be

```
SUM(PLAYER2WEEK__field_data_field_score.field_score_value) / PLAYER_COST.field_cost_value AS new_field

```

I just need some help in getting strated on the code in my custom module

This answer seems to meet my requirements conceptually, I am just lost on how to construct the function.

# Answer
Turns out that I didn't need the hook at all. I was able to achieve the result by using a Math Expression within the views module
> 0 votes

---
Tags: entities, views
---


# Question
Title: Overriding the Blog username breadcrumb in the native Blog module
I want to disable the blog username in the breadcrumb which reads: Home \> Blogs \> John's blog \> Blog post

I have found the function in the core Blog module:

```
/**
 * Implements hook_view().
 */
function blog_view($node, $view_mode) {
  if ($view_mode == 'full' && node_is_page($node)) {
    // Breadcrumb navigation.  l() escapes title, so we should not escape !name.
    drupal_set_breadcrumb(array(l(t('Home'), NULL), l(t('Blogs'), 'blog'), l(t("!name's blog", array('!name' => format_username($node))), 'blog/' . $node->uid)));

  }
  return $node;
}

```

How should I best override this function in my theme?

# Answer
A node preprocess function in your template.php file would probably do the trick:

```
function MYTHEME_preprocess_node(&$vars) {
  if ($vars['node']->type == 'blog' && $vars['view_mode'] == 'full') {
    $bc = function_to_get_breadcrumb();
    drupal_set_breadcrumb($bc);
  }
}

```

This should happen early on enough in the page build process for the changes to make their way through to page.tpl.php. You could also look at doing this in `hook_node_view()` in a custom module if you'd prefer.
> 2 votes

# Answer
It is always advised one should **never hack core**, you could use Custom breadcrumbs module to do it.

> Allows administrators to set up parametrized breadcrumb trails for any node type. This allows CCK-style node types to have "Home \> User Blog \> 2005 \> January" style breadcrumbs on the node view page itself, synchronizing cleanly with custom views or pathauto aliases. Breadcrumb visibility can be customized via a php snippet.
> 1 votes

# Answer
Just edit the "modules\blog\blog.module" file, and look for the function where get the breadcrumbs array:

```
/**
 * Implements hook_view().
 */
function blog_view($node, $view_mode) {
  if ($view_mode == 'full' && node_is_page($node)) {
    // Breadcrumb navigation.  l() escapes title, so we should not escape !name.
    drupal_set_breadcrumb(array(l(t('Home'), NULL), l(t('Blogs'), 'blog')));
  }
  return $node;
}

```
> -1 votes

---
Tags: 7, theming
---


# Question
Title: Facebook Oauth and sending messages to facebook users
I have Facebook OAuth and Facebook Connect installed on a site. We need to be able to periodically send a message to one of our member's Facebook inbox who logged in with the Facebook Connect. I've looked all over, and haven't had much luck.

Can anyone point me in the right direction?

# Answer
> 1 votes
When a user registers or connects with his/her Facebook account, your web application receives that person's Facebook username which you can then store in a field.

On Facebook, you can receive external messages at username@facebook.com.

Now all that's left to for you to do is set up Rules module (maybe Facebook Rules module can help) so that if a user has connected his account on your website with his Facebook account an email is sent to username@facebook.com.

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


title: How should I structure my products

text:
# Question
Title: How should I structure my products
I have a computer product that fits many types of computers. The product has a brand, and more than one computer model can use the same product. I want to let users search by product, or click through by brand, or click through by product.

I'm having trouble figuring out how to set this up with Drupal Commerce. I read up and down on the site, but can't seem to get it.

One brand to many products. One product to many computer types. One computer type to many products.

Thanks for any help.

# Answer
> 1 votes
Brands are clearly taxonomies. The other two are two product types. With the help of Commerce Search API you can easily have facets on brands, as well as powerful search.

---
Tags: 7, commerce
---


title: Rss Feed Page Customization?

text:
# Question
Title: Rss Feed Page Customization?
I added a views adn feed type display for news. I want to customize the rss page. Currently it displaying like this :

```
<channel>
    <title> </title>
    <link> </link>
    <description></description>
    <language> </language>
          <item>
    <title> </title>
    <link> </link>
    <description> </description>
     <pubDate> </pubDate>
 <dc:creator> </dc:creator>
 <guid isPermaLink="false"> </guid>
  </item>
</channel>
</rss>

```

When i check it in firebug it includes in \<pre\> tag. But i want to customize it by css how to do that? How to remove \<pre\> tag?

# Answer
> 2 votes
There's a few issues confused into here based on the original question. I'll try to take these one at a time:

## 1 Is RSS the same as HTML?

No, these are different markup languages. RSS is a dialect of XML designed for syndicating content from podcasts, blogs, etc, etc. HTML is a web page specific markup format. In your question you mentioned that firebug is showing a `<pre>` tag in RSS feed, but this is impossible because `<pre>` is HTML only, and will never appear as RSS.

## 2 How can I style an RSS feed?

Typically, you don't need (or want) to do this. RSS Readers typically apply formatting to your RSS content, and if you change the formatting this could get confusing and ugly for your end users. Just as there are many browsers for HTML, there are many RSS REaders for RSS including iTunes, online services, Mozilla Thunderbird and hundreds of others. So, I recommend **NOT** styling your RSS feed.

However, if you need to style an RSS feed you can do using regular CSS by adding this tag to beginning of your RSS feed:

```
<?xml-stylesheet type="text/css" href="http://example.com/rss.css" ?>

```

Then you would need to create a css file called rss.css in the appropriate place on your server. Here's a great article that goes more in depth on this: http://www.petefreitag.com/item/208.cfm

## 3 How do I get Drupal to modify my RSS feed to include CSS?

This is really a great question, and a lot of people struggle with this. What makes this hard is that in Drupal 6 and 7 only HTML can be "themed", so many of the normal hooks that work on nodes which appear as HTML do not work on RSS feeds. What's also really anooying is that Drupal will escape all your HTML markup and put it inside your RSS feed, making your RSS feed nearly unreadable.

If it doesn't exist already, create a new folder called `template` inside your theme folder. Add a new file inside that folder called `views-view-rss.tpl.php`. This file will affect all your RSS feeds. Add this code inside `views-view-rss.tpl.php`:

```
<?php
/**
 * @file
 * Default template for feed displays that use the RSS style.
 *
 * @ingroup views_templates
 */
?>
<?php print "<?xml"; ?> version="1.0" encoding="utf-8" <?php print "?>"; ?>
<?php print "<?xml"; ?> type="text/css" href="http://example.com/rss.css" <?php print "?>"; ?>
<rss version="2.0" xml:base="<?php print $link; ?>"<?php print $namespaces; ?>>
  <channel>
    <title><?php print $title; ?></title>
    <link><?php print $link; ?></link>
    <description><?php print $node->body['und'][0]['value']?></description>
    <language><?php print $langcode; ?></language>
    <?php print $channel_elements; ?>
    <?php print $items; ?>
  </channel>
</rss>

```

For more details on this: https://drupal.org/node/1884558

## 4 How do I remove a specific tag from my RSS feed?

It depends on where the tag is appearing in your view. I assume it's showing up inside `<item>` tag somewhere. In the file you created earlier, change:

```
    <?php print $items; ?>

```

to:

```
    <?php print str_ireplace(array('<pre>','</pre>'), '', $items); ?>

```

Make sure to clear the cache.

---
Tags: 7, views, feeds
---


# Question
Title: How do I allow facets on my full content display page?
I have installed Kickstart Commerce 2. I have been able to allow facet searches on my collection pages, by simply adding collection/\* under the "Show block on specific pages" section of the blocks that I want to have the facet search block appear on. It works great, except they are not appearing on the full content display pages. The URL path for my product's content type shows as "examplesite.com/lightfixtures/", but adding "lightfixtures/\*" under the "Show block on specific pages" didn't make the block appear on my "lightfixtures" pages.

Currently, a user will see several products displayed in a teaser view. The user clicks on the product they want more information on and are brought to a full content display page of that one product. As this page contains no search facets, the user has to click their browser's back button in order to search for something else.

How do I allow facets on my full content display page?

Thank you to anyone they can offer some direction in this please.

# Answer
So I've decided this does not need to be done. When a user gets to the product page (however they land there), they simply click the next level of the breadcrumb link to get to that parent group.

Here are some examples of how this is shown is various e-commerce sites:

1. Macy's product page (no facets showing): http://www1.macys.com/shop/product/louis-raphael-pants-hidden-extention-pleated-pants?ID=796776&CategoryID=89#fn=sp%3D1%26spc%3D546%26ruleId%3D60%26slotId%3Drec%281%29
2. Then you click on "Pants" on the breadcrumb link and you see the facets: http://www1.macys.com/shop/mens-clothing/mens-pants?id=89

I hope that helps others who may have this question.

Best,

Tom
> 0 votes

---
Tags: blocks, commerce, search
---


# Question
Title: Restricted access url for an image uploaded to private filesystem
I have a custom content type with an image and a file field, both of which are uploaded to the private file system.

How do I create a public url to the image that will check for user permissions so that anonymous users are prevented from being able to browse to the image?

This is the code I tried first:

```
$url = file_create_url($node->field_my_private_image[$node->language][0]['uri']);

```

It generates a url to `system/files/` but that url is visible to anonymous users and it isn't being restricted by user permissions.

I saw a security patch for drupal 7.13, but it was supposedly fixed and I'm using drupal 7.22.

Is there a built-in way to do this or do I need to implement some functions in my module to respond to special urls to access these files which will check permissions and then stream the file back to the browser?

# Answer
You want to implement hook\_file\_download in Drupal 7.

> Control access to private file downloads and specify HTTP headers.
>
> This hook allows modules enforce permissions on file downloads when the private file download method is selected. Modules can also provide headers to specify information like the file's name or MIME type.

A small example:

```
function mymodule_file_download($uri) {
  global $user;

  // Does the user have access based on some criteria ?
  if (!user_access('ACCESS PAY-PER-DOWNLOAD-CONTENT', $user)) {
    return -1;
  }

  // Does this module own the file given by the $uri ?
  if (db_query('
          SELECT fu.module
          FROM {file_usage} fu
          WHERE fu.module = :module_name AND fu.uri = :uri',
          array(':module_name' => 'mymodule',
                ':uri' => $uri)->rowCount() < 1) {
    return NULL;
  }

  // If the above conditions fallthru then populate HTTP header arrays
  // for content download; If you need to grab the file object and work on
  // it -- say output CSV from the data, you can grab it as follows ...
  $files = file_load_multiple(array(), array('uri' => $uri));
  // If empty, $file will be false, otherwise will contain the required file.
  $file = reset($files);

  return array('Content-Type' => file_get_mimetype($uri));
}

```
> 1 votes

# Answer
From what I understand of the goals, personally I think this could be easily handled through `hook_menu` and defining permissions there. (API reference)

In a custom module you can setup the following:

```
function mymodule_menu(){
    $items['privatefiles'] = array(
        'title' = 'Private File Page',
        'page callback' = 'mymodule_list_private_files',
        ...
        'access arguments' = array('access my private files'),
    );
}

function mymodule_list_private_files() {
    //the logic in this function should
    //return the files you want the user to see.

    return $files;
}

```

What's happening here is basically we are providing a link that can only be accessed given the access rules in the access arguments. Only a person who has an account with those permissions will see this page and everyone else will get access denied.

The logic in the page call back retrieves a list of files from the database and renders them as you need.

This could get as complicated as you wanted to make it. You could even, for example, provide a dynamic link in the $item menu name where '%' would equal a username. With that you could even show files intended for that one person while another would see a completely different group of files (in the case they are purchasing images or something).

If you already have a link where the files are showing up publicly and you simply want to make those private, then you can use hook\_menu to change the permissions just for that page and avoid writing logic altogether to retrieve and display files.

I'm not sure how comfortable or familiar you are with module development or hook\_menu so I left the example a bit abstract. Please let me know if I can clarify anything.
> 0 votes

---
Tags: 7, files
---


# Question
Title: Payment Method displays after Page Refresh
I am using uc\_hotel booking module with Ubercart. When I add a hotel to cart and checkout it shows `No Payment Required` in `Payment Method`.

After Refreshing the Page it shows the credit card in payment method.

Why not it displaying the credit card option at first time when I click on `Checkout`.

# Answer
Solved by unchecking `Free order` from `Payment Method`.
> 0 votes

---
Tags: 7, ubercart
---


# Question
Title: How to 'SELECT FROM {entity_bundle} WHERE field_A + field_B <= given_number_X' with EntityFieldQuery
```
$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'node')
  ->entityCondition('bundle', 'MYCONTENTTYPE')

// Now say for instance I would like to grab the value of
// field_A and field_B, sum them up ( or subtract | divide | multiply them ).
// Then compare the result of that ( is greater than, equals to, smaller than )
// with a given number X. Is it possible with EntityFieldQuery?

$query_result = $query->execute();

```

I know I could do that by looping through the query result. Nontheless, if EntityFieldQuery allows me to do that at query time, I would like to know how.

# Answer
I dont believe you can do this with the core methods provided by the EFQ api.

But, you may always extend the default EFQ class with a version of your own. Or, you may implement a function such as hook\_entity\_query\_alter() or the addTag() method of EFQ.

Using `addTag` for instance on the EFQ you could then also implement hook\_query\_TAG\_alter() and alter the `SelectQuery` that is ultimately called from the original EFQ and alter the base query to include your additional (non-standard) logic.

This could look like this short example, we additionally use the SelectQuery::where() method:

```
// Within some function of yours, you execute your query; giving it a Tag.
$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'node')
  ->entityCondition('bundle', 'MYCONTENTTYPE')
  // Must call the method fieldCondition on field_A and field_B so
  // they get included in the SQL INNER JOIN statement.
  ->fieldCondition('field_A')
  ->fieldCondition('field_B')
  ->addTag('DoFunkyFieldLogic');
$query_result = $query->execute();

// ... elsewhere in your custom module ...

// Implements hook_query_TAG_alter
function mymodule_query_DoFunkyFieldLogic_alter(QueryAlterableInterface $query) {
  if ($query->hasTag('DoFunkyFieldLogic')) {
    // You will likely need to install Devel and call dpm($query) here.
    // Or else you wont know what the field names are in the raw SQL ...
    // you might be able to cheat and use full database table names and
    // column names, eg:
    //dpm($query);
    $query->where("field_data_field_A1.field_A_value + field_data_field_B2.field_B_value <= :my_quantity", array(':my_quantity' => variable_get('my_quantity', 5));
  }
}

```

There may be cleaner ways to do this -- but this approach is relatively straight forward. This code is untested; but should work.
> 4 votes

---
Tags: 7, database
---


# Question
Title: how to show breadcrumbs only on subpage?
How can I show breadcrumbs only when the depth level is more than 2.

i.e.:

1. home \> page \> subpage =\> show breadcrumb
2. home \> page =\> hide breadcrumb

Additionally I would like to hide 'home' also (and always), but this has less priority in my question.

Thanks for your explanation!

Regards, Hans

# Answer
If you are using Drupal 7, then you can use:

> Path breadcrumbs module helps you to create breadcrumbs for any page with any selection rules and load any entity from the URL!

> This is a plugin module for the context module. It takes the request URI part of the URL of the current page (for example /our-company/our-team/steve) and uses this path to build the breadcrumbs.
> 4 votes

# Answer
Your best bet is to use the Custom Breadcrumbs module:

> Allows administrators to set up parametrized breadcrumb trails for any node type. This allows CCK-style node types to have `Home > User Blog >
>  2005 > January` style breadcrumbs on the node view page itself, synchronizing cleanly with custom views or pathauto aliases. Breadcrumb visibility can be customized via a php snippet.
> -1 votes

---
Tags: 7, breadcrumbs
---


# Question
Title: Drupal installed in the web root but not at the base of the domain name
If I was to have my site in the web root, for example /var/www/ but the path to my site is http://example.com/drupal, how do I configure the base path etc.

If I set my base path to http://example.com/drupal it doesn't seem to work unless the site is also in a subdirectory (ie. /var/www/drupal/).

I know I can easily just move the site to /var/www/drupal/, but I'm curious to know if it is possible to do it at /var/www/ with just drupal config.

# Answer
It it impossible, unless you count `.htaccess` (or similar config file for your webserver) as Drupal config too. If you do, in Drupal UI change base URL to http://example.com/drupal and use `mod_rewrite` to remove "drupal" from URI before further processing.

Note that this will not disable direct access. Of course you can block any calls without "drupal" prefix, but it would mean nothing except Drupal can work there. So if your goal is anything more than marking it's Drupal in your URLs, it's not a way to go.

Note: your mileage may vary depending on web server used.
> 2 votes

---
Tags: uri
---


title: How to hide User Id's in Privatemsg

text:
# Question
Title: How to hide User Id's in Privatemsg
Currently with the Privatemsg (v7.x-1.3) module it shows the user ids when sending a new message and I'd like it to show the user names instead. Firstly is there any problem with doing this?

Secondly the 'Send this user a private message' link is formatted as:

```
 /messages/new/3?destination=user/3

```

and if I change it to:

```
 /messages/new/user_name

```

the 'To' field on the write new message page does not contain the username. Is there a setting or module that would allow this.

# Answer
I don't think there's an easy way to replace the user IDs with usernames, but you can easily add the usernames using the Realname integration (you have to set up the Realname module as well though).

My Privatemsg send page looks like this:

I did this by enabling Realname and following the instructions here. You will need the dev version as well; the 1.3 release has broken Realname AJAX.
> 1 votes

---
Tags: privatemsg
---


# Question
Title: Why can't i get simple form theming to work?
I've got this implementation of hook\_theme in a theme :

```
function uncoated_theme($existing, $type, $theme, $path) {

  return array(
    'uncoated_user_register_form' => array(
      'render element' => 'element',
    ),
  );

}

```

Furthermore, I've got the following function:

```
function uncoated_form_user_register_form_alter(&$form, &$form_state, $form_id) {
  $form['#theme'] = array('uncoated_user_register_form');
}

function theme_uncoated_user_register_form($element) {
  return '<div class="test"></div>";
}

```

However, the function `theme_uncoated_user_register_form` is never invoked. I've also tried to replace `$form['#theme']` with `$form['#theme_wrapper']` to see if I could at least wrap the form in additional markup; but that does not work either.

I can't really see what I'm doing wrong? Drupal seems to be totally ignoring the theme function I'm trying to run the form through.

# Answer
> 0 votes
I think it's the simplest of things...

`$form['#theme']` needs to be a string, not an array, so change

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

```

to

```
$form['#theme'] = 'uncoated_user_register_form';

```

# Answer
> -1 votes
`uncoated_form_user_register_form_alter` -\> `hook_form_user_register_form_alter` doesn't seem right. It looks like you're trying to alter the registration form, which is `user_register_form` and not `form_user_register_form`. I'm just guessing but it looks like it should be `uncoated_user_register_form_alter`. So it's not really a case of Drupal ignoring your theming function, you actually wrote a wrong name for the alter function and that never gets called, hence the theme never gets applied. Also specific form alters don't take parameter `$form_id`. If you're having trouble with form id's and naming correct hooks, try using the normal `hook_form_alter` which takes the `$form_id` as the 3rd parameter, and check it against `user_register_form` to apply the theme.

---
Tags: theming, forms
---


title: Is there any module for booking?

text:
# Question
Title: Is there any module for booking?
A module for `Booking` type system which allow me to add Different Hotels, Apartments etc. in Different countries. I want to show Availability calender also.

I tried uc\_hotel and AG Reservation but both don't meet my requirements.

1. I need price calculation based on room selected. If a user select only two rooms of an apartment and the apartment has 4 rooms, then the price is based on the selected room; filters are based on availability.
2. I need search functionality based on location, bedroom, people capacity, accommodation type, offers; the price is based on the extra facility provided.

# Answer
Then Drupal Rooms is the only option for you and it match your requirement for room calculation, it will update the pricing depend upon the rooms selected . Rooms is a booking and room management solution for hotels, vacation rentals and B&Bs.

> It allows an accommodation owner to:
>
> * Create rooms and assign availability (or on hold states) via a calendar.
> * Manage pricing for rooms using calendars that allow to set pricing for entire seasons or just change it for specific dates.
> * Define optional add-ons for rooms.
> * Charge either per-night or per-person.
> * Handle children discounts.
> * Create bookings and keep customer records.
> * Make rooms available for booking with a availability search functionality and/or calendar - handling both immediate bookings and bookings following owner confirmation.
> * Search by Room Type.
> * Full integration with Commerce to manage payments, a range of different payment gateways, and a host of other e-commerce features.
> * Accept full or partial payments (deposits) using Commerce features.
> 4 votes

---
Tags: 7, bookings
---