# Question
Title: Managed File Field and file_usage_add() - what should I attach the file to?
I'm creating a module which uses the Form API and integrates with the Mantis bugtracker system. I have included a managed file field on the form and am at the stage of handling the form submission. The Form API documentation mentions that you must make a call to file\_usage\_add:

```
Without the call to file_usage_add, file_managed_file_validate produces an error upon saving the form, saying that the uploaded file may not be referenced.

```

Here is the signature for file\_usage\_add():

```
file_usage_add(stdClass $file, $module, $type, $id, $count = 1)

```

And the explanation of the parameters:

```
$file: A file object.

$module: The name of the module using the file.

$type: The type of the object that contains the referenced file.

$id: The unique, numeric ID of the object containing the referenced file.

$count: (optional) The number of references to add to the object. Defaults to 1.

```

The problem I have is that my module doesn't create any nodes to attach the file to. I just want to store the file in the filesystem and then send it off to Mantis.

Any suggestions on what I can enter for the $type and $id parameters?

# Answer
I attached the file to user 1 and can't see any adverse effects as yet:

```
file_usage_add($file, 'mantis', 'user', 1);

```

I also OMITTED the following line from my submit function:

```
$file->status = FILE_STATUS_PERMANENT;

```

This means that the file will be deleted after 6 hours when cron runs.

If anyone has a better solution then I'll be happy to mark as answer.
> 4 votes

---
Tags: 7, forms, files
---


# Question
Title: How to use the uc_csv module for getting reports
I am using the ubercart module for purchasing products. I want to export the order records/history as csv file and view it in spreadsheet. So I searched and got the uc\_csv module. I have installed the module for Drupal 7. When I click the `csv export` link from store administration option it shows:

> "THERE ARE CURRENTLY NO CONFIGURED EXPORT REPORTS".

How can I configure this option? Please suggest some ideas.

# Answer
> 0 votes
you can create export reports by clicking the "CSV Export" menu item located under "Store administration" in the Drupal administrative menu system.

You can create any number of reports to export certain criteria. More granular criteria can be programmed later if there is demand for such a feature. Please provide feedback if this is the case.

---
Tags: 7, ubercart, importing-exporting
---


# Question
Title: How to build an install profile progmatically
I need to create an install profile from an existing site. My question is what to do with the site configurations? The site is pretty complex, so putting them manually in the profile is out of the question.

My current best idea is to create features from the site, and revert them during the install, but it has a big drawback: If I have to modify something on a site that is installed this way, the state of the features will be "overridden", so they need to be ignored or recreated.

I've checked out some possible solutions, but none of them seemed to be perfect.

* Ftools can "detach" features, but only for a few types of settings.
* Profiler seems to be exactly what I need, but it also lacks of support for most of the settings.
* With Features Override I can override the install profile's own features, but is it a good practice? I'm afraid it could cause problems when the complexity increases.
* I've heard about Ctools Export Bonus, but only 600 people downloaded it yet. Is it safe to use?

So wich is the best (or the least worst) solution currently, with drupal 7?

# Answer
> 0 votes
The questions you are asking are pretty hard to crack. We have build Kraftwagen which is a Drush extension and a bunch of Drupal modules that will fit your needs.

Please have a look and let us know if it worked for you.

---
Tags: 7, features, distributions
---


# Question
Title: Showing nested links in Drupal but still add classes to list elements
Very new to Drupal and a bit confused.

In order to render a menu in my theme I've been using this:

```
print theme('links', array('links' => $main_menu, 'attributes' => array('id' => 'main-menu', 'class' => array('links'))));

```

That works a treat and gives me an extra class on the first and last list items, which I need for styling. It doesn't, however, show any of the nested sub menus. So I found this that again, worked like a charm Show all nested menu links in Drupal 7 and shows all the top-level links in the main menu and the nested ones too. This doesn't give me the extra classes on the first and last list items which I need. Is there any way to use the code from the answer above and give the extra classes on the list items?

Thanks muchly

# Answer
Check out the Menu Attributes module. Here is a quote about it (from the module's project page):

> This simple module allows you to specify some additional attributes for menu items such as id, name, class, style, and rel.
>
> You should use this module when
>
> * You want to "nofollow" certain menu items to sculpt the flow of PageRank through your site
> * You want to give a menu item an ID so you can easily select it using jQuery
> * You want to add additional classes or styles to a menu item
> 1 votes

---
Tags: routes, navigation
---


# Question
Title: Hook to log results of calls to drupal_mail() made by other modules?
How can I get the success/failure response of drupal\_mail() generated by another modules?

hook\_mail\_alter() doesn't return success/fail and drupal\_mail() is only helpful if the message is coming from my module.

# Answer
The only way I can see is implementing hook\_watchdog(), and look for a error message that matches "Error sending e-mail (from %from to %to)."

```
function mymodule_watchdog(array $log_entry) {
  if ($log_entry['message'] == 'Error sending e-mail (from %from to %to)') {
    // ...
  }
}

```

The alternative would be implementing a class that replaces `DefaultMailSystem`, which is a class implementing MailSystemInterface. To achieve this, it is enough to change the value of the mail\_system Drupal variable.
> 2 votes

---
Tags: 7, emails
---


# Question
Title: How do I install the kurti devi 10 font for CKEditor?
I want to use the kurti devi 10 font in my new project. How do I install it for CKEditor?

# Answer
Check out @font-your-face module. It lets you to add fonts with UI, and it even have some kind of wysiwyg integration.
> 1 votes

---
Tags: theming
---


# Question
Title: Drupal 7 pass a custom form fileds input as arguments to the url on submit
How can I pass fields input as arguments to the url on custom form submit? I tried the following:

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

  $form['location'] = array(
    '#type' => 'radios',
    '#title' => t('Location'),
    '#options' => location_options(),
    '#default_value' => '',
    '#required' => TRUE,
  );

  $form['#submit'][] = 'custom_form_submit';
  return $form;
}

function location_options() {
  return array(
    'to' => 'To USA',
    'within' => 'Within USA',
  );
}

function custom_form_submit($form, &$form_state) {
  // I need a function here to redirect to a url with something like
  // move-quote?location=to
  // I tried $form_state['redirect'] but didn't work
}

```

# Answer
```
$form_state['redirect'] = array(
  'move-quote',
    array(
     'query' => array(
       'move-quote' => $form_state['values']['location'],
     ),
    'fragment' => 'optional',
  ),
);

```

should work in your submit function. Try also

```
$form['#submit'][0] = 'custom_form_submit';

```

and clear your caches. Also http://drupal.org/node/291680 was helpful
> 1 votes

---
Tags: 7, forms, redirection, uri
---


# Question
Title: Views, getting nodes type 1 which user have NO node of type 2 published that references the node type 1
I'm using drupal 7.20 with Views 3 module.

I've a content type "Homework" and a content type "Solution". The Solution content type has an entity reference field that references nodes of type "Homework".

Well, I'm trying to set up with Views a new Tab in the user profile menu: "Pending Homeworks" that lists all Homeworks that has no Solution referencing them and published by that user.

Best an example:

```
"Homework 1" <- "Solution (by user 1)"
             <- "Solution (by user 2)"
             <- "Solution (by user 3)"

"Homework 2" <- "Solution (by user 1)"
             <- "Solution (by user 3)"

"Homework 3" <- "Solution (by user 3)"

```

In this example, user 2 hasn't published yet his Solution for Homework 2 and Homework 3, so, the View I want, must output: Homework 2 and Homework 3.

Thanks in advance.

# Answer
> 0 votes
Thank you, Triskelion, for pointing me in the right direction.

Finally, I've set up a block with PHP and a single query:

```
<?php
global $user;
if (isset($user->uid)) {
  // Get uid of user logged in
  $x_uid = $user->uid;
  // If user is not empty or 0
  if ($x_uid) {
    // Subselect: Get desafio nids that have solutions published by $x_uid
    $select2 = db_select('field_data_field_enlace_al_enunciado','r');
    $select2->leftjoin('node','no','r.entity_id = no.nid');
    $select2->fields('r',array('field_enlace_al_enunciado_target_id'))
      ->condition('no.uid',$x_uid);
    // Get all desafio nids that are not in subselect
    $select = db_select('node','n')
      ->fields('n',array('nid','title'))
      ->condition('type','desafio')
      ->condition('n.nid',$select2,'NOT IN');
    // Execute the whole query
    $result = $select->execute();
    // Get results and print them out
    while ($record = $result->fetchAssoc()) {
      print '<a href="/'.drupal_get_path_alias('node/'.$record['nid']).'">'.$record['title'].'</a><br/>';
    }
  }
}
?>

```

It works! ;-)

# Answer
> 1 votes
This has already been answered here.

A simple view will not do what you want.

---
Tags: views
---


# Question
Title: How to generate a List of Dates with Start/End sorted by Month in Drupal7?
I have installed Drupal7 and created a content type (why not call it 'event' for now) to which I added a date field (lets name it 'event-date'). Some event-dates have start- and end-dates. Now I want to generate a list of these events sorted by Month, where every event is listed in one line, even the events with start- and end-dates should have one line for every day the event lasts - not only the start-till-end-row listing.

for example instead of

> JANUARY
> Mo, 04/02/2013 - 20:00 to Th, 06/02/2013 - 20:00 Event1

I need

> JANUARY
> Mo, 04/02/2013 Event1
>
> Tu, 05/02/2013 Event1
>
> Th, 06/02/2013 Event1

How could I realize that? thnx!

# Answer
You will have to use Views and Group by Month then by Day.

http://www.jeremyfrench.co.uk/node/1461
> 1 votes

---
Tags: 7, datetime, views
---


# Question
Title: Is it possible to add to different aliases to the same table in a dynamic query?
I would like to use a example query for retrieving a full tree of the nested set model in a dynamic query.

```
SELECT node.name
FROM nested_category AS node,
        nested_category AS parent
WHERE node.lft BETWEEN parent.lft AND parent.rgt
        AND parent.name = 'ELECTRONICS'
ORDER BY node.lft;

```

The problem is that dynamic queries can't alias the same table. Is there a work around for this?

# Answer
> 0 votes
The best answer I have at this point is to simply execute the subquery first using fetchAssoc() to return an array.

```
$subquery = db_select('nested_category', 'parent');
$subquery->addField('parent', 'lft');
$subquery->addField('parent', 'rgt');
$subquery->condition('name', $name, '=');
$parent = $subquery->execute()->fetchAssoc();

$query = db_select('nested_category', 'node');
$query->addField('node', 'name');
$query->condition('node.lft',$parent, 'BETWEEN');
$results = $query->execute()->fetchAll();

```

---
Tags: database
---


# Question
Title: What could be causing duplicate nodes to be posted?
One of the content editors for our site is encountering a duplication error when she posts calendar events. You can see what's happening on the front end here: https://www.library.drexel.edu/events

I'm pretty much brand new to administering drupal (outside of some minor content editing) and am just taking over the site in the interim after an employee left while we seek to fill the position.

# Answer
> 1 votes
We see this (or somthing similar) quite often. Some users create a new node, add text, hit save. So far so good, but sometimes they see an type error or so and go back with the browser Back button, make the corrections and hit then save again. Usually this creates a new node instead of editing the one they think they edited.

# Answer
> 0 votes
Check she's not double-clicking the submit button. You'd be surprised. Given that the duplicate events are different nodes, this is almost certainly operator error, though arguably the UI could be more fool-proof.

---
Tags: nodes
---


title: Changing Drupal theme completely

text:
# Question
Title: Changing Drupal theme completely
I am a newbie, I am in the middle of the website which was already created using the bartik theme and I want to change the theme completely like the way Main-menu looks and adding the slideshow in the middle of the page. I really don't understand how to do it. Any suggestions? Thanks.

# Answer
I would recommend starting with the "Stark" Drupal theme. It's the minimal theme, easier to customize.

You are also going to need to read about some basic Drupal concepts. Views, blocks, page templating.

Your question is far too "big" to be answered in this forum. You will have to read the documentation at drupal.org
> 0 votes

# Answer
The question suggest you do not know where to start with performing customizations to the appearance of your Drupal site.

It is best to use a base theme, such as Omega (ht tp://drupal.org/project/omega) , and create a sub theme. Omega Tools is a module (ht tp://drupal.org/project/omega\_tools) and provides a handy feature to create a sub theme.

It is good practice to use a sub theme, it saves a lot of time and effort if things go wrong and if updates become available to your base theme.

Most problems and questions you have will be answered in the following documentation: \- ht tp://drupal.org/documentation/theme \- ht tp://drupal.org/node/1351116

There are many modules Slideshows, here is a comparison of them ht tp://drupal.org/node/418616 . Personally I use ht tp://drupal.org/project/views\_slideshow .

I do not have enough rep here to post links so if someone could be so kind to find and replace "ht tp" with "http", thanks
> 0 votes

# Answer
The short answer is to make changes to the CSS files of you theme. Drupal Themes are more of a developer friendly environment than a graphic design environment like Wordpress themes.

Drupal "best practices" procedure is to work with a base theme and an overriding subtheme. The Zen theme is one of the most popular ways to do that. The reason to work this way is that you can update the theme without over-writing your subtheme, and hopefully the subtheme changes would be minimal.

Probably the easiest way to install a slideshow is with the Field Slideshow module. You need to add an image field to one of your content types, upload the images, and Field Slideshow instantly makes a slideshow, which you can put on any page with the block system. Well, not quite instantly, you need to grab a slideshow jquery library, but you don't have to use the amazing but complex Views module.
> -1 votes

---
Tags: theming
---


title: Open jump menu selection in new window

text:
# Question
Title: Open jump menu selection in new window
I have a views jump-menu of PDFs. I'd like the PDF to open in a new window when the user clicks the "go" button on the view.

I've tried using javascript to set the form's `target` attribute to `_blank`. It is showing in the markup, but it has no effect on the behavior of the form submission.

Any ideas on how to do this?

# Answer
> 1 votes
The only way I've found to do this so far is to alter the ctools jumpMenu behaviour with the following JS. This is probably a lot more code than I need, but it seems to do the job. Better answers are appreciated.

**JS**

```
// place this outside your .ready() function
Drupal.behaviors.CToolsJumpMenu = {
   attach: function(context) {
     $('.ctools-jump-menu-hide:not(.ctools-jump-menu-processed)')
       .addClass('ctools-jump-menu-processed')
       .hide();

     $('.ctools-jump-menu-change:not(.ctools-jump-menu-processed)')
       .addClass('ctools-jump-menu-processed')
       .change(function() {
         var loc = $(this).val();
         if (loc) {
           location.href = loc;
         }
         return false;
       });

     $('.ctools-jump-menu-button:not(.ctools-jump-menu-processed)')
       .addClass('ctools-jump-menu-processed')
       .click(function() {
         // Instead of submitting the form, just perform the redirect.

         // Find our sibling value.
         var $select = $(this).parents('form').find('.ctools-jump-menu-select');
         var loc = $select.val();
         if (loc) {
          // console.log(loc.slice(loc.indexOf('::') +2) );
           // location.href = loc.slice(loc.indexOf('::') +2);
           window.open(loc));
         }
         return false;
       });
   }
 }

```

Source

---
Tags: views, 7
---


title: Cleanup old nodes

text:
# Question
Title: Cleanup old nodes
How can I mass remove old nodes from drupal-6 by date? I can't find anything on Google or any option for doing that.

The closest module I found are the Revisions to Mass Delete, and the Auto Expire modules.

# Answer
> 1 votes
An option could be creating an *administration page* with the Views module, using filters and Views Bulk Operations.

---
Tags: 6, nodes
---


# Question
Title: How to display user form and hide some fields?
I'm building a website which has a member section. People subscribe and complete the "user" form (username, email, password and some other fields).

For an additional fee, they can be part of the "dating" part of the website, where they can meet new people.

After paying, I would like them to complete a form about them (height, eyes, etc.). Those fields are already in the user form.

I'm displaying the user form this way :

```
global $user;
module_load_include('inc', 'user', 'user.pages');
return drupal_render(drupal_get_form('user_profile_form', $user));

```

How would i go about hiding some fields that I don't want them to see/modify?

Thanks!

# Answer
You should alter the form *before* rendering it.

```
$form = drupal_get_form('user_profile_form', $user);

// Uncomment this line to inspect the structure of the form array (needs devel module)
//dpm($form '$form');

// hide field.
unset($form['field_name']);

return drupal_render($form);

```
> 1 votes

# Answer
I would implement `hook_form_alter()` and perform modifications there. The advantage of doing it in the form alter hook is that these changes will be applied whenever that form is requested (such as on other pages where you may also want to call it), and not just a single spot.

Additionally, don't use `unset()` to remove form elements, as other modules may depend on them being present, which will cause errors. Instead, set the element's access to FALSE:

```
$form['element_name']['#access'] = FALSE;

```
> -1 votes

---
Tags: forms
---


title: D7 Alter date field output in views

text:
# Question
Title: D7 Alter date field output in views
I have a view which shows a couple of fields in a list. One of the fields is a date field. I'm trying to alter the output of this field so that I can control the day, month and year seperately. So instead of the view putting out

```
<div>03/05/2013</div>

```

I want it to put out

```
<div>03</div>
<div>05</div>
<div>2013</div>

```

I've already tried doing it with the use of custom date formats, then adding the date field three times to the view, each with a different date format. Excluding the first two fields from display and rewriting the output result of the third field with tokens. But then the day/month/year is wrapped in a span tag when I just want the raw value.

Should I use a template file, preprocess function,... for this?

Thank you.

# Answer
This way requires installing Views PHP:

1. Hide (do not display) the date field
2. Create 3 more fields (day, month, year)
3. Rewrite the value of these fields, using the the token of the hidden date field, and custom PHP code. This example is for the year field:

```
echo date('Y', strtotime([token_datefield]));

```
> 1 votes

---
Tags: 7, views, datetime
---


# Question
Title: Git workflow from dev to live when central repo is in local network
I use @dev - @stage - @live workflow, managed with drush rsync and drush aliases to update code, syncing db down from @live to @dev / @stage to have recent state.

Recently, I am trying to implement very simple git workflow into it, to secure revisioning of my code. I am not git power user, so I can bear only simple workflow for a good clean simple start (as a single dev I can be spared of situations where many devs are merging/resolving etc.)

There is my local machine (@dev), and staging machine (@stage) that are in my local environment (parties that need to review/QA changes have intranet access to staging machine); @live machine is remote one, and code is drush rsynced to it.

Now, My Local @dev and @stage are not exposed to internet, (can push, but one cannot connect to them from outside)

I have choosen to create "central repo" on @stage machine. I followed strategy simmilar to this: http://toroid.org/ams/git-website-howto . There is bare repo and webroot. Then I cloned from that "central repo" to my @dev machine. When I commit and push to origin from @dev, there is post-receive hook that populates webroot of @stage server with new code state. It is then reviewed, QA-ed.

Now, I am thinking about strategies to propagate those changes on live. I was thinking to modifiy post-receive in such manner, that if "dev" branch is pushed from my local @dev to central repo, code is only propagated in webroot of @stage server. But if I push "master" branch, code would be propagated in webroot of @stage server, and drush rsync would be triggered to do syncing from @stage to @live. Remote @live site, in that case, does not need to have git installed.

I guess it could be done this way (I am testing this workflow already), but I am also considering would it be any gain if git repo would live on @live site too; and if answer is yes, how could I implement that safely (@live is already populated with stable state, but has no git(could have if needed)).

I cannot go to remote @live server and clone from central repo (that is on my @stage machine) because @stage is not exposed to internet (it could be in future, as new devs will probably join to work on project, and will need to clone from that, but for now, it needs to stay local). I am searching for way to push from central repo to @live on when master is updated. Maybe same post-receive that updates @stage after master is being pushed from @dev, can trigger pushing to @live (instad rsyncing to @live?). But how I could initialize repo on @live, bearing in mind central repo is not accessible over net ?

As a side question, is git friendly when I decide to change the whole proccess (for example, move my "central repo" on BitBucket or anoter remote site, more devs join in...?

I also noticed that git cloning does not keep any of interesting user:group privileges, and pushing code could propagate that "lost" file permissions, is this of some concern (I am not version controlling files and such, that is in .gitignore) ? Yet agian I could always run some commands to regain those privileges as in http://drupal.org/node/244924 but I am not sure if this is best practice.

I hope that some of this make sense and that someone with good nerves could give me advice or two. I know this is somewhat simmilar with (dis)advantages of staging dev-\>production using 'drush rsync' vs 'git'? but it differs in some details very important to me.

# Answer
Your question is a bit long, and too subjective. There are many ways to do things, and the answers to your questions are subjective. For better answers, post shorter questions that ask about a single factual item. It's hard to answer "what is the best workflow"-style questions on StackExchange; those are better handled on a discussion board.

Trying to pick out your specific questions: it is not necessary to use git to push to live, especially if you always keep a copy of the deployed code on your staging server. It might be helpful to record the hash tag that you pushed to live somewhere when your script runs. The main advantage to using git on the live site is that you don't need to do this, as you can use 'git log' to find out what is there. If you do use git on the live site, be sure that the .git files are not accessible to the webserver. I prefer to use this setup:

```
/path/www/mysite.com/.git
/path/www/mysite.com/htdocs/sites/all/default/settings.php

```

Regarding permissions, see also http://drupal.org/node/990812. Hopefully I'll have this fixed up and committed soon. It has been languishing for a while; it works, but needs some cleanup in the flags, et.al.
> 3 votes

---
Tags: drush, version-control, deployment
---


# Question
Title: Phising warnings (in gmail) when using a gmail address as the website email address. How to avoid it?
I would like to use a gmail address (a simple email address. i'm not using google apps) as my website's email.

The problem is that users receiving messages from the websites (notifications etc..) have a yellow bar warning them that this might be a fishing attempt.

I thought there might be some settings or best practices to avoid this problem.

Any ideas ?

# Answer
> 2 votes
I have been using this module for a long time without problems. You need to authenticate once, and then all your site emails are sent through the google smtp server.

http://drupal.org/project/smtp

# Answer
> 1 votes
You can try changing the Sender Policy Framework record to avoid getting your emails to go to Spam Folder.

> Sender Policy Framework (SPF) is an email validation system designed to prevent email spam by detecting email spoofing, a common vulnerability, by verifying sender IP addresses. SPF allows administrators to specify which hosts are allowed to send mail from a given domain by creating a specific SPF record (or TXT record) in the Domain Name System (DNS).

There is some Tools to test your SPF Records

---
Tags: 7, emails
---


title: Taxonomy breadcrumbs

text:
# Question
Title: Taxonomy breadcrumbs
I'm using the core taxonomy module for blog tags but when on a tag's page can only get the breadcrumb to appear as 'Home', whereas I'd like it ideally to be 'Home \> Blog \> #Tag#'. I'm using custom breadcrumb module to set breadcrumbs for content types (\<- doesn't allow for taxonomy breadcrumbs) and have tried using taxonomy breadcrumb module with absolutely no result, partly due to the fact that it's not a particularly configurable module. Blog tag pages (listing all the nodes under a term) seem to be generated from the core taxonomy module and not views so I can't resolve the issue in views.

If anyone could point me in the right direction I'd be grateful :)

# Answer
> 3 votes
This sounds like something you could do relatively easy with `drupal_set_breadcrumb` in a custom module.

This is most likely what custom breadcrumb module is using itself. You will have to alter the breadcrumbs after custom breadcrumb module but before they are rendered. This might be what is giving your some problems with the taxonomy breadcrumb module.

You might be able to use it if you alter it's weight in system table, depinging on how the two modules alter the breadcrumbs. My guess is that it's done with `hook_init`

# Answer
> 9 votes
This can be accomplished by overriding theme\_breadcrumb() in your theme's template.php An example implementation:

```
function mytheme_breadcrumb($breadcrumb) {

  if (arg(0) == 'taxonomy' && arg(1) == 'term' && is_numeric(arg(2))) {
    $breadcrumb = array();
    $breadcrumb[] = l(t('Home'), '<front>');
    $breadcrumb[] = l(t('Blog'), 'path/to/blog');

    $tid = arg(2);

    if ($term = taxonomy_term_load($tid)) {
      $uri = entity_uri('taxonomy_term', $term);
      $breadcrumb[] = l($term->name, $uri['path'], $uri['options']);
    }
  }

  // resume normal operation
  if (!empty($breadcrumb)) {
  // uncomment the next line to enable current page in the breadcrumb trail
    $title = drupal_get_title();
    if (!empty($title)) {
      $breadcrumb[] = $title;
      unset($title);
    }

    return '<div class="breadcrumb">'. implode(' > ', $breadcrumb) . '</div>';
  }
}

```

# Answer
> 4 votes
There is a module for that (well more than one):

Probably would choose custom breadcrumbs due to its flexibility, and ability to craft breadcrumbs for the rest of your site as well.

# Answer
> 2 votes
I was having the same problem with taxonomies. I came across the module "Easy Breadcrumbs", which looks off of the URL construction to generate the breadcrumbs (relies on Pathauto and Clean URLs).

For example:

example.com/style/mediterranean

Home \> Style \> Mediterranean

I understand that in many cases this will not help, but if your breadcrumbs mimic your URL construction, then Easy Breadcrumbs should solve your problems.

# Answer
> 1 votes
I was using Taxonomy Display and found that `drupal_set_breadcrumb()` was failing on `hook_init()` and breadcrumb overrides were failing in other modules.

See this issue for a patch and offered solution to users of this module: breadcrumb handling makes it impossible to alter breadcrumbs for terms without parents

# Answer
> 1 votes
**With Crumbs 7.x-2.x:**

1. Visit admin/structure/crumbs, and enable the taxonomy.\* plugin wildcard, or sth more specific from the taxonomy plugin family. (it might already be enabled, but have a look to be sure)
2. Go to `admin/structure/crumbs/entity-parent/taxonomy-term`, and set "blog" as the parent path for your chosen vocabulary.
3. Visit admin/structure/crumbs, make sure that crumbs.entityParent.\* (or something more specific) is enabled.

**With Crumbs 7.x-1.x:**

1. Visit admin/structure/crumbs, and enable the taxonomy.\* plugin wildcard, or sth more specific from the taxonomy plugin family. (it might already be enabled, but have a look to be sure)
2. Write a custom module with a Crumbs plugin (\*) that makes "blog" the parent path for "taxonomy/term/%taxonomy\_term".
3. Visit admin/structure/crumbs, enable your new plugin, and give it a priority weaker (further down) than the taxonomy.\* or taxonomy.termParent.\*.

(\*) Writing the plugin: http://drupal.org/node/1398876
The example may be a bit overkill for this purpose, I hope you can find your way.

---
Tags: 7, taxonomy-terms, breadcrumbs
---


# Question
Title: How to add a line item to show total cost in Ubercart 2?
I am using Ubercart 2 and I want to add a line item, which should add the total cost of all items instead of sell price. I tried to take the code from generic line item hook and used this to callback:

```
for each($op->products as item) {
  $cost += $item->cost;
}

```

I want this line item to appear in the AJAX cart, which I am using now. It should appear in the user panel before checkout and it should also shown in the user and store admin order emails. It is not working as of now. Is the code I am adding correct or I have done any misplacement?

# Answer
> 1 votes
There is uc\_order\_pane\_line\_items\_add

> Order pane submit callback: Add a line item to an order.

```
function uc_order_line_item_add($order_id, $type, $title, $amount, $weight = NULL, $data = NULL) {
  if (is_null($weight)) {
    $weight = _uc_line_item_data($type, 'weight');
  }

  $line_item = array(
    'order_id' => $order_id,
    'type' => $type,
    'title' => $title,
    'amount' => $amount,
    'weight' => $weight,
    'data' => $data,
  );
  drupal_write_record('uc_order_line_items', $line_item);

  return $line_item;
}

```

---
Tags: 7, ubercart
---


# Question
Title: How to display list of nodes that share the same Parent taxonomy term as current node
I have a vocabulary set up called (for example) "Produce". And it has parent terms like "fruit" and "vegetable". Child terms are like "banana", "apple" and "cucumber", "squash".

Whenever I create a new node about fruit or vegetables, I use a content type that I created. In this content type, I have a field set up called "field\_produce\_and\_name". So when I create a new "Fruit" page, called "papaya", I also create "papaya" as a child taxonomy term to "fruit". And I set the field field\_produce\_and\_name to "papaya".

When someone is viewing the "papaya" page/node, I would like a sidebar menu list to display the titles of other "fruit" nodes. That is, a list of nodes that share the Parent taxonomy term as "papaya".

I have tried using the contextual filter "Content: Has taxonomy term ID (with depth)" but it still isn't working :(

I also think that maybe I need to add a relationship, but am unsure how/which one.

Any ideas?

# Answer
> 0 votes
Yes, add a relationship for the taxonomy field and the parent contextual filter will be available.

# Answer
> 0 votes
I've done this with a content type that has a term reference field to associate a taxonomy term with a node. You can do this by adding two relationships.

* Taxonomy term: Parent term
* Taxonomy term: Content using

You can then add a new Taxonomy term field into your view and select Parent as the relationship for that field. You can also then group by this parent field.

Please feel free to ask questions if this isn't quite clear enough and I'll try and explain further.

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


title: Help With Taxonomy

text:
# Question
Title: Help With Taxonomy
I have a taxonomy menu of countries on the home page. When the user clicks on a country they are taken to the specific country page where the country flag and country related content is displayed. I achieved this using tags in the content, view with contextual arguments and the Panel page using the taxonomy term template.

On the country page is another taxonomy menu of sub-categories, (i.e.-movies, songs, tv). When the user clicks on one of the items I want them to be take to another Panel page that will display the specific content that is ALSO filtered by the country that they selected in step one.

I am at a lose as to how to achieve this. Any ideas?

# Answer
> 2 votes
You'll need to somehow append the country tid as an additional filter to the menu links ( e.g theme function ) and use that as a contextual filter in the view for country + sub category.

---
Tags: 7, views, taxonomy-terms, panels
---


# Question
Title: How to change the word "blog" for "journal"
I have used string overwrites for a lot of stuff but sometimes I hit a section I cannot change. One of these is the "User's blog" button. How do I change the word "blog" for "journal"? I am impressed no one seems to have asked this question before.

# Answer
Try in settings.php

```
$conf['locale_custom_strings_en'][''] = array(
  "!username's blog"      => "!username's journal",
);

```

You'll need to include the variable placeholder in the source / translation string.

More info: blog\_node\_view
> 0 votes

# Answer
There is String Overrides module.

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

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

# Answer
hook\_menu\_alter():

> Alter the data being saved to the {menu\_router} table after hook\_menu is invoked.

With devel module, do a `dpm` on `$items` and change the title var to what you want it to be.
> 0 votes

---
Tags: string-overrides
---


# Question
Title: Adding Node to Entity Reference List (Via Rules) Throws EntityMalformedException
I'm using rules and I'm trying to add a reference to an updated node to an entity reference on another node. I am getting the following exception.

EntityMalformedException: Missing bundle property on entity of type node. in entity\_extract\_ids() (line 7633 of /var/www/html/mysite/includes/common.inc).

I found another post that states - "EntityMalformedException: Missing bundle property on entity of type node." means that Drupal does not recognize your entity as a valid one. In the entity info listing, there is a mapping from "bundle" to "type", for nodes.

Either your $node doesn't have a -\>type, or Drupal no longer has the type registered. The type could have been removed, either from the UI, or by disabling a feature, and possibly in more interesting ways as well.

My question is - How can I go about debugging this and correcting the problem. I have Devel installed and I have debugged issues before I just need a little guidance to help me get to the bottom of this / or post the issue to whatever module has caused the error so the maintainers know about it.

Thanks very much and have a great day!

# Answer
Okay I've fixed the error and whilst I'm not 100% sure this was the issue I think it had to do with the fact that the new node had not been saved prior to my attempting to assign it to the other node. Hence it had no node id, hence the error - I think.
> 0 votes

---
Tags: rules, entities
---


title: Form results sent to different emails

text:
# Question
Title: Form results sent to different emails
I am using a webform module to create a contact us form. The customer has asked for a dropdown list for the visitor to select whom they would like to contact (web administrator/general enquiry). Is there a way to change the TO email depending on the selection? Or is there another way of achieving this?

# Answer
Here's how I did it in Drupal 7, without the use of any other add-on modules:

1. Add a select box to the form.
2. In the select box options field, add your info in this format:

> email-1@address.com|Select Option 1
>
> email-2@address.com|Select Option 2
>
> email-3@address.com|Select Option 3
3. Save your form, then click on the "Emails" sub-tab of the "Webform" primary tab.
4. Choose "Component Value \> The name of the field you created in step 1". Click "Add".
5. Adjust your settings as needed on the following page, and you're done! The webform will now send an email to the address associated with the choice selected in the select box.
> 3 votes

# Answer
You can achieve this with the Webform rules module. You can catch every webform submit and then apply actions on it depending on the submit values. This module helps exposing webform events to the rules module.

The Rules module is used to trigger actions on defined events, so for example when a webform is submitted you can create a condition (in Rules) that checks the dropdown value and then trigger an action that sends the mail accordingly. You can have as many rules as diferent recipients.
> 1 votes

# Answer
Build your own module, hook\_form\_alter($your\_forms\_id) and add your own submit handler like

```
/**
 * Implements hook_form_alter().
 */
function YOURMODULE_form_alter(&$form, &$form_state, $form_id) {
 if ($form_id == 'YOUR_forms_id'){
    $form['#submit'][] = 'my_submit_';
 }
}

```

PS:Your default (webform) submit handler is executed also ..

```
function  my_submit_($form, &$form_state) {
  drupal_set_message('success!')
...
  drupal_mail($form_state['values']['your element'])...
}

```
> 0 votes

# Answer
Have a look at issues \[#800350\] or \[#1026758\]. In short: you can do so by adding the following (templated) code:

```
   /**
     * Implements hook_mail_alter
     * @see http://api.drupal.org/api/drupal/modules--system--system.api.php/functio... *
     * @param array $message
     */
    function mymodule_mail_alter(&$message) {
      if ($message['id'] == 'webform_submission') {
        if (isset($message['params']['node']) && isset($message['params']['submission'])) {
          $node = $message['params']['node'];
          $submission = $message['params']['submission'];
          // do your work, e.g. changing $message['from'], $message['to'], etc.
          ...
        }
      }
    }

```

By using hook\_mail\_alter you will also catch resubmissions, that most other solutions don't.
> 0 votes

---
Tags: webforms
---


# Question
Title: Accessing Drupal.settings outside of attach function
I'm trying to make some of my Javascript in a Drupal 7 module a bit more modular, as I want to access a function inside `Drupal.behaviors.attach()` from another JS file. So first of all I need to move some variable declarations, and then the functions, outside of the attach function and hopefully access the variables from inside it with this.vars.myVariable - I'll try and explain a bit further with some slightly dummified code...

Initial, working code:

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

    attach: function(context, settings) {

      var initial_page = Drupal.settings.myModule.initial_page;
      console.log(initial_page); // returns a value

    }
  }
})(jQuery);

```

However, this doesn't work:

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

    vars: {
      initial_page : Drupal.settings.myModule.initial_page
      // Uncaught TypeError: Cannot read property 'initial_page' of undefined
    },

    attach: function(context, settings) {

      console.log(this.vars.initial_page);

    }
  }
})(jQuery);

```

It seems that outside of the scope of the attach function, `Drupal.settings` doesn't exist. Is there any way I can access these settings (defined in my .module file) from anywhere within behaviors.myModule\_someJS ?

Thanks! Matt

# Answer
> 1 votes
Worked it out myself.

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

    anotherFunction: function() {
      console.log(this.vars.initial_page);
    },

    attach: function(context, settings) {

      this.vars = {
        initial_page  : Drupal.settings.myModule.initial_page
      }

      this.anotherFunction();

    }
  }
})(jQuery);

```

Drupal.settings won't contain the custom stuff sent through from my module *until* the attach function is called, so therefore every settings variable can only be called inside attach()

(and from Alice's comments above, it may be a matter of drupal\_add\_js being called from within the page rather than in the init() hook)

---
Tags: 7, javascript
---


title: hook_menu and Access Denied

text:
# Question
Title: hook_menu and Access Denied
Why do all of these menu items return "Access Denied" pages no matter how many times I drush cc all and clear cache from admin/config/performance?

```
/**
 * Implements hook_menu()
 */
function caplogin_menu() {
  $items = array();
  $items['join'] = array(
    'title' => 'Foo settings',
    'access arguments' => array('access content'),
    'type' => MENU_NORMAL_ITEM,
  );
  $items['join/signup'] = array(
    'page callback' => 'caplogin_unified_registration',
    'access arguments' => array('access content'),
    'title' => 'Request Member Online Credentials',
    'type' => MENU_DEFAULT_LOCAL_TASK,
  );
  $items['join/login'] = array(
    'page callback' => 'caplogin_unified_login',
    'access arguments' => array('access content'),
    'title' => 'Members Login',
    'type' => MENU_LOCAL_TASK,
  );
  return $items;
}

```

# Answer
For the first menu item, you didn't provide any page callback, and `MENU_DEFAULT_LOCAL_TASK` menu items inherited it from the parent menu item. In this case, Drupal returns a 403 error.
For the last one, the reason can be one of the following:

* The page callback function doesn't exist, or it is defined in a file that is not the module file
* The user account doesn't have the permission 'access content'
> 5 votes

---
Tags: routes
---


title: Wrap text fields with custom HTML

text:
# Question
Title: Wrap text fields with custom HTML
I have a content type with body tag. I want to add content which has a repeating HTML mark-up.

**Example:**

```
<div class = "some-class">
<p>Main Content 1</p>
</div>
<div class = "some-class">
<p>Main Content 2</p>
</div>

```

This pattern repeats itself except for the text within the `<p>` tag. Right now I'm typing tons of repeating HTML code into the body of the content type. It would be helpful if I could just focus on the main content and not on the repeating mark-up which could save lots of time.

1. Is there a way to surround fields with custom HTML tags, so that I can focus on the main content and not on the HTML mark-up?
2. Is there a module that I can use to do the same?

# Answer
> 6 votes
There are a number of ways you can handle this. The three best that come to mind are:

1. Use a theme hook template file to modify the output. You can do this at either the field level or the content type level.
2. Use Display Suite to create a field template.
3. Create a custom field formatter with Custom Formatters module. This plays nicely with display suite.

In your case Display Suite is probably overkill unless you wanted to use it for managing all your output. It’s an extremely powerful module that if implemented correctly allows you to not have to manipulate template files.

In either case I would suggest taking a good look at Display Suite as it really speeds up the theming process.

# Answer
> 1 votes
One way is using Display Suite.

You have to enable Display Suite Extras module coming with Display Suite, then you have to enable field wrappers in the DS Extra settings (admin/structure/ds/list/extras). After that you can go to "Manage display" of a content type and select "Expert" for a field.

---
Tags: 7, nodes
---


title: No hooks are called on webform submit

text:
# Question
Title: No hooks are called on webform submit
I have created a registration form via webform 7.x-3.18. In my custome module I wrote following hooks

> MYMODULE\_node\_submit($node, $form, &$form\_state)
>
> MYMODULE\_node\_insert($info)

But on form submission none of the hooks are triggered. I tried submission with normal article page content form and at that time my custom module hooks are triggered. Could someone tell the problem with my code??

# Answer
> 2 votes
Please check on the Webform's hooks list Webform Module Hooks here. These hooks are associated with each webform activities.

---
Tags: 7, hooks, webforms
---


# Question
Title: How to send a email message to specific user role when the site goes to the maintenance mode in drupal 7?
I would like to use emails to communicate with users. So i really want to send a email message for all users(or just a number of users with specific role) when the site goes to the maintenance mode and send another one when the site comes online.

I checked triggers, rules, actions but couldn't find anything to help.

How can I solve this?

# Answer
Checkout this module Maintenance mode API .

> Maintenance mode API notifies other modules when the site is switched into or from maintenance mode.
>
> This means that other modules can respond to this, for example:
>
> **Alerting a list of users when the site goes into or out of maintenance mode**

This module provides a hook, hook\_change\_maintenance\_mode which any custom modules can interact

EDIT:

You can create a custom rule set with actions as send emails to your desired users. (An example guide how to create it).

Then invoke the rule set using rules\_invoke\_event() function inside the hook hook\_change\_maintenance\_mode
> 3 votes

---
Tags: 7, emails, notifications, maintenance-mode
---


# Question
Title: Superfish menu with user id as a parameter
My question is how to get the user id on a URL path when creating a link in a superfish menu.

# Answer
> 1 votes
Checkout this module Menu token

> Menu Token module provides tokens, that could be used in title or in path of menu items (links). For example, if you create a menu item with path: "user/\[current-user:uid\]", the url will be changed "on fly" to: "user/1" (assuming you are user 1).

---
Tags: routes, navigation
---


title: jquery and an if statement

text:
# Question
Title: jquery and an if statement
Drupal 7. I have a radio button set. When one of the items is selected I would like it to set the node add title to some string. This is as far as I got, but I get the error: "TypeError: '\[object Object\]' is not a function (evaluating '$("#edit-field-i-need-help-with-und-printer-ink")')"

```
(function ($) {
      Drupal.behaviors.cgps_helpdesk_misc = {
        attach: function (context, settings) {
          $("#edit-field-i-need-help-with-und-printer-ink").change(function ($) {
              if ($("#edit-field-i-need-help-with-und-printer-ink").attr("checked")) {
                alert('Handler for .change() called.');
                $('#edit-title').val($('#edit-title').val() + 'bla bla bla');
              }
          });
        }
      };
    }(jQuery));

```

# Answer
> 1 votes
What MPD is saying is change this line:

```
$("#edit-field-i-need-help-with-und-printer-ink").change(function ($) {

```

to this:

```
$("#edit-field-i-need-help-with-und-printer-ink").change(function () {

```

You have declared two functions as $ and that may be killing the script.

# Answer
> 1 votes
```
(function ($) {
  Drupal.behaviors.cgps_helpdesk_misc = {
    attach: function (context, settings) {
      $("#edit-field-i-need-help-with-und-printer-ink").change(function (eventObject) {
          if ($("#edit-field-i-need-help-with-und-printer-ink").attr("checked")) {
            alert('Handler for .change() called.');
            $('#edit-title').val($('#edit-title').val() + 'bla bla bla');
          }
      });
    }
  };
}(jQuery));

```

The only part that was wrong in the original is `.change(function ($)` This part is overriding the $ variable which is a jQuery object and setting it to an event object. The change event send an event object to the listener functions.

The question is already answered, but I thought it would be good to try to explain what is actually going on to give the op a better understanding

# Answer
> 0 votes
Got it working. I have a feeling the jQuery substitution of the $ is not the "Drupal 7 way", and I would be curious to know what that way is, but this works:

```
(function ($) {
      Drupal.behaviors.cgps_helpdesk_misc = {
        attach: function (context, settings) {
          $("#edit-field-i-need-help-with-und-printer-ink").change(function ($) {
              if (jQuery("#edit-field-i-need-help-with-und-printer-ink").attr("checked")) {
                alert('Handler for .change() called.');
                jQuery('#edit-title').val(jQuery('#edit-title').val() + 'bla bla bla');
              }
          });
        }
      };
    }(jQuery));

```

Full solution at http://agerson.net/setting-title-field-based-radio-button-node-add-form-drupal-7-jquery

---
Tags: javascript
---


title: Filter by relative date

text:
# Question
Title: Filter by relative date
I have a view constructed with many fields, one of those fields is a date field. I added a filter on my date field that is asking for a relative date. OK, this is no problem, but I have a request to gather all results from month to date. For example, I want to get the results from today's date, back to the beginning of the month. I used for this filter, the operator, "is equal to", the relative date, "this month," and I get no results back, even though there is results between now and the beginning of the month. I was thinking I am using the wrong relative date. I looked up the documentation here: http://php.net/manual/en/datetime.formats.relative.php, and "this month" looks like the correct format, but maybe it is not. Can someone point me in the right direction.

# Answer
I figured out the answer to my question. In the filter option, if you filter the relative time format "first day of this month," and assign the operator "is equal to or greater than," the output will be the first day of the month to the current day. Hope this helps anyone that reads my post.
> 1 votes

# Answer
I don't think the author has correctly answered his own question.

```
php -r "echo sprintf('%+d', strtotime('first day of this month'));"

```

This will output `+1362137143`

The code in the views\_handler\_filter\_date (op\_simple method) is:

```
$value = intval(strtotime($this->value['value'], 0));
if (!empty($this->value['type']) && $this->value['type'] == 'offset') {
  $value = '***CURRENT_TIME***' . sprintf('%+d', $value); // keep sign
}
$this->query->add_where_expression($this->options['group'], "$field $this->operator $value");

```

So the views query will be, e.g. `node.created >= time()+1362137143`, which isn't going to give you what you want.

If you want all nodes created this calendar month, use a Date argument with the granularity set to "Month".

Here's an issue suggesting that there should be an option to use absolute dates evaluated by strtotime; http://drupal.org/node/1935036
> 0 votes

---
Tags: views
---


# Question
Title: Autocomplete on a custom field on the registration form no longer working
thanks for reading.

I have a database table containing organisation names. When a user registers on the website, they use a text field I added, which autocompletes with existing organisation names, as a way of attaching them to existing organisations. This used to work fine, but doesn't seem to now, presumably after one of the updates. Now it simply doesn't load anything when typing in, though the little circle appears to indicate that it is connected.

Here's the code:

```
$items['org/autocomplete'] = array(
  'page callback' => '_org_autocomplete',
  'access callback' => TRUE,
  'type' => MENU_CALLBACK
);

```

...and...

```
function _org_autocomplete($string = '') {
  $matches = array();
  $query = db_select('org_orgs', 'c'); // I've checked that the table exists, contains data, and is of this name - that's fine
  $return = $query
    ->fields('c', array('name'))
    ->condition('c.name', '%' . db_like($string) . '%', 'LIKE')
    ->range(0, 10)
    ->execute();

  foreach($return as $row) {
    $matches[$row->name] = $row->name;
  }
  if ($_SERVER['HTTP_REFERER'] == url('user/register', array('absolute' => TRUE))){
    drupal_json_output($matches);

    // The if statement surrounding this line prevents users
    // from viewing the full list by going directly to the
    // /org/autocomplete URL. In removing the if statement, I can
    // test to see if it works at the URL, and it does just fine

  }
}

```

I've checked that the table exists, contains data, and is of this name - that's fine. The if statement surrounding the drupal\_json\_output() line prevents users from viewing the full list by going directly to the URL. In removing the if statement, I can test to see if it works at the URL, and it does just fine.

```
function org_form_user_register_form_alter(&$form, &$form_state, $form_id) {
  $form['field_organisation']['und'][0]['value']['#autocomplete_path'] = 'org/autocomplete';
  // Though no results appear, the 'org/autocomplete' path
  // is confirmed as the correct path because changing it to
  // anything else removes the little autocomplete circle.
  $form['field_organisation']['und'][0]['value']['#description'] = 'If your organisation appears in the above predefined dropdown menu, please select it.';
  $form['#validate'][] = 'org_form_validate';
  $form['#submit'][] = 'org_form_submit';
}

```

Though no results appear, the 'org/autocomplete' path is confirmed as the correct path because changing it to anything else removes the little autocomplete circle.

Do you have any ideas of what's gone wrong, or if not, what I can do to investigate?

Additionally, in searching for the solution, I found this drupal update: http://drupal.org/node/1901518 Could this be the cause? And if so, what can I do to correct it?

Thanks

# Answer
> 1 votes
What you say suggests it's this line that's the issue:

```
 if ($_SERVER['HTTP_REFERER'] == url('user/register', array('absolute' => TRUE))){

```

so there's presumably some difference between the referrer URL and the one generated by the url() function. You might add lines above it to record the two values using watchdog: that would confirm you are reaching that point in the code and help diagnose the issue.

# Answer
> 0 votes
I've discovered that the issue was caused by the reCAPTCHA module. Disabling the AJAX API in the configuration pages resolved this.

---
Tags: 7, javascript, users, ajax
---


# Question
Title: When a user goes from one page to another, how can I see where they came from and where they are going?
I need to hook into whenever a user moves from one page to another. I need to know where they are coming from and where they are going. My scenario is that anytime that a user heads to a certain section of the site (search) it modifies the path to add a variable. But I only want to to do so when they are coming from outside that section of the site.

I have been looking at hook\_url\_inbound\_alter() which gets me in when a user is about to move to another page, and gives me where they are going, but not where they came from. Any suggestions?

# Answer
Drupal does not track this information, so you need to do it yourself, using sessions (\*).

If your pages are not being cached, then the best place to track user progress would probably be in hook\_init. This is called very early on in the process - so in effect you have the information of knowing where the user wanted to go before anything is displayed (you could redirect the page at that stage for instance).

If your pages are being cached, in particular using a cache mechanism that bypasses Drupal such as Boost or an external cache proxy, then you will need a Javascript based solution that sends the information back to your site. How to implement this is beyond the scope of this answer.

(\*) Note however that Drupal implements it's own session handling, so you need to do some extra work to use session variables (the session variables you set are only available through $\_SESSION on the next page load - in the mean time you need to keep track of them yourself. Some people have written example implementations, or you may want to try the session api module).
> 1 votes

---
Tags: redirection, uri, search
---


title: Drupal Pricing Table Module

text:
# Question
Title: Drupal Pricing Table Module
What is the best way to create a Drupal pricing table for Drupal Commerce? I love the pricing table mentioned in this discussion. But I can't believe there is no ready-made module. What's your recommended architecture?

# Answer
> 1 votes
I think your Google-fu has failed you :)

Commerce price table:

> Drupal Commerce contrib project that allows to have a secondary price field that considers the quantity for displaying and using the prices. It also provides a field formatter to display the price/quantity values as a table.

---
Tags: 7
---


# Question
Title: Should I use Entity Views Attach module to solve my problem
I've check the question in this node: https://drupal.stackexchange.com/questions/5732/is-there-a-good-tutorial-for-entity-views-attach-module

And I see that maybe what is answered there is a partial solution to the issue I'm facing. To avoid writing I will paste the issues addresses I've been creating on my help search:

1. https://drupal.org/node/1928064
2. https://drupal.org/node/1929030
3. https://drupal.org/node/332001

Basically it's to send an argument from a view to another view, both displayed at the same time in the same page (one in block, the other in content). A further complication is that those views are contained in panels.

On the "block view", there is a list of let's say names (extracted from a content type) exposed as links which point to the "content view". This takes the argument (text of the link) from the clicked link of the "block view" as a filter to display some others fields from the same content type.

# Answer
> 0 votes
I suspect you might get a better answer if you were to say more about what you are trying to achieve than how you are doing so.

For example, reading between the lines of your question I wonder if you are working on some sort of faceted search? In which case I'd recommend you look at Search API. And this may be of interest: http://ygerasimov.com/ajaxified-solr-search-drupal-search-api-views-panels

---
Tags: panels, entities, views
---


title: Node reference field display

text:
# Question
Title: Node reference field display
I have a content type with several fields, some of them are node reference fields displaying multiple values. I've configured the display of one node reference field like teaser showing two fields "code, description". The problem is when the node reference has more than one value, keeps adding lines to the bottom. I want to display this node reference field like "code1/code2 description1/description2" in one line.

How can I achieve this? What template should I override, field.tpl.php or node.tpl.php?

# Answer
After a lot of research i finally solved my problem. I don't know if this is the best way of doing it but it works for me.

I added a THEME\_field() function to my template.php of the desired field.

Inside my template function i removed the even/odd css classes because i want all in a single line. Probably exists a better way to access field values, this was the solution i found. Digging the $item array i was able to get my code and color description values.

If someone knows a better way of doing this please help me improve it. There goes the code i hope it helps someone else. Don't forget to replace THEME by your theme name and the FIELDNAME.

```
function THEME_field__FIELDNAME($variables) {
$output = '';

// Render the label, if it's not hidden.
if (!$variables['label_hidden']) {
  $output .= '<div class="field-label"' . $variables['title_attributes'] . '>' . $variables['label'] . ': </div>';
}

// Render the items.
$output .= '<div class="field-items"' . $variables['content_attributes'] . '>';
$codes = "";
$colors ="";
foreach ($variables['items'] as $delta => $item) {

    $code = $item['field_color_description']['#object']->title_field['und'][0]['value'];
    $color = $item['field_color_description']['#object']->field_color_description['und'][0]['node']->title;

    $codes .= $code."/";
        //avoid repeated color descriptions
        if (strpos($colors,$color) === false)
        {
        $colors .= $color."/";
        }
     }
     $classes = 'field-item even';

     $codeAndColors = rtrim($codes,"/") . " ". rtrim($colors,"/");
     $output .= '<div class="' . $classes . '"' . ' title="'. $codeAndColors.'" '. $variables['item_attributes'][$delta] . '>' . $codeAndColors . '</div>';
     $output .= '</div>';

     // Render the top-level DIV.
     $output = '<div class="' . $variables['classes'] . '"' . $variables['attributes'] . '>' . $output . '</div>';

     return $output;

```

}
> 1 votes

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


title: Theming a view of comments

text:
# Question
Title: Theming a view of comments
I have a view which creates a block of comments. I have a comment.tpl.php in my theme folder which I use to theme the comments on the node.

To theme the view, I need a variant of comment.tpl.php and have tried the following:

comment-view.tpl.php comment-views.tpl.php comment-view--name-of-view.tpl.php comment-view-name-of-view.tpl.php

After cache clearing each option the template is still not picked up.

How can I theme this view please? By the way I am using the Omega theme.

# Answer
Ok, I came up with some sort of solution, thanks to @clive.

```
function hook_preprocess_comment(&$vars){
    if (isset($vars['view'])) {
        $view = $vars['view'];

            if ($view->name == "my_view_name"){
            $vars['theme_hook_suggestion'] = 'comment__' . str_replace('-', '_', $view->name);
    }
  }
}

```

I tried to do $vars\['theme\_hook\_suggestions'\]\[\] but those templates were never picked up. Is it ok to directly set theme\_hook\_suggestion.

Really hope this helps someone else out there..
> 1 votes

# Answer
When in the views UI, under 'advanced' on the right hand side, down the bottom you will see 'Theme' with a link next to it saying 'information' (under the 'Other' heading). Click the information link to see many template file name suggestions.
> 0 votes

---
Tags: comments, theming
---


# Question
Title: Can I add a description for Ubercart catalog categories?
I am working on an Ubercart store with several products with a hierarchy of categories.

I'm wondering if it is possible to add a description at the top of the catalog page for each category?

I know that each category is a taxonomy term with which I can set its description, but I can't see any way of displaying that. I've also looked at the option of using a custom block and using a token in the block body but tokens don't seem to be recognised in the block's body.

Any ideas?

Thanks, Alan

# Answer
In the catalog view, enable a Global:Text area in the Header, and set the input filter to PHP code.

The following code will print the term description and any associated taxonomy image in the view header.

```
<?php
$view = views_get_current_view();
$tid = $view->args[0];
$description = "";

if ( is_numeric( $tid ) ) {
  $term = taxonomy_term_load($tid);

  $description = $description . "<div class='term-description'>";

  if (isset($term->uc_catalog_image['und'][0]['uri'] )) {
     $description = $description . "<img src='" . image_style_url( 'uc_product_list', $term->uc_catalog_image['und'][0]['uri']) . "' class='term-image' /> ";
  }

  if (module_exists('i18n_taxonomy') && i18n_taxonomy_vocabulary_mode($term->vid) == I18N_MODE_LOCALIZE) {
    $description = $description . i18n_string("taxonomy:term:$term->tid:description", $term->description);
  } else {
    $description = $description . $term->description;
  }
  $description = $description . "</div>";
  print $description;
}
?>

```
> 1 votes

---
Tags: views, taxonomy-terms, blocks, ubercart
---


# Question
Title: Can Webforms include the URL they were submitted from in their emails?
I have a bunch of webforms in blocks on taxonomy pages. It would be helpful for the recipient of the resulting emails to know what taxonomy page the user was on at the time they wrote their query. Do I use the %get token in a hidden field? And if so then what \[key\] value returns the full (pathauto) url? Webforms can only use %get\[key\] and %post\[key\] for non-authenticated users.

# Answer
You can achieve this by using the `%server` token as the value of the hidden field. To be more precise `http://%server[SERVER_NAME]%server[REQUEST_URI]` should get you the full url (path alias is also preserved). For a complete list of options that can be used with the `%server` token check out the manual.

UPDATE:

The `%server` token only works for authenticated users since Webform version 2.8 due to potential security/privacy issues with some values. Since you only need the url in e-mails a better solution should actually be to put a appropriately themed version of `<?php print url($_GET['q'], array('absolute' => TRUE)); ?>` inside your copy of `webform-mail.tpl.php` file (or `webform-mail-[node id here].tpl.php`).
> 2 votes

# Answer
You can simply use the yoursite.com/%get\[q\] this token is for drupal's special request parameter which holds the current path
> 2 votes

# Answer
If you are working with Drupal 7 + Webform 7.x-3.18 you can add a Hidden field to your webform.

Then in the hidden type you can choose the option "Secure value (allows use of all tokens)"

This allows you to use all tokens types, like %server\[SERVER\_NAME\] or %server\[REQUEST\_URI\]

Tested with anonymous users and working fine.
> 2 votes

# Answer
When I required token support for my webforms I used the webform patched module. It's the webform module already patched to support tokens. So you could use in your hidden field the token \[current-page:url\]. I have not tried this in a block webform but I do not see a reason it should not work.
> 0 votes

---
Tags: 6, webforms, uri, tokens, path-aliases
---


# Question
Title: How to split configurations in features to minimize conflicts
I need to put all configurations of a site to features. Some say that it is not a good idea to put all of the site configurations in one big feature. I have also experienced strange behaviour of the features ui when I tried it once.

My question is what kind of rules I need to implement on splitting the configurations between multiple features, to fulfil one important thing: Every small configurations, every new strongarm variable, or field, etc should be completly clear where to put to, to avoid confuse and conflicts in the future.

# Answer
What I try to do is to build up features in layers. At the bottom most layer you put all the things that do not depend on anything else in your features, such as contrib modules, site settings and the like.

At each layer you add features that depend on the layer below, trying to avoid cross-dependencies. Each feature should be as standalone as possible apart from its depndencies on lower-level features.

It's difficult to achieve perfection, though, because a new feature may affect things you have already configured. For example if you install the field permissions module for a specific need, that'll add extra settings to fields you have already configured. So that module effectively becomes a dependency of sorts even though logically it isn't.
> 0 votes

---
Tags: 7, features
---


# Question
Title: Taxonomy terms not translating on the edit/add node form
I'm trying to translate the interface on a drupal 7 installation but somehow the terms and the taxonomy names are not being translated.

The vocabulary names and the terms names are already translated and the field names were also translated but the node creation form are still just showing on the default language.

Has anyone had the same problem?

Here's the page where this is happening: http://www.cuipcairo.org/ar/node/add/initiative

# Answer
> 1 votes
Best guess based on your description is that you need to enable the URL detection at

> /admin/config/regional/language/configure

since that appears to be how you are distinguishing the interface. This recipe from http://drupal.org/node/1281704#comment-5253460 should also help:

* Enable ALL i18n modules
* Add your extra languages (optional) - Enable Localization update and run Update translations at /admin/config/regional/translate/update
* Enable URL detection method at /admin/config/regional/language/configure (optional) - Throw that Language Switcher block into a visible section of your site
* Add your Localized vocabularies and translate them
* Add your terms and translate them
* Edit the content types you want term references to appear in and Enable Multilingual Support (with translation) in Publication Options vertical tab (recommended) - In the Synchronize Translations vertical tab check the first two checkboxes of the Extended language options. That is: "Set current language as default for new content" and "Require language (Do not allow Language Neutral)"
* Add term reference fields to the content types you want

# Answer
> 1 votes
Figured it out.

It had to do with the fact that I was testing the Select (or other) taxonomy module, for Drupal 7.

On line 125 replaced

```
foreach ($taxonomy_terms as $term) {
    $options[$term->tid] = $term->name;
}

```

with

```
foreach ($taxonomy_terms as $term) {
    $options[$term->tid] = i18n_taxonomy_term_name(taxonomy_term_load($term->tid));
}

```

Still having trouble translating the field labels thought. Some how the t() function is not working on

```
'#title' => isset($instance['label']) ? t($title) : NULL,

```

---
Tags: taxonomy-terms, i18n-l10n
---


# Question
Title: Block displaying one parent and many children nodes using only Views 3 Drupal 7?
I'm trying to generate a block that looks like this in Drupal 7 Views 3:

---

* Parent Node (fields)
+ Child Node 1 (fields)
+ Child Node 2 (fields)
+ Child Node 3 (fields)
+ ...

---

Parent node is a different content type than child node. For the time being, I've added a matching taxonomy field to the two content types. So to potentially establish a relationship, this value would be the same.

What is the best way to achieve this? It seems like a simple enough goal that Views should be able to handle. I prefer to thoroughly understand the core software w/ Views, before I blindly install a bunch of modules that I may not need.

# Answer
I've achieved the desired output by creating a vocabulary of taxonomy terms which is essentially just a flat list of foreign keys. There is no semantic representation of a hierarchy here.

**NOTE:** This is a different example than the event calendar I described in the comments of my initial post, however the data model is the same.

* Parent content type (Rich Menu) contains this taxonomy term field, in this example called "Menu".
* Child content type (Rich Menu Item) also contains the "Menu" taxonomy term field.
* If Rich Menu Item is a child of Rich Menu, the two term fields are set to match. **NOTE:** I wonder if this idea can be simplified using node references (References module) instead of taxonomy.

Then I created a new block view called "Rich Section Menu". This block will display the parent content type, Rich Menu, filtered by the taxonomy term from the field "Menu" (value = Section). Create an attachment to be displayed after the block which will render a list of children from the Rich Menu Item content type. The child content type will also be filtered by the Menu term field (value = Section). **NOTE:** Adding the relational term field to the list of filters is only necessary if you expect to have multiple parent/child relationships that share the same content types.

Tried to post screenshots of my Views configuration for clarity, but my reputation isn't high enough.

This achieves the output I desire, however it's a bit simplistic. I would prefer to create a semantically correct parent/child hierarchy using taxonomy or node references, and have Views render that output in a single block, without an attachment, with support for children more than one level deep.

So this works, but is there any way that I can do it better?
> 1 votes

---
Tags: views
---


# Question
Title: D7 auto nodetitle, title with pattern node:nid and rules php node_save($node)
I want to make automatic title like node-333, using auto nodetitle module. When creating node there is no nid, so pattern node-\[node:nid\] gives me after saving new content "node-". When I edit again this node - title is changing as expected.

So I thought, that using rules I do simple "After saving node" condition "Node type is" and action Execute php node\_save($node). But it is not working, I'm getting

PDOException: SQLSTATE\[23000\]: Integrity constraint violation

Does anyone deal with this or have some workaround?

# Answer
> 2 votes
You are on the right track. I have been doing this for a while now with the following code snippet in rules.

```
auto_nodetitle_operations_update(array($node->nid));

```

---
Tags: 7, rules, nodes
---


title: What are [meta] issues on D.O?

text:
# Question
Title: What are [meta] issues on D.O?
On drupal.org, what are exactly meta issues? Meta issues meaning issues that contain the word \[meta\] at the beginning of the issue queue on drupal.org.

Issues that contain other smaller issues?

# Answer
> 4 votes
'meta' loosely means 'about', like the discussions on the meta site here. They are about the site, not drupal. Meta Tags are about the page, placing it in context. The \[meta\] issues are not about functionality, but rather about policy, code-cleanup, documentation, standards etc., rather than regular (functional) issues which are about achieving a result through code.

---
Tags: community-official-site
---


# Question
Title: Drupal 7 EVA fields not rendered on unpublished nodes
In a node type with 3 EVA fields, if I unpublish the node, the node view tab shows only the pink watermark "Unpublished" and the EVA fields are not rendered at all. The EVA related view does not have any publish filter nor any permission that prevents unpublished content to be rendered. All modules are updated to latest stable version. Any idea?

# Answer
Solved using the View Unpublished module. This is not related to EVA module but it is related to the drupal unpublished nodes built in user permissions
> 0 votes

---
Tags: views, nodes
---


# Question
Title: Migrating a forum created with Advanced Forum 1.x branch from Drupal 6 to a Drupal 7 site running Advanced Forum 2.x branch?
What's the best way to do it? What module(s) should I use to export the data from the Drupal 6 site and import the data into Drupal 7 and what do I need to think about regarding the different branches? Please also describe the process if you have experience with it.

# Answer
First, upgrade the site to Advanced Forum 6.2.x, then, after everything is correct, migrate to D7.

The upgrade to 6.2.x should be relatively smooth (there were no problems in my experience).

You might have to have several tries for the D6-\>D7 migation, depending on your site configuration. Always do it in a separate installation, and back up everything, step by step. If something does not go right, this will allow you to reset the site to a point where you can restart a step, rather than going back to a fresh install and starting from scratch.

Follow the Upgrading from previous versions on D.O. to the letter.
> 1 votes

---
Tags: migrations, nodes
---


title: Show number of pages views

text:
# Question
Title: Show number of pages views
I am new to Drupal, so I want to know how do I echo number of views of a page ? or of a category ?

# Answer
If you go your modules admin screen (/admin/modules), you'll see there's a module called **Statistics** that actually comes with core Drupal. Make sure you enable it on this screen if it isn't enabled already.

This will print out page views at the bottom of your pages, but you have to make sure you visit the permissions screen to give anonymous users (if that's what you're trying to do) the ability to see that. After the module has been enabled, you'll see the following set of permissions for your site(/admin/people/permissions):

* Administer statistics
* View content access statistics
* View content hits

You'd just need to check the last one for whomever you want to be able to see the page views!

You can find additional information about this module on your own site's help pages: /admin/help/statistics
> 3 votes

---
Tags: views, theming, nodes
---


# Question
Title: Unusual renewal of subscription products
Marketing wants to sell a subscription product at a discounted price of 5 septims a year for 3 years, and then return it to its regular price of 10 septims after that.

In discussion the idea came up to:

* Generate 3 new products (SUB\_Y1, SUB\_Y2, and SUB\_Y3 in addition to the existing SUB product)
* Set up the renewals notifications for the first 3 products to encourage users to renew
* Direct them only to the next product in the series
* Offer them the regular product after the first 3 cheap years

However, I know my marketing department; if I do this, they will want more, and by the end of the year I will have 25 different series, each of which having 2 to 5 steps in the process. My /admin/store/products/view will be a nightmare to behold.

Is there a cleaner way of handling this that will not use up much of the 25 minutes actual coding time I am alotted each week?

# Answer
Ultimately I altered the custom module with a toggle to extend the "different price after first month" to 1,3,6, or 12 months, and attach that to the product. Given that the module was outdated custom variant of a Ubercart mod in the first place, there was nothing to contrib to. Solution worked very well though, if anyone bumps into it.
> 0 votes

# Answer
I've not used UC Recurring Payments and Subscriptions before properly, but if each payment is a fully fledged order then I imagine you could use Conditional Actions to look at the date compared to the initial purchase date and give a discount if that is within the three years. The coding effort is then just creating a new condition using hook\_ca\_condition() which is not hard, and then after that setting up the pricing rules in the CA interface.
> 0 votes

---
Tags: ubercart, notifications
---


# Question
Title: Two Login Forms for the Site in Drupal 7
I've a site setup in Drupal 7 where every user who is not authorized is shown a username/password page through Logintoboggan Module.

All went good, until a unique requirement came.

First Scenario:-

I need to have a universal login page which will only have a password field. So whenever a user comes to the site and is not logged in, he will be shown a page with only Password Entry, where he will enter a password and will enter the site. The role of this user would be Authenticated User. (I guess this can be done if I hide the username field somehow and pass a hidden username field along with the form )

Second Scenario:-

Whenever user, who is not logged in, wants to log in as an admin, he/she will enter the URL as **www.site.com/admin** and should be shown normal authentication page, which will have username/password field. One can then, enter the credentials and enter the site as an admin (normally, as we are doing now with every page).

Hence, I need two login page forms; one would have only password field and other would have normal username/pwd fields at a specific URL.

I'd be very thankful if you can help me in any regard.

Thanks.

# Answer
If you are talking about a single account that everyone who uses the site will use, the security implications are horrible. In the context of a business site, what happens if an employee is terminated. Does everyone have to learn a new password. What about the case of one disgruntled user who does something malicious? Do you want to have to track responsibility by back-tracing an IP address? There are so many reasons not to implement this requirement.

Drupal looks up password by user (user name or unique email) and being able to attribute site changes to an individual user, and to control access by individual user is extremely important with most sites. To deviate from the tried and true method will require a custom module, and I seriously doubt it is a good idea simply to alter the user experience.
> 1 votes

---
Tags: users
---


# Question
Title: How to prepopulate drupal form and still execute a custom submit handler
I want to build a custom edit form for a existing node. The edit form should not show all fields and should be populated with the existing field values. Furthermore I want to add a few custom submit buttons. I know I can pre populate the fields with #default\_value, but there are quite a lot of fields I have to pre populate like that, so I wanted to pre populate them all at once.

I have made a form function with the following code:

```
$node = (array)node_load($nid);
$form_state = array();
$form_state['values'] = $node;
$form = node_form($form_state, $node);
drupal_prepare_form('node_form', $form, $form_state);

```

I have also defined a custom submit button:

```
   $form['submit_one'] = array(
       '#type' => 'submit',
       '#value' => t('Gereed'),
       '#weight' => 10,
       '#submit' => array('custom_form_submit_one'),
   );

```

And a submit handler:

```
 function custom_form_submit_one($form_id, $form_values) {
   watchdog ("Hello","Hello");
 }

```

When I press the submit button, the submit handler is not called.

When I disable the statement:

```
$node = (array)node_load($nid);

```

and I press the submit button, the submit handler is called. However, my form is not pre populated with the values.

Is it possible what I want to do? Can I use a custom form and pre populate the fields (without specifying #default\_value for each field)?

# Answer
Why must you have a separate form? I think a simpler approach would be to modify the existing form on a conditional basis via a form alter hook:

```
function hook_form_alter(&$form, &$form_state, $form_id) {
  // match our custom content type ('yourContentType_node_form') edit form, and ensure
  // we're editing a specific node
  if ($form_id == 'yourContentType_node_form' && arg(1) == '123') {
    // add new submit buttons
    $form['actions']['submit_one'] = array(
      '#type' => 'submit',
      '#value' => t('Gereed'),
      '#weight' => 10,
      '#submit' => array('custom_form_submit_one'),
    );
  }
}

```
> 1 votes

---
Tags: forms
---


# Question
Title: How can I resend the commerce email from the admin orders screen?
Is there any way of allowing site admins to resend the default order email that commerce provides to the user after a completed order?

# Answer
> 5 votes
Since I was using the commerce email module, it was a pretty easy setup to use a rules component and then add it to my /admin/commerce/orders vbo view.

```
{ "rules_resend_order_email_to_customer" : {
    "LABEL" : "Resend order email to customer",
    "PLUGIN" : "action set",
    "REQUIRES" : [ "variable_email" ],
    "USES VARIABLES" : { "commerce_order" : { "label" : "Commerce Order", "type" : "commerce_order" } },
    "ACTION SET" : [
      { "variable_email_mail" : {
          "to" : [ "commerce-order:mail" ],
          "variable" : "commerce_email_order_[mail_part]",
          "language" : "default"
        }
      }
    ]
  }
}

```

# Answer
> 0 votes
No, there's no such functionality.

Such functionality could be implemented on top of Commerce Message (since it can save sent messages into entities, allowing them to be resent later). Will require someone to code it and submit a patch.

---
Tags: commerce
---


# Question
Title: How to include specific roles in auto-complete search?
I am using the auto-complete module for searches. It works like a charm. I am looking for to learn how to show only specific roles on the results it pulls. There are advanced areas in the configuration and I think something could be used there, yet I am not sure what.

# Answer
The best way to do this is create a View of the search results you would want. e.g. If you create a view of Users with role, "editor", then Autocomplete can be used to pull only from that view. Using the Filters ability of views, this should be a relatively simple task.

http://drupal.org/project/search\_autocomplete supports this feature.
> 0 votes

---
Tags: 7, users, ajax
---


title: multisite or multi install?

text:
# Question
Title: multisite or multi install?
I am planning a Drupal 7 site for video sharing, where registered users can share videos.

Main Site: example.com
Subdomain for blog for registered users would be: blog.example.com.

The database would be different for main site and subdomain. Since the target of main site would be very high traffic, what would be the efficient choice ? either Multisite or Multiple Drupal installation (one installation for Main and another installation for blog) ?

what would you advice and why ? (I mean from personal experience, difficulty to handle and maintain, performance issues, etc)

# Answer
Your choice of site architecture (e.g. multisite or multiple drupal installations) doesn't necessarily play into performance. Meaning any site can be made performant using the right mix of modules (memcache, Varnish on the front end, etc.);

With that in mind, look at the following criteria when selecting multisite over multi-installation instead:

* Will most of the modules on the sites be shared with one another?
* Related, will the modules always be in sync via version? i.e. Context 3 vs. Context 2.
* Will the versions need to be in sync? i.e. If you upgrade the main site, will the blog site also need to be upgraded?

If the answer to any of these questions is yes, use a multisite. If there is concern about them, use two document roots with one site a piece. Sharing content can easily be done through any of the following projects so multisite or multi-installation doesn't matter:
> 2 votes

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


# Question
Title: git post-receive hook to trigger drush rsync without prompt or with predefined answer
I have set up post-receive hook on my staging server, so whenever I push from dev server a master branch, it updates staging webroot and triggers drush rsync to update live site.

```
#!/bin/bash

    while read oldrev newrev ref
    do
      branch=`echo $ref | cut -d/ -f3`

      if [ "master" == "$branch" ]; then
    git --work-tree=/var/www/drupal/ checkout -f $branch
    drush rsync --delete --exclude='.htaccess' --exclude='io' --log-file=rsynclog.txt --exclude-files @stage @live

        echo 'Changes pushed live.'
      fi

      if [ "dev" == "$branch" ]; then
        git --work-tree=/var/www/drupal/ checkout -f $branch
        echo 'Changes pushed to staging.'
      fi
    done

```

Or i hoped to do so :) I have ssh keys in place and that is not the problem, what i can see is that it hangs on destroy yes no question. Output after **git push origin from** dev machine:

> Counting objects: 15, done.
>
> Delta compression using up to 4 threads. Compressing objects: 100% (8/8), done. Writing objects: 100% (8/8), 762 bytes, done. Total 8 (delta 5), reused 0 (delta 0)
>
> remote: Already on 'master'
>
> remote: You will destroy data from mydomain.com:/var/www/drupal/ and replace with data from /var/www/drupal// remote: **Do you really want to continue? (y/n): Aborting. \[cancel\]**
>
> remote: Changes pushed live. To root@dev:/git/drupal 65abd19..7205946 master -\> master

So I would need somehow to tell script that answer is y, or I need a way to avoid that question at all.

Also, I am not pro bash scripter ;) , are those commands being excecuted in line, like in php, so one is not executed before other finishes ? (to make sure changes are propagated on staging webroot first, then rsynced all to live).

# Answer
Add the --yes option to your Drush command. This assuredly *will* work if you place it *before* the rsync directive.

For example:

```
drush --yes rsync @dev @live

```

Drush rsync is different than most Drush commands in that it uses strict option handling. Commands that work with strict options pass *all extra flags* that appear after the Drush command name on to the tool that is being invoked. Thus, `drush rsync --yes @dev @live` will fail, because the --yes will be ignored by Drush and passed on to rsync.

For more information, see:

drush topic docs-strict-options
> 5 votes

---
Tags: drush, version-control, deployment
---


# Question
Title: Can I add the value of a field in a checkout pane to a completed order email?
I would like to add a select list box to a checkout pane in drupal commerce that will allow me to use the selected value as a token to be added to the completed order email?

# Answer
> 3 votes
Typically, you'd alter a form via hook\_form\_alter() and then sort out through a custom validate / submit handler how to process and save the data so it could be used later. However, I'd recommend something different, because in that approach you'd have to also create a place to store the data and a way to render it in a token, field, Rules data selector etc. yourself.

The easiest way to collect data and use it later in these various scenarios is to use a field. So instead of altering the form directly, I'd figure out how to get a custom field into the checkout form. You have two basic options:

1. If the data has something to do with customer profile information, like billing or shipping information, simply add the field to the customer profile type and it will appear on the checkout form. I'm not entirely sure how the token system works with respect to the Rules e-mail action, but the data will be there and field tokens will be there to make it happen somehow. Might require further investigation or a module.
2. If this data is stand alone and you just need it to appear on the form in its own checkout pane, I'd add the field to the order in a fieldgroup and use the Commerce Fieldgroup Panes module to make it into a checkout pane. Then you'd have the field data on your order usable from a token as well.

---
Tags: tokens, commerce
---


title: Reference Custom Field on User Profile

text:
# Question
Title: Reference Custom Field on User Profile
I'm very close to getting this working right. I created a custom content type with several decimal fields and an entity reference field where you select a user to assign the content to. I am using a computed field to add up the decimal fields and would like to multiply them by a field that I've added to the User profile.

The problem is that I don't know how to reference the field.

This doesn't seem to work:

```
field_get_items($entity_type, $entity, 'field_percentage_split')[0]

```

I'm using Drupal 7. Any ideas?

Thank you!

# Answer
You should expand the code in your question a little.

First you need to get the assigned uid with something like:

```
$assigned_uid = $node->field_assigned_user[LANGUAGE_NONE][0]['target_id'];

```

Then you need to load the user object:

```
$assigned_user = user_load($assigned_uid);

```

Then you have access to the value:

```
$percentage_split = $user->field_percentage_split[LANGUAGE_NONE][0]['value'];

```

To help visualize the $node and $user objects and how to access the information, you can put the print\_r() function into a php-enabled block in your footer.

EDIT:

I looked at your code, and you should not try to do everything in a single statement. No wonder you are having problems. Break it out step by step like this:

```
// Get the assigned User ID from the node object

$assigned_uid = $node->field_assigned_user[LANGUAGE_NONE][0]['uid'];
// Load the user object for the assigned User.
$assigned_user = user_load($assigned_uid);
// Get the Percentage Split from the user object for the Assigned User (default to 0).
$percentage_split = (isset($assigned_user->field_percentage_split[LANGUAGE_NONE][0]['value'])) ? $assigned_user->field_percentage_split[LANGUAGE_NONE][0]['value'] : 0;
// Get the remaining values from the node object, defaulting to 0 if not there.
$other_ins = (isset($node->field_other_ins_[LANGUAGE_NONE][0]['value'])) ? $node->field_other_ins_[LANGUAGE_NONE][0]['value'] : 0;
$vb = (isset($node->field_vb[LANGUAGE_NONE][0]['value'])) ? $node->field_vb[LANGUAGE_NONE][0]['value'] : 0;
$finder_s_fee = (isset($node->field_finder_s_fee[LANGUAGE_NONE][0]['value'])) ? $node->field_finder_s_fee[LANGUAGE_NONE][0]['value'] : 0;
$broker_fee = (isset($node->field_broker_fee[LANGUAGE_NONE][0]['value'])) ? $node->field_broker_fee[LANGUAGE_NONE][0]['value'] : 0;
$dlc_franchise_fee_hst = (isset($node->field_dlc_franchise_fee_hst[LANGUAGE_NONE][0]['value'])) ? $node->field_dlc_franchise_fee_hst[LANGUAGE_NONE][0]['value'] : 0;

// Do the math.

$value = ($other_ins + $vb + $finder_s_fee + $broker_fee - $dlc_franchise_fee_hst ) * $percentage_split;

```

You also seem to be trying to use D6 data structures (won't work in D7), and it will also not work to try to give a function array keys.
> 1 votes

---
Tags: entities
---


# Question
Title: Old site migration and keeping links (as aliases)
I'm migrating an older site into Drupal 7 and have had a lot of success so far. One item where I'm stumped is on links to user profiles. The older system would link to teachers via

`site.edu/faculty.php?PID=FirstnameLastname`

Might there be a way to effectively copy that URL as the page's alias `faculty.php?PID=FirstnameLastname`? And yes, is there a way to escape the http encodings (`?`, `=`, and `&`)?

# Answer
> 2 votes
There's no real need to escape the URI string.

Here's one way to handle this:

1. In a custom module, implement `hook_menu()`, creating an item for the path 'faculty.php'
2. In your php function callback for the above path, look at the `PID` value, look up the new path (you do have a database table mapping old content to new content, right? :) ), and do a 301 redirect.

Another approach is to do this lookup on all 404 pages with something like the following code in a `hook_init()`:

```
function hook_init() {
  if (!menu_get_item($_GET['q'])) {
    $pid = isset($_GET['PID']) ? $_GET['PID'] : FALSE;

    if ($pid) {
      // lookup new path and 301 to it
    }
  }
}

```

---
Tags: path-aliases
---


# Question
Title: Attach an image gallery carousel to nodes
I want to attach an image gallery to a node, showing the images in a carousel view so that only a few thumbnails are shown and clicking on them opens a ColorBox overlay.

I have a gallery content type that contains all images in a field, and in an article the gallery is referenced using an entity reference field.

I found the Gallery Formatter module which does nearly want I want. But I don't want to display the large image on the page, only the carousel showing thumbnails. To get the full size image one should click on one of the thumbnails.

So I need a field formatter that can display the contents of an image field as a carousel. Any ideas on how I can achieve this?

# Answer
> 1 votes
Check out Adding a jQuery Image Carousel to your Node View.

Though the above article is for Drupal 6, you can follow this like below:

* As the gallery is referenced in the "Article" content type, you can modify the template file for that content type, and fetch the gallery images.
* After that, you can display that in carousel.

The other way is using a theme preprocess function.

```
function YOURTHEME_preprocess_node(&$variables) {
  // Your code.
}

```

# Answer
> 1 votes
I had the same problem recently, the best solution i think is to use this module Field Slideshow. Read about it, what you need is to install this module, then u need to create two image styles for thumbnails and for image. In your content type in **Manage Display** settings u can configure your carousel. Also u need to install this modules

```
Libraries API,
Jquery Cycle plugin, JCarousel

```

you can read about this module here

# Answer
> 1 votes
You can achieve this with the Lightbox2 module. Check out the Grouped images example.

---
Tags: 7, entities, media
---